bots-garden/mini-mepublic Fork
⑂ 54ca9a6
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

✨ llamacpp autoStart (#223, #257): mm starts llama-server and stops it with the last session

- llamacpp.autoStart (opt-in): when nothing answers at a loopback address
  (nor 8080, nor the fallback), mm starts llama-server in router mode with a
  models.ini naming the agent's model (downloaded on first load), waits until
  it is loaded, and stops it with the last mm session using it
- internal/llamastart: registry per address under the user cache dir
  (server.json, one lease per mm pid, lock, log); stale leases cleaned; a
  server mm did not start is never stopped; process group / taskkill /T
- launch settings (#257): ctxSize, modelsMax, modelsMemoryMargin, fitTarget,
  sleepIdleSeconds, specDefault — optional router flags (absent = llama-server
  default), validated; serverArgs for the rest
- exit hook: the lease is released after the unload of #255; Ctrl-C/SIGTERM
  during the start stop it
- mm init asks --autostart (default yes) and --launch-settings (default no,
  the Llama app's values)
- docs EN+FR

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-24T18:53:41+01:00 Browse files
54ca9a6 parent: 15abe15
modified .tickets/issues/0223-llamacpp-start-llama-server-when-it-is-not-runnin.yaml +54 -7
@@ -1,12 +1,12 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 223
33 title: "llamacpp: start llama-server when it is not running, stop it with the last mm session"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-18T07:13:12.000Z
9-updatedAt: 2026-11-20T07:29:52.000Z
9+updatedAt: 2026-11-24T17:52:58.000Z
1010 labels:
1111 - kind::feature
1212 milestone: v2.0.1
@@ -93,44 +93,54 @@ body: |
9393 tasks:
9494 - id: 1
9595 title: Decide - opt-in key, server arguments (router mode, model, extra args), binary lookup
96- state: open
96+ state: closed
9797 priority: high
9898 author:
9999 name: k33g
100100 email: ph.charriere@gmail.com
101101 createdAt: 2026-11-18T07:13:12.000Z
102+ updatedAt: 2026-11-24T17:14:24.000Z
103+ closedAt: 2026-11-24T17:14:24.000Z
102104 - id: 2
103105 title: Start and wait - spawn llama-server detached, log file, readiness on /models with a timeout
104- state: open
106+ state: closed
105107 priority: high
106108 author:
107109 name: k33g
108110 email: ph.charriere@gmail.com
109111 createdAt: 2026-11-18T07:13:12.000Z
112+ updatedAt: 2026-11-24T17:14:24.000Z
113+ closedAt: 2026-11-24T17:14:24.000Z
110114 - id: 3
111115 title: Shared lifetime - registry + file lock, one lease per mm process, the last one stops the server; stale leases cleaned
112- state: open
116+ state: closed
113117 priority: high
114118 author:
115119 name: k33g
116120 email: ph.charriere@gmail.com
117121 createdAt: 2026-11-18T07:13:12.000Z
122+ updatedAt: 2026-11-24T17:14:24.000Z
123+ closedAt: 2026-11-24T17:14:24.000Z
118124 - id: 4
119125 title: Never stop a server mm did not start (the user's, the Llama app's); no start for a remote baseUrl or in a container
120- state: open
126+ state: closed
121127 priority: medium
122128 author:
123129 name: k33g
124130 email: ph.charriere@gmail.com
125131 createdAt: 2026-11-18T07:13:12.000Z
132+ updatedAt: 2026-11-24T17:14:24.000Z
133+ closedAt: 2026-11-24T17:14:24.000Z
126134 - id: 5
127135 title: Tests with a fake llama-server; docs EN+FR (run-with-llama-cpp, configuration)
128- state: open
136+ state: closed
129137 priority: medium
130138 author:
131139 name: k33g
132140 email: ph.charriere@gmail.com
133141 createdAt: 2026-11-18T07:13:12.000Z
142+ updatedAt: 2026-11-24T17:14:24.000Z
143+ closedAt: 2026-11-24T17:14:24.000Z
134144 comments:
135145 - id: 1
136146 author:
@@ -184,3 +194,40 @@ comments:
184194 - Port 9931, the default since #218: a server the app started and a
185195 server mm would start compete for it; mm must recognise a server
186196 it did not start and leave it alone.
197+ - id: 2
198+ author:
199+ name: k33g
200+ email: ph.charriere@gmail.com
201+ createdAt: 2026-11-24T17:14:24.000Z
202+ body: |
203+ Implemented on branch `feature/llamacpp-autostart` (not committed).
204+ Decisions (user, 2026-11-24): opt-in `llamacpp.autoStart` (mm init writes
205+ true for a local llamacpp agent); wait for the model at start-up;
206+ Windows included.
207+ Measured on llama.cpp build 12359 (Linux arm64, installed in the sandbox):
208+ router mode lists the HF cache + a `--models-preset`; a preset entry
209+ `hf-repo = org/repo:QUANT` is downloaded on first load; the cache is
210+ scanned once at start; `/models/load` is async, status `loading` →
211+ `loaded`, or `unloaded` + `failed: true` + `exit_code`; killing the
212+ router's pid alone leaves its model children running → stop the group.
213+ - `internal/llamastart`: registry `<cache>/mm/llama-server/<host>-<port>/`
214+ (server.json, leases/<pid>, lock, models.ini, llama-server.log),
215+ Acquire / Lease.Release; process group (unix) / taskkill /T (Windows).
216+ - `engine.LlamaStartAddress`: loopback only, no AGENT_BASE_URL, and no
217+ OTHER llamacpp address (8080, fallback) answering.
218+ - main: started before engine.New; released through the exit hook of
219+ #255 (after the unload); Ctrl-C/SIGTERM during the start stop it.
220+ Live (sandbox, gemma-3-1b): -p start→answer→unload→stop in 1 s; two
221+ sessions share, the last stops; kill -9 of one, the next cleans the
222+ stale lease and stops the server at its exit.
223+ Not checked live: macOS, Windows (cross-compiled only), the Llama app on
224+ 9931 (handled as "a server mm did not start"), Ctrl-C during a download.
225+ Known limit (documented): a second session with ANOTHER model on a
226+ server mm started finds it missing until the server restarts.
227+ - id: 3
228+ author:
229+ name: k33g
230+ email: ph.charriere@gmail.com
231+ createdAt: 2026-11-24T17:52:58.000Z
232+ body: |
233+ Tested by the user; merged into `main` with tickets 223 and 257.
@@ -1,12 +1,12 @@
1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2 id: 2232 id: 223
3 title: "llamacpp: start llama-server when it is not running, stop it with the last mm session"3 title: "llamacpp: start llama-server when it is not running, stop it with the last mm session"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-18T07:13:12.000Z8 createdAt: 2026-11-18T07:13:12.000Z
9-updatedAt: 2026-11-20T07:29:52.000Z9+updatedAt: 2026-11-24T17:52:58.000Z
10 labels:10 labels:
11 - kind::feature11 - kind::feature
12 milestone: v2.0.112 milestone: v2.0.1
@@ -93,44 +93,54 @@ body: |
93 tasks:93 tasks:
94 - id: 194 - id: 1
95 title: Decide - opt-in key, server arguments (router mode, model, extra args), binary lookup95 title: Decide - opt-in key, server arguments (router mode, model, extra args), binary lookup
96- state: open96+ state: closed
97 priority: high97 priority: high
98 author:98 author:
99 name: k33g99 name: k33g
100 email: ph.charriere@gmail.com100 email: ph.charriere@gmail.com
101 createdAt: 2026-11-18T07:13:12.000Z101 createdAt: 2026-11-18T07:13:12.000Z
102+ updatedAt: 2026-11-24T17:14:24.000Z
103+ closedAt: 2026-11-24T17:14:24.000Z
102 - id: 2104 - id: 2
103 title: Start and wait - spawn llama-server detached, log file, readiness on /models with a timeout105 title: Start and wait - spawn llama-server detached, log file, readiness on /models with a timeout
104- state: open106+ state: closed
105 priority: high107 priority: high
106 author:108 author:
107 name: k33g109 name: k33g
108 email: ph.charriere@gmail.com110 email: ph.charriere@gmail.com
109 createdAt: 2026-11-18T07:13:12.000Z111 createdAt: 2026-11-18T07:13:12.000Z
112+ updatedAt: 2026-11-24T17:14:24.000Z
113+ closedAt: 2026-11-24T17:14:24.000Z
110 - id: 3114 - id: 3
111 title: Shared lifetime - registry + file lock, one lease per mm process, the last one stops the server; stale leases cleaned115 title: Shared lifetime - registry + file lock, one lease per mm process, the last one stops the server; stale leases cleaned
112- state: open116+ state: closed
113 priority: high117 priority: high
114 author:118 author:
115 name: k33g119 name: k33g
116 email: ph.charriere@gmail.com120 email: ph.charriere@gmail.com
117 createdAt: 2026-11-18T07:13:12.000Z121 createdAt: 2026-11-18T07:13:12.000Z
122+ updatedAt: 2026-11-24T17:14:24.000Z
123+ closedAt: 2026-11-24T17:14:24.000Z
118 - id: 4124 - id: 4
119 title: Never stop a server mm did not start (the user's, the Llama app's); no start for a remote baseUrl or in a container125 title: Never stop a server mm did not start (the user's, the Llama app's); no start for a remote baseUrl or in a container
120- state: open126+ state: closed
121 priority: medium127 priority: medium
122 author:128 author:
123 name: k33g129 name: k33g
124 email: ph.charriere@gmail.com130 email: ph.charriere@gmail.com
125 createdAt: 2026-11-18T07:13:12.000Z131 createdAt: 2026-11-18T07:13:12.000Z
132+ updatedAt: 2026-11-24T17:14:24.000Z
133+ closedAt: 2026-11-24T17:14:24.000Z
126 - id: 5134 - id: 5
127 title: Tests with a fake llama-server; docs EN+FR (run-with-llama-cpp, configuration)135 title: Tests with a fake llama-server; docs EN+FR (run-with-llama-cpp, configuration)
128- state: open136+ state: closed
129 priority: medium137 priority: medium
130 author:138 author:
131 name: k33g139 name: k33g
132 email: ph.charriere@gmail.com140 email: ph.charriere@gmail.com
133 createdAt: 2026-11-18T07:13:12.000Z141 createdAt: 2026-11-18T07:13:12.000Z
142+ updatedAt: 2026-11-24T17:14:24.000Z
143+ closedAt: 2026-11-24T17:14:24.000Z
134 comments:144 comments:
135 - id: 1145 - id: 1
136 author:146 author:
@@ -184,3 +194,40 @@ comments:
184 - Port 9931, the default since #218: a server the app started and a194 - Port 9931, the default since #218: a server the app started and a
185 server mm would start compete for it; mm must recognise a server195 server mm would start compete for it; mm must recognise a server
186 it did not start and leave it alone.196 it did not start and leave it alone.
197+ - id: 2
198+ author:
199+ name: k33g
200+ email: ph.charriere@gmail.com
201+ createdAt: 2026-11-24T17:14:24.000Z
202+ body: |
203+ Implemented on branch `feature/llamacpp-autostart` (not committed).
204+ Decisions (user, 2026-11-24): opt-in `llamacpp.autoStart` (mm init writes
205+ true for a local llamacpp agent); wait for the model at start-up;
206+ Windows included.
207+ Measured on llama.cpp build 12359 (Linux arm64, installed in the sandbox):
208+ router mode lists the HF cache + a `--models-preset`; a preset entry
209+ `hf-repo = org/repo:QUANT` is downloaded on first load; the cache is
210+ scanned once at start; `/models/load` is async, status `loading` →
211+ `loaded`, or `unloaded` + `failed: true` + `exit_code`; killing the
212+ router's pid alone leaves its model children running → stop the group.
213+ - `internal/llamastart`: registry `<cache>/mm/llama-server/<host>-<port>/`
214+ (server.json, leases/<pid>, lock, models.ini, llama-server.log),
215+ Acquire / Lease.Release; process group (unix) / taskkill /T (Windows).
216+ - `engine.LlamaStartAddress`: loopback only, no AGENT_BASE_URL, and no
217+ OTHER llamacpp address (8080, fallback) answering.
218+ - main: started before engine.New; released through the exit hook of
219+ #255 (after the unload); Ctrl-C/SIGTERM during the start stop it.
220+ Live (sandbox, gemma-3-1b): -p start→answer→unload→stop in 1 s; two
221+ sessions share, the last stops; kill -9 of one, the next cleans the
222+ stale lease and stops the server at its exit.
223+ Not checked live: macOS, Windows (cross-compiled only), the Llama app on
224+ 9931 (handled as "a server mm did not start"), Ctrl-C during a download.
225+ Known limit (documented): a second session with ANOTHER model on a
226+ server mm started finds it missing until the server restarts.
227+ - id: 3
228+ author:
229+ name: k33g
230+ email: ph.charriere@gmail.com
231+ createdAt: 2026-11-24T17:52:58.000Z
232+ body: |
233+ Tested by the user; merged into `main` with tickets 223 and 257.
added .tickets/issues/0257-llamacpp-declare-llama-server-launch-settings-in-the.yaml +167 -0
new file mode 100644
@@ -0,0 +1,167 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 257
3+title: "llamacpp: declare llama-server launch settings in the llamacpp section"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-24T17:26:42.000Z
9+updatedAt: 2026-11-24T17:52:58.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+milestone: v2.0.1
14+epic: Providers (LLM Engine)
15+related:
16+ - 223
17+body: |
18+ Follow-up of [#223 — llamacpp: start llama-server when it is not running](.tickets/issues/0223-llamacpp-start-llama-server-when-it-is-not-runnin.yaml)
19+ (branch `feature/llamacpp-autostart`, same branch for this one).
20+
21+ ## Asked (user, 2026-11-24)
22+ In the `llamacpp:` section, declare the settings llama-server is
23+ started with, instead of only a raw `serverArgs` list.
24+
25+ ## Today
26+ `llamacpp.serverArgs` appends raw arguments to the router's command line
27+ (`--host --port --models-preset <file>`). The preset file mm writes has
28+ one section, the agent's model, with only `hf-repo`. Settings that
29+ belong to the MODEL (context size, GPU layers, KV cache type…) go to the
30+ router's command line, where they apply to every model it loads — or are
31+ not passed on to the child at all (to check).
32+
33+ ## Proposal (to discuss)
34+ Named, validated keys, written by mm where llama-server reads them:
35+
36+ ```yaml
37+ llamacpp:
38+ autoStart: true
39+ server: # the router (command line)
40+ sleepIdleSeconds: 300 # --sleep-idle-seconds
41+ modelsMax: 0 # --models-max
42+ modelsMemoryMargin: 1024 # --models-memory-margin (MiB)
43+ model: # the agent's model (its models.ini section)
44+ ctxSize: 32768 # ctx-size / -c
45+ gpuLayers: 99 # n-gpu-layers / -ngl
46+ flashAttn: auto # flash-attn: on | off | auto
47+ cacheTypeK: q8_0 # cache-type-k
48+ cacheTypeV: q8_0 # cache-type-v
49+ threads: 8 # threads / -t
50+ parallel: 1 # parallel / -np
51+ serverArgs: [--spec-default] # still there: anything not listed above
52+ ```
53+
54+ - Check against `llama-server --help` (build 12359 has `-c`, `-ngl`,
55+ `-fa on|off|auto`, `-ctk/-ctv`, `-t`, `--models-max`,
56+ `--models-memory-margin`, `--sleep-idle-seconds`) and measure which
57+ keys a models.ini section accepts (long names without `--`?).
58+ - Naming: the existing `server:` key is the executable path — rename it
59+ (`binary:`/`executable:`) or nest differently; decide before release
60+ (v2.0.1 not shipped yet, no compatibility to keep).
61+ - `contextWindow` vs `ctxSize`: when mm starts the server, one should
62+ feed the other (the window mm counts with = the one it asked for).
63+ - An unknown key or a bad value: config error at load, not a server that
64+ fails to start.
65+ - Keep `mm init`: write the `model:` block from the machine row
66+ (ctx size, GPU layers) with its reasons, like the other settings.
67+
68+ ## Acceptance criteria
69+ - The declared settings reach llama-server (checked live: `/props` of the
70+ loaded model shows the ctx size; the router's `/models` args show them).
71+ - Validation errors name the key; unknown keys refused.
72+ - Unit tests (command line + models.ini content); docs EN+FR
73+ (configuration, run-with-llama-cpp).
74+tasks:
75+ - id: 1
76+ title: Measure which settings a models.ini section accepts and which belong to the router's command line
77+ state: closed
78+ priority: high
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-11-24T17:26:42.000Z
83+ updatedAt: 2026-11-24T17:41:22.000Z
84+ closedAt: 2026-11-24T17:41:22.000Z
85+ - id: 2
86+ title: Decide the keys and names (server path key, router vs model settings, contextWindow link)
87+ state: closed
88+ priority: high
89+ author:
90+ name: k33g
91+ email: ph.charriere@gmail.com
92+ createdAt: 2026-11-24T17:26:42.000Z
93+ updatedAt: 2026-11-24T17:41:22.000Z
94+ closedAt: 2026-11-24T17:41:22.000Z
95+ - id: 3
96+ title: Config struct + validation; write the command line and the models.ini section
97+ state: closed
98+ priority: none
99+ author:
100+ name: k33g
101+ email: ph.charriere@gmail.com
102+ createdAt: 2026-11-24T17:26:42.000Z
103+ updatedAt: 2026-11-24T17:41:22.000Z
104+ closedAt: 2026-11-24T17:41:22.000Z
105+ - id: 4
106+ title: mm init writes the model settings from the machine row
107+ state: closed
108+ priority: low
109+ author:
110+ name: k33g
111+ email: ph.charriere@gmail.com
112+ createdAt: 2026-11-24T17:26:42.000Z
113+ updatedAt: 2026-11-24T17:45:25.000Z
114+ closedAt: 2026-11-24T17:45:25.000Z
115+ - id: 5
116+ title: Tests, live check, docs EN+FR
117+ state: closed
118+ priority: none
119+ author:
120+ name: k33g
121+ email: ph.charriere@gmail.com
122+ createdAt: 2026-11-24T17:26:42.000Z
123+ updatedAt: 2026-11-24T17:41:22.000Z
124+ closedAt: 2026-11-24T17:41:22.000Z
125+comments:
126+ - id: 1
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-24T17:41:22.000Z
131+ body: |
132+ User (2026-11-24): as simple as possible — a key left out takes the
133+ default; the set to cover is the Llama app's launch line.
134+ Measured (build 12359): the router hands its model flags on to the
135+ model it loads (`--ctx-size`, `--fit-target`, `--sleep-idle-seconds`,
136+ `--spec-default` appear in the child's args; `/props` n_ctx follows),
137+ so everything goes on the router's command line — no models.ini change,
138+ no nesting, the `server:` key (executable path) keeps its name.
139+ Implemented on `feature/llamacpp-autostart`: flat optional keys
140+ `ctxSize, modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds,
141+ specDefault` (`LlamaCppConfig.LaunchArgs`, then `serverArgs`);
142+ validation (>= 0, `sleepIdleSeconds` >= -1) names the key.
143+ Live: the router and the model got the flags, banner `ctx: 4096 (/props)`.
144+ Not done (simplest): mm init does not write these keys; the Llama app's
145+ environment variables (GGML_METAL_NO_RESIDENCY, HF_HUB_CACHE,
146+ LLAMA_CACHE) are not settable — llama.cpp's defaults apply.
147+ - id: 2
148+ author:
149+ name: k33g
150+ email: ph.charriere@gmail.com
151+ createdAt: 2026-11-24T17:45:25.000Z
152+ body: |
153+ Task 4 done differently, at the user's request: mm init ASKS (llamacpp
154+ on this machine) "Let mm start llama-server…?" (`--autostart`, default
155+ yes → `autoStart: true|false`) and, when yes, "Write llama-server's
156+ launch settings?" (`--launch-settings`, default no → the Llama app's
157+ values, ctxSize and serverArgs commented). Line mode, window and
158+ mm acp-create share the Flow (acp deps: autostart←provider,endpoint;
159+ launch←autostart). Docs EN+FR: cli.md flags, create-an-agent.md,
160+ run-with-llama-cpp.md, configuration.md.
161+ - id: 3
162+ author:
163+ name: k33g
164+ email: ph.charriere@gmail.com
165+ createdAt: 2026-11-24T17:52:58.000Z
166+ body: |
167+ Tested by the user; merged into `main` with tickets 223 and 257.
new file mode 100644
@@ -0,0 +1,167 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 257
3+title: "llamacpp: declare llama-server launch settings in the llamacpp section"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-24T17:26:42.000Z
9+updatedAt: 2026-11-24T17:52:58.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+milestone: v2.0.1
14+epic: Providers (LLM Engine)
15+related:
16+ - 223
17+body: |
18+ Follow-up of [#223 — llamacpp: start llama-server when it is not running](.tickets/issues/0223-llamacpp-start-llama-server-when-it-is-not-runnin.yaml)
19+ (branch `feature/llamacpp-autostart`, same branch for this one).
20+
21+ ## Asked (user, 2026-11-24)
22+ In the `llamacpp:` section, declare the settings llama-server is
23+ started with, instead of only a raw `serverArgs` list.
24+
25+ ## Today
26+ `llamacpp.serverArgs` appends raw arguments to the router's command line
27+ (`--host --port --models-preset <file>`). The preset file mm writes has
28+ one section, the agent's model, with only `hf-repo`. Settings that
29+ belong to the MODEL (context size, GPU layers, KV cache type…) go to the
30+ router's command line, where they apply to every model it loads — or are
31+ not passed on to the child at all (to check).
32+
33+ ## Proposal (to discuss)
34+ Named, validated keys, written by mm where llama-server reads them:
35+
36+ ```yaml
37+ llamacpp:
38+ autoStart: true
39+ server: # the router (command line)
40+ sleepIdleSeconds: 300 # --sleep-idle-seconds
41+ modelsMax: 0 # --models-max
42+ modelsMemoryMargin: 1024 # --models-memory-margin (MiB)
43+ model: # the agent's model (its models.ini section)
44+ ctxSize: 32768 # ctx-size / -c
45+ gpuLayers: 99 # n-gpu-layers / -ngl
46+ flashAttn: auto # flash-attn: on | off | auto
47+ cacheTypeK: q8_0 # cache-type-k
48+ cacheTypeV: q8_0 # cache-type-v
49+ threads: 8 # threads / -t
50+ parallel: 1 # parallel / -np
51+ serverArgs: [--spec-default] # still there: anything not listed above
52+ ```
53+
54+ - Check against `llama-server --help` (build 12359 has `-c`, `-ngl`,
55+ `-fa on|off|auto`, `-ctk/-ctv`, `-t`, `--models-max`,
56+ `--models-memory-margin`, `--sleep-idle-seconds`) and measure which
57+ keys a models.ini section accepts (long names without `--`?).
58+ - Naming: the existing `server:` key is the executable path — rename it
59+ (`binary:`/`executable:`) or nest differently; decide before release
60+ (v2.0.1 not shipped yet, no compatibility to keep).
61+ - `contextWindow` vs `ctxSize`: when mm starts the server, one should
62+ feed the other (the window mm counts with = the one it asked for).
63+ - An unknown key or a bad value: config error at load, not a server that
64+ fails to start.
65+ - Keep `mm init`: write the `model:` block from the machine row
66+ (ctx size, GPU layers) with its reasons, like the other settings.
67+
68+ ## Acceptance criteria
69+ - The declared settings reach llama-server (checked live: `/props` of the
70+ loaded model shows the ctx size; the router's `/models` args show them).
71+ - Validation errors name the key; unknown keys refused.
72+ - Unit tests (command line + models.ini content); docs EN+FR
73+ (configuration, run-with-llama-cpp).
74+tasks:
75+ - id: 1
76+ title: Measure which settings a models.ini section accepts and which belong to the router's command line
77+ state: closed
78+ priority: high
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-11-24T17:26:42.000Z
83+ updatedAt: 2026-11-24T17:41:22.000Z
84+ closedAt: 2026-11-24T17:41:22.000Z
85+ - id: 2
86+ title: Decide the keys and names (server path key, router vs model settings, contextWindow link)
87+ state: closed
88+ priority: high
89+ author:
90+ name: k33g
91+ email: ph.charriere@gmail.com
92+ createdAt: 2026-11-24T17:26:42.000Z
93+ updatedAt: 2026-11-24T17:41:22.000Z
94+ closedAt: 2026-11-24T17:41:22.000Z
95+ - id: 3
96+ title: Config struct + validation; write the command line and the models.ini section
97+ state: closed
98+ priority: none
99+ author:
100+ name: k33g
101+ email: ph.charriere@gmail.com
102+ createdAt: 2026-11-24T17:26:42.000Z
103+ updatedAt: 2026-11-24T17:41:22.000Z
104+ closedAt: 2026-11-24T17:41:22.000Z
105+ - id: 4
106+ title: mm init writes the model settings from the machine row
107+ state: closed
108+ priority: low
109+ author:
110+ name: k33g
111+ email: ph.charriere@gmail.com
112+ createdAt: 2026-11-24T17:26:42.000Z
113+ updatedAt: 2026-11-24T17:45:25.000Z
114+ closedAt: 2026-11-24T17:45:25.000Z
115+ - id: 5
116+ title: Tests, live check, docs EN+FR
117+ state: closed
118+ priority: none
119+ author:
120+ name: k33g
121+ email: ph.charriere@gmail.com
122+ createdAt: 2026-11-24T17:26:42.000Z
123+ updatedAt: 2026-11-24T17:41:22.000Z
124+ closedAt: 2026-11-24T17:41:22.000Z
125+comments:
126+ - id: 1
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-24T17:41:22.000Z
131+ body: |
132+ User (2026-11-24): as simple as possible — a key left out takes the
133+ default; the set to cover is the Llama app's launch line.
134+ Measured (build 12359): the router hands its model flags on to the
135+ model it loads (`--ctx-size`, `--fit-target`, `--sleep-idle-seconds`,
136+ `--spec-default` appear in the child's args; `/props` n_ctx follows),
137+ so everything goes on the router's command line — no models.ini change,
138+ no nesting, the `server:` key (executable path) keeps its name.
139+ Implemented on `feature/llamacpp-autostart`: flat optional keys
140+ `ctxSize, modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds,
141+ specDefault` (`LlamaCppConfig.LaunchArgs`, then `serverArgs`);
142+ validation (>= 0, `sleepIdleSeconds` >= -1) names the key.
143+ Live: the router and the model got the flags, banner `ctx: 4096 (/props)`.
144+ Not done (simplest): mm init does not write these keys; the Llama app's
145+ environment variables (GGML_METAL_NO_RESIDENCY, HF_HUB_CACHE,
146+ LLAMA_CACHE) are not settable — llama.cpp's defaults apply.
147+ - id: 2
148+ author:
149+ name: k33g
150+ email: ph.charriere@gmail.com
151+ createdAt: 2026-11-24T17:45:25.000Z
152+ body: |
153+ Task 4 done differently, at the user's request: mm init ASKS (llamacpp
154+ on this machine) "Let mm start llama-server…?" (`--autostart`, default
155+ yes → `autoStart: true|false`) and, when yes, "Write llama-server's
156+ launch settings?" (`--launch-settings`, default no → the Llama app's
157+ values, ctxSize and serverArgs commented). Line mode, window and
158+ mm acp-create share the Flow (acp deps: autostart←provider,endpoint;
159+ launch←autostart). Docs EN+FR: cli.md flags, create-an-agent.md,
160+ run-with-llama-cpp.md, configuration.md.
161+ - id: 3
162+ author:
163+ name: k33g
164+ email: ph.charriere@gmail.com
165+ createdAt: 2026-11-24T17:52:58.000Z
166+ body: |
167+ Tested by the user; merged into `main` with tickets 223 and 257.
modified docs/en/how-to/create-an-agent.md +1 -0
@@ -81,6 +81,7 @@ This guide shows how to write a new agent.yaml for a model and a job, with mm's
8181 - **See the file without writing it.** `-o -` prints it on stdout. Nothing is created, not even the `.mm` or skills folder.
8282 - **Everything in a `.mm` folder.** Answer `yes` to the first question, or give `--project yes`: mm creates `.mm/` and writes `.mm/agent.yaml`, its paths written from the project root. Started from that root, `mm` and `mm tui` find it with no argument. See [How to keep a project's mini-me files in a `.mm` folder](keep-the-config-in-a-mm-folder.md).
8383 - **Sessions and skills.** `--sessions yes` writes a `sessions` section, so every conversation is saved and `/resume` can reopen it. `--skills yes` writes `skillsDir` and creates the folder (`skills/`, or `.mm/skills/` with `--project yes`); add your skills there (see [How to add a skill](add-a-skill.md)).
84+- **llama-server started by mm.** For `llamacpp` on this machine, mm init asks whether mm may start llama-server when it is not running (`--autostart`, default yes), then whether to write its launch settings with the Llama app's values (`--launch-settings`, default no). See [Let mm start llama-server](run-with-llama-cpp.md#let-mm-start-llama-server).
8485 - **An OpenAI-compatible service (OpenAI, Cerebras, Hugging Face…).** Choose `openai`: two more questions follow, the endpoint (`https://api.openai.com/v1` by default) and the name of the variable that holds the API key (`OPENAI_API_KEY` by default, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Export the key before running `mm init`: with it, the model question lists the service's models; without it, you type the model's ID (the question says the variable is not set). Flags: `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. The file gets `baseUrl` and `apiKeyEnv`, and a commented `reasoning_effort: none` in `sampling`, to uncomment if the API answers "Function tools with reasoning_effort are not supported". For an OpenAI reasoning model that must keep reasoning while it calls tools, choose `openai-responses` instead: the same questions, and the file talks to the Responses API (see [How to keep reasoning and tools together with OpenAI's Responses API](use-the-openai-responses-api.md)).
8586 - **A server elsewhere.** `--base-url http://192.168.1.20:17434/v1`; it is written into the file as `baseUrl`. Without it, the file has no `baseUrl` and records the provider's default address and fallback as comments, ready to uncomment.
8687 - **A server that does not answer.** mm says so and asks for the model's name: the settings then come from the family table only.
@@ -81,6 +81,7 @@ This guide shows how to write a new agent.yaml for a model and a job, with mm's
81 - **See the file without writing it.** `-o -` prints it on stdout. Nothing is created, not even the `.mm` or skills folder.81 - **See the file without writing it.** `-o -` prints it on stdout. Nothing is created, not even the `.mm` or skills folder.
82 - **Everything in a `.mm` folder.** Answer `yes` to the first question, or give `--project yes`: mm creates `.mm/` and writes `.mm/agent.yaml`, its paths written from the project root. Started from that root, `mm` and `mm tui` find it with no argument. See [How to keep a project's mini-me files in a `.mm` folder](keep-the-config-in-a-mm-folder.md).82 - **Everything in a `.mm` folder.** Answer `yes` to the first question, or give `--project yes`: mm creates `.mm/` and writes `.mm/agent.yaml`, its paths written from the project root. Started from that root, `mm` and `mm tui` find it with no argument. See [How to keep a project's mini-me files in a `.mm` folder](keep-the-config-in-a-mm-folder.md).
83 - **Sessions and skills.** `--sessions yes` writes a `sessions` section, so every conversation is saved and `/resume` can reopen it. `--skills yes` writes `skillsDir` and creates the folder (`skills/`, or `.mm/skills/` with `--project yes`); add your skills there (see [How to add a skill](add-a-skill.md)).83 - **Sessions and skills.** `--sessions yes` writes a `sessions` section, so every conversation is saved and `/resume` can reopen it. `--skills yes` writes `skillsDir` and creates the folder (`skills/`, or `.mm/skills/` with `--project yes`); add your skills there (see [How to add a skill](add-a-skill.md)).
84+- **llama-server started by mm.** For `llamacpp` on this machine, mm init asks whether mm may start llama-server when it is not running (`--autostart`, default yes), then whether to write its launch settings with the Llama app's values (`--launch-settings`, default no). See [Let mm start llama-server](run-with-llama-cpp.md#let-mm-start-llama-server).
84 - **An OpenAI-compatible service (OpenAI, Cerebras, Hugging Face…).** Choose `openai`: two more questions follow, the endpoint (`https://api.openai.com/v1` by default) and the name of the variable that holds the API key (`OPENAI_API_KEY` by default, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Export the key before running `mm init`: with it, the model question lists the service's models; without it, you type the model's ID (the question says the variable is not set). Flags: `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. The file gets `baseUrl` and `apiKeyEnv`, and a commented `reasoning_effort: none` in `sampling`, to uncomment if the API answers "Function tools with reasoning_effort are not supported". For an OpenAI reasoning model that must keep reasoning while it calls tools, choose `openai-responses` instead: the same questions, and the file talks to the Responses API (see [How to keep reasoning and tools together with OpenAI's Responses API](use-the-openai-responses-api.md)).85 - **An OpenAI-compatible service (OpenAI, Cerebras, Hugging Face…).** Choose `openai`: two more questions follow, the endpoint (`https://api.openai.com/v1` by default) and the name of the variable that holds the API key (`OPENAI_API_KEY` by default, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Export the key before running `mm init`: with it, the model question lists the service's models; without it, you type the model's ID (the question says the variable is not set). Flags: `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. The file gets `baseUrl` and `apiKeyEnv`, and a commented `reasoning_effort: none` in `sampling`, to uncomment if the API answers "Function tools with reasoning_effort are not supported". For an OpenAI reasoning model that must keep reasoning while it calls tools, choose `openai-responses` instead: the same questions, and the file talks to the Responses API (see [How to keep reasoning and tools together with OpenAI's Responses API](use-the-openai-responses-api.md)).
85 - **A server elsewhere.** `--base-url http://192.168.1.20:17434/v1`; it is written into the file as `baseUrl`. Without it, the file has no `baseUrl` and records the provider's default address and fallback as comments, ready to uncomment.86 - **A server elsewhere.** `--base-url http://192.168.1.20:17434/v1`; it is written into the file as `baseUrl`. Without it, the file has no `baseUrl` and records the provider's default address and fallback as comments, ready to uncomment.
86 - **A server that does not answer.** mm says so and asks for the model's name: the settings then come from the family table only.87 - **A server that does not answer.** mm says so and asks for the model's name: the settings then come from the family table only.
modified docs/en/how-to/run-with-llama-cpp.md +42 -0
@@ -22,6 +22,48 @@ This guide shows how to point `mm` at a `llama-server` you start yourself. It as
2222
2323 3. Check the banner. `provider: llamacpp` confirms the provider, and `ctx: 32768 (/props)` confirms the agent read the served context size from the server's `/props` endpoint.
2424
25+## Let mm start llama-server
26+
27+Instead of step 1, mm can start the server itself when nothing answers — and stop it when you quit:
28+
29+```yaml
30+provider: llamacpp
31+model: "ggml-org/gemma-3-1b-it-GGUF:Q4_K_M" # a Hugging Face repo:quant
32+llamacpp:
33+ autoStart: true
34+```
35+
36+```text
37+$ mm
38+🦙 starting llama-server on 127.0.0.1:9931 (pid 74312, log ~/.cache/mm/llama-server/127.0.0.1-9931/llama-server.log)
39+🦙 ggml-org/gemma-3-1b-it-GGUF:Q4_K_M loaded
40+…
41+> /quit
42+🧹 unloaded ggml-org/gemma-3-1b-it-GGUF:Q4_K_M
43+🦙 stopped llama-server (pid 74312)
44+```
45+
46+- **When.** Only when the agent's address is on this machine (no `baseUrl`, or `127.0.0.1` / `localhost`), `AGENT_BASE_URL` is not set, and nothing answers there, nor on `8080`, nor at the `fallback` (the host's server, seen from a container). A server already running — yours, the Llama app's — is used as before, and never stopped.
47+- **How.** `llama-server --host 127.0.0.1 --port <the agent's port> --models-preset <file>` in router mode (or `llama serve …` when only the `llama` command is installed). The preset file names the agent's model, so a model missing from the Hugging Face cache is downloaded on its first load. mm waits until the model is loaded (spinner, up to `startTimeout`, 15 minutes by default) — a large download does not hit the first question's timeout. The server's output goes to the log file named on the first line.
48+- **Several sessions.** A second mm on the same address shares the server (`🦙 llama-server already started by mm …`). Quitting keeps it while another session uses it (`kept running: 1 other mm session(s) use it`); the last one stops it. A session that crashed leaves a lease the next mm removes.
49+- **Launch settings.** Each optional key is one llama-server flag; a key left out is not passed, llama-server keeps its default. The router hands the model settings on to the model it loads (the banner then shows `ctx: 32768 (/props)`). The values the Llama app starts its server with:
50+
51+ ```yaml
52+ llamacpp:
53+ autoStart: true
54+ ctxSize: 32768 # --ctx-size (default: the model's own)
55+ modelsMax: 0 # --models-max: 0 = no limit (default 4)
56+ modelsMemoryMargin: 1024 # --models-memory-margin, MiB kept free (default 0 = off)
57+ fitTarget: 1024 # --fit-target, MiB per device (default 1024)
58+ sleepIdleSeconds: 300 # --sleep-idle-seconds: free the model when idle (default -1 = never)
59+ specDefault: true # --spec-default: default speculative decoding
60+ serverArgs: [--no-webui] # any other flag, after the ones above
61+ ```
62+
63+ A negative value is a configuration error naming the key (`-1` is allowed for `sleepIdleSeconds`).
64+- **Other settings.** `server:` the executable's path when it is not on the `PATH`; `startTimeout:`. `mm init` asks, for a llamacpp agent on this machine, whether mm may start the server (default yes) and whether to write the launch settings below (default no).
65+- **Limits.** The server lists the models it knew when it started: a second session with another model finds it missing (a warning) until the sessions using the server have quit. Ctrl-C or SIGTERM during the start stops it.
66+
2567 ## Variants
2668
2769 - **llama-server on 8080.** An older build, the official Docker image or a server started with `--port 8080`: nothing to set. When `baseUrl` is llama-server's default (`http://127.0.0.1:9931/v1`, or no `baseUrl` at all) and does not answer, mm tries `http://127.0.0.1:8080/v1` before the container address. `mm init` and `mm acp-create` list the models from whichever answers.
@@ -22,6 +22,48 @@ This guide shows how to point `mm` at a `llama-server` you start yourself. It as
22 22
23 3. Check the banner. `provider: llamacpp` confirms the provider, and `ctx: 32768 (/props)` confirms the agent read the served context size from the server's `/props` endpoint.23 3. Check the banner. `provider: llamacpp` confirms the provider, and `ctx: 32768 (/props)` confirms the agent read the served context size from the server's `/props` endpoint.
24 24
25+## Let mm start llama-server
26+
27+Instead of step 1, mm can start the server itself when nothing answers — and stop it when you quit:
28+
29+```yaml
30+provider: llamacpp
31+model: "ggml-org/gemma-3-1b-it-GGUF:Q4_K_M" # a Hugging Face repo:quant
32+llamacpp:
33+ autoStart: true
34+```
35+
36+```text
37+$ mm
38+🦙 starting llama-server on 127.0.0.1:9931 (pid 74312, log ~/.cache/mm/llama-server/127.0.0.1-9931/llama-server.log)
39+🦙 ggml-org/gemma-3-1b-it-GGUF:Q4_K_M loaded
40+…
41+> /quit
42+🧹 unloaded ggml-org/gemma-3-1b-it-GGUF:Q4_K_M
43+🦙 stopped llama-server (pid 74312)
44+```
45+
46+- **When.** Only when the agent's address is on this machine (no `baseUrl`, or `127.0.0.1` / `localhost`), `AGENT_BASE_URL` is not set, and nothing answers there, nor on `8080`, nor at the `fallback` (the host's server, seen from a container). A server already running — yours, the Llama app's — is used as before, and never stopped.
47+- **How.** `llama-server --host 127.0.0.1 --port <the agent's port> --models-preset <file>` in router mode (or `llama serve …` when only the `llama` command is installed). The preset file names the agent's model, so a model missing from the Hugging Face cache is downloaded on its first load. mm waits until the model is loaded (spinner, up to `startTimeout`, 15 minutes by default) — a large download does not hit the first question's timeout. The server's output goes to the log file named on the first line.
48+- **Several sessions.** A second mm on the same address shares the server (`🦙 llama-server already started by mm …`). Quitting keeps it while another session uses it (`kept running: 1 other mm session(s) use it`); the last one stops it. A session that crashed leaves a lease the next mm removes.
49+- **Launch settings.** Each optional key is one llama-server flag; a key left out is not passed, llama-server keeps its default. The router hands the model settings on to the model it loads (the banner then shows `ctx: 32768 (/props)`). The values the Llama app starts its server with:
50+
51+ ```yaml
52+ llamacpp:
53+ autoStart: true
54+ ctxSize: 32768 # --ctx-size (default: the model's own)
55+ modelsMax: 0 # --models-max: 0 = no limit (default 4)
56+ modelsMemoryMargin: 1024 # --models-memory-margin, MiB kept free (default 0 = off)
57+ fitTarget: 1024 # --fit-target, MiB per device (default 1024)
58+ sleepIdleSeconds: 300 # --sleep-idle-seconds: free the model when idle (default -1 = never)
59+ specDefault: true # --spec-default: default speculative decoding
60+ serverArgs: [--no-webui] # any other flag, after the ones above
61+ ```
62+
63+ A negative value is a configuration error naming the key (`-1` is allowed for `sleepIdleSeconds`).
64+- **Other settings.** `server:` the executable's path when it is not on the `PATH`; `startTimeout:`. `mm init` asks, for a llamacpp agent on this machine, whether mm may start the server (default yes) and whether to write the launch settings below (default no).
65+- **Limits.** The server lists the models it knew when it started: a second session with another model finds it missing (a warning) until the sessions using the server have quit. Ctrl-C or SIGTERM during the start stops it.
66+
25 ## Variants67 ## Variants
26 68
27 - **llama-server on 8080.** An older build, the official Docker image or a server started with `--port 8080`: nothing to set. When `baseUrl` is llama-server's default (`http://127.0.0.1:9931/v1`, or no `baseUrl` at all) and does not answer, mm tries `http://127.0.0.1:8080/v1` before the container address. `mm init` and `mm acp-create` list the models from whichever answers.69 - **llama-server on 8080.** An older build, the official Docker image or a server started with `--port 8080`: nothing to set. When `baseUrl` is llama-server's default (`http://127.0.0.1:9931/v1`, or no `baseUrl` at all) and does not answer, mm tries `http://127.0.0.1:8080/v1` before the container address. `mm init` and `mm acp-create` list the models from whichever answers.
modified docs/en/reference/cli.md +2 -0
@@ -258,6 +258,8 @@ An agent file outside the workspace only gives a warning: see [when the agent fi
258258 | `--yolo yes\|no` | Ask before each command or file change? — only for usages with `bash`, file tools or `fetch_content` | the usage's |
259259 | `--sessions yes\|no` | Save the conversations? | `no`; `yes`: a `sessions` section (`enabled: true`, `dir: .mm/sessions`); `no`: no section, mm's default (off) applies |
260260 | `--skills yes\|no` | Use skills? | `no` (`skillsDir: no-skills`); `yes`: `skillsDir: skills`, or `.mm/skills` with `--project yes`, and the folder is created next to the project root once the file is written |
261+| `--autostart yes\|no` | Let mm start llama-server when it is not running? (llamacpp on this machine only) | `yes` (`llamacpp.autoStart: true`); `no`: `autoStart: false`, you start the server |
262+| `--launch-settings yes\|no` | Write llama-server's launch settings? (with `--autostart yes` only) | `no` (llama-server's defaults); `yes`: the Llama app's values — `modelsMax: 0`, `modelsMemoryMargin: 1024`, `fitTarget: 1024`, `sleepIdleSeconds: 300`, `specDefault: true` |
261263 | `--name` | Agent name (`acp.name`) | the usage's name |
262264 | `-o`, `--output` | File to write (`-` = stdout: nothing is created, whatever the other answers). With `--project yes`, a file that is not directly in a `.mm` folder is refused | `agent.yaml`; `.mm/agent.yaml` with `--project yes` |
263265 | `--check` | — | off; on: after writing, runs this mm with `-config <file> -p "Say hello in one line."` and reports whether the model answered (5 min at most) |
@@ -258,6 +258,8 @@ An agent file outside the workspace only gives a warning: see [when the agent fi
258 | `--yolo yes\|no` | Ask before each command or file change? — only for usages with `bash`, file tools or `fetch_content` | the usage's |258 | `--yolo yes\|no` | Ask before each command or file change? — only for usages with `bash`, file tools or `fetch_content` | the usage's |
259 | `--sessions yes\|no` | Save the conversations? | `no`; `yes`: a `sessions` section (`enabled: true`, `dir: .mm/sessions`); `no`: no section, mm's default (off) applies |259 | `--sessions yes\|no` | Save the conversations? | `no`; `yes`: a `sessions` section (`enabled: true`, `dir: .mm/sessions`); `no`: no section, mm's default (off) applies |
260 | `--skills yes\|no` | Use skills? | `no` (`skillsDir: no-skills`); `yes`: `skillsDir: skills`, or `.mm/skills` with `--project yes`, and the folder is created next to the project root once the file is written |260 | `--skills yes\|no` | Use skills? | `no` (`skillsDir: no-skills`); `yes`: `skillsDir: skills`, or `.mm/skills` with `--project yes`, and the folder is created next to the project root once the file is written |
261+| `--autostart yes\|no` | Let mm start llama-server when it is not running? (llamacpp on this machine only) | `yes` (`llamacpp.autoStart: true`); `no`: `autoStart: false`, you start the server |
262+| `--launch-settings yes\|no` | Write llama-server's launch settings? (with `--autostart yes` only) | `no` (llama-server's defaults); `yes`: the Llama app's values — `modelsMax: 0`, `modelsMemoryMargin: 1024`, `fitTarget: 1024`, `sleepIdleSeconds: 300`, `specDefault: true` |
261 | `--name` | Agent name (`acp.name`) | the usage's name |263 | `--name` | Agent name (`acp.name`) | the usage's name |
262 | `-o`, `--output` | File to write (`-` = stdout: nothing is created, whatever the other answers). With `--project yes`, a file that is not directly in a `.mm` folder is refused | `agent.yaml`; `.mm/agent.yaml` with `--project yes` |264 | `-o`, `--output` | File to write (`-` = stdout: nothing is created, whatever the other answers). With `--project yes`, a file that is not directly in a `.mm` folder is refused | `agent.yaml`; `.mm/agent.yaml` with `--project yes` |
263 | `--check` | — | off; on: after writing, runs this mm with `-config <file> -p "Say hello in one line."` and reports whether the model answered (5 min at most) |265 | `--check` | — | off; on: after writing, runs this mm with `-config <file> -p "Say hello in one line."` and reports whether the model answered (5 min at most) |
modified docs/en/reference/configuration.md +1 -0
@@ -37,6 +37,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
3737 | `saveAnswerTool` | bool | `false` | Declare `save_answer`, which writes an answer the model already gave to a new file: the model sends a file name, not the text again. Off by default. The `/save` command exists either way. See [tools](tools.md#save_answer). |
3838 | `unloadModels` | bool | `true` | The `/unload [model]` command (terminal, window, editor) and the `unload_model` tool, which free a model from the server's memory: llmman and Ollama, Kronk, llama-server in router mode. `false` removes both. The tool is never declared beside a `structuredOutput` or a `decision` block. See [tools](tools.md#unload_model) and [How to free a model's memory](../how-to/unload-a-model.md). |
3939 | `unloadOnExit` | bool | `true` | When mm exits — `/quit`, Ctrl-C at the prompt, Ctrl-D, the window closed, the end of a `-p` run, the editor closing the ACP session, SIGTERM, SIGHUP — unload the agent's model from the server's memory, so it does not keep its RAM after the session. One `🧹` line on stderr (none in ACP mode); nothing when the model was not loaded or the server cannot unload (dmr, openai, a single-model llama-server). Bounded to 3 s: a server that does not answer never holds the exit. Only the agent's own model — not the decision models, not the `mmConfigs` agents (each unloads its own when it stops). `false`: the model stays loaded (faster next start, or another session or tool uses it — mm does not know who else uses it). Independent of `unloadModels`. Overridden by `AGENT_UNLOAD_ON_EXIT`. See [How to free a model's memory](../how-to/unload-a-model.md#when-mm-exits). |
40+| `llamacpp` | `{autoStart, server, ctxSize, modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault, serverArgs, startTimeout}` | `autoStart: false` | Provider `llamacpp` only. `autoStart: true`: when nothing answers at the agent's address (a loopback one, `AGENT_BASE_URL` unset) nor on 8080 nor at the `fallback`, mm starts llama-server in router mode with the agent's model (downloaded on first load), waits until it is loaded, and stops it with the last mm session using it; a server mm did not start is never stopped. `server`: the executable (default `llama-server`, then `llama serve`, on the `PATH`). Launch settings, each one optional, each one a llama-server flag (absent = llama-server's default): `ctxSize` (`--ctx-size`), `modelsMax` (`--models-max`), `modelsMemoryMargin` (`--models-memory-margin`), `fitTarget` (`--fit-target`), `sleepIdleSeconds` (`--sleep-idle-seconds`, `-1` allowed), `specDefault` (`--spec-default`); a negative value is a configuration error. `serverArgs`: any other flag, added last. `startTimeout` (default `15m`): start, download and load. Registry and log: `<user cache dir>/mm/llama-server/<host>-<port>/`. `mm init` asks for a llamacpp agent on this machine (`--autostart`, default yes; `--launch-settings`, the Llama app's values, default no). See [Let mm start llama-server](../how-to/run-with-llama-cpp.md#let-mm-start-llama-server). |
4041 | `autoPull` | bool | `false` | At start-up, download the models this agent will use and the server does not list: its own, its `mmConfigs` agents', its `skillRouting` / `toolRouting` deciders'. The progress goes to stderr — one line rewritten in place on a terminal (`⬇ pulling <model> — 52 MB / 145 MB (35 %)`), a line per tenth elsewhere — then `⬇ pulled <model> in 0.8s`. The agent's own model failing stops `mm` with the server's message (`[engine error: autoPull: <model>: the server says: …]`); another model failing, a server that does not answer, or a provider that cannot pull is a `[warning: autoPull: …]`. An agent started by `/ask` or `ask_agent` pulls nothing; `mm --ask` pulls nothing either. A model the server already lists is never pulled (a name without a tag also matches its `:latest` entry). By provider: `llmman` and `ollama` — `POST /api/pull`; `kronk` — `POST /v1/kronk/models/pull`, the pull counting as done only when Kronk's stream ends with `"downloaded": true` (Kronk answers 200 to a failed pull; its last status is then the message); `dmr` — `POST /models/create` on the runner (the base URL without `/engines/…`), the pull counting as done once the runner lists the model; `llamacpp` — no download over the API: the warning says to start llama-server with `-hf <repo>:<quant>`, or to put the GGUF in the router's models directory; `openai` — a warning. |
4142 | `sampling` | map | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Generation settings, OpenAI API key names, passed to the server. The file's block is merged with these defaults: a default the file does not name is still sent. **Except with `provider: openai` and `provider: openai-responses`**: the request carries exactly the file's block, nothing added (no block: no sampling key, the server's defaults apply) — the hosted OpenAI reasoning models refuse `max_tokens` and accept only the default temperature, so a default left in would be a 400. A key the OpenAI API does not declare is sent as it is, at the top level of the request — for example `chat_template_kwargs: {enable_thinking: false}`, which tells a llama.cpp server (`dmr`, `llamacpp`, `llmman`) or Kronk not to reason; `reasoning_effort: none` does the same on Ollama. `messages`, `tools`, `tool_choice` (and the legacy `functions`, `function_call`) are ignored: Genkit builds them from the conversation. The shipped `agent.yaml` adds `parallel_tool_calls: false`. `max_tokens` also bounds one tool call: a `write_file` of a long document (or a thinking model's reasoning plus the call) can hit it, and the call is then cut off. mm hands it back to the model twice, asking for smaller pieces, then stops with `the model hit max_tokens (N) while writing a tool call`; raise the value if that happens. A config that names the limit `max_completion_tokens` (the OpenAI API's name for its newer models) is read the same way: that name is used in this message and for the summary request of the context compression. With streaming, mm also asks the server for token counts (`stream_options.include_usage`). |
4243 | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. |
@@ -37,6 +37,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
37 | `saveAnswerTool` | bool | `false` | Declare `save_answer`, which writes an answer the model already gave to a new file: the model sends a file name, not the text again. Off by default. The `/save` command exists either way. See [tools](tools.md#save_answer). |37 | `saveAnswerTool` | bool | `false` | Declare `save_answer`, which writes an answer the model already gave to a new file: the model sends a file name, not the text again. Off by default. The `/save` command exists either way. See [tools](tools.md#save_answer). |
38 | `unloadModels` | bool | `true` | The `/unload [model]` command (terminal, window, editor) and the `unload_model` tool, which free a model from the server's memory: llmman and Ollama, Kronk, llama-server in router mode. `false` removes both. The tool is never declared beside a `structuredOutput` or a `decision` block. See [tools](tools.md#unload_model) and [How to free a model's memory](../how-to/unload-a-model.md). |38 | `unloadModels` | bool | `true` | The `/unload [model]` command (terminal, window, editor) and the `unload_model` tool, which free a model from the server's memory: llmman and Ollama, Kronk, llama-server in router mode. `false` removes both. The tool is never declared beside a `structuredOutput` or a `decision` block. See [tools](tools.md#unload_model) and [How to free a model's memory](../how-to/unload-a-model.md). |
39 | `unloadOnExit` | bool | `true` | When mm exits — `/quit`, Ctrl-C at the prompt, Ctrl-D, the window closed, the end of a `-p` run, the editor closing the ACP session, SIGTERM, SIGHUP — unload the agent's model from the server's memory, so it does not keep its RAM after the session. One `🧹` line on stderr (none in ACP mode); nothing when the model was not loaded or the server cannot unload (dmr, openai, a single-model llama-server). Bounded to 3 s: a server that does not answer never holds the exit. Only the agent's own model — not the decision models, not the `mmConfigs` agents (each unloads its own when it stops). `false`: the model stays loaded (faster next start, or another session or tool uses it — mm does not know who else uses it). Independent of `unloadModels`. Overridden by `AGENT_UNLOAD_ON_EXIT`. See [How to free a model's memory](../how-to/unload-a-model.md#when-mm-exits). |39 | `unloadOnExit` | bool | `true` | When mm exits — `/quit`, Ctrl-C at the prompt, Ctrl-D, the window closed, the end of a `-p` run, the editor closing the ACP session, SIGTERM, SIGHUP — unload the agent's model from the server's memory, so it does not keep its RAM after the session. One `🧹` line on stderr (none in ACP mode); nothing when the model was not loaded or the server cannot unload (dmr, openai, a single-model llama-server). Bounded to 3 s: a server that does not answer never holds the exit. Only the agent's own model — not the decision models, not the `mmConfigs` agents (each unloads its own when it stops). `false`: the model stays loaded (faster next start, or another session or tool uses it — mm does not know who else uses it). Independent of `unloadModels`. Overridden by `AGENT_UNLOAD_ON_EXIT`. See [How to free a model's memory](../how-to/unload-a-model.md#when-mm-exits). |
40+| `llamacpp` | `{autoStart, server, ctxSize, modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault, serverArgs, startTimeout}` | `autoStart: false` | Provider `llamacpp` only. `autoStart: true`: when nothing answers at the agent's address (a loopback one, `AGENT_BASE_URL` unset) nor on 8080 nor at the `fallback`, mm starts llama-server in router mode with the agent's model (downloaded on first load), waits until it is loaded, and stops it with the last mm session using it; a server mm did not start is never stopped. `server`: the executable (default `llama-server`, then `llama serve`, on the `PATH`). Launch settings, each one optional, each one a llama-server flag (absent = llama-server's default): `ctxSize` (`--ctx-size`), `modelsMax` (`--models-max`), `modelsMemoryMargin` (`--models-memory-margin`), `fitTarget` (`--fit-target`), `sleepIdleSeconds` (`--sleep-idle-seconds`, `-1` allowed), `specDefault` (`--spec-default`); a negative value is a configuration error. `serverArgs`: any other flag, added last. `startTimeout` (default `15m`): start, download and load. Registry and log: `<user cache dir>/mm/llama-server/<host>-<port>/`. `mm init` asks for a llamacpp agent on this machine (`--autostart`, default yes; `--launch-settings`, the Llama app's values, default no). See [Let mm start llama-server](../how-to/run-with-llama-cpp.md#let-mm-start-llama-server). |
40 | `autoPull` | bool | `false` | At start-up, download the models this agent will use and the server does not list: its own, its `mmConfigs` agents', its `skillRouting` / `toolRouting` deciders'. The progress goes to stderr — one line rewritten in place on a terminal (`⬇ pulling <model> — 52 MB / 145 MB (35 %)`), a line per tenth elsewhere — then `⬇ pulled <model> in 0.8s`. The agent's own model failing stops `mm` with the server's message (`[engine error: autoPull: <model>: the server says: …]`); another model failing, a server that does not answer, or a provider that cannot pull is a `[warning: autoPull: …]`. An agent started by `/ask` or `ask_agent` pulls nothing; `mm --ask` pulls nothing either. A model the server already lists is never pulled (a name without a tag also matches its `:latest` entry). By provider: `llmman` and `ollama` — `POST /api/pull`; `kronk` — `POST /v1/kronk/models/pull`, the pull counting as done only when Kronk's stream ends with `"downloaded": true` (Kronk answers 200 to a failed pull; its last status is then the message); `dmr` — `POST /models/create` on the runner (the base URL without `/engines/…`), the pull counting as done once the runner lists the model; `llamacpp` — no download over the API: the warning says to start llama-server with `-hf <repo>:<quant>`, or to put the GGUF in the router's models directory; `openai` — a warning. |41 | `autoPull` | bool | `false` | At start-up, download the models this agent will use and the server does not list: its own, its `mmConfigs` agents', its `skillRouting` / `toolRouting` deciders'. The progress goes to stderr — one line rewritten in place on a terminal (`⬇ pulling <model> — 52 MB / 145 MB (35 %)`), a line per tenth elsewhere — then `⬇ pulled <model> in 0.8s`. The agent's own model failing stops `mm` with the server's message (`[engine error: autoPull: <model>: the server says: …]`); another model failing, a server that does not answer, or a provider that cannot pull is a `[warning: autoPull: …]`. An agent started by `/ask` or `ask_agent` pulls nothing; `mm --ask` pulls nothing either. A model the server already lists is never pulled (a name without a tag also matches its `:latest` entry). By provider: `llmman` and `ollama` — `POST /api/pull`; `kronk` — `POST /v1/kronk/models/pull`, the pull counting as done only when Kronk's stream ends with `"downloaded": true` (Kronk answers 200 to a failed pull; its last status is then the message); `dmr` — `POST /models/create` on the runner (the base URL without `/engines/…`), the pull counting as done once the runner lists the model; `llamacpp` — no download over the API: the warning says to start llama-server with `-hf <repo>:<quant>`, or to put the GGUF in the router's models directory; `openai` — a warning. |
41 | `sampling` | map | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Generation settings, OpenAI API key names, passed to the server. The file's block is merged with these defaults: a default the file does not name is still sent. **Except with `provider: openai` and `provider: openai-responses`**: the request carries exactly the file's block, nothing added (no block: no sampling key, the server's defaults apply) — the hosted OpenAI reasoning models refuse `max_tokens` and accept only the default temperature, so a default left in would be a 400. A key the OpenAI API does not declare is sent as it is, at the top level of the request — for example `chat_template_kwargs: {enable_thinking: false}`, which tells a llama.cpp server (`dmr`, `llamacpp`, `llmman`) or Kronk not to reason; `reasoning_effort: none` does the same on Ollama. `messages`, `tools`, `tool_choice` (and the legacy `functions`, `function_call`) are ignored: Genkit builds them from the conversation. The shipped `agent.yaml` adds `parallel_tool_calls: false`. `max_tokens` also bounds one tool call: a `write_file` of a long document (or a thinking model's reasoning plus the call) can hit it, and the call is then cut off. mm hands it back to the model twice, asking for smaller pieces, then stops with `the model hit max_tokens (N) while writing a tool call`; raise the value if that happens. A config that names the limit `max_completion_tokens` (the OpenAI API's name for its newer models) is read the same way: that name is used in this message and for the summary request of the context compression. With streaming, mm also asks the server for token counts (`stream_options.include_usage`). |42 | `sampling` | map | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Generation settings, OpenAI API key names, passed to the server. The file's block is merged with these defaults: a default the file does not name is still sent. **Except with `provider: openai` and `provider: openai-responses`**: the request carries exactly the file's block, nothing added (no block: no sampling key, the server's defaults apply) — the hosted OpenAI reasoning models refuse `max_tokens` and accept only the default temperature, so a default left in would be a 400. A key the OpenAI API does not declare is sent as it is, at the top level of the request — for example `chat_template_kwargs: {enable_thinking: false}`, which tells a llama.cpp server (`dmr`, `llamacpp`, `llmman`) or Kronk not to reason; `reasoning_effort: none` does the same on Ollama. `messages`, `tools`, `tool_choice` (and the legacy `functions`, `function_call`) are ignored: Genkit builds them from the conversation. The shipped `agent.yaml` adds `parallel_tool_calls: false`. `max_tokens` also bounds one tool call: a `write_file` of a long document (or a thinking model's reasoning plus the call) can hit it, and the call is then cut off. mm hands it back to the model twice, asking for smaller pieces, then stops with `the model hit max_tokens (N) while writing a tool call`; raise the value if that happens. A config that names the limit `max_completion_tokens` (the OpenAI API's name for its newer models) is read the same way: that name is used in this message and for the summary request of the context compression. With streaming, mm also asks the server for token counts (`stream_options.include_usage`). |
42 | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. |43 | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. |
modified docs/fr/how-to/create-an-agent.md +1 -0
@@ -81,6 +81,7 @@ Ce guide montre comment écrire un nouvel agent.yaml pour un modèle et une tâc
8181 - **Voir le fichier sans l'écrire.** `-o -` l'affiche sur la sortie standard. Rien n'est créé, pas même le dossier `.mm` ni celui des skills.
8282 - **Tout dans un dossier `.mm`.** Répondez `yes` à la première question, ou donnez `--project yes` : mm crée `.mm/` et écrit `.mm/agent.yaml`, avec ses chemins écrits depuis la racine du projet. Lancés depuis cette racine, `mm` et `mm tui` le trouvent sans argument. Voir [Comment ranger les fichiers mini-me d'un projet dans un dossier `.mm`](keep-the-config-in-a-mm-folder.md).
8383 - **Sessions et skills.** `--sessions yes` écrit une section `sessions` : chaque conversation est enregistrée, et `/resume` peut la rouvrir. `--skills yes` écrit `skillsDir` et crée le dossier (`skills/`, ou `.mm/skills/` avec `--project yes`) ; ajoutez-y vos skills (voir [Comment ajouter un skill](add-a-skill.md)).
84+- **llama-server démarré par mm.** Pour `llamacpp` sur cette machine, mm init demande si mm peut démarrer llama-server quand il ne tourne pas (`--autostart`, oui par défaut), puis s'il faut écrire ses réglages de lancement avec les valeurs de l'application Llama (`--launch-settings`, non par défaut). Voir [Laisser mm démarrer llama-server](run-with-llama-cpp.md#laisser-mm-démarrer-llama-server).
8485 - **Un service compatible OpenAI (OpenAI, Cerebras, Hugging Face…).** Choisissez `openai` : deux questions de plus suivent, l'endpoint (`https://api.openai.com/v1` par défaut) et le nom de la variable qui contient la clé d'API (`OPENAI_API_KEY` par défaut, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Exportez la clé avant de lancer `mm init` : avec elle, la question du modèle liste les modèles du service ; sans elle, vous tapez l'ID du modèle (la question dit que la variable n'est pas renseignée). Options : `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. Le fichier reçoit `baseUrl` et `apiKeyEnv`, et un `reasoning_effort: none` en commentaire dans `sampling`, à décommenter si l'API répond « Function tools with reasoning_effort are not supported ». Pour un modèle de raisonnement d'OpenAI qui doit continuer à raisonner pendant qu'il appelle des outils, choisissez plutôt `openai-responses` : les mêmes questions, et le fichier parle à l'API Responses (voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](use-the-openai-responses-api.md)).
8586 - **Un serveur ailleurs.** `--base-url http://192.168.1.20:17434/v1` ; il est écrit dans le fichier comme `baseUrl`. Sans lui, le fichier n'a pas de `baseUrl` et garde en commentaire l'adresse par défaut du fournisseur et son fallback, prêts à être décommentés.
8687 - **Un serveur qui ne répond pas.** mm le dit et demande le nom du modèle : les réglages viennent alors de la seule table des familles.
@@ -81,6 +81,7 @@ Ce guide montre comment écrire un nouvel agent.yaml pour un modèle et une tâc
81 - **Voir le fichier sans l'écrire.** `-o -` l'affiche sur la sortie standard. Rien n'est créé, pas même le dossier `.mm` ni celui des skills.81 - **Voir le fichier sans l'écrire.** `-o -` l'affiche sur la sortie standard. Rien n'est créé, pas même le dossier `.mm` ni celui des skills.
82 - **Tout dans un dossier `.mm`.** Répondez `yes` à la première question, ou donnez `--project yes` : mm crée `.mm/` et écrit `.mm/agent.yaml`, avec ses chemins écrits depuis la racine du projet. Lancés depuis cette racine, `mm` et `mm tui` le trouvent sans argument. Voir [Comment ranger les fichiers mini-me d'un projet dans un dossier `.mm`](keep-the-config-in-a-mm-folder.md).82 - **Tout dans un dossier `.mm`.** Répondez `yes` à la première question, ou donnez `--project yes` : mm crée `.mm/` et écrit `.mm/agent.yaml`, avec ses chemins écrits depuis la racine du projet. Lancés depuis cette racine, `mm` et `mm tui` le trouvent sans argument. Voir [Comment ranger les fichiers mini-me d'un projet dans un dossier `.mm`](keep-the-config-in-a-mm-folder.md).
83 - **Sessions et skills.** `--sessions yes` écrit une section `sessions` : chaque conversation est enregistrée, et `/resume` peut la rouvrir. `--skills yes` écrit `skillsDir` et crée le dossier (`skills/`, ou `.mm/skills/` avec `--project yes`) ; ajoutez-y vos skills (voir [Comment ajouter un skill](add-a-skill.md)).83 - **Sessions et skills.** `--sessions yes` écrit une section `sessions` : chaque conversation est enregistrée, et `/resume` peut la rouvrir. `--skills yes` écrit `skillsDir` et crée le dossier (`skills/`, ou `.mm/skills/` avec `--project yes`) ; ajoutez-y vos skills (voir [Comment ajouter un skill](add-a-skill.md)).
84+- **llama-server démarré par mm.** Pour `llamacpp` sur cette machine, mm init demande si mm peut démarrer llama-server quand il ne tourne pas (`--autostart`, oui par défaut), puis s'il faut écrire ses réglages de lancement avec les valeurs de l'application Llama (`--launch-settings`, non par défaut). Voir [Laisser mm démarrer llama-server](run-with-llama-cpp.md#laisser-mm-démarrer-llama-server).
84 - **Un service compatible OpenAI (OpenAI, Cerebras, Hugging Face…).** Choisissez `openai` : deux questions de plus suivent, l'endpoint (`https://api.openai.com/v1` par défaut) et le nom de la variable qui contient la clé d'API (`OPENAI_API_KEY` par défaut, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Exportez la clé avant de lancer `mm init` : avec elle, la question du modèle liste les modèles du service ; sans elle, vous tapez l'ID du modèle (la question dit que la variable n'est pas renseignée). Options : `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. Le fichier reçoit `baseUrl` et `apiKeyEnv`, et un `reasoning_effort: none` en commentaire dans `sampling`, à décommenter si l'API répond « Function tools with reasoning_effort are not supported ». Pour un modèle de raisonnement d'OpenAI qui doit continuer à raisonner pendant qu'il appelle des outils, choisissez plutôt `openai-responses` : les mêmes questions, et le fichier parle à l'API Responses (voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](use-the-openai-responses-api.md)).85 - **Un service compatible OpenAI (OpenAI, Cerebras, Hugging Face…).** Choisissez `openai` : deux questions de plus suivent, l'endpoint (`https://api.openai.com/v1` par défaut) et le nom de la variable qui contient la clé d'API (`OPENAI_API_KEY` par défaut, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Exportez la clé avant de lancer `mm init` : avec elle, la question du modèle liste les modèles du service ; sans elle, vous tapez l'ID du modèle (la question dit que la variable n'est pas renseignée). Options : `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. Le fichier reçoit `baseUrl` et `apiKeyEnv`, et un `reasoning_effort: none` en commentaire dans `sampling`, à décommenter si l'API répond « Function tools with reasoning_effort are not supported ». Pour un modèle de raisonnement d'OpenAI qui doit continuer à raisonner pendant qu'il appelle des outils, choisissez plutôt `openai-responses` : les mêmes questions, et le fichier parle à l'API Responses (voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](use-the-openai-responses-api.md)).
85 - **Un serveur ailleurs.** `--base-url http://192.168.1.20:17434/v1` ; il est écrit dans le fichier comme `baseUrl`. Sans lui, le fichier n'a pas de `baseUrl` et garde en commentaire l'adresse par défaut du fournisseur et son fallback, prêts à être décommentés.86 - **Un serveur ailleurs.** `--base-url http://192.168.1.20:17434/v1` ; il est écrit dans le fichier comme `baseUrl`. Sans lui, le fichier n'a pas de `baseUrl` et garde en commentaire l'adresse par défaut du fournisseur et son fallback, prêts à être décommentés.
86 - **Un serveur qui ne répond pas.** mm le dit et demande le nom du modèle : les réglages viennent alors de la seule table des familles.87 - **Un serveur qui ne répond pas.** mm le dit et demande le nom du modèle : les réglages viennent alors de la seule table des familles.
modified docs/fr/how-to/run-with-llama-cpp.md +42 -0
@@ -22,6 +22,48 @@ Ce guide montre comment pointer `mm` vers un `llama-server` que vous démarrez v
2222
2323 3. Vérifiez la bannière. `provider: llamacpp` confirme le fournisseur, et `ctx: 32768 (/props)` confirme que l'agent a lu la taille de contexte servie sur le point d'accès `/props` du serveur.
2424
25+## Laisser mm démarrer llama-server
26+
27+À la place de l'étape 1, mm peut démarrer le serveur lui-même quand rien ne répond — et l'arrêter quand vous quittez :
28+
29+```yaml
30+provider: llamacpp
31+model: "ggml-org/gemma-3-1b-it-GGUF:Q4_K_M" # un dépôt:quant Hugging Face
32+llamacpp:
33+ autoStart: true
34+```
35+
36+```text
37+$ mm
38+🦙 starting llama-server on 127.0.0.1:9931 (pid 74312, log ~/.cache/mm/llama-server/127.0.0.1-9931/llama-server.log)
39+🦙 ggml-org/gemma-3-1b-it-GGUF:Q4_K_M loaded
40+…
41+> /quit
42+🧹 unloaded ggml-org/gemma-3-1b-it-GGUF:Q4_K_M
43+🦙 stopped llama-server (pid 74312)
44+```
45+
46+- **Quand.** Seulement quand l'adresse de l'agent est sur cette machine (pas de `baseUrl`, ou `127.0.0.1` / `localhost`), qu'`AGENT_BASE_URL` n'est pas positionnée, et que rien n'y répond, ni sur `8080`, ni au `fallback` (le serveur de l'hôte, vu d'un conteneur). Un serveur qui tourne déjà — le vôtre, celui de l'application Llama — est utilisé comme avant, et jamais arrêté.
47+- **Comment.** `llama-server --host 127.0.0.1 --port <le port de l'agent> --models-preset <fichier>` en mode routeur (ou `llama serve …` quand seule la commande `llama` est installée). Le fichier preset nomme le modèle de l'agent : un modèle absent du cache Hugging Face est téléchargé à son premier chargement. mm attend que le modèle soit chargé (spinner, jusqu'à `startTimeout`, 15 minutes par défaut) — un gros téléchargement ne déclenche pas le délai de la première question. La sortie du serveur va dans le fichier de log nommé sur la première ligne.
48+- **Plusieurs sessions.** Un second mm sur la même adresse partage le serveur (`🦙 llama-server already started by mm …`). Quitter le garde tant qu'une autre session l'utilise (`kept running: 1 other mm session(s) use it`) ; la dernière l'arrête. Une session qui a planté laisse un bail que le mm suivant supprime.
49+- **Réglages de lancement.** Chaque clé facultative est une option de llama-server ; une clé absente n'est pas passée, llama-server garde sa valeur par défaut. Le routeur transmet les réglages du modèle au modèle qu'il charge (la bannière affiche alors `ctx: 32768 (/props)`). Les valeurs avec lesquelles l'application Llama démarre son serveur :
50+
51+ ```yaml
52+ llamacpp:
53+ autoStart: true
54+ ctxSize: 32768 # --ctx-size (par défaut : celle du modèle)
55+ modelsMax: 0 # --models-max : 0 = sans limite (4 par défaut)
56+ modelsMemoryMargin: 1024 # --models-memory-margin, Mio gardés libres (0 par défaut = désactivé)
57+ fitTarget: 1024 # --fit-target, Mio par périphérique (1024 par défaut)
58+ sleepIdleSeconds: 300 # --sleep-idle-seconds : libère le modèle inactif (-1 par défaut = jamais)
59+ specDefault: true # --spec-default : décodage spéculatif par défaut
60+ serverArgs: [--no-webui] # toute autre option, après celles du dessus
61+ ```
62+
63+ Une valeur négative est une erreur de configuration qui nomme la clé (`-1` est accepté pour `sleepIdleSeconds`).
64+- **Autres réglages.** `server:` le chemin de l'exécutable quand il n'est pas dans le `PATH` ; `startTimeout:`. `mm init` demande, pour un agent llamacpp sur cette machine, si mm peut démarrer le serveur (oui par défaut) et s'il faut écrire les réglages de lancement ci-dessous (non par défaut).
65+- **Limites.** Le serveur liste les modèles qu'il connaissait à son démarrage : une seconde session avec un autre modèle ne le trouve pas (un avertissement) tant que les sessions qui utilisent le serveur n'ont pas quitté. Ctrl-C ou SIGTERM pendant le démarrage l'arrête.
66+
2567 ## Variantes
2668
2769 - **llama-server sur 8080.** Une build plus ancienne, l'image Docker officielle ou un serveur lancé avec `--port 8080` : rien à régler. Quand `baseUrl` est l'adresse par défaut de llama-server (`http://127.0.0.1:9931/v1`, ou pas de `baseUrl` du tout) et ne répond pas, mm essaie `http://127.0.0.1:8080/v1` avant l'adresse du conteneur. `mm init` et `mm acp-create` listent les modèles depuis celle qui répond.
@@ -22,6 +22,48 @@ Ce guide montre comment pointer `mm` vers un `llama-server` que vous démarrez v
22 22
23 3. Vérifiez la bannière. `provider: llamacpp` confirme le fournisseur, et `ctx: 32768 (/props)` confirme que l'agent a lu la taille de contexte servie sur le point d'accès `/props` du serveur.23 3. Vérifiez la bannière. `provider: llamacpp` confirme le fournisseur, et `ctx: 32768 (/props)` confirme que l'agent a lu la taille de contexte servie sur le point d'accès `/props` du serveur.
24 24
25+## Laisser mm démarrer llama-server
26+
27+À la place de l'étape 1, mm peut démarrer le serveur lui-même quand rien ne répond — et l'arrêter quand vous quittez :
28+
29+```yaml
30+provider: llamacpp
31+model: "ggml-org/gemma-3-1b-it-GGUF:Q4_K_M" # un dépôt:quant Hugging Face
32+llamacpp:
33+ autoStart: true
34+```
35+
36+```text
37+$ mm
38+🦙 starting llama-server on 127.0.0.1:9931 (pid 74312, log ~/.cache/mm/llama-server/127.0.0.1-9931/llama-server.log)
39+🦙 ggml-org/gemma-3-1b-it-GGUF:Q4_K_M loaded
40+…
41+> /quit
42+🧹 unloaded ggml-org/gemma-3-1b-it-GGUF:Q4_K_M
43+🦙 stopped llama-server (pid 74312)
44+```
45+
46+- **Quand.** Seulement quand l'adresse de l'agent est sur cette machine (pas de `baseUrl`, ou `127.0.0.1` / `localhost`), qu'`AGENT_BASE_URL` n'est pas positionnée, et que rien n'y répond, ni sur `8080`, ni au `fallback` (le serveur de l'hôte, vu d'un conteneur). Un serveur qui tourne déjà — le vôtre, celui de l'application Llama — est utilisé comme avant, et jamais arrêté.
47+- **Comment.** `llama-server --host 127.0.0.1 --port <le port de l'agent> --models-preset <fichier>` en mode routeur (ou `llama serve …` quand seule la commande `llama` est installée). Le fichier preset nomme le modèle de l'agent : un modèle absent du cache Hugging Face est téléchargé à son premier chargement. mm attend que le modèle soit chargé (spinner, jusqu'à `startTimeout`, 15 minutes par défaut) — un gros téléchargement ne déclenche pas le délai de la première question. La sortie du serveur va dans le fichier de log nommé sur la première ligne.
48+- **Plusieurs sessions.** Un second mm sur la même adresse partage le serveur (`🦙 llama-server already started by mm …`). Quitter le garde tant qu'une autre session l'utilise (`kept running: 1 other mm session(s) use it`) ; la dernière l'arrête. Une session qui a planté laisse un bail que le mm suivant supprime.
49+- **Réglages de lancement.** Chaque clé facultative est une option de llama-server ; une clé absente n'est pas passée, llama-server garde sa valeur par défaut. Le routeur transmet les réglages du modèle au modèle qu'il charge (la bannière affiche alors `ctx: 32768 (/props)`). Les valeurs avec lesquelles l'application Llama démarre son serveur :
50+
51+ ```yaml
52+ llamacpp:
53+ autoStart: true
54+ ctxSize: 32768 # --ctx-size (par défaut : celle du modèle)
55+ modelsMax: 0 # --models-max : 0 = sans limite (4 par défaut)
56+ modelsMemoryMargin: 1024 # --models-memory-margin, Mio gardés libres (0 par défaut = désactivé)
57+ fitTarget: 1024 # --fit-target, Mio par périphérique (1024 par défaut)
58+ sleepIdleSeconds: 300 # --sleep-idle-seconds : libère le modèle inactif (-1 par défaut = jamais)
59+ specDefault: true # --spec-default : décodage spéculatif par défaut
60+ serverArgs: [--no-webui] # toute autre option, après celles du dessus
61+ ```
62+
63+ Une valeur négative est une erreur de configuration qui nomme la clé (`-1` est accepté pour `sleepIdleSeconds`).
64+- **Autres réglages.** `server:` le chemin de l'exécutable quand il n'est pas dans le `PATH` ; `startTimeout:`. `mm init` demande, pour un agent llamacpp sur cette machine, si mm peut démarrer le serveur (oui par défaut) et s'il faut écrire les réglages de lancement ci-dessous (non par défaut).
65+- **Limites.** Le serveur liste les modèles qu'il connaissait à son démarrage : une seconde session avec un autre modèle ne le trouve pas (un avertissement) tant que les sessions qui utilisent le serveur n'ont pas quitté. Ctrl-C ou SIGTERM pendant le démarrage l'arrête.
66+
25 ## Variantes67 ## Variantes
26 68
27 - **llama-server sur 8080.** Une build plus ancienne, l'image Docker officielle ou un serveur lancé avec `--port 8080` : rien à régler. Quand `baseUrl` est l'adresse par défaut de llama-server (`http://127.0.0.1:9931/v1`, ou pas de `baseUrl` du tout) et ne répond pas, mm essaie `http://127.0.0.1:8080/v1` avant l'adresse du conteneur. `mm init` et `mm acp-create` listent les modèles depuis celle qui répond.69 - **llama-server sur 8080.** Une build plus ancienne, l'image Docker officielle ou un serveur lancé avec `--port 8080` : rien à régler. Quand `baseUrl` est l'adresse par défaut de llama-server (`http://127.0.0.1:9931/v1`, ou pas de `baseUrl` du tout) et ne répond pas, mm essaie `http://127.0.0.1:8080/v1` avant l'adresse du conteneur. `mm init` et `mm acp-create` listent les modèles depuis celle qui répond.
modified docs/fr/reference/cli.md +2 -0
@@ -258,6 +258,8 @@ Un fichier d'agent hors du workspace ne donne qu'un avertissement : voir [quand
258258 | `--yolo yes\|no` | Demander avant chaque commande ou modification de fichier ? — seulement pour les usages avec `bash`, les outils de fichiers ou `fetch_content` | celui de l'usage |
259259 | `--sessions yes\|no` | Enregistrer les conversations ? | `no` ; `yes` : une section `sessions` (`enabled: true`, `dir: .mm/sessions`) ; `no` : pas de section, le défaut de mm (désactivé) s'applique |
260260 | `--skills yes\|no` | Utiliser des skills ? | `no` (`skillsDir: no-skills`) ; `yes` : `skillsDir: skills`, ou `.mm/skills` avec `--project yes`, et le dossier est créé depuis la racine du projet une fois le fichier écrit |
261+| `--autostart yes\|no` | Laisser mm démarrer llama-server quand il ne tourne pas ? (llamacpp sur cette machine seulement) | `yes` (`llamacpp.autoStart: true`) ; `no` : `autoStart: false`, vous démarrez le serveur |
262+| `--launch-settings yes\|no` | Écrire les réglages de lancement de llama-server ? (avec `--autostart yes` seulement) | `no` (les valeurs par défaut de llama-server) ; `yes` : les valeurs de l'application Llama — `modelsMax: 0`, `modelsMemoryMargin: 1024`, `fitTarget: 1024`, `sleepIdleSeconds: 300`, `specDefault: true` |
261263 | `--name` | Nom de l'agent (`acp.name`) | le nom de l'usage |
262264 | `-o`, `--output` | Fichier à écrire (`-` = sortie standard : rien n'est créé, quelles que soient les autres réponses). Avec `--project yes`, un fichier qui n'est pas directement dans un dossier `.mm` est refusé | `agent.yaml` ; `.mm/agent.yaml` avec `--project yes` |
263265 | `--check` | — | désactivé ; activé : après l'écriture, lance ce mm avec `-config <fichier> -p "Say hello in one line."` et indique si le modèle a répondu (5 min au plus) |
@@ -258,6 +258,8 @@ Un fichier d'agent hors du workspace ne donne qu'un avertissement : voir [quand
258 | `--yolo yes\|no` | Demander avant chaque commande ou modification de fichier ? — seulement pour les usages avec `bash`, les outils de fichiers ou `fetch_content` | celui de l'usage |258 | `--yolo yes\|no` | Demander avant chaque commande ou modification de fichier ? — seulement pour les usages avec `bash`, les outils de fichiers ou `fetch_content` | celui de l'usage |
259 | `--sessions yes\|no` | Enregistrer les conversations ? | `no` ; `yes` : une section `sessions` (`enabled: true`, `dir: .mm/sessions`) ; `no` : pas de section, le défaut de mm (désactivé) s'applique |259 | `--sessions yes\|no` | Enregistrer les conversations ? | `no` ; `yes` : une section `sessions` (`enabled: true`, `dir: .mm/sessions`) ; `no` : pas de section, le défaut de mm (désactivé) s'applique |
260 | `--skills yes\|no` | Utiliser des skills ? | `no` (`skillsDir: no-skills`) ; `yes` : `skillsDir: skills`, ou `.mm/skills` avec `--project yes`, et le dossier est créé depuis la racine du projet une fois le fichier écrit |260 | `--skills yes\|no` | Utiliser des skills ? | `no` (`skillsDir: no-skills`) ; `yes` : `skillsDir: skills`, ou `.mm/skills` avec `--project yes`, et le dossier est créé depuis la racine du projet une fois le fichier écrit |
261+| `--autostart yes\|no` | Laisser mm démarrer llama-server quand il ne tourne pas ? (llamacpp sur cette machine seulement) | `yes` (`llamacpp.autoStart: true`) ; `no` : `autoStart: false`, vous démarrez le serveur |
262+| `--launch-settings yes\|no` | Écrire les réglages de lancement de llama-server ? (avec `--autostart yes` seulement) | `no` (les valeurs par défaut de llama-server) ; `yes` : les valeurs de l'application Llama — `modelsMax: 0`, `modelsMemoryMargin: 1024`, `fitTarget: 1024`, `sleepIdleSeconds: 300`, `specDefault: true` |
261 | `--name` | Nom de l'agent (`acp.name`) | le nom de l'usage |263 | `--name` | Nom de l'agent (`acp.name`) | le nom de l'usage |
262 | `-o`, `--output` | Fichier à écrire (`-` = sortie standard : rien n'est créé, quelles que soient les autres réponses). Avec `--project yes`, un fichier qui n'est pas directement dans un dossier `.mm` est refusé | `agent.yaml` ; `.mm/agent.yaml` avec `--project yes` |264 | `-o`, `--output` | Fichier à écrire (`-` = sortie standard : rien n'est créé, quelles que soient les autres réponses). Avec `--project yes`, un fichier qui n'est pas directement dans un dossier `.mm` est refusé | `agent.yaml` ; `.mm/agent.yaml` avec `--project yes` |
263 | `--check` | — | désactivé ; activé : après l'écriture, lance ce mm avec `-config <fichier> -p "Say hello in one line."` et indique si le modèle a répondu (5 min au plus) |265 | `--check` | — | désactivé ; activé : après l'écriture, lance ce mm avec `-config <fichier> -p "Say hello in one line."` et indique si le modèle a répondu (5 min au plus) |
modified docs/fr/reference/configuration.md +1 -0
@@ -37,6 +37,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
3737 | `saveAnswerTool` | bool | `false` | Déclare `save_answer`, qui écrit dans un nouveau fichier une réponse que le modèle a déjà donnée : le modèle envoie un nom de fichier, pas le texte une seconde fois. Désactivé par défaut. La commande `/save` existe dans tous les cas. Voir les [outils](tools.md#save_answer). |
3838 | `unloadModels` | bool | `true` | La commande `/unload [modèle]` (terminal, fenêtre, éditeur) et l'outil `unload_model`, qui libèrent un modèle de la mémoire du serveur : llmman et Ollama, Kronk, llama-server en mode router. `false` retire les deux. L'outil n'est jamais déclaré à côté d'une `structuredOutput` ni d'un bloc `decision`. Voir les [outils](tools.md#unload_model) et [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md). |
3939 | `unloadOnExit` | booléen | `true` | Quand mm se termine — `/quit`, Ctrl-C à l'invite, Ctrl-D, la fenêtre fermée, la fin d'un `-p`, l'éditeur qui ferme la session ACP, SIGTERM, SIGHUP —, décharge le modèle de l'agent de la mémoire du serveur, pour qu'il ne garde pas sa RAM après la session. Une ligne `🧹` sur stderr (aucune en mode ACP) ; rien quand le modèle n'était pas chargé ou que le serveur ne sait pas décharger (dmr, openai, un llama-server mono-modèle). Borné à 3 s : un serveur qui ne répond pas ne retient jamais la sortie. Seul le modèle de l'agent — pas les modèles de décision, pas les agents `mmConfigs` (chacun décharge le sien quand il s'arrête). `false` : le modèle reste chargé (redémarrage plus rapide, ou une autre session ou un autre outil s'en sert — mm ne sait pas qui d'autre l'utilise). Indépendant d'`unloadModels`. Surchargé par `AGENT_UNLOAD_ON_EXIT`. Voir [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md#quand-mm-se-termine). |
40+| `llamacpp` | `{autoStart, server, ctxSize, modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault, serverArgs, startTimeout}` | `autoStart: false` | Fournisseur `llamacpp` seulement. `autoStart: true` : quand rien ne répond à l'adresse de l'agent (une adresse de boucle locale, `AGENT_BASE_URL` non positionnée), ni sur 8080, ni au `fallback`, mm démarre llama-server en mode routeur avec le modèle de l'agent (téléchargé à son premier chargement), attend qu'il soit chargé, et l'arrête avec la dernière session mm qui l'utilise ; un serveur que mm n'a pas démarré n'est jamais arrêté. `server` : l'exécutable (par défaut `llama-server`, puis `llama serve`, dans le `PATH`). Réglages de lancement, tous facultatifs, chacun une option de llama-server (absent = la valeur par défaut de llama-server) : `ctxSize` (`--ctx-size`), `modelsMax` (`--models-max`), `modelsMemoryMargin` (`--models-memory-margin`), `fitTarget` (`--fit-target`), `sleepIdleSeconds` (`--sleep-idle-seconds`, `-1` accepté), `specDefault` (`--spec-default`) ; une valeur négative est une erreur de configuration. `serverArgs` : toute autre option, ajoutée en dernier. `startTimeout` (`15m` par défaut) : démarrage, téléchargement et chargement. Registre et log : `<dossier cache de l'utilisateur>/mm/llama-server/<hôte>-<port>/`. `mm init` le demande pour un agent llamacpp sur cette machine (`--autostart`, oui par défaut ; `--launch-settings`, les valeurs de l'application Llama, non par défaut). Voir [Laisser mm démarrer llama-server](../how-to/run-with-llama-cpp.md#laisser-mm-démarrer-llama-server). |
4041 | `autoPull` | booléen | `false` | Au démarrage, télécharge les modèles que cet agent utilisera et que le serveur ne liste pas : le sien, ceux de ses agents `mmConfigs`, ceux de ses deciders `skillRouting` / `toolRouting`. La progression va sur stderr — une ligne réécrite sur place dans un terminal (`⬇ pulling <modèle> — 52 MB / 145 MB (35 %)`), une ligne par dixième ailleurs — puis `⬇ pulled <modèle> in 0.8s`. Un échec sur le modèle de l'agent arrête `mm` avec le message du serveur (`[engine error: autoPull: <modèle>: the server says: …]`) ; un échec sur un autre modèle, un serveur qui ne répond pas ou un fournisseur qui ne sait pas télécharger donne un `[warning: autoPull: …]`. Un agent lancé par `/ask` ou `ask_agent` ne télécharge rien ; `mm --ask` non plus. Un modèle que le serveur liste déjà n'est jamais téléchargé (un nom sans tag correspond aussi à son entrée `:latest`). Par fournisseur : `llmman` et `ollama` — `POST /api/pull` ; `kronk` — `POST /v1/kronk/models/pull`, le téléchargement ne comptant comme fait que si le flux de Kronk se termine par `"downloaded": true` (Kronk répond 200 à un téléchargement raté ; son dernier statut est alors le message) ; `dmr` — `POST /models/create` sur le runner (l'URL de base sans `/engines/…`), le téléchargement ne comptant comme fait qu'une fois le modèle listé par le runner ; `llamacpp` — pas de téléchargement par l'API : l'avertissement dit de lancer llama-server avec `-hf <dépôt>:<quant>`, ou de mettre le GGUF dans le dossier de modèles du router ; `openai` — un avertissement. |
4142 | `sampling` | dictionnaire | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Paramètres de génération, noms de l'API OpenAI, transmis au serveur. Le bloc du fichier est fusionné avec ces valeurs par défaut : une valeur par défaut que le fichier ne nomme pas est quand même envoyée. **Sauf avec `provider: openai` et `provider: openai-responses`** : la requête porte exactement le bloc du fichier, rien d'ajouté (pas de bloc : aucune clé de génération, les valeurs par défaut du serveur s'appliquent) — les modèles de raisonnement hébergés par OpenAI refusent `max_tokens` et n'acceptent que la température par défaut, une valeur par défaut laissée là donnerait une erreur 400. Une clé que l'API OpenAI ne déclare pas est envoyée telle quelle, au premier niveau de la requête — par exemple `chat_template_kwargs: {enable_thinking: false}`, qui demande à un serveur llama.cpp (`dmr`, `llamacpp`, `llmman`) ou à Kronk de ne pas raisonner ; `reasoning_effort: none` fait de même avec Ollama. `messages`, `tools`, `tool_choice` (et les anciens `functions`, `function_call`) sont ignorées : Genkit les construit à partir de la conversation. L'`agent.yaml` livré ajoute `parallel_tool_calls: false`. `max_tokens` borne aussi un appel d'outil : un `write_file` de long document (ou le raisonnement d'un modèle « thinking » plus l'appel) peut l'atteindre, et l'appel est alors coupé. mm le rend deux fois au modèle en lui demandant de procéder par morceaux, puis s'arrête avec `the model hit max_tokens (N) while writing a tool call` ; augmentez la valeur si cela arrive. Une configuration qui nomme la limite `max_completion_tokens` (le nom de l'API OpenAI pour ses modèles récents) est lue de la même façon : ce nom est repris dans ce message et dans la requête de résumé de la compression du contexte. En streaming, mm demande aussi au serveur le compte des tokens (`stream_options.include_usage`). |
4243 | `watchdogTimeout` | durée | `20s` | Silence toléré entre deux tokens diffusés avant de déclarer la connexion bloquée. Doublé pour les requêtes de résumé. |
@@ -37,6 +37,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
37 | `saveAnswerTool` | bool | `false` | Déclare `save_answer`, qui écrit dans un nouveau fichier une réponse que le modèle a déjà donnée : le modèle envoie un nom de fichier, pas le texte une seconde fois. Désactivé par défaut. La commande `/save` existe dans tous les cas. Voir les [outils](tools.md#save_answer). |37 | `saveAnswerTool` | bool | `false` | Déclare `save_answer`, qui écrit dans un nouveau fichier une réponse que le modèle a déjà donnée : le modèle envoie un nom de fichier, pas le texte une seconde fois. Désactivé par défaut. La commande `/save` existe dans tous les cas. Voir les [outils](tools.md#save_answer). |
38 | `unloadModels` | bool | `true` | La commande `/unload [modèle]` (terminal, fenêtre, éditeur) et l'outil `unload_model`, qui libèrent un modèle de la mémoire du serveur : llmman et Ollama, Kronk, llama-server en mode router. `false` retire les deux. L'outil n'est jamais déclaré à côté d'une `structuredOutput` ni d'un bloc `decision`. Voir les [outils](tools.md#unload_model) et [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md). |38 | `unloadModels` | bool | `true` | La commande `/unload [modèle]` (terminal, fenêtre, éditeur) et l'outil `unload_model`, qui libèrent un modèle de la mémoire du serveur : llmman et Ollama, Kronk, llama-server en mode router. `false` retire les deux. L'outil n'est jamais déclaré à côté d'une `structuredOutput` ni d'un bloc `decision`. Voir les [outils](tools.md#unload_model) et [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md). |
39 | `unloadOnExit` | booléen | `true` | Quand mm se termine — `/quit`, Ctrl-C à l'invite, Ctrl-D, la fenêtre fermée, la fin d'un `-p`, l'éditeur qui ferme la session ACP, SIGTERM, SIGHUP —, décharge le modèle de l'agent de la mémoire du serveur, pour qu'il ne garde pas sa RAM après la session. Une ligne `🧹` sur stderr (aucune en mode ACP) ; rien quand le modèle n'était pas chargé ou que le serveur ne sait pas décharger (dmr, openai, un llama-server mono-modèle). Borné à 3 s : un serveur qui ne répond pas ne retient jamais la sortie. Seul le modèle de l'agent — pas les modèles de décision, pas les agents `mmConfigs` (chacun décharge le sien quand il s'arrête). `false` : le modèle reste chargé (redémarrage plus rapide, ou une autre session ou un autre outil s'en sert — mm ne sait pas qui d'autre l'utilise). Indépendant d'`unloadModels`. Surchargé par `AGENT_UNLOAD_ON_EXIT`. Voir [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md#quand-mm-se-termine). |39 | `unloadOnExit` | booléen | `true` | Quand mm se termine — `/quit`, Ctrl-C à l'invite, Ctrl-D, la fenêtre fermée, la fin d'un `-p`, l'éditeur qui ferme la session ACP, SIGTERM, SIGHUP —, décharge le modèle de l'agent de la mémoire du serveur, pour qu'il ne garde pas sa RAM après la session. Une ligne `🧹` sur stderr (aucune en mode ACP) ; rien quand le modèle n'était pas chargé ou que le serveur ne sait pas décharger (dmr, openai, un llama-server mono-modèle). Borné à 3 s : un serveur qui ne répond pas ne retient jamais la sortie. Seul le modèle de l'agent — pas les modèles de décision, pas les agents `mmConfigs` (chacun décharge le sien quand il s'arrête). `false` : le modèle reste chargé (redémarrage plus rapide, ou une autre session ou un autre outil s'en sert — mm ne sait pas qui d'autre l'utilise). Indépendant d'`unloadModels`. Surchargé par `AGENT_UNLOAD_ON_EXIT`. Voir [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md#quand-mm-se-termine). |
40+| `llamacpp` | `{autoStart, server, ctxSize, modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault, serverArgs, startTimeout}` | `autoStart: false` | Fournisseur `llamacpp` seulement. `autoStart: true` : quand rien ne répond à l'adresse de l'agent (une adresse de boucle locale, `AGENT_BASE_URL` non positionnée), ni sur 8080, ni au `fallback`, mm démarre llama-server en mode routeur avec le modèle de l'agent (téléchargé à son premier chargement), attend qu'il soit chargé, et l'arrête avec la dernière session mm qui l'utilise ; un serveur que mm n'a pas démarré n'est jamais arrêté. `server` : l'exécutable (par défaut `llama-server`, puis `llama serve`, dans le `PATH`). Réglages de lancement, tous facultatifs, chacun une option de llama-server (absent = la valeur par défaut de llama-server) : `ctxSize` (`--ctx-size`), `modelsMax` (`--models-max`), `modelsMemoryMargin` (`--models-memory-margin`), `fitTarget` (`--fit-target`), `sleepIdleSeconds` (`--sleep-idle-seconds`, `-1` accepté), `specDefault` (`--spec-default`) ; une valeur négative est une erreur de configuration. `serverArgs` : toute autre option, ajoutée en dernier. `startTimeout` (`15m` par défaut) : démarrage, téléchargement et chargement. Registre et log : `<dossier cache de l'utilisateur>/mm/llama-server/<hôte>-<port>/`. `mm init` le demande pour un agent llamacpp sur cette machine (`--autostart`, oui par défaut ; `--launch-settings`, les valeurs de l'application Llama, non par défaut). Voir [Laisser mm démarrer llama-server](../how-to/run-with-llama-cpp.md#laisser-mm-démarrer-llama-server). |
40 | `autoPull` | booléen | `false` | Au démarrage, télécharge les modèles que cet agent utilisera et que le serveur ne liste pas : le sien, ceux de ses agents `mmConfigs`, ceux de ses deciders `skillRouting` / `toolRouting`. La progression va sur stderr — une ligne réécrite sur place dans un terminal (`⬇ pulling <modèle> — 52 MB / 145 MB (35 %)`), une ligne par dixième ailleurs — puis `⬇ pulled <modèle> in 0.8s`. Un échec sur le modèle de l'agent arrête `mm` avec le message du serveur (`[engine error: autoPull: <modèle>: the server says: …]`) ; un échec sur un autre modèle, un serveur qui ne répond pas ou un fournisseur qui ne sait pas télécharger donne un `[warning: autoPull: …]`. Un agent lancé par `/ask` ou `ask_agent` ne télécharge rien ; `mm --ask` non plus. Un modèle que le serveur liste déjà n'est jamais téléchargé (un nom sans tag correspond aussi à son entrée `:latest`). Par fournisseur : `llmman` et `ollama` — `POST /api/pull` ; `kronk` — `POST /v1/kronk/models/pull`, le téléchargement ne comptant comme fait que si le flux de Kronk se termine par `"downloaded": true` (Kronk répond 200 à un téléchargement raté ; son dernier statut est alors le message) ; `dmr` — `POST /models/create` sur le runner (l'URL de base sans `/engines/…`), le téléchargement ne comptant comme fait qu'une fois le modèle listé par le runner ; `llamacpp` — pas de téléchargement par l'API : l'avertissement dit de lancer llama-server avec `-hf <dépôt>:<quant>`, ou de mettre le GGUF dans le dossier de modèles du router ; `openai` — un avertissement. |41 | `autoPull` | booléen | `false` | Au démarrage, télécharge les modèles que cet agent utilisera et que le serveur ne liste pas : le sien, ceux de ses agents `mmConfigs`, ceux de ses deciders `skillRouting` / `toolRouting`. La progression va sur stderr — une ligne réécrite sur place dans un terminal (`⬇ pulling <modèle> — 52 MB / 145 MB (35 %)`), une ligne par dixième ailleurs — puis `⬇ pulled <modèle> in 0.8s`. Un échec sur le modèle de l'agent arrête `mm` avec le message du serveur (`[engine error: autoPull: <modèle>: the server says: …]`) ; un échec sur un autre modèle, un serveur qui ne répond pas ou un fournisseur qui ne sait pas télécharger donne un `[warning: autoPull: …]`. Un agent lancé par `/ask` ou `ask_agent` ne télécharge rien ; `mm --ask` non plus. Un modèle que le serveur liste déjà n'est jamais téléchargé (un nom sans tag correspond aussi à son entrée `:latest`). Par fournisseur : `llmman` et `ollama` — `POST /api/pull` ; `kronk` — `POST /v1/kronk/models/pull`, le téléchargement ne comptant comme fait que si le flux de Kronk se termine par `"downloaded": true` (Kronk répond 200 à un téléchargement raté ; son dernier statut est alors le message) ; `dmr` — `POST /models/create` sur le runner (l'URL de base sans `/engines/…`), le téléchargement ne comptant comme fait qu'une fois le modèle listé par le runner ; `llamacpp` — pas de téléchargement par l'API : l'avertissement dit de lancer llama-server avec `-hf <dépôt>:<quant>`, ou de mettre le GGUF dans le dossier de modèles du router ; `openai` — un avertissement. |
41 | `sampling` | dictionnaire | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Paramètres de génération, noms de l'API OpenAI, transmis au serveur. Le bloc du fichier est fusionné avec ces valeurs par défaut : une valeur par défaut que le fichier ne nomme pas est quand même envoyée. **Sauf avec `provider: openai` et `provider: openai-responses`** : la requête porte exactement le bloc du fichier, rien d'ajouté (pas de bloc : aucune clé de génération, les valeurs par défaut du serveur s'appliquent) — les modèles de raisonnement hébergés par OpenAI refusent `max_tokens` et n'acceptent que la température par défaut, une valeur par défaut laissée là donnerait une erreur 400. Une clé que l'API OpenAI ne déclare pas est envoyée telle quelle, au premier niveau de la requête — par exemple `chat_template_kwargs: {enable_thinking: false}`, qui demande à un serveur llama.cpp (`dmr`, `llamacpp`, `llmman`) ou à Kronk de ne pas raisonner ; `reasoning_effort: none` fait de même avec Ollama. `messages`, `tools`, `tool_choice` (et les anciens `functions`, `function_call`) sont ignorées : Genkit les construit à partir de la conversation. L'`agent.yaml` livré ajoute `parallel_tool_calls: false`. `max_tokens` borne aussi un appel d'outil : un `write_file` de long document (ou le raisonnement d'un modèle « thinking » plus l'appel) peut l'atteindre, et l'appel est alors coupé. mm le rend deux fois au modèle en lui demandant de procéder par morceaux, puis s'arrête avec `the model hit max_tokens (N) while writing a tool call` ; augmentez la valeur si cela arrive. Une configuration qui nomme la limite `max_completion_tokens` (le nom de l'API OpenAI pour ses modèles récents) est lue de la même façon : ce nom est repris dans ce message et dans la requête de résumé de la compression du contexte. En streaming, mm demande aussi au serveur le compte des tokens (`stream_options.include_usage`). |42 | `sampling` | dictionnaire | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Paramètres de génération, noms de l'API OpenAI, transmis au serveur. Le bloc du fichier est fusionné avec ces valeurs par défaut : une valeur par défaut que le fichier ne nomme pas est quand même envoyée. **Sauf avec `provider: openai` et `provider: openai-responses`** : la requête porte exactement le bloc du fichier, rien d'ajouté (pas de bloc : aucune clé de génération, les valeurs par défaut du serveur s'appliquent) — les modèles de raisonnement hébergés par OpenAI refusent `max_tokens` et n'acceptent que la température par défaut, une valeur par défaut laissée là donnerait une erreur 400. Une clé que l'API OpenAI ne déclare pas est envoyée telle quelle, au premier niveau de la requête — par exemple `chat_template_kwargs: {enable_thinking: false}`, qui demande à un serveur llama.cpp (`dmr`, `llamacpp`, `llmman`) ou à Kronk de ne pas raisonner ; `reasoning_effort: none` fait de même avec Ollama. `messages`, `tools`, `tool_choice` (et les anciens `functions`, `function_call`) sont ignorées : Genkit les construit à partir de la conversation. L'`agent.yaml` livré ajoute `parallel_tool_calls: false`. `max_tokens` borne aussi un appel d'outil : un `write_file` de long document (ou le raisonnement d'un modèle « thinking » plus l'appel) peut l'atteindre, et l'appel est alors coupé. mm le rend deux fois au modèle en lui demandant de procéder par morceaux, puis s'arrête avec `the model hit max_tokens (N) while writing a tool call` ; augmentez la valeur si cela arrive. Une configuration qui nomme la limite `max_completion_tokens` (le nom de l'API OpenAI pour ses modèles récents) est lue de la même façon : ce nom est repris dans ce message et dans la requête de résumé de la compression du contexte. En streaming, mm demande aussi au serveur le compte des tokens (`stream_options.include_usage`). |
42 | `watchdogTimeout` | durée | `20s` | Silence toléré entre deux tokens diffusés avant de déclarer la connexion bloquée. Doublé pour les requêtes de résumé. |43 | `watchdogTimeout` | durée | `20s` | Silence toléré entre deux tokens diffusés avant de déclarer la connexion bloquée. Doublé pour les requêtes de résumé. |
modified internal/acpcreate/ask.go +2 -0
@@ -115,6 +115,8 @@ var agentDeps = map[string][]string{
115115 "yolo": {"usage"},
116116 "name": {"usage"},
117117 "skills": {"project"},
118+ "autostart": {"provider", "endpoint"},
119+ "launch": {"autostart"},
118120 "file": {"project"},
119121 "overwrite": {"file"},
120122 }
@@ -115,6 +115,8 @@ var agentDeps = map[string][]string{
115 "yolo": {"usage"},115 "yolo": {"usage"},
116 "name": {"usage"},116 "name": {"usage"},
117 "skills": {"project"},117 "skills": {"project"},
118+ "autostart": {"provider", "endpoint"},
119+ "launch": {"autostart"},
118 "file": {"project"},120 "file": {"project"},
119 "overwrite": {"file"},121 "overwrite": {"file"},
120 }122 }
modified internal/agentinit/decide.go +6 -0
@@ -27,6 +27,12 @@ type Choices struct {
2727 // Skills writes a skillsDir (skills, or .mm/skills with Project) and
2828 // creates that folder. nil = no: skillsDir: no-skills.
2929 Skills *bool
30+ // AutoStart (ticket 223, provider llamacpp on this machine): mm starts
31+ // llama-server when nothing answers. nil = yes, the question's default.
32+ AutoStart *bool
33+ // Launch (ticket 257): write llama-server's launch settings — the
34+ // values the Llama app starts its server with. nil = no.
35+ Launch *bool
3036 }
3137
3238 // on reads an optional yes/no answer: nil is no.
@@ -27,6 +27,12 @@ type Choices struct {
27 // Skills writes a skillsDir (skills, or .mm/skills with Project) and27 // Skills writes a skillsDir (skills, or .mm/skills with Project) and
28 // creates that folder. nil = no: skillsDir: no-skills.28 // creates that folder. nil = no: skillsDir: no-skills.
29 Skills *bool29 Skills *bool
30+ // AutoStart (ticket 223, provider llamacpp on this machine): mm starts
31+ // llama-server when nothing answers. nil = yes, the question's default.
32+ AutoStart *bool
33+ // Launch (ticket 257): write llama-server's launch settings — the
34+ // values the Llama app starts its server with. nil = no.
35+ Launch *bool
30 }36 }
31 37
32 // on reads an optional yes/no answer: nil is no.38 // on reads an optional yes/no answer: nil is no.
modified internal/agentinit/decide_test.go +74 -0
@@ -1,6 +1,7 @@
11 package agentinit
22
33 import (
4+ "context"
45 "os"
56 "path/filepath"
67 "strings"
@@ -177,6 +178,16 @@ func TestRenderRecordsTheDefaultURLs(t *testing.T) {
177178 if strings.Contains(own, "For the record") || !strings.Contains(own, "baseUrl: \"http://box:17434/v1\"") {
178179 t.Errorf("a file with its own baseUrl:\n%s", own)
179180 }
181+ // Ticket 223: a llamacpp file on this machine lets mm start the server;
182+ // one on another machine cannot, and gets no block.
183+ if !strings.Contains(llamacpp, "llamacpp:\n autoStart: true\n") {
184+ t.Errorf("llamacpp without the autoStart block:\n%s", llamacpp)
185+ }
186+ loadRendered(t, llamacpp)
187+ remote := Render(Decide(p, Choices{Provider: "llamacpp", BaseURL: "http://box:9931/v1", Model: "qwen3", Usage: "assistant", Machine: "small"}, Facts{}))
188+ if strings.Contains(remote, "autoStart") || strings.Contains(llmman, "autoStart") {
189+ t.Errorf("autoStart written for a remote llamacpp or for llmman")
190+ }
180191 // Uncommented, the two lines are the same settings, written out.
181192 uncommented := strings.Replace(strings.Replace(llmman, "# baseUrl:", "baseUrl:", 1), "# fallback:", "fallback:", 1)
182193 loadRendered(t, uncommented)
@@ -317,3 +328,66 @@ func TestRenderAcpNameAndTitle(t *testing.T) {
317328 }
318329 }
319330 }
331+
332+// Tickets 223 and 257: the autostart answer is written as is (yes when not
333+// asked), the launch settings only when asked for — and mm loads the file
334+// with every one of them.
335+func TestRenderLlamaCppAutoStartAndLaunchSettings(t *testing.T) {
336+ p, _ := LoadPresets()
337+ yes, no := true, false
338+ render := func(start, launch *bool) string {
339+ return Render(Decide(p, Choices{Provider: "llamacpp", Model: "org/m-GGUF:Q4_K_M", Usage: "assistant", Machine: "small", AutoStart: start, Launch: launch}, Facts{}))
340+ }
341+ off := render(&no, nil)
342+ if !strings.Contains(off, "llamacpp:\n autoStart: false\n") || strings.Contains(off, "modelsMax") {
343+ t.Errorf("autostart no:\n%s", off)
344+ }
345+ plain := render(&yes, &no)
346+ if !strings.Contains(plain, " autoStart: true\n") || strings.Contains(plain, "modelsMax") {
347+ t.Errorf("autostart yes, no launch settings:\n%s", plain)
348+ }
349+ full := render(&yes, &yes)
350+ for _, want := range []string{" modelsMax: 0 ", " modelsMemoryMargin: 1024 ", " fitTarget: 1024 ", " sleepIdleSeconds: 300 ", " specDefault: true "} {
351+ if !strings.Contains(full, want) {
352+ t.Errorf("launch settings lack %q:\n%s", want, full)
353+ }
354+ }
355+ loadRendered(t, full)
356+ // loadRendered restores Cfg at cleanup only: Cfg is what it loaded.
357+ if got := strings.Join(config.Cfg.LlamaCpp.LaunchArgs(), " "); got != "--models-max 0 --models-memory-margin 1024 --fit-target 1024 --sleep-idle-seconds 300 --spec-default" || !config.Cfg.LlamaCpp.AutoStart {
358+ t.Errorf("loaded: autoStart %v, launch args %q", config.Cfg.LlamaCpp.AutoStart, got)
359+ }
360+ loadRendered(t, off)
361+}
362+
363+// The two questions exist only for llamacpp on this machine, and the
364+// launch settings only once the start is on.
365+func TestFlowAsksAutoStartForALocalLlamaCpp(t *testing.T) {
366+ p, _ := LoadPresets()
367+ keys := func(f *Flow) string {
368+ var k []string
369+ for _, st := range f.Steps() {
370+ k = append(k, st.Key)
371+ }
372+ return strings.Join(k, ",")
373+ }
374+ f := NewFlow(context.Background(), p, Choices{Provider: "llamacpp"}, "")
375+ if k := keys(f); !strings.Contains(k, "skills,autostart,launch,name") {
376+ t.Errorf("llamacpp steps: %s", k)
377+ }
378+ if st := f.Step("autostart"); st.Default != "yes" {
379+ t.Errorf("autostart default %q, want yes", st.Default)
380+ }
381+ if st := f.Step("launch"); st.Default != "no" {
382+ t.Errorf("launch default %q, want no", st.Default)
383+ }
384+ _ = f.Set("autostart", "no")
385+ if k := keys(f); strings.Contains(k, "launch") {
386+ t.Errorf("autostart no, launch still asked: %s", k)
387+ }
388+ for _, c := range []Choices{{Provider: "llmman"}, {Provider: "llamacpp", BaseURL: "http://box:9931/v1"}} {
389+ if k := keys(NewFlow(context.Background(), p, c, "")); strings.Contains(k, "autostart") {
390+ t.Errorf("%s %s: asks autostart: %s", c.Provider, c.BaseURL, k)
391+ }
392+ }
393+}
@@ -1,6 +1,7 @@
1 package agentinit1 package agentinit
2 2
3 import (3 import (
4+ "context"
4 "os"5 "os"
5 "path/filepath"6 "path/filepath"
6 "strings"7 "strings"
@@ -177,6 +178,16 @@ func TestRenderRecordsTheDefaultURLs(t *testing.T) {
177 if strings.Contains(own, "For the record") || !strings.Contains(own, "baseUrl: \"http://box:17434/v1\"") {178 if strings.Contains(own, "For the record") || !strings.Contains(own, "baseUrl: \"http://box:17434/v1\"") {
178 t.Errorf("a file with its own baseUrl:\n%s", own)179 t.Errorf("a file with its own baseUrl:\n%s", own)
179 }180 }
181+ // Ticket 223: a llamacpp file on this machine lets mm start the server;
182+ // one on another machine cannot, and gets no block.
183+ if !strings.Contains(llamacpp, "llamacpp:\n autoStart: true\n") {
184+ t.Errorf("llamacpp without the autoStart block:\n%s", llamacpp)
185+ }
186+ loadRendered(t, llamacpp)
187+ remote := Render(Decide(p, Choices{Provider: "llamacpp", BaseURL: "http://box:9931/v1", Model: "qwen3", Usage: "assistant", Machine: "small"}, Facts{}))
188+ if strings.Contains(remote, "autoStart") || strings.Contains(llmman, "autoStart") {
189+ t.Errorf("autoStart written for a remote llamacpp or for llmman")
190+ }
180 // Uncommented, the two lines are the same settings, written out.191 // Uncommented, the two lines are the same settings, written out.
181 uncommented := strings.Replace(strings.Replace(llmman, "# baseUrl:", "baseUrl:", 1), "# fallback:", "fallback:", 1)192 uncommented := strings.Replace(strings.Replace(llmman, "# baseUrl:", "baseUrl:", 1), "# fallback:", "fallback:", 1)
182 loadRendered(t, uncommented)193 loadRendered(t, uncommented)
@@ -317,3 +328,66 @@ func TestRenderAcpNameAndTitle(t *testing.T) {
317 }328 }
318 }329 }
319 }330 }
331+
332+// Tickets 223 and 257: the autostart answer is written as is (yes when not
333+// asked), the launch settings only when asked for — and mm loads the file
334+// with every one of them.
335+func TestRenderLlamaCppAutoStartAndLaunchSettings(t *testing.T) {
336+ p, _ := LoadPresets()
337+ yes, no := true, false
338+ render := func(start, launch *bool) string {
339+ return Render(Decide(p, Choices{Provider: "llamacpp", Model: "org/m-GGUF:Q4_K_M", Usage: "assistant", Machine: "small", AutoStart: start, Launch: launch}, Facts{}))
340+ }
341+ off := render(&no, nil)
342+ if !strings.Contains(off, "llamacpp:\n autoStart: false\n") || strings.Contains(off, "modelsMax") {
343+ t.Errorf("autostart no:\n%s", off)
344+ }
345+ plain := render(&yes, &no)
346+ if !strings.Contains(plain, " autoStart: true\n") || strings.Contains(plain, "modelsMax") {
347+ t.Errorf("autostart yes, no launch settings:\n%s", plain)
348+ }
349+ full := render(&yes, &yes)
350+ for _, want := range []string{" modelsMax: 0 ", " modelsMemoryMargin: 1024 ", " fitTarget: 1024 ", " sleepIdleSeconds: 300 ", " specDefault: true "} {
351+ if !strings.Contains(full, want) {
352+ t.Errorf("launch settings lack %q:\n%s", want, full)
353+ }
354+ }
355+ loadRendered(t, full)
356+ // loadRendered restores Cfg at cleanup only: Cfg is what it loaded.
357+ if got := strings.Join(config.Cfg.LlamaCpp.LaunchArgs(), " "); got != "--models-max 0 --models-memory-margin 1024 --fit-target 1024 --sleep-idle-seconds 300 --spec-default" || !config.Cfg.LlamaCpp.AutoStart {
358+ t.Errorf("loaded: autoStart %v, launch args %q", config.Cfg.LlamaCpp.AutoStart, got)
359+ }
360+ loadRendered(t, off)
361+}
362+
363+// The two questions exist only for llamacpp on this machine, and the
364+// launch settings only once the start is on.
365+func TestFlowAsksAutoStartForALocalLlamaCpp(t *testing.T) {
366+ p, _ := LoadPresets()
367+ keys := func(f *Flow) string {
368+ var k []string
369+ for _, st := range f.Steps() {
370+ k = append(k, st.Key)
371+ }
372+ return strings.Join(k, ",")
373+ }
374+ f := NewFlow(context.Background(), p, Choices{Provider: "llamacpp"}, "")
375+ if k := keys(f); !strings.Contains(k, "skills,autostart,launch,name") {
376+ t.Errorf("llamacpp steps: %s", k)
377+ }
378+ if st := f.Step("autostart"); st.Default != "yes" {
379+ t.Errorf("autostart default %q, want yes", st.Default)
380+ }
381+ if st := f.Step("launch"); st.Default != "no" {
382+ t.Errorf("launch default %q, want no", st.Default)
383+ }
384+ _ = f.Set("autostart", "no")
385+ if k := keys(f); strings.Contains(k, "launch") {
386+ t.Errorf("autostart no, launch still asked: %s", k)
387+ }
388+ for _, c := range []Choices{{Provider: "llmman"}, {Provider: "llamacpp", BaseURL: "http://box:9931/v1"}} {
389+ if k := keys(NewFlow(context.Background(), p, c, "")); strings.Contains(k, "autostart") {
390+ t.Errorf("%s %s: asks autostart: %s", c.Provider, c.BaseURL, k)
391+ }
392+ }
393+}
modified internal/agentinit/flow.go +41 -2
@@ -47,12 +47,13 @@ type Step struct {
4747 // OpenAI-compatible service — OpenAI, Cerebras, Hugging Face… — so its
4848 // address and the variable holding its key are the user's to give.
4949 // project comes first (ticket 205): it decides where everything else goes.
50-var stepKeys = []string{"project", "provider", "endpoint", "keyenv", "model", "family", "usage", "machine", "yolo", "sessions", "skills", "name", "file"}
50+var stepKeys = []string{"project", "provider", "endpoint", "keyenv", "model", "family", "usage", "machine", "yolo", "sessions", "skills", "autostart", "launch", "name", "file"}
5151
5252 var stepTitles = map[string]string{
5353 "provider": "Server", "endpoint": "Endpoint", "keyenv": "API key", "model": "Model", "family": "Family",
5454 "usage": "Usage", "machine": "Machine", "yolo": "Ask first", "name": "Name", "file": "File", "overwrite": "Overwrite",
5555 "project": "Project", "sessions": "Sessions", "skills": "Skills",
56+ "autostart": "Start server", "launch": "Server settings",
5657 }
5758
5859 // defaultKeyEnv is where the openai provider reads its key when the file
@@ -114,7 +115,7 @@ func NewFlow(ctx context.Context, p Presets, given Choices, output string) *Flow
114115 f.given[key], f.answer[key] = true, value
115116 }
116117 }
117- for key, value := range map[string]*bool{"yolo": given.Yolo, "project": given.Project, "sessions": given.Sessions, "skills": given.Skills} {
118+ for key, value := range map[string]*bool{"yolo": given.Yolo, "project": given.Project, "sessions": given.Sessions, "skills": given.Skills, "autostart": given.AutoStart, "launch": given.Launch} {
118119 if value != nil {
119120 f.given[key], f.answer[key] = true, yesNo(*value)
120121 }
@@ -147,6 +148,9 @@ func (f *Flow) Steps() []Step {
147148 if (key == "endpoint" || key == "keyenv") && !isOpenAI(f.c.Provider) {
148149 continue
149150 }
151+ if (key == "autostart" && !f.asksAutoStart()) || (key == "launch" && !(f.asksAutoStart() && autoStartOn(f.c.AutoStart))) {
152+ continue
153+ }
150154 out = append(out, f.Step(key))
151155 }
152156 if asksOverwrite {
@@ -174,6 +178,15 @@ func (f *Flow) Pending() []Step {
174178 return out
175179 }
176180
181+// asksAutoStart: mm can start the server only for llamacpp on this machine.
182+func (f *Flow) asksAutoStart() bool {
183+ return f.c.Provider == "llamacpp" && localURL(f.c.BaseURL)
184+}
185+
186+// autoStartOn reads the autostart answer: nil (not asked yet) is its
187+// default, yes.
188+func autoStartOn(b *bool) bool { return b == nil || *b }
189+
177190 func (f *Flow) asksYolo() bool {
178191 u, ok := f.presets.Usage(f.usageOrDefault())
179192 return ok && (u.Tools["bashTool"] || u.Tools["editTools"] || u.Tools["fetchContentTool"])
@@ -269,6 +282,15 @@ func (f *Flow) Step(key string) Step {
269282 st = yesNoStep(st, "Use skills?",
270283 "writes skillsDir: "+f.c.SkillsDir()+" and creates that folder",
271284 "skillsDir: no-skills")
285+ case "autostart":
286+ st = yesNoStep(st, "Let mm start llama-server when it is not running?",
287+ "llamacpp.autoStart: true — mm starts it with this model (downloaded on first use) and stops it with the last mm session",
288+ "llamacpp.autoStart: false — you start llama-server yourself")
289+ st.Default = "yes"
290+ case "launch":
291+ st = yesNoStep(st, "Write llama-server's launch settings?",
292+ "the Llama app's values (modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault), each one editable or removable",
293+ "none: llama-server's own defaults")
272294 case "file":
273295 st.Prompt, st.Kind, st.Default = "File to write?", elicit.Text, f.defaultFile()
274296 case "overwrite":
@@ -399,6 +421,19 @@ func (f *Flow) Set(key, value string) error {
399421 if err := setYesNo(key, value, &f.c.Skills); err != nil {
400422 return err
401423 }
424+ case "autostart":
425+ if err := setYesNo(key, value, &f.c.AutoStart); err != nil {
426+ return err
427+ }
428+ if !on(f.c.AutoStart) && !f.given["launch"] {
429+ // No start, no launch settings: the question is gone.
430+ f.c.Launch = nil
431+ delete(f.answer, "launch")
432+ }
433+ case "launch":
434+ if err := setYesNo(key, value, &f.c.Launch); err != nil {
435+ return err
436+ }
402437 case "name":
403438 f.c.Name = value
404439 case "file":
@@ -478,6 +513,10 @@ func (f *Flow) Unset(key string) {
478513 f.c.Sessions = nil
479514 case "skills":
480515 f.c.Skills = nil
516+ case "autostart":
517+ f.c.AutoStart = nil
518+ case "launch":
519+ f.c.Launch = nil
481520 case "name":
482521 f.c.Name = ""
483522 case "file":
@@ -47,12 +47,13 @@ type Step struct {
47 // OpenAI-compatible service — OpenAI, Cerebras, Hugging Face… — so its47 // OpenAI-compatible service — OpenAI, Cerebras, Hugging Face… — so its
48 // address and the variable holding its key are the user's to give.48 // address and the variable holding its key are the user's to give.
49 // project comes first (ticket 205): it decides where everything else goes.49 // project comes first (ticket 205): it decides where everything else goes.
50-var stepKeys = []string{"project", "provider", "endpoint", "keyenv", "model", "family", "usage", "machine", "yolo", "sessions", "skills", "name", "file"}50+var stepKeys = []string{"project", "provider", "endpoint", "keyenv", "model", "family", "usage", "machine", "yolo", "sessions", "skills", "autostart", "launch", "name", "file"}
51 51
52 var stepTitles = map[string]string{52 var stepTitles = map[string]string{
53 "provider": "Server", "endpoint": "Endpoint", "keyenv": "API key", "model": "Model", "family": "Family",53 "provider": "Server", "endpoint": "Endpoint", "keyenv": "API key", "model": "Model", "family": "Family",
54 "usage": "Usage", "machine": "Machine", "yolo": "Ask first", "name": "Name", "file": "File", "overwrite": "Overwrite",54 "usage": "Usage", "machine": "Machine", "yolo": "Ask first", "name": "Name", "file": "File", "overwrite": "Overwrite",
55 "project": "Project", "sessions": "Sessions", "skills": "Skills",55 "project": "Project", "sessions": "Sessions", "skills": "Skills",
56+ "autostart": "Start server", "launch": "Server settings",
56 }57 }
57 58
58 // defaultKeyEnv is where the openai provider reads its key when the file59 // defaultKeyEnv is where the openai provider reads its key when the file
@@ -114,7 +115,7 @@ func NewFlow(ctx context.Context, p Presets, given Choices, output string) *Flow
114 f.given[key], f.answer[key] = true, value115 f.given[key], f.answer[key] = true, value
115 }116 }
116 }117 }
117- for key, value := range map[string]*bool{"yolo": given.Yolo, "project": given.Project, "sessions": given.Sessions, "skills": given.Skills} {118+ for key, value := range map[string]*bool{"yolo": given.Yolo, "project": given.Project, "sessions": given.Sessions, "skills": given.Skills, "autostart": given.AutoStart, "launch": given.Launch} {
118 if value != nil {119 if value != nil {
119 f.given[key], f.answer[key] = true, yesNo(*value)120 f.given[key], f.answer[key] = true, yesNo(*value)
120 }121 }
@@ -147,6 +148,9 @@ func (f *Flow) Steps() []Step {
147 if (key == "endpoint" || key == "keyenv") && !isOpenAI(f.c.Provider) {148 if (key == "endpoint" || key == "keyenv") && !isOpenAI(f.c.Provider) {
148 continue149 continue
149 }150 }
151+ if (key == "autostart" && !f.asksAutoStart()) || (key == "launch" && !(f.asksAutoStart() && autoStartOn(f.c.AutoStart))) {
152+ continue
153+ }
150 out = append(out, f.Step(key))154 out = append(out, f.Step(key))
151 }155 }
152 if asksOverwrite {156 if asksOverwrite {
@@ -174,6 +178,15 @@ func (f *Flow) Pending() []Step {
174 return out178 return out
175 }179 }
176 180
181+// asksAutoStart: mm can start the server only for llamacpp on this machine.
182+func (f *Flow) asksAutoStart() bool {
183+ return f.c.Provider == "llamacpp" && localURL(f.c.BaseURL)
184+}
185+
186+// autoStartOn reads the autostart answer: nil (not asked yet) is its
187+// default, yes.
188+func autoStartOn(b *bool) bool { return b == nil || *b }
189+
177 func (f *Flow) asksYolo() bool {190 func (f *Flow) asksYolo() bool {
178 u, ok := f.presets.Usage(f.usageOrDefault())191 u, ok := f.presets.Usage(f.usageOrDefault())
179 return ok && (u.Tools["bashTool"] || u.Tools["editTools"] || u.Tools["fetchContentTool"])192 return ok && (u.Tools["bashTool"] || u.Tools["editTools"] || u.Tools["fetchContentTool"])
@@ -269,6 +282,15 @@ func (f *Flow) Step(key string) Step {
269 st = yesNoStep(st, "Use skills?",282 st = yesNoStep(st, "Use skills?",
270 "writes skillsDir: "+f.c.SkillsDir()+" and creates that folder",283 "writes skillsDir: "+f.c.SkillsDir()+" and creates that folder",
271 "skillsDir: no-skills")284 "skillsDir: no-skills")
285+ case "autostart":
286+ st = yesNoStep(st, "Let mm start llama-server when it is not running?",
287+ "llamacpp.autoStart: true — mm starts it with this model (downloaded on first use) and stops it with the last mm session",
288+ "llamacpp.autoStart: false — you start llama-server yourself")
289+ st.Default = "yes"
290+ case "launch":
291+ st = yesNoStep(st, "Write llama-server's launch settings?",
292+ "the Llama app's values (modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault), each one editable or removable",
293+ "none: llama-server's own defaults")
272 case "file":294 case "file":
273 st.Prompt, st.Kind, st.Default = "File to write?", elicit.Text, f.defaultFile()295 st.Prompt, st.Kind, st.Default = "File to write?", elicit.Text, f.defaultFile()
274 case "overwrite":296 case "overwrite":
@@ -399,6 +421,19 @@ func (f *Flow) Set(key, value string) error {
399 if err := setYesNo(key, value, &f.c.Skills); err != nil {421 if err := setYesNo(key, value, &f.c.Skills); err != nil {
400 return err422 return err
401 }423 }
424+ case "autostart":
425+ if err := setYesNo(key, value, &f.c.AutoStart); err != nil {
426+ return err
427+ }
428+ if !on(f.c.AutoStart) && !f.given["launch"] {
429+ // No start, no launch settings: the question is gone.
430+ f.c.Launch = nil
431+ delete(f.answer, "launch")
432+ }
433+ case "launch":
434+ if err := setYesNo(key, value, &f.c.Launch); err != nil {
435+ return err
436+ }
402 case "name":437 case "name":
403 f.c.Name = value438 f.c.Name = value
404 case "file":439 case "file":
@@ -478,6 +513,10 @@ func (f *Flow) Unset(key string) {
478 f.c.Sessions = nil513 f.c.Sessions = nil
479 case "skills":514 case "skills":
480 f.c.Skills = nil515 f.c.Skills = nil
516+ case "autostart":
517+ f.c.AutoStart = nil
518+ case "launch":
519+ f.c.Launch = nil
481 case "name":520 case "name":
482 f.c.Name = ""521 f.c.Name = ""
483 case "file":522 case "file":
modified internal/agentinit/render.go +55 -0
@@ -2,6 +2,8 @@ package agentinit
22
33 import (
44 "fmt"
5+ "net"
6+ "net/url"
57 "strconv"
68 "strings"
79 "unicode"
@@ -45,6 +47,9 @@ func Render(s Settings) string {
4547 if isOpenAI(c.Provider) {
4648 writeKeyEnv(&b, c)
4749 }
50+ if c.Provider == "llamacpp" && localURL(c.BaseURL) {
51+ writeLlamaCpp(&b, c)
52+ }
4853 b.WriteString("\n")
4954
5055 writeSettings(&b, "", s.Top)
@@ -319,3 +324,53 @@ func wrap(text string, width int) []string {
319324 }
320325 return out
321326 }
327+
328+// writeLlamaCpp writes the llamacpp block (tickets 223, 257): autoStart as
329+// answered (yes when not asked), and the launch settings when asked for —
330+// the values the Llama app starts its server with.
331+func writeLlamaCpp(b *strings.Builder, c Choices) {
332+ if !autoStartOn(c.AutoStart) {
333+ b.WriteString("# true: mm starts llama-server when nothing answers, and stops it with the\n# last mm session using it.\nllamacpp:\n autoStart: false\n")
334+ return
335+ }
336+ b.WriteString(`# Nothing answers at this address: mm starts llama-server (router mode, this
337+# model, downloaded on first use) and stops it with the last mm session using
338+# it. A server you started yourself is never stopped. false: start it yourself.
339+llamacpp:
340+ autoStart: true
341+`)
342+ if on(c.Launch) {
343+ b.WriteString(llamaLaunch)
344+ }
345+}
346+
347+// llamaLaunch is the launch settings block: the Llama app's values. Each
348+// key is one llama-server flag; a key removed takes llama-server's default.
349+const llamaLaunch = ` # Launch settings, the Llama app's values: each key is one llama-server
350+ # flag; remove a key and llama-server keeps its own default.
351+ # ctxSize: 32768 # --ctx-size (default: the model's own window)
352+ modelsMax: 0 # --models-max: 0 = no limit on loaded models (default 4)
353+ modelsMemoryMargin: 1024 # --models-memory-margin: MiB kept free (default 0 = off)
354+ fitTarget: 1024 # --fit-target: MiB margin per device (default 1024)
355+ sleepIdleSeconds: 300 # --sleep-idle-seconds: free the model when idle (default -1 = never)
356+ specDefault: true # --spec-default: default speculative decoding
357+ # serverArgs: [] # any other flag
358+`
359+
360+// localURL reports whether a base URL is on this machine — the default
361+// (empty) or a loopback host: the only place mm can start a server.
362+func localURL(base string) bool {
363+ if base == "" {
364+ return true
365+ }
366+ u, err := url.Parse(base)
367+ if err != nil {
368+ return false
369+ }
370+ h := u.Hostname()
371+ if h == "localhost" {
372+ return true
373+ }
374+ ip := net.ParseIP(h)
375+ return ip != nil && ip.IsLoopback()
376+}
@@ -2,6 +2,8 @@ package agentinit
2 2
3 import (3 import (
4 "fmt"4 "fmt"
5+ "net"
6+ "net/url"
5 "strconv"7 "strconv"
6 "strings"8 "strings"
7 "unicode"9 "unicode"
@@ -45,6 +47,9 @@ func Render(s Settings) string {
45 if isOpenAI(c.Provider) {47 if isOpenAI(c.Provider) {
46 writeKeyEnv(&b, c)48 writeKeyEnv(&b, c)
47 }49 }
50+ if c.Provider == "llamacpp" && localURL(c.BaseURL) {
51+ writeLlamaCpp(&b, c)
52+ }
48 b.WriteString("\n")53 b.WriteString("\n")
49 54
50 writeSettings(&b, "", s.Top)55 writeSettings(&b, "", s.Top)
@@ -319,3 +324,53 @@ func wrap(text string, width int) []string {
319 }324 }
320 return out325 return out
321 }326 }
327+
328+// writeLlamaCpp writes the llamacpp block (tickets 223, 257): autoStart as
329+// answered (yes when not asked), and the launch settings when asked for —
330+// the values the Llama app starts its server with.
331+func writeLlamaCpp(b *strings.Builder, c Choices) {
332+ if !autoStartOn(c.AutoStart) {
333+ b.WriteString("# true: mm starts llama-server when nothing answers, and stops it with the\n# last mm session using it.\nllamacpp:\n autoStart: false\n")
334+ return
335+ }
336+ b.WriteString(`# Nothing answers at this address: mm starts llama-server (router mode, this
337+# model, downloaded on first use) and stops it with the last mm session using
338+# it. A server you started yourself is never stopped. false: start it yourself.
339+llamacpp:
340+ autoStart: true
341+`)
342+ if on(c.Launch) {
343+ b.WriteString(llamaLaunch)
344+ }
345+}
346+
347+// llamaLaunch is the launch settings block: the Llama app's values. Each
348+// key is one llama-server flag; a key removed takes llama-server's default.
349+const llamaLaunch = ` # Launch settings, the Llama app's values: each key is one llama-server
350+ # flag; remove a key and llama-server keeps its own default.
351+ # ctxSize: 32768 # --ctx-size (default: the model's own window)
352+ modelsMax: 0 # --models-max: 0 = no limit on loaded models (default 4)
353+ modelsMemoryMargin: 1024 # --models-memory-margin: MiB kept free (default 0 = off)
354+ fitTarget: 1024 # --fit-target: MiB margin per device (default 1024)
355+ sleepIdleSeconds: 300 # --sleep-idle-seconds: free the model when idle (default -1 = never)
356+ specDefault: true # --spec-default: default speculative decoding
357+ # serverArgs: [] # any other flag
358+`
359+
360+// localURL reports whether a base URL is on this machine — the default
361+// (empty) or a loopback host: the only place mm can start a server.
362+func localURL(base string) bool {
363+ if base == "" {
364+ return true
365+ }
366+ u, err := url.Parse(base)
367+ if err != nil {
368+ return false
369+ }
370+ h := u.Hostname()
371+ if h == "localhost" {
372+ return true
373+ }
374+ ip := net.ParseIP(h)
375+ return ip != nil && ip.IsLoopback()
376+}
modified internal/agentinit/wizard.go +4 -2
@@ -115,7 +115,7 @@ func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a
115115 fs := flag.NewFlagSet(name, flag.ContinueOnError)
116116 fs.SetOutput(out)
117117 c := &a.Choices
118- var yolo, project, sessions, skills string
118+ var yolo, project, sessions, skills, autostart, launch string
119119 fs.StringVar(&c.Provider, "provider", "", "model server: "+strings.Join(providers, ", "))
120120 fs.StringVar(&c.BaseURL, "base-url", "", "the server's OpenAI-compatible address (default: the provider's); for openai, the endpoint question")
121121 fs.StringVar(&c.APIKeyEnv, "api-key-env", "", "openai: the environment variable that holds the API key (default OPENAI_API_KEY)")
@@ -128,6 +128,8 @@ func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a
128128 fs.StringVar(&project, "project", "", "yes: create .mm/ and write .mm/agent.yaml, paths from the project root; no: one agent.yaml (default: no)")
129129 fs.StringVar(&sessions, "sessions", "", "yes: write a sessions section that saves every conversation; no: none (default: no)")
130130 fs.StringVar(&skills, "skills", "", "yes: write skillsDir and create the folder (skills/, or .mm/skills/ with --project yes); no: skillsDir: no-skills (default: no)")
131+ fs.StringVar(&autostart, "autostart", "", "llamacpp on this machine — yes: mm starts llama-server when it is not running and stops it with the last session; no: you start it (default: yes)")
132+ fs.StringVar(&launch, "launch-settings", "", "llamacpp with --autostart yes — yes: write llama-server's launch settings (the Llama app's values); no: llama-server's defaults (default: no)")
131133 fs.StringVar(&a.Output, "o", "", "the file to write (default agent.yaml, .mm/agent.yaml with --project yes; - for stdout, which creates nothing); an existing file is replaced only if you agree, never with --yes")
132134 fs.StringVar(&a.Output, "output", "", "same as -o")
133135 if lineSwitches {
@@ -154,7 +156,7 @@ func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a
154156 for flagName, value := range map[string]struct {
155157 text string
156158 target **bool
157- }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}} {
159+ }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}, "autostart": {autostart, &c.AutoStart}, "launch-settings": {launch, &c.Launch}} {
158160 if value.text == "" {
159161 continue
160162 }
@@ -115,7 +115,7 @@ func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a
115 fs := flag.NewFlagSet(name, flag.ContinueOnError)115 fs := flag.NewFlagSet(name, flag.ContinueOnError)
116 fs.SetOutput(out)116 fs.SetOutput(out)
117 c := &a.Choices117 c := &a.Choices
118- var yolo, project, sessions, skills string118+ var yolo, project, sessions, skills, autostart, launch string
119 fs.StringVar(&c.Provider, "provider", "", "model server: "+strings.Join(providers, ", "))119 fs.StringVar(&c.Provider, "provider", "", "model server: "+strings.Join(providers, ", "))
120 fs.StringVar(&c.BaseURL, "base-url", "", "the server's OpenAI-compatible address (default: the provider's); for openai, the endpoint question")120 fs.StringVar(&c.BaseURL, "base-url", "", "the server's OpenAI-compatible address (default: the provider's); for openai, the endpoint question")
121 fs.StringVar(&c.APIKeyEnv, "api-key-env", "", "openai: the environment variable that holds the API key (default OPENAI_API_KEY)")121 fs.StringVar(&c.APIKeyEnv, "api-key-env", "", "openai: the environment variable that holds the API key (default OPENAI_API_KEY)")
@@ -128,6 +128,8 @@ func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a
128 fs.StringVar(&project, "project", "", "yes: create .mm/ and write .mm/agent.yaml, paths from the project root; no: one agent.yaml (default: no)")128 fs.StringVar(&project, "project", "", "yes: create .mm/ and write .mm/agent.yaml, paths from the project root; no: one agent.yaml (default: no)")
129 fs.StringVar(&sessions, "sessions", "", "yes: write a sessions section that saves every conversation; no: none (default: no)")129 fs.StringVar(&sessions, "sessions", "", "yes: write a sessions section that saves every conversation; no: none (default: no)")
130 fs.StringVar(&skills, "skills", "", "yes: write skillsDir and create the folder (skills/, or .mm/skills/ with --project yes); no: skillsDir: no-skills (default: no)")130 fs.StringVar(&skills, "skills", "", "yes: write skillsDir and create the folder (skills/, or .mm/skills/ with --project yes); no: skillsDir: no-skills (default: no)")
131+ fs.StringVar(&autostart, "autostart", "", "llamacpp on this machine — yes: mm starts llama-server when it is not running and stops it with the last session; no: you start it (default: yes)")
132+ fs.StringVar(&launch, "launch-settings", "", "llamacpp with --autostart yes — yes: write llama-server's launch settings (the Llama app's values); no: llama-server's defaults (default: no)")
131 fs.StringVar(&a.Output, "o", "", "the file to write (default agent.yaml, .mm/agent.yaml with --project yes; - for stdout, which creates nothing); an existing file is replaced only if you agree, never with --yes")133 fs.StringVar(&a.Output, "o", "", "the file to write (default agent.yaml, .mm/agent.yaml with --project yes; - for stdout, which creates nothing); an existing file is replaced only if you agree, never with --yes")
132 fs.StringVar(&a.Output, "output", "", "same as -o")134 fs.StringVar(&a.Output, "output", "", "same as -o")
133 if lineSwitches {135 if lineSwitches {
@@ -154,7 +156,7 @@ func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a
154 for flagName, value := range map[string]struct {156 for flagName, value := range map[string]struct {
155 text string157 text string
156 target **bool158 target **bool
157- }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}} {159+ }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}, "autostart": {autostart, &c.AutoStart}, "launch-settings": {launch, &c.Launch}} {
158 if value.text == "" {160 if value.text == "" {
159 continue161 continue
160 }162 }
modified internal/config/config.go +98 -0
@@ -199,6 +199,10 @@ type Config struct {
199199 // nothing. Override: AGENT_UNLOAD_ON_EXIT.
200200 UnloadOnExit bool `yaml:"unloadOnExit"`
201201
202+ // LlamaCpp: provider llamacpp only — mm starts llama-server itself
203+ // when nothing answers (ticket 223). See LlamaCppConfig.
204+ LlamaCpp LlamaCppConfig `yaml:"llamacpp"`
205+
202206 // Sampling: generation settings (OpenAI API keys; the plugin converts them.)
203207 Sampling map[string]any `yaml:"sampling"`
204208
@@ -321,6 +325,97 @@ const YoloEnv = "AGENT_YOLO"
321325 // mmConfigs entry says `askUser`.
322326 const AskUserEnv = "AGENT_ASK_USER"
323327
328+// LlamaCppConfig is the `llamacpp:` block (ticket 223, internal/llamastart).
329+//
330+// llamacpp:
331+// autoStart: true
332+// server: /opt/homebrew/bin/llama-server # default: llama-server, then llama, on the PATH
333+// ctxSize: 32768 # launch settings: absent = llama-server's default
334+// sleepIdleSeconds: 300
335+// serverArgs: [--no-webui] # any other flag
336+// startTimeout: 15m # start + download + load
337+type LlamaCppConfig struct {
338+ // AutoStart: when nothing answers at the agent's address (a loopback
339+ // one, no AGENT_BASE_URL) nor at the other llamacpp addresses, start
340+ // llama-server in router mode with the agent's model, wait until the
341+ // model is loaded, and stop the server with the last mm session using
342+ // it. Off by default; `mm init` writes true. A server mm did not start
343+ // is never stopped.
344+ AutoStart bool `yaml:"autoStart"`
345+ // Server is the llama-server (or `llama`) executable.
346+ Server string `yaml:"server"`
347+ // The launch settings (ticket 257), each one a llama-server flag. A key
348+ // left out is not passed: llama-server keeps its own default. The router
349+ // hands the model settings (ctxSize, fitTarget, sleepIdleSeconds,
350+ // specDefault) on to every model it loads (measured, build 12359).
351+ CtxSize *int `yaml:"ctxSize"` // --ctx-size; 0 = the model's own
352+ ModelsMax *int `yaml:"modelsMax"` // --models-max; 0 = unlimited (default 4)
353+ ModelsMemoryMargin *int `yaml:"modelsMemoryMargin"` // --models-memory-margin, MiB (default 0 = off)
354+ FitTarget *int `yaml:"fitTarget"` // --fit-target, MiB per device (default 1024)
355+ SleepIdleSeconds *int `yaml:"sleepIdleSeconds"` // --sleep-idle-seconds; -1 = never (default)
356+ SpecDefault bool `yaml:"specDefault"` // --spec-default: default speculative decoding
357+
358+ // ServerArgs are added after mm's own arguments and the settings above:
359+ // any flag that has no key.
360+ ServerArgs []string `yaml:"serverArgs"`
361+ // StartTimeout bounds the start, the model's download and its load.
362+ StartTimeout time.Duration `yaml:"startTimeout"`
363+}
364+
365+// LaunchArgs is the llama-server command line the launch settings make,
366+// then ServerArgs.
367+//
368+// llamacpp: {ctxSize: 32768, specDefault: true} → [--ctx-size 32768 --spec-default]
369+func (l LlamaCppConfig) LaunchArgs() []string {
370+ var args []string
371+ for _, f := range []struct {
372+ flag string
373+ value *int
374+ }{
375+ {"--ctx-size", l.CtxSize},
376+ {"--models-max", l.ModelsMax},
377+ {"--models-memory-margin", l.ModelsMemoryMargin},
378+ {"--fit-target", l.FitTarget},
379+ {"--sleep-idle-seconds", l.SleepIdleSeconds},
380+ } {
381+ if f.value != nil {
382+ args = append(args, f.flag, strconv.Itoa(*f.value))
383+ }
384+ }
385+ if l.SpecDefault {
386+ args = append(args, "--spec-default")
387+ }
388+ return append(args, l.ServerArgs...)
389+}
390+
391+// validate refuses a value llama-server would refuse at start-up — better
392+// a configuration error naming the key than a server that does not start.
393+func (l LlamaCppConfig) validate() error {
394+ for _, f := range []struct {
395+ key string
396+ value *int
397+ min int
398+ }{
399+ {"ctxSize", l.CtxSize, 0},
400+ {"modelsMax", l.ModelsMax, 0},
401+ {"modelsMemoryMargin", l.ModelsMemoryMargin, 0},
402+ {"fitTarget", l.FitTarget, 0},
403+ {"sleepIdleSeconds", l.SleepIdleSeconds, -1},
404+ } {
405+ if f.value != nil && *f.value < f.min {
406+ return fmt.Errorf("llamacpp.%s must be >= %d, not %d", f.key, f.min, *f.value)
407+ }
408+ }
409+ if l.StartTimeout < 0 {
410+ return errors.New("llamacpp.startTimeout must be >= 0")
411+ }
412+ return nil
413+}
414+
415+// DefaultLlamaStartTimeout is llamacpp.startTimeout when the file does not
416+// set it: a download of several GB fits in it on a usual connection.
417+const DefaultLlamaStartTimeout = 15 * time.Minute
418+
324419 // UnloadOnExitEnv names the variable that overrides `unloadOnExit` for one
325420 // run — `AGENT_UNLOAD_ON_EXIT=false mm -p …` in a loop keeps the model
326421 // loaded between the runs.
@@ -1028,6 +1123,9 @@ func (s LSPServer) claimExtension(where, e string, seen map[string]string) error
10281123
10291124 // validate catches the settings that would break the agent at runtime.
10301125 func (c Config) validate() error {
1126+ if err := c.LlamaCpp.validate(); err != nil {
1127+ return err
1128+ }
10311129 switch {
10321130 case c.Provider == "":
10331131 return errors.New("provider must not be empty")
@@ -199,6 +199,10 @@ type Config struct {
199 // nothing. Override: AGENT_UNLOAD_ON_EXIT.199 // nothing. Override: AGENT_UNLOAD_ON_EXIT.
200 UnloadOnExit bool `yaml:"unloadOnExit"`200 UnloadOnExit bool `yaml:"unloadOnExit"`
201 201
202+ // LlamaCpp: provider llamacpp only — mm starts llama-server itself
203+ // when nothing answers (ticket 223). See LlamaCppConfig.
204+ LlamaCpp LlamaCppConfig `yaml:"llamacpp"`
205+
202 // Sampling: generation settings (OpenAI API keys; the plugin converts them.)206 // Sampling: generation settings (OpenAI API keys; the plugin converts them.)
203 Sampling map[string]any `yaml:"sampling"`207 Sampling map[string]any `yaml:"sampling"`
204 208
@@ -321,6 +325,97 @@ const YoloEnv = "AGENT_YOLO"
321 // mmConfigs entry says `askUser`.325 // mmConfigs entry says `askUser`.
322 const AskUserEnv = "AGENT_ASK_USER"326 const AskUserEnv = "AGENT_ASK_USER"
323 327
328+// LlamaCppConfig is the `llamacpp:` block (ticket 223, internal/llamastart).
329+//
330+// llamacpp:
331+// autoStart: true
332+// server: /opt/homebrew/bin/llama-server # default: llama-server, then llama, on the PATH
333+// ctxSize: 32768 # launch settings: absent = llama-server's default
334+// sleepIdleSeconds: 300
335+// serverArgs: [--no-webui] # any other flag
336+// startTimeout: 15m # start + download + load
337+type LlamaCppConfig struct {
338+ // AutoStart: when nothing answers at the agent's address (a loopback
339+ // one, no AGENT_BASE_URL) nor at the other llamacpp addresses, start
340+ // llama-server in router mode with the agent's model, wait until the
341+ // model is loaded, and stop the server with the last mm session using
342+ // it. Off by default; `mm init` writes true. A server mm did not start
343+ // is never stopped.
344+ AutoStart bool `yaml:"autoStart"`
345+ // Server is the llama-server (or `llama`) executable.
346+ Server string `yaml:"server"`
347+ // The launch settings (ticket 257), each one a llama-server flag. A key
348+ // left out is not passed: llama-server keeps its own default. The router
349+ // hands the model settings (ctxSize, fitTarget, sleepIdleSeconds,
350+ // specDefault) on to every model it loads (measured, build 12359).
351+ CtxSize *int `yaml:"ctxSize"` // --ctx-size; 0 = the model's own
352+ ModelsMax *int `yaml:"modelsMax"` // --models-max; 0 = unlimited (default 4)
353+ ModelsMemoryMargin *int `yaml:"modelsMemoryMargin"` // --models-memory-margin, MiB (default 0 = off)
354+ FitTarget *int `yaml:"fitTarget"` // --fit-target, MiB per device (default 1024)
355+ SleepIdleSeconds *int `yaml:"sleepIdleSeconds"` // --sleep-idle-seconds; -1 = never (default)
356+ SpecDefault bool `yaml:"specDefault"` // --spec-default: default speculative decoding
357+
358+ // ServerArgs are added after mm's own arguments and the settings above:
359+ // any flag that has no key.
360+ ServerArgs []string `yaml:"serverArgs"`
361+ // StartTimeout bounds the start, the model's download and its load.
362+ StartTimeout time.Duration `yaml:"startTimeout"`
363+}
364+
365+// LaunchArgs is the llama-server command line the launch settings make,
366+// then ServerArgs.
367+//
368+// llamacpp: {ctxSize: 32768, specDefault: true} → [--ctx-size 32768 --spec-default]
369+func (l LlamaCppConfig) LaunchArgs() []string {
370+ var args []string
371+ for _, f := range []struct {
372+ flag string
373+ value *int
374+ }{
375+ {"--ctx-size", l.CtxSize},
376+ {"--models-max", l.ModelsMax},
377+ {"--models-memory-margin", l.ModelsMemoryMargin},
378+ {"--fit-target", l.FitTarget},
379+ {"--sleep-idle-seconds", l.SleepIdleSeconds},
380+ } {
381+ if f.value != nil {
382+ args = append(args, f.flag, strconv.Itoa(*f.value))
383+ }
384+ }
385+ if l.SpecDefault {
386+ args = append(args, "--spec-default")
387+ }
388+ return append(args, l.ServerArgs...)
389+}
390+
391+// validate refuses a value llama-server would refuse at start-up — better
392+// a configuration error naming the key than a server that does not start.
393+func (l LlamaCppConfig) validate() error {
394+ for _, f := range []struct {
395+ key string
396+ value *int
397+ min int
398+ }{
399+ {"ctxSize", l.CtxSize, 0},
400+ {"modelsMax", l.ModelsMax, 0},
401+ {"modelsMemoryMargin", l.ModelsMemoryMargin, 0},
402+ {"fitTarget", l.FitTarget, 0},
403+ {"sleepIdleSeconds", l.SleepIdleSeconds, -1},
404+ } {
405+ if f.value != nil && *f.value < f.min {
406+ return fmt.Errorf("llamacpp.%s must be >= %d, not %d", f.key, f.min, *f.value)
407+ }
408+ }
409+ if l.StartTimeout < 0 {
410+ return errors.New("llamacpp.startTimeout must be >= 0")
411+ }
412+ return nil
413+}
414+
415+// DefaultLlamaStartTimeout is llamacpp.startTimeout when the file does not
416+// set it: a download of several GB fits in it on a usual connection.
417+const DefaultLlamaStartTimeout = 15 * time.Minute
418+
324 // UnloadOnExitEnv names the variable that overrides `unloadOnExit` for one419 // UnloadOnExitEnv names the variable that overrides `unloadOnExit` for one
325 // run — `AGENT_UNLOAD_ON_EXIT=false mm -p …` in a loop keeps the model420 // run — `AGENT_UNLOAD_ON_EXIT=false mm -p …` in a loop keeps the model
326 // loaded between the runs.421 // loaded between the runs.
@@ -1028,6 +1123,9 @@ func (s LSPServer) claimExtension(where, e string, seen map[string]string) error
1028 1123
1029 // validate catches the settings that would break the agent at runtime.1124 // validate catches the settings that would break the agent at runtime.
1030 func (c Config) validate() error {1125 func (c Config) validate() error {
1126+ if err := c.LlamaCpp.validate(); err != nil {
1127+ return err
1128+ }
1031 switch {1129 switch {
1032 case c.Provider == "":1130 case c.Provider == "":
1033 return errors.New("provider must not be empty")1131 return errors.New("provider must not be empty")
added internal/config/llamacpp_test.go +29 -0
new file mode 100644
@@ -0,0 +1,29 @@
1+package config
2+
3+import (
4+ "strings"
5+ "testing"
6+)
7+
8+// Ticket 257: each launch setting is one llama-server flag, a key left out
9+// is not passed, serverArgs come last; a value llama-server refuses is a
10+// configuration error naming the key.
11+func TestLlamaCppLaunchArgs(t *testing.T) {
12+ n := func(v int) *int { return &v }
13+ if got := (LlamaCppConfig{}).LaunchArgs(); len(got) != 0 {
14+ t.Errorf("nothing set: %v, want no flag", got)
15+ }
16+ l := LlamaCppConfig{CtxSize: n(32768), ModelsMax: n(0), ModelsMemoryMargin: n(1024), FitTarget: n(1024),
17+ SleepIdleSeconds: n(300), SpecDefault: true, ServerArgs: []string{"--no-webui"}}
18+ want := "--ctx-size 32768 --models-max 0 --models-memory-margin 1024 --fit-target 1024 --sleep-idle-seconds 300 --spec-default --no-webui"
19+ if got := strings.Join(l.LaunchArgs(), " "); got != want {
20+ t.Errorf("all set:\n got %s\nwant %s", got, want)
21+ }
22+
23+ if err := (LlamaCppConfig{SleepIdleSeconds: n(-1)}).validate(); err != nil {
24+ t.Errorf("sleepIdleSeconds -1 (never): %v", err)
25+ }
26+ if err := (LlamaCppConfig{CtxSize: n(-5)}).validate(); err == nil || !strings.Contains(err.Error(), "llamacpp.ctxSize") {
27+ t.Errorf("ctxSize -5: %v, want an error naming the key", err)
28+ }
29+}
new file mode 100644
@@ -0,0 +1,29 @@
1+package config
2+
3+import (
4+ "strings"
5+ "testing"
6+)
7+
8+// Ticket 257: each launch setting is one llama-server flag, a key left out
9+// is not passed, serverArgs come last; a value llama-server refuses is a
10+// configuration error naming the key.
11+func TestLlamaCppLaunchArgs(t *testing.T) {
12+ n := func(v int) *int { return &v }
13+ if got := (LlamaCppConfig{}).LaunchArgs(); len(got) != 0 {
14+ t.Errorf("nothing set: %v, want no flag", got)
15+ }
16+ l := LlamaCppConfig{CtxSize: n(32768), ModelsMax: n(0), ModelsMemoryMargin: n(1024), FitTarget: n(1024),
17+ SleepIdleSeconds: n(300), SpecDefault: true, ServerArgs: []string{"--no-webui"}}
18+ want := "--ctx-size 32768 --models-max 0 --models-memory-margin 1024 --fit-target 1024 --sleep-idle-seconds 300 --spec-default --no-webui"
19+ if got := strings.Join(l.LaunchArgs(), " "); got != want {
20+ t.Errorf("all set:\n got %s\nwant %s", got, want)
21+ }
22+
23+ if err := (LlamaCppConfig{SleepIdleSeconds: n(-1)}).validate(); err != nil {
24+ t.Errorf("sleepIdleSeconds -1 (never): %v", err)
25+ }
26+ if err := (LlamaCppConfig{CtxSize: n(-5)}).validate(); err == nil || !strings.Contains(err.Error(), "llamacpp.ctxSize") {
27+ t.Errorf("ctxSize -5: %v, want an error naming the key", err)
28+ }
29+}
added internal/engine/llamastart.go +70 -0
new file mode 100644
@@ -0,0 +1,70 @@
1+package engine
2+
3+import (
4+ "net"
5+ "net/url"
6+ "os"
7+ "strconv"
8+
9+ "mm/internal/config"
10+)
11+
12+// LlamaStartAddress says where mm may start llama-server for cfg
13+// (llamacpp.autoStart, ticket 223): the host and port of the agent's
14+// address, when that address is on this machine and no OTHER llamacpp
15+// address answers — 8080, or host.docker.internal from a container, where
16+// the user's server would be. ok is false for any other provider, with
17+// autoStart off, with AGENT_BASE_URL set (whoever set it chose the server),
18+// or for an address that is not a loopback one.
19+//
20+// It does not require the agent's own address to be silent: a server mm
21+// started there for another session answers, and this session takes a lease
22+// on it (internal/llamastart decides, from its registry, whether it is mm's).
23+func LlamaStartAddress(cfg config.Config) (host string, port int, ok bool) {
24+ if cfg.Provider != "llamacpp" || !cfg.LlamaCpp.AutoStart || os.Getenv("AGENT_BASE_URL") != "" {
25+ return "", 0, false
26+ }
27+ p, _ := registry["llamacpp"].(*openaiCompat)
28+ if p == nil {
29+ return "", 0, false
30+ }
31+ base := cfg.BaseURL
32+ if base == "" {
33+ base = p.baseURL
34+ }
35+ u, err := url.Parse(base)
36+ if err != nil {
37+ return "", 0, false
38+ }
39+ host = u.Hostname()
40+ if host == "localhost" {
41+ host = "127.0.0.1"
42+ }
43+ if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
44+ return "", 0, false
45+ }
46+ port, err = strconv.Atoi(u.Port())
47+ if err != nil {
48+ return "", 0, false
49+ }
50+ if reachable(base) {
51+ return host, port, true
52+ }
53+ var others []string
54+ if base == p.baseURL {
55+ others = append(others, p.alternates...)
56+ }
57+ fallback := p.fallback
58+ if cfg.Fallback != nil {
59+ fallback = *cfg.Fallback
60+ }
61+ if fallback != "" {
62+ others = append(others, fallback)
63+ }
64+ for _, o := range others {
65+ if reachable(o) {
66+ return "", 0, false
67+ }
68+ }
69+ return host, port, true
70+}
new file mode 100644
@@ -0,0 +1,70 @@
1+package engine
2+
3+import (
4+ "net"
5+ "net/url"
6+ "os"
7+ "strconv"
8+
9+ "mm/internal/config"
10+)
11+
12+// LlamaStartAddress says where mm may start llama-server for cfg
13+// (llamacpp.autoStart, ticket 223): the host and port of the agent's
14+// address, when that address is on this machine and no OTHER llamacpp
15+// address answers — 8080, or host.docker.internal from a container, where
16+// the user's server would be. ok is false for any other provider, with
17+// autoStart off, with AGENT_BASE_URL set (whoever set it chose the server),
18+// or for an address that is not a loopback one.
19+//
20+// It does not require the agent's own address to be silent: a server mm
21+// started there for another session answers, and this session takes a lease
22+// on it (internal/llamastart decides, from its registry, whether it is mm's).
23+func LlamaStartAddress(cfg config.Config) (host string, port int, ok bool) {
24+ if cfg.Provider != "llamacpp" || !cfg.LlamaCpp.AutoStart || os.Getenv("AGENT_BASE_URL") != "" {
25+ return "", 0, false
26+ }
27+ p, _ := registry["llamacpp"].(*openaiCompat)
28+ if p == nil {
29+ return "", 0, false
30+ }
31+ base := cfg.BaseURL
32+ if base == "" {
33+ base = p.baseURL
34+ }
35+ u, err := url.Parse(base)
36+ if err != nil {
37+ return "", 0, false
38+ }
39+ host = u.Hostname()
40+ if host == "localhost" {
41+ host = "127.0.0.1"
42+ }
43+ if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
44+ return "", 0, false
45+ }
46+ port, err = strconv.Atoi(u.Port())
47+ if err != nil {
48+ return "", 0, false
49+ }
50+ if reachable(base) {
51+ return host, port, true
52+ }
53+ var others []string
54+ if base == p.baseURL {
55+ others = append(others, p.alternates...)
56+ }
57+ fallback := p.fallback
58+ if cfg.Fallback != nil {
59+ fallback = *cfg.Fallback
60+ }
61+ if fallback != "" {
62+ others = append(others, fallback)
63+ }
64+ for _, o := range others {
65+ if reachable(o) {
66+ return "", 0, false
67+ }
68+ }
69+ return host, port, true
70+}
added internal/engine/llamastart_test.go +49 -0
new file mode 100644
@@ -0,0 +1,49 @@
1+package engine
2+
3+import (
4+ "net/http"
5+ "net/http/httptest"
6+ "testing"
7+
8+ "mm/internal/config"
9+)
10+
11+// mm starts llama-server only for llamacpp with autoStart, on a loopback
12+// address, when no other llamacpp address answers.
13+func TestLlamaStartAddress(t *testing.T) {
14+ t.Setenv("AGENT_BASE_URL", "")
15+ none := ""
16+ cfg := config.Config{Provider: "llamacpp", BaseURL: "http://localhost:1/v1", Fallback: &none,
17+ LlamaCpp: config.LlamaCppConfig{AutoStart: true}}
18+ if h, p, ok := LlamaStartAddress(cfg); !ok || h != "127.0.0.1" || p != 1 {
19+ t.Errorf("loopback, nothing answers: %s %d %v, want 127.0.0.1 1 true", h, p, ok)
20+ }
21+
22+ off := cfg
23+ off.LlamaCpp.AutoStart = false
24+ remote := cfg
25+ remote.BaseURL = "http://192.168.1.20:9931/v1"
26+ other := cfg
27+ other.Provider = "llmman"
28+ for name, c := range map[string]config.Config{"autoStart off": off, "remote": remote, "llmman": other} {
29+ if _, _, ok := LlamaStartAddress(c); ok {
30+ t.Errorf("%s: ok, want no start", name)
31+ }
32+ }
33+
34+ t.Setenv("AGENT_BASE_URL", "http://127.0.0.1:1/v1")
35+ if _, _, ok := LlamaStartAddress(cfg); ok {
36+ t.Error("AGENT_BASE_URL set: ok, want no start")
37+ }
38+ t.Setenv("AGENT_BASE_URL", "")
39+
40+ // The fallback (the host's server, seen from a container) answers.
41+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"data":[]}`)) }))
42+ t.Cleanup(srv.Close)
43+ fb := srv.URL + "/v1"
44+ withFallback := cfg
45+ withFallback.Fallback = &fb
46+ if _, _, ok := LlamaStartAddress(withFallback); ok {
47+ t.Error("fallback answers: ok, want no start")
48+ }
49+}
new file mode 100644
@@ -0,0 +1,49 @@
1+package engine
2+
3+import (
4+ "net/http"
5+ "net/http/httptest"
6+ "testing"
7+
8+ "mm/internal/config"
9+)
10+
11+// mm starts llama-server only for llamacpp with autoStart, on a loopback
12+// address, when no other llamacpp address answers.
13+func TestLlamaStartAddress(t *testing.T) {
14+ t.Setenv("AGENT_BASE_URL", "")
15+ none := ""
16+ cfg := config.Config{Provider: "llamacpp", BaseURL: "http://localhost:1/v1", Fallback: &none,
17+ LlamaCpp: config.LlamaCppConfig{AutoStart: true}}
18+ if h, p, ok := LlamaStartAddress(cfg); !ok || h != "127.0.0.1" || p != 1 {
19+ t.Errorf("loopback, nothing answers: %s %d %v, want 127.0.0.1 1 true", h, p, ok)
20+ }
21+
22+ off := cfg
23+ off.LlamaCpp.AutoStart = false
24+ remote := cfg
25+ remote.BaseURL = "http://192.168.1.20:9931/v1"
26+ other := cfg
27+ other.Provider = "llmman"
28+ for name, c := range map[string]config.Config{"autoStart off": off, "remote": remote, "llmman": other} {
29+ if _, _, ok := LlamaStartAddress(c); ok {
30+ t.Errorf("%s: ok, want no start", name)
31+ }
32+ }
33+
34+ t.Setenv("AGENT_BASE_URL", "http://127.0.0.1:1/v1")
35+ if _, _, ok := LlamaStartAddress(cfg); ok {
36+ t.Error("AGENT_BASE_URL set: ok, want no start")
37+ }
38+ t.Setenv("AGENT_BASE_URL", "")
39+
40+ // The fallback (the host's server, seen from a container) answers.
41+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"data":[]}`)) }))
42+ t.Cleanup(srv.Close)
43+ fb := srv.URL + "/v1"
44+ withFallback := cfg
45+ withFallback.Fallback = &fb
46+ if _, _, ok := LlamaStartAddress(withFallback); ok {
47+ t.Error("fallback answers: ok, want no start")
48+ }
49+}
added internal/llamastart/llamastart.go +493 -0
new file mode 100644
@@ -0,0 +1,493 @@
1+// Package llamastart starts llama-server for a llamacpp agent when nothing
2+// answers at its address, and stops it with the last mm session that uses it
3+// (ticket 223, config `llamacpp.autoStart`).
4+//
5+// Measured on llama.cpp build 12359 (2026-11-24, Linux arm64):
6+//
7+// - started without -m, llama-server is a ROUTER: it lists the models of
8+// the Hugging Face cache (`org/repo:QUANT`) and of a --models-preset
9+// file, and runs each loaded model as a child llama-server;
10+// - it scans the cache once, at start: a model downloaded later is not
11+// listed until a restart. A preset entry `hf-repo = org/repo:QUANT` is
12+// listed even when the model is not downloaded, and loading it downloads
13+// it first — so mm writes one entry, the agent's model;
14+// - POST /models/load {"model"} returns at once; GET /models then shows the
15+// model's status.value "loading", then "loaded" — or "unloaded" with
16+// `failed: true` and the child's `exit_code`;
17+// - stopping only the router's pid leaves its children running: the whole
18+// process group (a process tree on Windows) has to be stopped.
19+//
20+// The lifetime is shared. A small registry per address, under the user's
21+// cache directory, holds the pid of the server mm started (server.json) and
22+// one lease file per running mm process (leases/<pid>). The last mm to
23+// release its lease stops the server. A lease whose process is gone (a
24+// crash) is removed by the next mm that reads the registry. A server mm did
25+// not start — the user's own, the Llama app's — has no server.json: mm takes
26+// no lease on it and never stops it. A lock file keeps two mm starting at
27+// the same time from starting two servers.
28+package llamastart
29+
30+import (
31+ "context"
32+ "encoding/json"
33+ "errors"
34+ "fmt"
35+ "net/http"
36+ "os"
37+ "os/exec"
38+ "path/filepath"
39+ "strconv"
40+ "strings"
41+ "sync"
42+ "time"
43+)
44+
45+// Options says which server to start and how to talk about it.
46+type Options struct {
47+ // Binary is the llama-server (or `llama`) executable; "" = llama-server
48+ // on the PATH, then llama (as `llama serve`).
49+ Binary string
50+ // Args are added after mm's own arguments (config llamacpp.serverArgs).
51+ Args []string
52+ // Host and Port are where the server listens: the agent's address.
53+ Host string
54+ Port int
55+ // Model is the agent's model, loaded before Acquire returns.
56+ Model string
57+ // StateDir holds the registries; "" = <user cache dir>/mm/llama-server.
58+ StateDir string
59+ // Timeout bounds the start and the model's download and load.
60+ Timeout time.Duration
61+ // Report receives one line per step worth showing; nil = quiet.
62+ Report func(line string)
63+ // Wait shows that mm is waiting (a spinner) until the returned function
64+ // is called; nil = nothing shown.
65+ Wait func(text string) (stop func())
66+}
67+
68+// Lease is this process's use of a server mm started. Release it on exit.
69+// A nil *Lease (no server mm started) releases nothing.
70+type Lease struct {
71+ dir string
72+ report func(string)
73+ once sync.Once
74+}
75+
76+// record is server.json: the server mm started at this address.
77+type record struct {
78+ PID int `json:"pid"`
79+ Binary string `json:"binary"`
80+ Args []string `json:"args"`
81+ Started time.Time `json:"started"`
82+}
83+
84+// lockWait bounds the wait for another mm's start; lockStale is the age
85+// past which a lock whose holder still runs is taken anyway.
86+var (
87+ lockWait = time.Minute
88+ lockStale = 2 * time.Minute
89+ stopGrace = 5 * time.Second
90+ // poll is the step of every wait loop.
91+ poll = 200 * time.Millisecond
92+)
93+
94+// ErrNotFound: no llama-server binary to start.
95+var ErrNotFound = errors.New("llama-server not found on the PATH — install llama.cpp (macOS: brew install llama.cpp; Linux, Windows: an archive from https://github.com/ggml-org/llama.cpp/releases) or set llamacpp.server to its path")
96+
97+// Acquire makes sure a server answers at o.Host:o.Port with o.Model loaded,
98+// starting it when nothing answers, and returns this process's lease on
99+// it. It returns a nil lease and no error when a server mm did not start
100+// already answers there: that one is left alone. On an error after a start,
101+// the server is stopped again unless another mm uses it.
102+func Acquire(ctx context.Context, o Options) (*Lease, error) {
103+ if o.Timeout <= 0 {
104+ o.Timeout = 10 * time.Minute
105+ }
106+ dir, err := registryDir(o)
107+ if err != nil {
108+ return nil, err
109+ }
110+ base := "http://" + hostPort(o.Host, o.Port)
111+ l := &Lease{dir: dir, report: o.Report}
112+
113+ unlock, err := lock(ctx, dir)
114+ if err != nil {
115+ return nil, err
116+ }
117+ rec := readRecord(dir)
118+ if rec != nil && !alive(rec.PID) {
119+ removeRecord(dir)
120+ rec = nil
121+ }
122+ up := healthy(base)
123+ switch {
124+ case up && rec == nil:
125+ unlock()
126+ return nil, nil // not ours: never stopped
127+ case up:
128+ l.add()
129+ unlock()
130+ o.say("🦙 llama-server already started by mm (pid %d): shared with this session", rec.PID)
131+ default:
132+ if rec != nil { // ours, alive, not answering: hung — replace it
133+ stop(rec.PID)
134+ removeRecord(dir)
135+ }
136+ if err := start(ctx, o, dir, base); err != nil {
137+ unlock()
138+ return nil, err
139+ }
140+ l.add()
141+ unlock()
142+ }
143+ if err := ensureModel(ctx, o, base); err != nil {
144+ return l, err
145+ }
146+ return l, nil
147+}
148+
149+// Release removes this process's lease and stops the server when no live
150+// lease remains. Safe to call more than once, and on a nil lease.
151+func (l *Lease) Release() {
152+ if l == nil {
153+ return
154+ }
155+ l.once.Do(func() {
156+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
157+ defer cancel()
158+ unlock, err := lock(ctx, l.dir)
159+ if err != nil {
160+ return // another mm holds it: it will see our lease is stale
161+ }
162+ defer unlock()
163+ _ = os.Remove(filepath.Join(l.dir, "leases", strconv.Itoa(os.Getpid())))
164+ others := liveLeases(l.dir)
165+ rec := readRecord(l.dir)
166+ switch {
167+ case rec == nil:
168+ case others > 0:
169+ l.say("🦙 llama-server kept running: %d other mm session(s) use it", others)
170+ default:
171+ stop(rec.PID)
172+ removeRecord(l.dir)
173+ l.say("🦙 stopped llama-server (pid %d)", rec.PID)
174+ }
175+ })
176+}
177+
178+func (l *Lease) add() {
179+ _ = os.WriteFile(filepath.Join(l.dir, "leases", strconv.Itoa(os.Getpid())), nil, 0o644)
180+}
181+
182+func (l *Lease) say(format string, args ...any) {
183+ if l.report != nil {
184+ l.report(fmt.Sprintf(format, args...))
185+ }
186+}
187+
188+func (o Options) say(format string, args ...any) {
189+ if o.Report != nil {
190+ o.Report(fmt.Sprintf(format, args...))
191+ }
192+}
193+
194+func (o Options) wait(text string) func() {
195+ if o.Wait == nil {
196+ return func() {}
197+ }
198+ return o.Wait(text)
199+}
200+
201+// registryDir is <StateDir>/<host>-<port>, with its leases directory.
202+func registryDir(o Options) (string, error) {
203+ root := o.StateDir
204+ if root == "" {
205+ cache, err := os.UserCacheDir()
206+ if err != nil {
207+ return "", err
208+ }
209+ root = filepath.Join(cache, "mm", "llama-server")
210+ }
211+ name := strings.NewReplacer(":", "_", "/", "_", "\\", "_").Replace(o.Host) + "-" + strconv.Itoa(o.Port)
212+ dir := filepath.Join(root, name)
213+ return dir, os.MkdirAll(filepath.Join(dir, "leases"), 0o755)
214+}
215+
216+// LogPath is where the server started for o writes its output.
217+func LogPath(o Options) string {
218+ dir, err := registryDir(o)
219+ if err != nil {
220+ return ""
221+ }
222+ return filepath.Join(dir, "llama-server.log")
223+}
224+
225+// command is the binary and arguments that start a router on o's address,
226+// with the agent's model in a preset file written to dir.
227+func command(o Options, dir string) (string, []string, error) {
228+ bin, serve := o.Binary, false
229+ if bin == "" {
230+ if p, err := exec.LookPath("llama-server"); err == nil {
231+ bin = p
232+ } else if p, err := exec.LookPath("llama"); err == nil {
233+ bin, serve = p, true
234+ } else {
235+ return "", nil, ErrNotFound
236+ }
237+ } else {
238+ if _, err := exec.LookPath(bin); err != nil {
239+ return "", nil, fmt.Errorf("llamacpp.server %q: %w", bin, err)
240+ }
241+ name := strings.TrimSuffix(filepath.Base(bin), ".exe")
242+ serve = name == "llama"
243+ }
244+ var args []string
245+ if serve {
246+ args = append(args, "serve")
247+ }
248+ args = append(args, "--host", o.Host, "--port", strconv.Itoa(o.Port))
249+ if strings.Contains(o.Model, "/") {
250+ preset := filepath.Join(dir, "models.ini")
251+ body := fmt.Sprintf("# Written by mm (llamacpp.autoStart): the agent's model, downloaded on its first load.\n[%s]\nhf-repo = %s\n", o.Model, o.Model)
252+ if err := os.WriteFile(preset, []byte(body), 0o644); err != nil {
253+ return "", nil, err
254+ }
255+ args = append(args, "--models-preset", preset)
256+ }
257+ return bin, append(args, o.Args...), nil
258+}
259+
260+// start launches the server detached from mm (its own process group, its
261+// output in the log file), records it and waits until /health answers.
262+func start(ctx context.Context, o Options, dir, base string) error {
263+ bin, args, err := command(o, dir)
264+ if err != nil {
265+ return err
266+ }
267+ logPath := filepath.Join(dir, "llama-server.log")
268+ logFile, err := os.Create(logPath)
269+ if err != nil {
270+ return err
271+ }
272+ cmd := exec.Command(bin, args...)
273+ cmd.Stdout, cmd.Stderr = logFile, logFile
274+ detach(cmd)
275+ if err := cmd.Start(); err != nil {
276+ _ = logFile.Close()
277+ return fmt.Errorf("start %s: %w", bin, err)
278+ }
279+ _ = logFile.Close()
280+ exited := make(chan error, 1)
281+ go func() { exited <- cmd.Wait() }() // reaps it if it ends while mm runs
282+ rec := record{PID: cmd.Process.Pid, Binary: bin, Args: args, Started: time.Now()}
283+ if err := writeRecord(dir, rec); err != nil {
284+ stop(rec.PID)
285+ return err
286+ }
287+ o.say("🦙 starting llama-server on %s (pid %d, log %s)", hostPort(o.Host, o.Port), rec.PID, logPath)
288+
289+ done := o.wait("Starting llama-server…")
290+ defer done()
291+ ctx, cancel := context.WithTimeout(ctx, o.Timeout)
292+ defer cancel()
293+ for !healthy(base) {
294+ select {
295+ case err := <-exited:
296+ removeRecord(dir)
297+ return fmt.Errorf("llama-server stopped at once (%v) — see %s", err, logPath)
298+ case <-ctx.Done():
299+ stop(rec.PID)
300+ removeRecord(dir)
301+ return fmt.Errorf("llama-server did not answer within %s — see %s", o.Timeout, logPath)
302+ case <-time.After(poll):
303+ }
304+ }
305+ return nil
306+}
307+
308+// routerModel is one entry of a router's GET /models.
309+type routerModel struct {
310+ ID string `json:"id"`
311+ Status struct {
312+ Value string `json:"value"`
313+ Failed bool `json:"failed"`
314+ ExitCode int `json:"exit_code"`
315+ } `json:"status"`
316+}
317+
318+// ensureModel loads o.Model on the router at base and waits until it is
319+// loaded — downloaded first when it is not in the cache.
320+func ensureModel(ctx context.Context, o Options, base string) error {
321+ if o.Model == "" {
322+ return nil
323+ }
324+ m, found, err := findModel(ctx, base, o.Model)
325+ switch {
326+ case err != nil:
327+ return err
328+ case !found:
329+ return fmt.Errorf("the llama-server mm started does not list %s (it was started for another model; quit the other mm sessions so the next start lists this one)", o.Model)
330+ case m.Status.Value == "loaded":
331+ return nil
332+ }
333+ done := o.wait("Loading " + o.Model + " (downloaded first when missing)…")
334+ defer done()
335+ ctx, cancel := context.WithTimeout(ctx, o.Timeout)
336+ defer cancel()
337+ body := fmt.Sprintf(`{"model":%q}`, o.Model)
338+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/models/load", strings.NewReader(body))
339+ if err != nil {
340+ return err
341+ }
342+ req.Header.Set("Content-Type", "application/json")
343+ resp, err := http.DefaultClient.Do(req)
344+ if err != nil {
345+ return err
346+ }
347+ _ = resp.Body.Close()
348+ if resp.StatusCode != http.StatusOK {
349+ return fmt.Errorf("llama-server refused to load %s (%d)", o.Model, resp.StatusCode)
350+ }
351+ for {
352+ m, _, err := findModel(ctx, base, o.Model)
353+ switch {
354+ case err != nil && ctx.Err() != nil:
355+ return fmt.Errorf("%s was not loaded within %s — see %s", o.Model, o.Timeout, LogPath(o))
356+ case err != nil:
357+ return err
358+ case m.Status.Value == "loaded":
359+ o.say("🦙 %s loaded", o.Model)
360+ return nil
361+ case m.Status.Failed:
362+ return fmt.Errorf("llama-server could not load %s (exit code %d) — see %s", o.Model, m.Status.ExitCode, LogPath(o))
363+ }
364+ select {
365+ case <-ctx.Done():
366+ return fmt.Errorf("%s was not loaded within %s — see %s", o.Model, o.Timeout, LogPath(o))
367+ case <-time.After(poll):
368+ }
369+ }
370+}
371+
372+func findModel(ctx context.Context, base, model string) (routerModel, bool, error) {
373+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
374+ if err != nil {
375+ return routerModel{}, false, err
376+ }
377+ resp, err := http.DefaultClient.Do(req)
378+ if err != nil {
379+ return routerModel{}, false, err
380+ }
381+ defer func() { _ = resp.Body.Close() }()
382+ var list struct {
383+ Data []routerModel `json:"data"`
384+ }
385+ if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
386+ return routerModel{}, false, fmt.Errorf("GET /models: %w", err)
387+ }
388+ for _, m := range list.Data {
389+ if m.ID == model {
390+ return m, true, nil
391+ }
392+ }
393+ return routerModel{}, false, nil
394+}
395+
396+var healthClient = &http.Client{Timeout: time.Second}
397+
398+func healthy(base string) bool {
399+ resp, err := healthClient.Get(base + "/health")
400+ if err != nil {
401+ return false
402+ }
403+ _ = resp.Body.Close()
404+ return resp.StatusCode == http.StatusOK
405+}
406+
407+func hostPort(host string, port int) string {
408+ if strings.Contains(host, ":") {
409+ host = "[" + host + "]"
410+ }
411+ return host + ":" + strconv.Itoa(port)
412+}
413+
414+// liveLeases counts the leases whose process still runs, removing the
415+// others (a crashed mm).
416+func liveLeases(dir string) int {
417+ entries, _ := os.ReadDir(filepath.Join(dir, "leases"))
418+ n := 0
419+ for _, e := range entries {
420+ pid, err := strconv.Atoi(e.Name())
421+ if err == nil && alive(pid) {
422+ n++
423+ continue
424+ }
425+ _ = os.Remove(filepath.Join(dir, "leases", e.Name()))
426+ }
427+ return n
428+}
429+
430+func readRecord(dir string) *record {
431+ data, err := os.ReadFile(filepath.Join(dir, "server.json"))
432+ if err != nil {
433+ return nil
434+ }
435+ var r record
436+ if json.Unmarshal(data, &r) != nil || r.PID <= 0 {
437+ return nil
438+ }
439+ return &r
440+}
441+
442+func writeRecord(dir string, r record) error {
443+ data, err := json.MarshalIndent(r, "", " ")
444+ if err != nil {
445+ return err
446+ }
447+ return os.WriteFile(filepath.Join(dir, "server.json"), data, 0o644)
448+}
449+
450+func removeRecord(dir string) { _ = os.Remove(filepath.Join(dir, "server.json")) }
451+
452+// lock takes dir's lock file — created exclusively, holding our pid — and
453+// returns its release. A lock whose holder is gone, or older than
454+// lockStale, is taken over.
455+func lock(ctx context.Context, dir string) (func(), error) {
456+ path := filepath.Join(dir, "lock")
457+ ctx, cancel := context.WithTimeout(ctx, lockWait)
458+ defer cancel()
459+ for {
460+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
461+ if err == nil {
462+ _, _ = f.WriteString(strconv.Itoa(os.Getpid()))
463+ _ = f.Close()
464+ return func() { _ = os.Remove(path) }, nil
465+ }
466+ if !errors.Is(err, os.ErrExist) {
467+ return nil, err
468+ }
469+ if staleLock(path) {
470+ _ = os.Remove(path)
471+ continue
472+ }
473+ select {
474+ case <-ctx.Done():
475+ return nil, fmt.Errorf("another mm is starting llama-server (lock %s)", path)
476+ case <-time.After(poll):
477+ }
478+ }
479+}
480+
481+func staleLock(path string) bool {
482+ info, err := os.Stat(path)
483+ if err != nil {
484+ return false // gone meanwhile: retry
485+ }
486+ data, _ := os.ReadFile(path)
487+ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
488+ if err != nil {
489+ // Being written right now, or garbage: only an old one is stale.
490+ return time.Since(info.ModTime()) > lockStale
491+ }
492+ return !alive(pid) || time.Since(info.ModTime()) > lockStale
493+}
new file mode 100644
@@ -0,0 +1,493 @@
1+// Package llamastart starts llama-server for a llamacpp agent when nothing
2+// answers at its address, and stops it with the last mm session that uses it
3+// (ticket 223, config `llamacpp.autoStart`).
4+//
5+// Measured on llama.cpp build 12359 (2026-11-24, Linux arm64):
6+//
7+// - started without -m, llama-server is a ROUTER: it lists the models of
8+// the Hugging Face cache (`org/repo:QUANT`) and of a --models-preset
9+// file, and runs each loaded model as a child llama-server;
10+// - it scans the cache once, at start: a model downloaded later is not
11+// listed until a restart. A preset entry `hf-repo = org/repo:QUANT` is
12+// listed even when the model is not downloaded, and loading it downloads
13+// it first — so mm writes one entry, the agent's model;
14+// - POST /models/load {"model"} returns at once; GET /models then shows the
15+// model's status.value "loading", then "loaded" — or "unloaded" with
16+// `failed: true` and the child's `exit_code`;
17+// - stopping only the router's pid leaves its children running: the whole
18+// process group (a process tree on Windows) has to be stopped.
19+//
20+// The lifetime is shared. A small registry per address, under the user's
21+// cache directory, holds the pid of the server mm started (server.json) and
22+// one lease file per running mm process (leases/<pid>). The last mm to
23+// release its lease stops the server. A lease whose process is gone (a
24+// crash) is removed by the next mm that reads the registry. A server mm did
25+// not start — the user's own, the Llama app's — has no server.json: mm takes
26+// no lease on it and never stops it. A lock file keeps two mm starting at
27+// the same time from starting two servers.
28+package llamastart
29+
30+import (
31+ "context"
32+ "encoding/json"
33+ "errors"
34+ "fmt"
35+ "net/http"
36+ "os"
37+ "os/exec"
38+ "path/filepath"
39+ "strconv"
40+ "strings"
41+ "sync"
42+ "time"
43+)
44+
45+// Options says which server to start and how to talk about it.
46+type Options struct {
47+ // Binary is the llama-server (or `llama`) executable; "" = llama-server
48+ // on the PATH, then llama (as `llama serve`).
49+ Binary string
50+ // Args are added after mm's own arguments (config llamacpp.serverArgs).
51+ Args []string
52+ // Host and Port are where the server listens: the agent's address.
53+ Host string
54+ Port int
55+ // Model is the agent's model, loaded before Acquire returns.
56+ Model string
57+ // StateDir holds the registries; "" = <user cache dir>/mm/llama-server.
58+ StateDir string
59+ // Timeout bounds the start and the model's download and load.
60+ Timeout time.Duration
61+ // Report receives one line per step worth showing; nil = quiet.
62+ Report func(line string)
63+ // Wait shows that mm is waiting (a spinner) until the returned function
64+ // is called; nil = nothing shown.
65+ Wait func(text string) (stop func())
66+}
67+
68+// Lease is this process's use of a server mm started. Release it on exit.
69+// A nil *Lease (no server mm started) releases nothing.
70+type Lease struct {
71+ dir string
72+ report func(string)
73+ once sync.Once
74+}
75+
76+// record is server.json: the server mm started at this address.
77+type record struct {
78+ PID int `json:"pid"`
79+ Binary string `json:"binary"`
80+ Args []string `json:"args"`
81+ Started time.Time `json:"started"`
82+}
83+
84+// lockWait bounds the wait for another mm's start; lockStale is the age
85+// past which a lock whose holder still runs is taken anyway.
86+var (
87+ lockWait = time.Minute
88+ lockStale = 2 * time.Minute
89+ stopGrace = 5 * time.Second
90+ // poll is the step of every wait loop.
91+ poll = 200 * time.Millisecond
92+)
93+
94+// ErrNotFound: no llama-server binary to start.
95+var ErrNotFound = errors.New("llama-server not found on the PATH — install llama.cpp (macOS: brew install llama.cpp; Linux, Windows: an archive from https://github.com/ggml-org/llama.cpp/releases) or set llamacpp.server to its path")
96+
97+// Acquire makes sure a server answers at o.Host:o.Port with o.Model loaded,
98+// starting it when nothing answers, and returns this process's lease on
99+// it. It returns a nil lease and no error when a server mm did not start
100+// already answers there: that one is left alone. On an error after a start,
101+// the server is stopped again unless another mm uses it.
102+func Acquire(ctx context.Context, o Options) (*Lease, error) {
103+ if o.Timeout <= 0 {
104+ o.Timeout = 10 * time.Minute
105+ }
106+ dir, err := registryDir(o)
107+ if err != nil {
108+ return nil, err
109+ }
110+ base := "http://" + hostPort(o.Host, o.Port)
111+ l := &Lease{dir: dir, report: o.Report}
112+
113+ unlock, err := lock(ctx, dir)
114+ if err != nil {
115+ return nil, err
116+ }
117+ rec := readRecord(dir)
118+ if rec != nil && !alive(rec.PID) {
119+ removeRecord(dir)
120+ rec = nil
121+ }
122+ up := healthy(base)
123+ switch {
124+ case up && rec == nil:
125+ unlock()
126+ return nil, nil // not ours: never stopped
127+ case up:
128+ l.add()
129+ unlock()
130+ o.say("🦙 llama-server already started by mm (pid %d): shared with this session", rec.PID)
131+ default:
132+ if rec != nil { // ours, alive, not answering: hung — replace it
133+ stop(rec.PID)
134+ removeRecord(dir)
135+ }
136+ if err := start(ctx, o, dir, base); err != nil {
137+ unlock()
138+ return nil, err
139+ }
140+ l.add()
141+ unlock()
142+ }
143+ if err := ensureModel(ctx, o, base); err != nil {
144+ return l, err
145+ }
146+ return l, nil
147+}
148+
149+// Release removes this process's lease and stops the server when no live
150+// lease remains. Safe to call more than once, and on a nil lease.
151+func (l *Lease) Release() {
152+ if l == nil {
153+ return
154+ }
155+ l.once.Do(func() {
156+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
157+ defer cancel()
158+ unlock, err := lock(ctx, l.dir)
159+ if err != nil {
160+ return // another mm holds it: it will see our lease is stale
161+ }
162+ defer unlock()
163+ _ = os.Remove(filepath.Join(l.dir, "leases", strconv.Itoa(os.Getpid())))
164+ others := liveLeases(l.dir)
165+ rec := readRecord(l.dir)
166+ switch {
167+ case rec == nil:
168+ case others > 0:
169+ l.say("🦙 llama-server kept running: %d other mm session(s) use it", others)
170+ default:
171+ stop(rec.PID)
172+ removeRecord(l.dir)
173+ l.say("🦙 stopped llama-server (pid %d)", rec.PID)
174+ }
175+ })
176+}
177+
178+func (l *Lease) add() {
179+ _ = os.WriteFile(filepath.Join(l.dir, "leases", strconv.Itoa(os.Getpid())), nil, 0o644)
180+}
181+
182+func (l *Lease) say(format string, args ...any) {
183+ if l.report != nil {
184+ l.report(fmt.Sprintf(format, args...))
185+ }
186+}
187+
188+func (o Options) say(format string, args ...any) {
189+ if o.Report != nil {
190+ o.Report(fmt.Sprintf(format, args...))
191+ }
192+}
193+
194+func (o Options) wait(text string) func() {
195+ if o.Wait == nil {
196+ return func() {}
197+ }
198+ return o.Wait(text)
199+}
200+
201+// registryDir is <StateDir>/<host>-<port>, with its leases directory.
202+func registryDir(o Options) (string, error) {
203+ root := o.StateDir
204+ if root == "" {
205+ cache, err := os.UserCacheDir()
206+ if err != nil {
207+ return "", err
208+ }
209+ root = filepath.Join(cache, "mm", "llama-server")
210+ }
211+ name := strings.NewReplacer(":", "_", "/", "_", "\\", "_").Replace(o.Host) + "-" + strconv.Itoa(o.Port)
212+ dir := filepath.Join(root, name)
213+ return dir, os.MkdirAll(filepath.Join(dir, "leases"), 0o755)
214+}
215+
216+// LogPath is where the server started for o writes its output.
217+func LogPath(o Options) string {
218+ dir, err := registryDir(o)
219+ if err != nil {
220+ return ""
221+ }
222+ return filepath.Join(dir, "llama-server.log")
223+}
224+
225+// command is the binary and arguments that start a router on o's address,
226+// with the agent's model in a preset file written to dir.
227+func command(o Options, dir string) (string, []string, error) {
228+ bin, serve := o.Binary, false
229+ if bin == "" {
230+ if p, err := exec.LookPath("llama-server"); err == nil {
231+ bin = p
232+ } else if p, err := exec.LookPath("llama"); err == nil {
233+ bin, serve = p, true
234+ } else {
235+ return "", nil, ErrNotFound
236+ }
237+ } else {
238+ if _, err := exec.LookPath(bin); err != nil {
239+ return "", nil, fmt.Errorf("llamacpp.server %q: %w", bin, err)
240+ }
241+ name := strings.TrimSuffix(filepath.Base(bin), ".exe")
242+ serve = name == "llama"
243+ }
244+ var args []string
245+ if serve {
246+ args = append(args, "serve")
247+ }
248+ args = append(args, "--host", o.Host, "--port", strconv.Itoa(o.Port))
249+ if strings.Contains(o.Model, "/") {
250+ preset := filepath.Join(dir, "models.ini")
251+ body := fmt.Sprintf("# Written by mm (llamacpp.autoStart): the agent's model, downloaded on its first load.\n[%s]\nhf-repo = %s\n", o.Model, o.Model)
252+ if err := os.WriteFile(preset, []byte(body), 0o644); err != nil {
253+ return "", nil, err
254+ }
255+ args = append(args, "--models-preset", preset)
256+ }
257+ return bin, append(args, o.Args...), nil
258+}
259+
260+// start launches the server detached from mm (its own process group, its
261+// output in the log file), records it and waits until /health answers.
262+func start(ctx context.Context, o Options, dir, base string) error {
263+ bin, args, err := command(o, dir)
264+ if err != nil {
265+ return err
266+ }
267+ logPath := filepath.Join(dir, "llama-server.log")
268+ logFile, err := os.Create(logPath)
269+ if err != nil {
270+ return err
271+ }
272+ cmd := exec.Command(bin, args...)
273+ cmd.Stdout, cmd.Stderr = logFile, logFile
274+ detach(cmd)
275+ if err := cmd.Start(); err != nil {
276+ _ = logFile.Close()
277+ return fmt.Errorf("start %s: %w", bin, err)
278+ }
279+ _ = logFile.Close()
280+ exited := make(chan error, 1)
281+ go func() { exited <- cmd.Wait() }() // reaps it if it ends while mm runs
282+ rec := record{PID: cmd.Process.Pid, Binary: bin, Args: args, Started: time.Now()}
283+ if err := writeRecord(dir, rec); err != nil {
284+ stop(rec.PID)
285+ return err
286+ }
287+ o.say("🦙 starting llama-server on %s (pid %d, log %s)", hostPort(o.Host, o.Port), rec.PID, logPath)
288+
289+ done := o.wait("Starting llama-server…")
290+ defer done()
291+ ctx, cancel := context.WithTimeout(ctx, o.Timeout)
292+ defer cancel()
293+ for !healthy(base) {
294+ select {
295+ case err := <-exited:
296+ removeRecord(dir)
297+ return fmt.Errorf("llama-server stopped at once (%v) — see %s", err, logPath)
298+ case <-ctx.Done():
299+ stop(rec.PID)
300+ removeRecord(dir)
301+ return fmt.Errorf("llama-server did not answer within %s — see %s", o.Timeout, logPath)
302+ case <-time.After(poll):
303+ }
304+ }
305+ return nil
306+}
307+
308+// routerModel is one entry of a router's GET /models.
309+type routerModel struct {
310+ ID string `json:"id"`
311+ Status struct {
312+ Value string `json:"value"`
313+ Failed bool `json:"failed"`
314+ ExitCode int `json:"exit_code"`
315+ } `json:"status"`
316+}
317+
318+// ensureModel loads o.Model on the router at base and waits until it is
319+// loaded — downloaded first when it is not in the cache.
320+func ensureModel(ctx context.Context, o Options, base string) error {
321+ if o.Model == "" {
322+ return nil
323+ }
324+ m, found, err := findModel(ctx, base, o.Model)
325+ switch {
326+ case err != nil:
327+ return err
328+ case !found:
329+ return fmt.Errorf("the llama-server mm started does not list %s (it was started for another model; quit the other mm sessions so the next start lists this one)", o.Model)
330+ case m.Status.Value == "loaded":
331+ return nil
332+ }
333+ done := o.wait("Loading " + o.Model + " (downloaded first when missing)…")
334+ defer done()
335+ ctx, cancel := context.WithTimeout(ctx, o.Timeout)
336+ defer cancel()
337+ body := fmt.Sprintf(`{"model":%q}`, o.Model)
338+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/models/load", strings.NewReader(body))
339+ if err != nil {
340+ return err
341+ }
342+ req.Header.Set("Content-Type", "application/json")
343+ resp, err := http.DefaultClient.Do(req)
344+ if err != nil {
345+ return err
346+ }
347+ _ = resp.Body.Close()
348+ if resp.StatusCode != http.StatusOK {
349+ return fmt.Errorf("llama-server refused to load %s (%d)", o.Model, resp.StatusCode)
350+ }
351+ for {
352+ m, _, err := findModel(ctx, base, o.Model)
353+ switch {
354+ case err != nil && ctx.Err() != nil:
355+ return fmt.Errorf("%s was not loaded within %s — see %s", o.Model, o.Timeout, LogPath(o))
356+ case err != nil:
357+ return err
358+ case m.Status.Value == "loaded":
359+ o.say("🦙 %s loaded", o.Model)
360+ return nil
361+ case m.Status.Failed:
362+ return fmt.Errorf("llama-server could not load %s (exit code %d) — see %s", o.Model, m.Status.ExitCode, LogPath(o))
363+ }
364+ select {
365+ case <-ctx.Done():
366+ return fmt.Errorf("%s was not loaded within %s — see %s", o.Model, o.Timeout, LogPath(o))
367+ case <-time.After(poll):
368+ }
369+ }
370+}
371+
372+func findModel(ctx context.Context, base, model string) (routerModel, bool, error) {
373+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
374+ if err != nil {
375+ return routerModel{}, false, err
376+ }
377+ resp, err := http.DefaultClient.Do(req)
378+ if err != nil {
379+ return routerModel{}, false, err
380+ }
381+ defer func() { _ = resp.Body.Close() }()
382+ var list struct {
383+ Data []routerModel `json:"data"`
384+ }
385+ if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
386+ return routerModel{}, false, fmt.Errorf("GET /models: %w", err)
387+ }
388+ for _, m := range list.Data {
389+ if m.ID == model {
390+ return m, true, nil
391+ }
392+ }
393+ return routerModel{}, false, nil
394+}
395+
396+var healthClient = &http.Client{Timeout: time.Second}
397+
398+func healthy(base string) bool {
399+ resp, err := healthClient.Get(base + "/health")
400+ if err != nil {
401+ return false
402+ }
403+ _ = resp.Body.Close()
404+ return resp.StatusCode == http.StatusOK
405+}
406+
407+func hostPort(host string, port int) string {
408+ if strings.Contains(host, ":") {
409+ host = "[" + host + "]"
410+ }
411+ return host + ":" + strconv.Itoa(port)
412+}
413+
414+// liveLeases counts the leases whose process still runs, removing the
415+// others (a crashed mm).
416+func liveLeases(dir string) int {
417+ entries, _ := os.ReadDir(filepath.Join(dir, "leases"))
418+ n := 0
419+ for _, e := range entries {
420+ pid, err := strconv.Atoi(e.Name())
421+ if err == nil && alive(pid) {
422+ n++
423+ continue
424+ }
425+ _ = os.Remove(filepath.Join(dir, "leases", e.Name()))
426+ }
427+ return n
428+}
429+
430+func readRecord(dir string) *record {
431+ data, err := os.ReadFile(filepath.Join(dir, "server.json"))
432+ if err != nil {
433+ return nil
434+ }
435+ var r record
436+ if json.Unmarshal(data, &r) != nil || r.PID <= 0 {
437+ return nil
438+ }
439+ return &r
440+}
441+
442+func writeRecord(dir string, r record) error {
443+ data, err := json.MarshalIndent(r, "", " ")
444+ if err != nil {
445+ return err
446+ }
447+ return os.WriteFile(filepath.Join(dir, "server.json"), data, 0o644)
448+}
449+
450+func removeRecord(dir string) { _ = os.Remove(filepath.Join(dir, "server.json")) }
451+
452+// lock takes dir's lock file — created exclusively, holding our pid — and
453+// returns its release. A lock whose holder is gone, or older than
454+// lockStale, is taken over.
455+func lock(ctx context.Context, dir string) (func(), error) {
456+ path := filepath.Join(dir, "lock")
457+ ctx, cancel := context.WithTimeout(ctx, lockWait)
458+ defer cancel()
459+ for {
460+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
461+ if err == nil {
462+ _, _ = f.WriteString(strconv.Itoa(os.Getpid()))
463+ _ = f.Close()
464+ return func() { _ = os.Remove(path) }, nil
465+ }
466+ if !errors.Is(err, os.ErrExist) {
467+ return nil, err
468+ }
469+ if staleLock(path) {
470+ _ = os.Remove(path)
471+ continue
472+ }
473+ select {
474+ case <-ctx.Done():
475+ return nil, fmt.Errorf("another mm is starting llama-server (lock %s)", path)
476+ case <-time.After(poll):
477+ }
478+ }
479+}
480+
481+func staleLock(path string) bool {
482+ info, err := os.Stat(path)
483+ if err != nil {
484+ return false // gone meanwhile: retry
485+ }
486+ data, _ := os.ReadFile(path)
487+ pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
488+ if err != nil {
489+ // Being written right now, or garbage: only an old one is stale.
490+ return time.Since(info.ModTime()) > lockStale
491+ }
492+ return !alive(pid) || time.Since(info.ModTime()) > lockStale
493+}
added internal/llamastart/llamastart_test.go +298 -0
new file mode 100644
@@ -0,0 +1,298 @@
1+package llamastart
2+
3+import (
4+ "bufio"
5+ "context"
6+ "encoding/json"
7+ "flag"
8+ "fmt"
9+ "net"
10+ "net/http"
11+ "net/http/httptest"
12+ "os"
13+ "os/exec"
14+ "path/filepath"
15+ "runtime"
16+ "strconv"
17+ "strings"
18+ "sync"
19+ "testing"
20+ "time"
21+)
22+
23+// The test binary is also the fake llama-server: started with
24+// LLAMASTART_FAKE=1 it serves what a router answers (measured, see the
25+// package comment) — /health, /models with the preset's models and their
26+// status, /models/load that loads after a moment or fails for a model whose
27+// name holds "fail". LLAMASTART_FAKE=hang never answers.
28+func TestMain(m *testing.M) {
29+ switch os.Getenv("LLAMASTART_FAKE") {
30+ case "1":
31+ fakeRouter()
32+ return
33+ case "hang":
34+ time.Sleep(time.Minute)
35+ return
36+ }
37+ os.Exit(m.Run())
38+}
39+
40+func fakeRouter() {
41+ fs := flag.NewFlagSet("fake", flag.ExitOnError)
42+ host := fs.String("host", "127.0.0.1", "")
43+ port := fs.Int("port", 0, "")
44+ preset := fs.String("models-preset", "", "")
45+ _ = fs.Parse(os.Args[1:])
46+
47+ var mu sync.Mutex
48+ status := map[string]string{}
49+ if f, err := os.Open(*preset); err == nil {
50+ sc := bufio.NewScanner(f)
51+ for sc.Scan() {
52+ if l := sc.Text(); strings.HasPrefix(l, "[") {
53+ status[strings.Trim(l, "[]")] = "unloaded"
54+ }
55+ }
56+ _ = f.Close()
57+ }
58+ mux := http.NewServeMux()
59+ mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"status":"ok"}`)) })
60+ mux.HandleFunc("/models", func(w http.ResponseWriter, _ *http.Request) {
61+ mu.Lock()
62+ defer mu.Unlock()
63+ var data []map[string]any
64+ for id, s := range status {
65+ st := map[string]any{"value": s}
66+ if s == "failed" {
67+ st = map[string]any{"value": "unloaded", "failed": true, "exit_code": 1}
68+ }
69+ data = append(data, map[string]any{"id": id, "status": st})
70+ }
71+ _ = json.NewEncoder(w).Encode(map[string]any{"data": data, "object": "list"})
72+ })
73+ mux.HandleFunc("/models/load", func(w http.ResponseWriter, r *http.Request) {
74+ var body struct{ Model string }
75+ _ = json.NewDecoder(r.Body).Decode(&body)
76+ mu.Lock()
77+ defer mu.Unlock()
78+ if _, ok := status[body.Model]; !ok {
79+ w.WriteHeader(http.StatusNotFound)
80+ return
81+ }
82+ status[body.Model] = "loading"
83+ go func() {
84+ time.Sleep(300 * time.Millisecond)
85+ mu.Lock()
86+ defer mu.Unlock()
87+ status[body.Model] = map[bool]string{true: "failed", false: "loaded"}[strings.Contains(body.Model, "fail")]
88+ }()
89+ _, _ = w.Write([]byte(`{"success":true}`))
90+ })
91+ _ = http.ListenAndServe(net.JoinHostPort(*host, strconv.Itoa(*port)), mux)
92+}
93+
94+func freePort(t *testing.T) int {
95+ t.Helper()
96+ l, err := net.Listen("tcp", "127.0.0.1:0")
97+ if err != nil {
98+ t.Fatal(err)
99+ }
100+ defer func() { _ = l.Close() }()
101+ return l.Addr().(*net.TCPAddr).Port
102+}
103+
104+// options for a fake server on a free port, the registry in a temp dir.
105+func options(t *testing.T, model string) (Options, *[]string) {
106+ t.Helper()
107+ if runtime.GOOS == "windows" {
108+ t.Skip("the fake server relies on process groups and signals")
109+ }
110+ t.Setenv("LLAMASTART_FAKE", "1")
111+ self, err := os.Executable()
112+ if err != nil {
113+ t.Fatal(err)
114+ }
115+ var lines []string
116+ o := Options{Binary: self, Host: "127.0.0.1", Port: freePort(t), Model: model,
117+ StateDir: t.TempDir(), Timeout: 10 * time.Second,
118+ Report: func(l string) { lines = append(lines, l) }}
119+ t.Cleanup(func() {
120+ if dir, err := registryDir(o); err == nil {
121+ if r := readRecord(dir); r != nil {
122+ stop(r.PID)
123+ }
124+ }
125+ })
126+ return o, &lines
127+}
128+
129+func base(o Options) string { return "http://" + hostPort(o.Host, o.Port) }
130+
131+// otherSession is a live process standing for another mm: its lease keeps
132+// the server running.
133+func otherSession(t *testing.T, o Options) *exec.Cmd {
134+ t.Helper()
135+ cmd := exec.Command("sleep", "30")
136+ if err := cmd.Start(); err != nil {
137+ t.Fatal(err)
138+ }
139+ t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() })
140+ dir, _ := registryDir(o)
141+ _ = os.WriteFile(filepath.Join(dir, "leases", strconv.Itoa(cmd.Process.Pid)), nil, 0o644)
142+ return cmd
143+}
144+
145+// Nothing answers: mm starts the server, loads the model, and the last
146+// session's release stops it; while another session holds a lease, a
147+// release keeps it. A crashed session's lease does not keep it forever.
148+func TestAcquireStartsSharesAndStopsWithTheLastSession(t *testing.T) {
149+ o, lines := options(t, "org/model-GGUF:Q4_K_M")
150+ l1, err := Acquire(context.Background(), o)
151+ if err != nil || l1 == nil {
152+ t.Fatalf("Acquire: %v, %v", l1, err)
153+ }
154+ if !healthy(base(o)) {
155+ t.Fatal("the server does not answer after Acquire")
156+ }
157+ if m, _, _ := findModel(context.Background(), base(o), o.Model); m.Status.Value != "loaded" {
158+ t.Fatalf("model status %q, want loaded", m.Status.Value)
159+ }
160+ if data, _ := os.ReadFile(LogPath(o)); data == nil {
161+ t.Error("no log file")
162+ }
163+
164+ other := otherSession(t, o)
165+ l1.Release()
166+ l1.Release() // twice: no effect
167+ if !healthy(base(o)) {
168+ t.Fatal("a release stopped the server another session uses")
169+ }
170+
171+ l2, err := Acquire(context.Background(), o)
172+ if err != nil || l2 == nil {
173+ t.Fatalf("second Acquire: %v, %v", l2, err)
174+ }
175+ _ = other.Process.Kill()
176+ _ = other.Wait() // the other session crashed: its lease is stale
177+ l2.Release()
178+ deadline := time.Now().Add(3 * time.Second)
179+ for healthy(base(o)) && time.Now().Before(deadline) {
180+ time.Sleep(50 * time.Millisecond)
181+ }
182+ if healthy(base(o)) {
183+ t.Fatal("the last release did not stop the server")
184+ }
185+ dir, _ := registryDir(o)
186+ if readRecord(dir) != nil {
187+ t.Error("server.json left behind")
188+ }
189+ got := strings.Join(*lines, "\n")
190+ for _, want := range []string{"starting llama-server", "loaded", "kept running: 1 other", "already started by mm", "stopped llama-server"} {
191+ if !strings.Contains(got, want) {
192+ t.Errorf("report lacks %q:\n%s", want, got)
193+ }
194+ }
195+}
196+
197+// A server mm did not start answers already: no lease, never stopped.
198+func TestAcquireLeavesAForeignServerAlone(t *testing.T) {
199+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}))
200+ t.Cleanup(srv.Close)
201+ addr := srv.Listener.Addr().(*net.TCPAddr)
202+ l, err := Acquire(context.Background(), Options{Host: "127.0.0.1", Port: addr.Port, Model: "m", StateDir: t.TempDir()})
203+ if l != nil || err != nil {
204+ t.Fatalf("Acquire = %v, %v, want no lease and no error", l, err)
205+ }
206+ l.Release() // nil lease: nothing
207+ if resp, err := http.Get(srv.URL + "/health"); err != nil {
208+ t.Fatal("the foreign server was stopped")
209+ } else {
210+ _ = resp.Body.Close()
211+ }
212+}
213+
214+// A model the server cannot load is an error that names the log; the
215+// lease is still returned, so the exit stops the server.
216+func TestAcquireReportsAFailedLoad(t *testing.T) {
217+ o, _ := options(t, "org/fail-GGUF:Q4_K_M")
218+ l, err := Acquire(context.Background(), o)
219+ if err == nil || !strings.Contains(err.Error(), "could not load") || !strings.Contains(err.Error(), "llama-server.log") {
220+ t.Fatalf("err = %v, want could not load + the log", err)
221+ }
222+ if l == nil {
223+ t.Fatal("no lease: the server would never be stopped")
224+ }
225+ l.Release()
226+ if healthy(base(o)) {
227+ t.Error("server still running after the release")
228+ }
229+}
230+
231+// A server that never answers is stopped after the timeout.
232+func TestAcquireTimesOut(t *testing.T) {
233+ o, _ := options(t, "")
234+ t.Setenv("LLAMASTART_FAKE", "hang")
235+ o.Timeout = 500 * time.Millisecond
236+ start := time.Now()
237+ _, err := Acquire(context.Background(), o)
238+ if err == nil || !strings.Contains(err.Error(), "did not answer within") {
239+ t.Fatalf("err = %v, want a timeout", err)
240+ }
241+ if time.Since(start) > 8*time.Second {
242+ t.Errorf("took %s", time.Since(start))
243+ }
244+ dir, _ := registryDir(o)
245+ if readRecord(dir) != nil {
246+ t.Error("server.json left behind")
247+ }
248+}
249+
250+// A lock left by a process that is gone is taken over.
251+func TestStaleLockIsTakenOver(t *testing.T) {
252+ dir := t.TempDir()
253+ dead := exec.Command("true")
254+ _ = dead.Run()
255+ _ = os.WriteFile(filepath.Join(dir, "lock"), []byte(strconv.Itoa(dead.Process.Pid)), 0o644)
256+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
257+ defer cancel()
258+ unlock, err := lock(ctx, dir)
259+ if err != nil {
260+ t.Fatalf("lock: %v", err)
261+ }
262+ unlock()
263+}
264+
265+// The binary: llama-server first, else llama (as `llama serve`); a
266+// configured path named llama gets `serve` too; none is ErrNotFound.
267+func TestCommandFindsTheBinary(t *testing.T) {
268+ if runtime.GOOS == "windows" {
269+ t.Skip("shell scripts as fake binaries")
270+ }
271+ bin := t.TempDir()
272+ llama := filepath.Join(bin, "llama")
273+ _ = os.WriteFile(llama, []byte("#!/bin/sh\n"), 0o755)
274+ t.Setenv("PATH", bin)
275+ dir := t.TempDir()
276+ o := Options{Host: "127.0.0.1", Port: 9931, Model: "org/m-GGUF:Q4_K_M", Args: []string{"-c", "8192"}}
277+
278+ got, args, err := command(o, dir)
279+ want := fmt.Sprintf("serve --host 127.0.0.1 --port 9931 --models-preset %s -c 8192", filepath.Join(dir, "models.ini"))
280+ if err != nil || got != llama || strings.Join(args, " ") != want {
281+ t.Errorf("llama only: %s %v (%v), want %s %s", got, args, err, llama, want)
282+ }
283+ preset, _ := os.ReadFile(filepath.Join(dir, "models.ini"))
284+ if !strings.Contains(string(preset), "[org/m-GGUF:Q4_K_M]\nhf-repo = org/m-GGUF:Q4_K_M\n") {
285+ t.Errorf("preset:\n%s", preset)
286+ }
287+
288+ server := filepath.Join(bin, "llama-server")
289+ _ = os.WriteFile(server, []byte("#!/bin/sh\n"), 0o755)
290+ if got, args, _ := command(o, dir); got != server || args[0] != "--host" {
291+ t.Errorf("llama-server present: %s %v", got, args)
292+ }
293+
294+ t.Setenv("PATH", t.TempDir())
295+ if _, _, err := command(o, dir); err != ErrNotFound {
296+ t.Errorf("nothing on PATH: %v, want ErrNotFound", err)
297+ }
298+}
new file mode 100644
@@ -0,0 +1,298 @@
1+package llamastart
2+
3+import (
4+ "bufio"
5+ "context"
6+ "encoding/json"
7+ "flag"
8+ "fmt"
9+ "net"
10+ "net/http"
11+ "net/http/httptest"
12+ "os"
13+ "os/exec"
14+ "path/filepath"
15+ "runtime"
16+ "strconv"
17+ "strings"
18+ "sync"
19+ "testing"
20+ "time"
21+)
22+
23+// The test binary is also the fake llama-server: started with
24+// LLAMASTART_FAKE=1 it serves what a router answers (measured, see the
25+// package comment) — /health, /models with the preset's models and their
26+// status, /models/load that loads after a moment or fails for a model whose
27+// name holds "fail". LLAMASTART_FAKE=hang never answers.
28+func TestMain(m *testing.M) {
29+ switch os.Getenv("LLAMASTART_FAKE") {
30+ case "1":
31+ fakeRouter()
32+ return
33+ case "hang":
34+ time.Sleep(time.Minute)
35+ return
36+ }
37+ os.Exit(m.Run())
38+}
39+
40+func fakeRouter() {
41+ fs := flag.NewFlagSet("fake", flag.ExitOnError)
42+ host := fs.String("host", "127.0.0.1", "")
43+ port := fs.Int("port", 0, "")
44+ preset := fs.String("models-preset", "", "")
45+ _ = fs.Parse(os.Args[1:])
46+
47+ var mu sync.Mutex
48+ status := map[string]string{}
49+ if f, err := os.Open(*preset); err == nil {
50+ sc := bufio.NewScanner(f)
51+ for sc.Scan() {
52+ if l := sc.Text(); strings.HasPrefix(l, "[") {
53+ status[strings.Trim(l, "[]")] = "unloaded"
54+ }
55+ }
56+ _ = f.Close()
57+ }
58+ mux := http.NewServeMux()
59+ mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"status":"ok"}`)) })
60+ mux.HandleFunc("/models", func(w http.ResponseWriter, _ *http.Request) {
61+ mu.Lock()
62+ defer mu.Unlock()
63+ var data []map[string]any
64+ for id, s := range status {
65+ st := map[string]any{"value": s}
66+ if s == "failed" {
67+ st = map[string]any{"value": "unloaded", "failed": true, "exit_code": 1}
68+ }
69+ data = append(data, map[string]any{"id": id, "status": st})
70+ }
71+ _ = json.NewEncoder(w).Encode(map[string]any{"data": data, "object": "list"})
72+ })
73+ mux.HandleFunc("/models/load", func(w http.ResponseWriter, r *http.Request) {
74+ var body struct{ Model string }
75+ _ = json.NewDecoder(r.Body).Decode(&body)
76+ mu.Lock()
77+ defer mu.Unlock()
78+ if _, ok := status[body.Model]; !ok {
79+ w.WriteHeader(http.StatusNotFound)
80+ return
81+ }
82+ status[body.Model] = "loading"
83+ go func() {
84+ time.Sleep(300 * time.Millisecond)
85+ mu.Lock()
86+ defer mu.Unlock()
87+ status[body.Model] = map[bool]string{true: "failed", false: "loaded"}[strings.Contains(body.Model, "fail")]
88+ }()
89+ _, _ = w.Write([]byte(`{"success":true}`))
90+ })
91+ _ = http.ListenAndServe(net.JoinHostPort(*host, strconv.Itoa(*port)), mux)
92+}
93+
94+func freePort(t *testing.T) int {
95+ t.Helper()
96+ l, err := net.Listen("tcp", "127.0.0.1:0")
97+ if err != nil {
98+ t.Fatal(err)
99+ }
100+ defer func() { _ = l.Close() }()
101+ return l.Addr().(*net.TCPAddr).Port
102+}
103+
104+// options for a fake server on a free port, the registry in a temp dir.
105+func options(t *testing.T, model string) (Options, *[]string) {
106+ t.Helper()
107+ if runtime.GOOS == "windows" {
108+ t.Skip("the fake server relies on process groups and signals")
109+ }
110+ t.Setenv("LLAMASTART_FAKE", "1")
111+ self, err := os.Executable()
112+ if err != nil {
113+ t.Fatal(err)
114+ }
115+ var lines []string
116+ o := Options{Binary: self, Host: "127.0.0.1", Port: freePort(t), Model: model,
117+ StateDir: t.TempDir(), Timeout: 10 * time.Second,
118+ Report: func(l string) { lines = append(lines, l) }}
119+ t.Cleanup(func() {
120+ if dir, err := registryDir(o); err == nil {
121+ if r := readRecord(dir); r != nil {
122+ stop(r.PID)
123+ }
124+ }
125+ })
126+ return o, &lines
127+}
128+
129+func base(o Options) string { return "http://" + hostPort(o.Host, o.Port) }
130+
131+// otherSession is a live process standing for another mm: its lease keeps
132+// the server running.
133+func otherSession(t *testing.T, o Options) *exec.Cmd {
134+ t.Helper()
135+ cmd := exec.Command("sleep", "30")
136+ if err := cmd.Start(); err != nil {
137+ t.Fatal(err)
138+ }
139+ t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() })
140+ dir, _ := registryDir(o)
141+ _ = os.WriteFile(filepath.Join(dir, "leases", strconv.Itoa(cmd.Process.Pid)), nil, 0o644)
142+ return cmd
143+}
144+
145+// Nothing answers: mm starts the server, loads the model, and the last
146+// session's release stops it; while another session holds a lease, a
147+// release keeps it. A crashed session's lease does not keep it forever.
148+func TestAcquireStartsSharesAndStopsWithTheLastSession(t *testing.T) {
149+ o, lines := options(t, "org/model-GGUF:Q4_K_M")
150+ l1, err := Acquire(context.Background(), o)
151+ if err != nil || l1 == nil {
152+ t.Fatalf("Acquire: %v, %v", l1, err)
153+ }
154+ if !healthy(base(o)) {
155+ t.Fatal("the server does not answer after Acquire")
156+ }
157+ if m, _, _ := findModel(context.Background(), base(o), o.Model); m.Status.Value != "loaded" {
158+ t.Fatalf("model status %q, want loaded", m.Status.Value)
159+ }
160+ if data, _ := os.ReadFile(LogPath(o)); data == nil {
161+ t.Error("no log file")
162+ }
163+
164+ other := otherSession(t, o)
165+ l1.Release()
166+ l1.Release() // twice: no effect
167+ if !healthy(base(o)) {
168+ t.Fatal("a release stopped the server another session uses")
169+ }
170+
171+ l2, err := Acquire(context.Background(), o)
172+ if err != nil || l2 == nil {
173+ t.Fatalf("second Acquire: %v, %v", l2, err)
174+ }
175+ _ = other.Process.Kill()
176+ _ = other.Wait() // the other session crashed: its lease is stale
177+ l2.Release()
178+ deadline := time.Now().Add(3 * time.Second)
179+ for healthy(base(o)) && time.Now().Before(deadline) {
180+ time.Sleep(50 * time.Millisecond)
181+ }
182+ if healthy(base(o)) {
183+ t.Fatal("the last release did not stop the server")
184+ }
185+ dir, _ := registryDir(o)
186+ if readRecord(dir) != nil {
187+ t.Error("server.json left behind")
188+ }
189+ got := strings.Join(*lines, "\n")
190+ for _, want := range []string{"starting llama-server", "loaded", "kept running: 1 other", "already started by mm", "stopped llama-server"} {
191+ if !strings.Contains(got, want) {
192+ t.Errorf("report lacks %q:\n%s", want, got)
193+ }
194+ }
195+}
196+
197+// A server mm did not start answers already: no lease, never stopped.
198+func TestAcquireLeavesAForeignServerAlone(t *testing.T) {
199+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}))
200+ t.Cleanup(srv.Close)
201+ addr := srv.Listener.Addr().(*net.TCPAddr)
202+ l, err := Acquire(context.Background(), Options{Host: "127.0.0.1", Port: addr.Port, Model: "m", StateDir: t.TempDir()})
203+ if l != nil || err != nil {
204+ t.Fatalf("Acquire = %v, %v, want no lease and no error", l, err)
205+ }
206+ l.Release() // nil lease: nothing
207+ if resp, err := http.Get(srv.URL + "/health"); err != nil {
208+ t.Fatal("the foreign server was stopped")
209+ } else {
210+ _ = resp.Body.Close()
211+ }
212+}
213+
214+// A model the server cannot load is an error that names the log; the
215+// lease is still returned, so the exit stops the server.
216+func TestAcquireReportsAFailedLoad(t *testing.T) {
217+ o, _ := options(t, "org/fail-GGUF:Q4_K_M")
218+ l, err := Acquire(context.Background(), o)
219+ if err == nil || !strings.Contains(err.Error(), "could not load") || !strings.Contains(err.Error(), "llama-server.log") {
220+ t.Fatalf("err = %v, want could not load + the log", err)
221+ }
222+ if l == nil {
223+ t.Fatal("no lease: the server would never be stopped")
224+ }
225+ l.Release()
226+ if healthy(base(o)) {
227+ t.Error("server still running after the release")
228+ }
229+}
230+
231+// A server that never answers is stopped after the timeout.
232+func TestAcquireTimesOut(t *testing.T) {
233+ o, _ := options(t, "")
234+ t.Setenv("LLAMASTART_FAKE", "hang")
235+ o.Timeout = 500 * time.Millisecond
236+ start := time.Now()
237+ _, err := Acquire(context.Background(), o)
238+ if err == nil || !strings.Contains(err.Error(), "did not answer within") {
239+ t.Fatalf("err = %v, want a timeout", err)
240+ }
241+ if time.Since(start) > 8*time.Second {
242+ t.Errorf("took %s", time.Since(start))
243+ }
244+ dir, _ := registryDir(o)
245+ if readRecord(dir) != nil {
246+ t.Error("server.json left behind")
247+ }
248+}
249+
250+// A lock left by a process that is gone is taken over.
251+func TestStaleLockIsTakenOver(t *testing.T) {
252+ dir := t.TempDir()
253+ dead := exec.Command("true")
254+ _ = dead.Run()
255+ _ = os.WriteFile(filepath.Join(dir, "lock"), []byte(strconv.Itoa(dead.Process.Pid)), 0o644)
256+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
257+ defer cancel()
258+ unlock, err := lock(ctx, dir)
259+ if err != nil {
260+ t.Fatalf("lock: %v", err)
261+ }
262+ unlock()
263+}
264+
265+// The binary: llama-server first, else llama (as `llama serve`); a
266+// configured path named llama gets `serve` too; none is ErrNotFound.
267+func TestCommandFindsTheBinary(t *testing.T) {
268+ if runtime.GOOS == "windows" {
269+ t.Skip("shell scripts as fake binaries")
270+ }
271+ bin := t.TempDir()
272+ llama := filepath.Join(bin, "llama")
273+ _ = os.WriteFile(llama, []byte("#!/bin/sh\n"), 0o755)
274+ t.Setenv("PATH", bin)
275+ dir := t.TempDir()
276+ o := Options{Host: "127.0.0.1", Port: 9931, Model: "org/m-GGUF:Q4_K_M", Args: []string{"-c", "8192"}}
277+
278+ got, args, err := command(o, dir)
279+ want := fmt.Sprintf("serve --host 127.0.0.1 --port 9931 --models-preset %s -c 8192", filepath.Join(dir, "models.ini"))
280+ if err != nil || got != llama || strings.Join(args, " ") != want {
281+ t.Errorf("llama only: %s %v (%v), want %s %s", got, args, err, llama, want)
282+ }
283+ preset, _ := os.ReadFile(filepath.Join(dir, "models.ini"))
284+ if !strings.Contains(string(preset), "[org/m-GGUF:Q4_K_M]\nhf-repo = org/m-GGUF:Q4_K_M\n") {
285+ t.Errorf("preset:\n%s", preset)
286+ }
287+
288+ server := filepath.Join(bin, "llama-server")
289+ _ = os.WriteFile(server, []byte("#!/bin/sh\n"), 0o755)
290+ if got, args, _ := command(o, dir); got != server || args[0] != "--host" {
291+ t.Errorf("llama-server present: %s %v", got, args)
292+ }
293+
294+ t.Setenv("PATH", t.TempDir())
295+ if _, _, err := command(o, dir); err != ErrNotFound {
296+ t.Errorf("nothing on PATH: %v, want ErrNotFound", err)
297+ }
298+}
added internal/llamastart/proc_unix.go +50 -0
new file mode 100644
@@ -0,0 +1,50 @@
1+//go:build !windows
2+
3+package llamastart
4+
5+import (
6+ "errors"
7+ "os"
8+ "os/exec"
9+ "strconv"
10+ "strings"
11+ "syscall"
12+ "time"
13+)
14+
15+// detach puts the server in its own process group: a Ctrl-C in mm's
16+// terminal does not reach it, and stop can end the router with the model
17+// processes it started.
18+func detach(cmd *exec.Cmd) {
19+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
20+}
21+
22+// alive reports whether pid runs. A zombie (ended, not yet reaped — a
23+// container whose pid 1 does not reap) is not alive.
24+func alive(pid int) bool {
25+ if pid <= 0 {
26+ return false
27+ }
28+ err := syscall.Kill(pid, 0)
29+ if err != nil && !errors.Is(err, syscall.EPERM) {
30+ return false
31+ }
32+ if stat, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat"); err == nil {
33+ // "pid (comm) S …": the state follows the last ')'.
34+ if i := strings.LastIndexByte(string(stat), ')'); i > 0 && i+2 < len(stat) && stat[i+2] == 'Z' {
35+ return false
36+ }
37+ }
38+ return true
39+}
40+
41+// stop ends the server's process group: SIGTERM, then SIGKILL after
42+// stopGrace.
43+func stop(pid int) {
44+ _ = syscall.Kill(-pid, syscall.SIGTERM)
45+ deadline := time.Now().Add(stopGrace)
46+ for alive(pid) && time.Now().Before(deadline) {
47+ time.Sleep(poll)
48+ }
49+ _ = syscall.Kill(-pid, syscall.SIGKILL)
50+}
new file mode 100644
@@ -0,0 +1,50 @@
1+//go:build !windows
2+
3+package llamastart
4+
5+import (
6+ "errors"
7+ "os"
8+ "os/exec"
9+ "strconv"
10+ "strings"
11+ "syscall"
12+ "time"
13+)
14+
15+// detach puts the server in its own process group: a Ctrl-C in mm's
16+// terminal does not reach it, and stop can end the router with the model
17+// processes it started.
18+func detach(cmd *exec.Cmd) {
19+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
20+}
21+
22+// alive reports whether pid runs. A zombie (ended, not yet reaped — a
23+// container whose pid 1 does not reap) is not alive.
24+func alive(pid int) bool {
25+ if pid <= 0 {
26+ return false
27+ }
28+ err := syscall.Kill(pid, 0)
29+ if err != nil && !errors.Is(err, syscall.EPERM) {
30+ return false
31+ }
32+ if stat, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat"); err == nil {
33+ // "pid (comm) S …": the state follows the last ')'.
34+ if i := strings.LastIndexByte(string(stat), ')'); i > 0 && i+2 < len(stat) && stat[i+2] == 'Z' {
35+ return false
36+ }
37+ }
38+ return true
39+}
40+
41+// stop ends the server's process group: SIGTERM, then SIGKILL after
42+// stopGrace.
43+func stop(pid int) {
44+ _ = syscall.Kill(-pid, syscall.SIGTERM)
45+ deadline := time.Now().Add(stopGrace)
46+ for alive(pid) && time.Now().Before(deadline) {
47+ time.Sleep(poll)
48+ }
49+ _ = syscall.Kill(-pid, syscall.SIGKILL)
50+}
added internal/llamastart/proc_windows.go +47 -0
new file mode 100644
@@ -0,0 +1,47 @@
1+//go:build windows
2+
3+package llamastart
4+
5+import (
6+ "os/exec"
7+ "strconv"
8+ "syscall"
9+)
10+
11+const (
12+ detachedProcess = 0x00000008
13+ processQueryLimitedInfo = 0x1000
14+ stillActive = 259
15+)
16+
17+// detach starts the server in its own process group, with no console: a
18+// Ctrl-C in mm's console does not reach it.
19+func detach(cmd *exec.Cmd) {
20+ cmd.SysProcAttr = &syscall.SysProcAttr{
21+ CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP | detachedProcess,
22+ HideWindow: true,
23+ }
24+}
25+
26+// alive reports whether pid runs.
27+func alive(pid int) bool {
28+ if pid <= 0 {
29+ return false
30+ }
31+ h, err := syscall.OpenProcess(processQueryLimitedInfo, false, uint32(pid))
32+ if err != nil {
33+ return false
34+ }
35+ defer func() { _ = syscall.CloseHandle(h) }()
36+ var code uint32
37+ if syscall.GetExitCodeProcess(h, &code) != nil {
38+ return false
39+ }
40+ return code == stillActive
41+}
42+
43+// stop ends the server and the model processes it started: Windows has no
44+// SIGTERM, taskkill /T ends the whole tree.
45+func stop(pid int) {
46+ _ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
47+}
new file mode 100644
@@ -0,0 +1,47 @@
1+//go:build windows
2+
3+package llamastart
4+
5+import (
6+ "os/exec"
7+ "strconv"
8+ "syscall"
9+)
10+
11+const (
12+ detachedProcess = 0x00000008
13+ processQueryLimitedInfo = 0x1000
14+ stillActive = 259
15+)
16+
17+// detach starts the server in its own process group, with no console: a
18+// Ctrl-C in mm's console does not reach it.
19+func detach(cmd *exec.Cmd) {
20+ cmd.SysProcAttr = &syscall.SysProcAttr{
21+ CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP | detachedProcess,
22+ HideWindow: true,
23+ }
24+}
25+
26+// alive reports whether pid runs.
27+func alive(pid int) bool {
28+ if pid <= 0 {
29+ return false
30+ }
31+ h, err := syscall.OpenProcess(processQueryLimitedInfo, false, uint32(pid))
32+ if err != nil {
33+ return false
34+ }
35+ defer func() { _ = syscall.CloseHandle(h) }()
36+ var code uint32
37+ if syscall.GetExitCodeProcess(h, &code) != nil {
38+ return false
39+ }
40+ return code == stillActive
41+}
42+
43+// stop ends the server and the model processes it started: Windows has no
44+// SIGTERM, taskkill /T ends the whole tree.
45+func stop(pid int) {
46+ _ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
47+}
added llama_wiring.go +60 -0
new file mode 100644
@@ -0,0 +1,60 @@
1+package main
2+
3+import (
4+ "context"
5+ "fmt"
6+ "os"
7+ "os/signal"
8+ "syscall"
9+
10+ "mm/internal/ask"
11+ "mm/internal/config"
12+ "mm/internal/engine"
13+ "mm/internal/llamastart"
14+ "mm/internal/spinner"
15+)
16+
17+// startLlamaServer starts llama-server for a llamacpp agent with
18+// llamacpp.autoStart when nothing answers at its address (ticket 223), and
19+// returns this process's lease on the server mm started — nil when mm did
20+// not start it (nothing to do, or the user's own server answers). A failure
21+// is a warning: mm goes on as without autoStart, and the probe says what
22+// does not answer.
23+func startLlamaServer(ctx context.Context, acpMode bool) *llamastart.Lease {
24+ host, port, ok := engine.LlamaStartAddress(config.Cfg)
25+ if !ok {
26+ return nil
27+ }
28+ lc := config.Cfg.LlamaCpp
29+ timeout := lc.StartTimeout
30+ if timeout <= 0 {
31+ timeout = config.DefaultLlamaStartTimeout
32+ }
33+ o := llamastart.Options{
34+ Binary: lc.Server, Args: lc.LaunchArgs(), Host: host, Port: port,
35+ Model: config.Cfg.Model, Timeout: timeout,
36+ // stderr, like autoPull's progress: stdout may carry a -p answer.
37+ Report: func(line string) { _, _ = fmt.Fprintln(os.Stderr, line) },
38+ }
39+ // The spinner in a terminal; in ACP mode (disabled spinner) and in an
40+ // agent asked by another one, the report lines only.
41+ if !acpMode && ask.Depth() == 0 {
42+ o.Wait = func(text string) func() { spinner.Start(text); return spinner.Stop }
43+ }
44+ // A download can take minutes: Ctrl-C, SIGTERM or SIGHUP meanwhile
45+ // stop the start — and the server, unless another mm uses it — then mm.
46+ sigCtx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
47+ defer stop()
48+ // The lease comes back even with an error after a start (the model
49+ // failed to load): the exit must still stop the server.
50+ lease, err := llamastart.Acquire(sigCtx, o)
51+ if sigCtx.Err() != nil && ctx.Err() == nil {
52+ _, _ = fmt.Fprintln(os.Stderr, "\n[llamacpp.autoStart: interrupted]")
53+ lease.Release()
54+ os.Exit(130)
55+ }
56+ if err != nil {
57+ _, _ = fmt.Fprintf(os.Stderr, "[warning: llamacpp.autoStart: %v]\n", err)
58+ }
59+ return lease
60+}
new file mode 100644
@@ -0,0 +1,60 @@
1+package main
2+
3+import (
4+ "context"
5+ "fmt"
6+ "os"
7+ "os/signal"
8+ "syscall"
9+
10+ "mm/internal/ask"
11+ "mm/internal/config"
12+ "mm/internal/engine"
13+ "mm/internal/llamastart"
14+ "mm/internal/spinner"
15+)
16+
17+// startLlamaServer starts llama-server for a llamacpp agent with
18+// llamacpp.autoStart when nothing answers at its address (ticket 223), and
19+// returns this process's lease on the server mm started — nil when mm did
20+// not start it (nothing to do, or the user's own server answers). A failure
21+// is a warning: mm goes on as without autoStart, and the probe says what
22+// does not answer.
23+func startLlamaServer(ctx context.Context, acpMode bool) *llamastart.Lease {
24+ host, port, ok := engine.LlamaStartAddress(config.Cfg)
25+ if !ok {
26+ return nil
27+ }
28+ lc := config.Cfg.LlamaCpp
29+ timeout := lc.StartTimeout
30+ if timeout <= 0 {
31+ timeout = config.DefaultLlamaStartTimeout
32+ }
33+ o := llamastart.Options{
34+ Binary: lc.Server, Args: lc.LaunchArgs(), Host: host, Port: port,
35+ Model: config.Cfg.Model, Timeout: timeout,
36+ // stderr, like autoPull's progress: stdout may carry a -p answer.
37+ Report: func(line string) { _, _ = fmt.Fprintln(os.Stderr, line) },
38+ }
39+ // The spinner in a terminal; in ACP mode (disabled spinner) and in an
40+ // agent asked by another one, the report lines only.
41+ if !acpMode && ask.Depth() == 0 {
42+ o.Wait = func(text string) func() { spinner.Start(text); return spinner.Stop }
43+ }
44+ // A download can take minutes: Ctrl-C, SIGTERM or SIGHUP meanwhile
45+ // stop the start — and the server, unless another mm uses it — then mm.
46+ sigCtx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
47+ defer stop()
48+ // The lease comes back even with an error after a start (the model
49+ // failed to load): the exit must still stop the server.
50+ lease, err := llamastart.Acquire(sigCtx, o)
51+ if sigCtx.Err() != nil && ctx.Err() == nil {
52+ _, _ = fmt.Fprintln(os.Stderr, "\n[llamacpp.autoStart: interrupted]")
53+ lease.Release()
54+ os.Exit(130)
55+ }
56+ if err != nil {
57+ _, _ = fmt.Fprintf(os.Stderr, "[warning: llamacpp.autoStart: %v]\n", err)
58+ }
59+ return lease
60+}
modified main.go +20 -18
@@ -267,22 +267,29 @@ func main() {
267267
268268 window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode)
269269
270+ // Every way out from here on — main returning, exit(), a signal — runs
271+ // onExit: the model's unload (unloadOnExit, ticket 255), then the
272+ // llama-server lease (llamacpp.autoStart, ticket 223).
273+ defer onExit.run()
274+ // llamacpp.autoStart (ticket 223): nothing answers at the agent's
275+ // address, mm starts llama-server and waits for the model — before the
276+ // engine picks its address, so it finds the server it started. It
277+ // handles a signal during the start itself; the watch starts after.
278+ onExit.release = startLlamaServer(ctx, *acpMode).Release
279+ defer watchExitSignals(onExit, *promptMode != "")()
280+
270281 e, err := engine.New(ctx)
271282 if err != nil {
272283 fail("[engine error: %v ]", err)
273- os.Exit(1)
284+ exit(1)
274285 }
275286 // autoPull (ticket 61): the missing models are downloaded before the
276287 // agent is ready, the progress on stderr.
277288 if err := autoPull(ctx, e, os.Stderr, stderrIsTerminal()); err != nil {
278289 fail("[engine error: %v ]", err)
279- os.Exit(1)
290+ exit(1)
280291 }
281- // unloadOnExit (ticket 255): the model leaves the server's memory on
282- // every way out — main returning, the os.Exit calls below, a signal.
283- exitU := newExitUnload(e, *acpMode)
284- defer exitU.run()
285- defer watchExitSignals(exitU, *promptMode != "")()
292+ onExit.arm(e, *acpMode)
286293
287294 // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this
288295 // agent's model before the hand-off, the asked agent's after it.
@@ -310,7 +317,7 @@ func main() {
310317 // is started for a file that is about to be refused.
311318 if err := config.DecisionConflict(); err != nil {
312319 fail("[config error: %v ]", err)
313- os.Exit(1)
320+ exit(1)
314321 }
315322 set := assembleTools(e, loopDetector, asker)
316323 defer set.close()
@@ -318,12 +325,12 @@ func main() {
318325 if err := config.StructuredOutputConflict(set.names); err != nil {
319326 fail("[config error: %v ]", err)
320327 set.close()
321- os.Exit(1)
328+ exit(1)
322329 }
323330 if err := installRouter(); err != nil {
324331 fail("[config error: %v ]", err)
325332 set.close()
326- os.Exit(1)
333+ exit(1)
327334 }
328335 agentTools := set.tools
329336 set.warnings = append(set.warnings, ask.Missing()...)
@@ -331,14 +338,10 @@ func main() {
331338 // Handle prompt mode: run a single prompt and exit
332339 if *promptMode != "" && e.IsDecider() {
333340 ui.Out = os.Stderr
334- code := runDecisionPrompt(ctx, e, *promptMode, os.Stdout)
335- exitU.run()
336- os.Exit(code)
341+ exit(runDecisionPrompt(ctx, e, *promptMode, os.Stdout))
337342 }
338343 if *promptMode != "" && config.Cfg.OutputSchema != nil {
339- code := runStructuredPrompt(ctx, e, *promptMode)
340- exitU.run()
341- os.Exit(code)
344+ exit(runStructuredPrompt(ctx, e, *promptMode))
342345 }
343346 if *promptMode != "" {
344347 // In prompt mode, no banner, no session persistence. A failed
@@ -347,8 +350,7 @@ func main() {
347350 if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {
348351 set.close()
349352 asker.Close()
350- exitU.run()
351- os.Exit(code)
353+ exit(code)
352354 }
353355 return
354356 }
@@ -267,22 +267,29 @@ func main() {
267 267
268 window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode)268 window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode)
269 269
270+ // Every way out from here on — main returning, exit(), a signal — runs
271+ // onExit: the model's unload (unloadOnExit, ticket 255), then the
272+ // llama-server lease (llamacpp.autoStart, ticket 223).
273+ defer onExit.run()
274+ // llamacpp.autoStart (ticket 223): nothing answers at the agent's
275+ // address, mm starts llama-server and waits for the model — before the
276+ // engine picks its address, so it finds the server it started. It
277+ // handles a signal during the start itself; the watch starts after.
278+ onExit.release = startLlamaServer(ctx, *acpMode).Release
279+ defer watchExitSignals(onExit, *promptMode != "")()
280+
270 e, err := engine.New(ctx)281 e, err := engine.New(ctx)
271 if err != nil {282 if err != nil {
272 fail("[engine error: %v ]", err)283 fail("[engine error: %v ]", err)
273- os.Exit(1)284+ exit(1)
274 }285 }
275 // autoPull (ticket 61): the missing models are downloaded before the286 // autoPull (ticket 61): the missing models are downloaded before the
276 // agent is ready, the progress on stderr.287 // agent is ready, the progress on stderr.
277 if err := autoPull(ctx, e, os.Stderr, stderrIsTerminal()); err != nil {288 if err := autoPull(ctx, e, os.Stderr, stderrIsTerminal()); err != nil {
278 fail("[engine error: %v ]", err)289 fail("[engine error: %v ]", err)
279- os.Exit(1)290+ exit(1)
280 }291 }
281- // unloadOnExit (ticket 255): the model leaves the server's memory on292+ onExit.arm(e, *acpMode)
282- // every way out — main returning, the os.Exit calls below, a signal.
283- exitU := newExitUnload(e, *acpMode)
284- defer exitU.run()
285- defer watchExitSignals(exitU, *promptMode != "")()
286 293
287 // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this294 // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this
288 // agent's model before the hand-off, the asked agent's after it.295 // agent's model before the hand-off, the asked agent's after it.
@@ -310,7 +317,7 @@ func main() {
310 // is started for a file that is about to be refused.317 // is started for a file that is about to be refused.
311 if err := config.DecisionConflict(); err != nil {318 if err := config.DecisionConflict(); err != nil {
312 fail("[config error: %v ]", err)319 fail("[config error: %v ]", err)
313- os.Exit(1)320+ exit(1)
314 }321 }
315 set := assembleTools(e, loopDetector, asker)322 set := assembleTools(e, loopDetector, asker)
316 defer set.close()323 defer set.close()
@@ -318,12 +325,12 @@ func main() {
318 if err := config.StructuredOutputConflict(set.names); err != nil {325 if err := config.StructuredOutputConflict(set.names); err != nil {
319 fail("[config error: %v ]", err)326 fail("[config error: %v ]", err)
320 set.close()327 set.close()
321- os.Exit(1)328+ exit(1)
322 }329 }
323 if err := installRouter(); err != nil {330 if err := installRouter(); err != nil {
324 fail("[config error: %v ]", err)331 fail("[config error: %v ]", err)
325 set.close()332 set.close()
326- os.Exit(1)333+ exit(1)
327 }334 }
328 agentTools := set.tools335 agentTools := set.tools
329 set.warnings = append(set.warnings, ask.Missing()...)336 set.warnings = append(set.warnings, ask.Missing()...)
@@ -331,14 +338,10 @@ func main() {
331 // Handle prompt mode: run a single prompt and exit338 // Handle prompt mode: run a single prompt and exit
332 if *promptMode != "" && e.IsDecider() {339 if *promptMode != "" && e.IsDecider() {
333 ui.Out = os.Stderr340 ui.Out = os.Stderr
334- code := runDecisionPrompt(ctx, e, *promptMode, os.Stdout)341+ exit(runDecisionPrompt(ctx, e, *promptMode, os.Stdout))
335- exitU.run()
336- os.Exit(code)
337 }342 }
338 if *promptMode != "" && config.Cfg.OutputSchema != nil {343 if *promptMode != "" && config.Cfg.OutputSchema != nil {
339- code := runStructuredPrompt(ctx, e, *promptMode)344+ exit(runStructuredPrompt(ctx, e, *promptMode))
340- exitU.run()
341- os.Exit(code)
342 }345 }
343 if *promptMode != "" {346 if *promptMode != "" {
344 // In prompt mode, no banner, no session persistence. A failed347 // In prompt mode, no banner, no session persistence. A failed
@@ -347,8 +350,7 @@ func main() {
347 if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {350 if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {
348 set.close()351 set.close()
349 asker.Close()352 asker.Close()
350- exitU.run()353+ exit(code)
351- os.Exit(code)
352 }354 }
353 return355 return
354 }356 }
modified unload_exit.go +37 -14
@@ -28,37 +28,60 @@ import (
2828 // A crash unloads nothing; the next start or the server's own idle timeout
2929 // takes care of it.
3030
31-// exitUnload unloads the agent's model once, within timeout. A zero
32-// exitUnload (unloadOnExit: false) does nothing.
31+// exitUnload unloads the agent's model once, within timeout, then runs
32+// release — the llama-server lease (ticket 223), which may stop the server.
33+// A zero exitUnload does nothing.
3334 type exitUnload struct {
3435 once sync.Once
3536 model string
36- unload func(ctx context.Context) string // "" = nothing to say
37+ unload func(ctx context.Context) string // "" = nothing to say; nil = unloadOnExit off
3738 timeout time.Duration
3839 out io.Writer // nil = say nothing (ACP mode: stderr is the editor's log)
40+ release func() // nil = no lease
3941 }
4042
41-// newExitUnload reads unloadOnExit and wires e's unload, its line going to
42-// stderr — stdout may be a -p answer or the ACP protocol.
43-func newExitUnload(e *engine.Engine, acpMode bool) *exitUnload {
43+// onExit is what every way out of mm runs (see exit).
44+var onExit = &exitUnload{}
45+
46+// exit runs onExit, then ends the process: the os.Exit of main once a
47+// server may have been started or a model loaded.
48+func exit(code int) {
49+ onExit.run()
50+ os.Exit(code)
51+}
52+
53+// arm reads unloadOnExit and wires e's unload, its line going to stderr —
54+// stdout may be a -p answer or the ACP protocol.
55+func (u *exitUnload) arm(e *engine.Engine, acpMode bool) {
4456 if !config.Cfg.UnloadOnExit {
45- return &exitUnload{}
57+ return
4658 }
47- u := &exitUnload{model: e.Backend.Model, unload: e.UnloadOnExit, timeout: config.UnloadOnExitTimeout}
59+ u.model, u.unload, u.timeout = e.Backend.Model, e.UnloadOnExit, config.UnloadOnExitTimeout
4860 if !acpMode {
4961 u.out = os.Stderr
5062 }
51- return u
5263 }
5364
54-// run unloads the model the first time it is called and does nothing after.
55-// It returns within u.timeout even when the unload does not: the request is
56-// left behind, the process is about to end.
65+// run unloads the model and releases the lease the first time it is called,
66+// and does nothing after. The unload returns within u.timeout even when the
67+// request does not: it is left behind, the process is about to end.
5768 func (u *exitUnload) run() {
58- if u == nil || u.unload == nil {
69+ if u == nil {
5970 return
6071 }
6172 u.once.Do(func() {
73+ u.unloadModel()
74+ if u.release != nil {
75+ u.release()
76+ }
77+ })
78+}
79+
80+func (u *exitUnload) unloadModel() {
81+ if u.unload == nil {
82+ return
83+ }
84+ {
6285 ctx, cancel := context.WithTimeout(context.Background(), u.timeout)
6386 defer cancel()
6487 done := make(chan string, 1)
@@ -72,7 +95,7 @@ func (u *exitUnload) run() {
7295 if line != "" && u.out != nil {
7396 _, _ = fmt.Fprintf(u.out, "🧹 %s\n", line)
7497 }
75- })
98+ }
7699 }
77100
78101 // watchExitSignals catches the signals that would end mm without main
@@ -28,37 +28,60 @@ import (
28 // A crash unloads nothing; the next start or the server's own idle timeout28 // A crash unloads nothing; the next start or the server's own idle timeout
29 // takes care of it.29 // takes care of it.
30 30
31-// exitUnload unloads the agent's model once, within timeout. A zero31+// exitUnload unloads the agent's model once, within timeout, then runs
32-// exitUnload (unloadOnExit: false) does nothing.32+// release — the llama-server lease (ticket 223), which may stop the server.
33+// A zero exitUnload does nothing.
33 type exitUnload struct {34 type exitUnload struct {
34 once sync.Once35 once sync.Once
35 model string36 model string
36- unload func(ctx context.Context) string // "" = nothing to say37+ unload func(ctx context.Context) string // "" = nothing to say; nil = unloadOnExit off
37 timeout time.Duration38 timeout time.Duration
38 out io.Writer // nil = say nothing (ACP mode: stderr is the editor's log)39 out io.Writer // nil = say nothing (ACP mode: stderr is the editor's log)
40+ release func() // nil = no lease
39 }41 }
40 42
41-// newExitUnload reads unloadOnExit and wires e's unload, its line going to43+// onExit is what every way out of mm runs (see exit).
42-// stderr — stdout may be a -p answer or the ACP protocol.44+var onExit = &exitUnload{}
43-func newExitUnload(e *engine.Engine, acpMode bool) *exitUnload {45+
46+// exit runs onExit, then ends the process: the os.Exit of main once a
47+// server may have been started or a model loaded.
48+func exit(code int) {
49+ onExit.run()
50+ os.Exit(code)
51+}
52+
53+// arm reads unloadOnExit and wires e's unload, its line going to stderr —
54+// stdout may be a -p answer or the ACP protocol.
55+func (u *exitUnload) arm(e *engine.Engine, acpMode bool) {
44 if !config.Cfg.UnloadOnExit {56 if !config.Cfg.UnloadOnExit {
45- return &exitUnload{}57+ return
46 }58 }
47- u := &exitUnload{model: e.Backend.Model, unload: e.UnloadOnExit, timeout: config.UnloadOnExitTimeout}59+ u.model, u.unload, u.timeout = e.Backend.Model, e.UnloadOnExit, config.UnloadOnExitTimeout
48 if !acpMode {60 if !acpMode {
49 u.out = os.Stderr61 u.out = os.Stderr
50 }62 }
51- return u
52 }63 }
53 64
54-// run unloads the model the first time it is called and does nothing after.65+// run unloads the model and releases the lease the first time it is called,
55-// It returns within u.timeout even when the unload does not: the request is66+// and does nothing after. The unload returns within u.timeout even when the
56-// left behind, the process is about to end.67+// request does not: it is left behind, the process is about to end.
57 func (u *exitUnload) run() {68 func (u *exitUnload) run() {
58- if u == nil || u.unload == nil {69+ if u == nil {
59 return70 return
60 }71 }
61 u.once.Do(func() {72 u.once.Do(func() {
73+ u.unloadModel()
74+ if u.release != nil {
75+ u.release()
76+ }
77+ })
78+}
79+
80+func (u *exitUnload) unloadModel() {
81+ if u.unload == nil {
82+ return
83+ }
84+ {
62 ctx, cancel := context.WithTimeout(context.Background(), u.timeout)85 ctx, cancel := context.WithTimeout(context.Background(), u.timeout)
63 defer cancel()86 defer cancel()
64 done := make(chan string, 1)87 done := make(chan string, 1)
@@ -72,7 +95,7 @@ func (u *exitUnload) run() {
72 if line != "" && u.out != nil {95 if line != "" && u.out != nil {
73 _, _ = fmt.Fprintf(u.out, "🧹 %s\n", line)96 _, _ = fmt.Fprintf(u.out, "🧹 %s\n", line)
74 }97 }
75- })98+ }
76 }99 }
77 100
78 // watchExitSignals catches the signals that would end mm without main101 // watchExitSignals catches the signals that would end mm without main
modified unload_exit_test.go +20 -0
@@ -54,3 +54,23 @@ func TestExitUnloadTimeout(t *testing.T) {
5454 t.Errorf("out %q, want the timeout line", out.String())
5555 }
5656 }
57+
58+// The llama-server lease (ticket 223) is released once, after the unload,
59+// with or without unloadOnExit.
60+func TestExitReleasesTheLeaseAfterTheUnload(t *testing.T) {
61+ var order []string
62+ u := &exitUnload{model: "m", timeout: time.Second,
63+ unload: func(context.Context) string { order = append(order, "unload"); return "" },
64+ release: func() { order = append(order, "release") }}
65+ u.run()
66+ u.run()
67+ if strings.Join(order, ",") != "unload,release" {
68+ t.Errorf("order %v, want unload then release, once", order)
69+ }
70+
71+ released := 0
72+ (&exitUnload{release: func() { released++ }}).run() // unloadOnExit: false
73+ if released != 1 {
74+ t.Errorf("unloadOnExit off: released %d times, want 1", released)
75+ }
76+}
@@ -54,3 +54,23 @@ func TestExitUnloadTimeout(t *testing.T) {
54 t.Errorf("out %q, want the timeout line", out.String())54 t.Errorf("out %q, want the timeout line", out.String())
55 }55 }
56 }56 }
57+
58+// The llama-server lease (ticket 223) is released once, after the unload,
59+// with or without unloadOnExit.
60+func TestExitReleasesTheLeaseAfterTheUnload(t *testing.T) {
61+ var order []string
62+ u := &exitUnload{model: "m", timeout: time.Second,
63+ unload: func(context.Context) string { order = append(order, "unload"); return "" },
64+ release: func() { order = append(order, "release") }}
65+ u.run()
66+ u.run()
67+ if strings.Join(order, ",") != "unload,release" {
68+ t.Errorf("order %v, want unload then release, once", order)
69+ }
70+
71+ released := 0
72+ (&exitUnload{release: func() { released++ }}).run() // unloadOnExit: false
73+ if released != 1 {
74+ t.Errorf("unloadOnExit off: released %d times, want 1", released)
75+ }
76+}