bots-garden/mini-mepublic Fork
⑂ a1769fe
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

Merge feature/unload-on-exit into main

agent committed 2026-11-24T17:59:59+01:00 Browse files
a1769fe parents: 832f35a c6fc7ea
modified .tickets/issues/0255-unload-the-model-when-mini-me-exits-unloadonexit.yaml +46 -7
@@ -1,12 +1,12 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 255
33 title: Unload the model when mini-me exits (unloadOnExit, on by default)
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T07:02:40.000Z
9-updatedAt: 2026-11-24T07:02:40.000Z
9+updatedAt: 2026-11-24T16:59:50.000Z
1010 labels:
1111 - enhancement
1212 - kind::feature
@@ -67,34 +67,73 @@ body: |
6767 tasks:
6868 - id: 1
6969 title: Config key unloadOnExit (default true), validation, mm init writes it
70- state: open
70+ state: closed
7171 priority: none
7272 author:
7373 name: k33g
7474 email: ph.charriere@gmail.com
7575 createdAt: 2026-11-24T07:02:40.000Z
76+ updatedAt: 2026-11-24T16:57:13.000Z
77+ closedAt: 2026-11-24T16:57:13.000Z
7678 - id: 2
7779 title: Call Engine.Unload on every exit path (terminal, window, -p, ACP, signals) with a short timeout
78- state: open
80+ state: closed
7981 priority: high
8082 author:
8183 name: k33g
8284 email: ph.charriere@gmail.com
8385 createdAt: 2026-11-24T07:02:40.000Z
86+ updatedAt: 2026-11-24T16:57:13.000Z
87+ closedAt: 2026-11-24T16:57:13.000Z
8488 - id: 3
8589 title: Decide -p behaviour and other users of the same model (see #223)
86- state: open
90+ state: closed
8791 priority: medium
8892 author:
8993 name: k33g
9094 email: ph.charriere@gmail.com
9195 createdAt: 2026-11-24T07:02:40.000Z
96+ updatedAt: 2026-11-24T16:57:13.000Z
97+ closedAt: 2026-11-24T16:57:13.000Z
9298 - id: 4
9399 title: Tests, EN+FR docs, release note (behaviour change)
94- state: open
100+ state: closed
95101 priority: none
96102 author:
97103 name: k33g
98104 email: ph.charriere@gmail.com
99105 createdAt: 2026-11-24T07:02:40.000Z
100-comments: []
106+ updatedAt: 2026-11-24T16:57:13.000Z
107+ closedAt: 2026-11-24T16:57:13.000Z
108+comments:
109+ - id: 1
110+ author:
111+ name: k33g
112+ email: ph.charriere@gmail.com
113+ createdAt: 2026-11-24T16:57:13.000Z
114+ body: |
115+ Implemented on branch `feature/unload-on-exit` (not committed).
116+ - `unloadOnExit` (default true) + `AGENT_UNLOAD_ON_EXIT`; `mm init` writes it.
117+ - `Engine.UnloadOnExit`: silent when not loaded or when the server cannot
118+ unload (dmr, openai, single-model llama-server: new `errCannotUnload`).
119+ - `unload_exit.go`: `exitUnload.run` (once, 3 s bound even if the request
120+ ignores its context) on main's return, before each `os.Exit` of the -p
121+ paths, and on SIGTERM/SIGHUP (+ SIGINT during -p) → exit 128+sig.
122+ One `🧹` line on stderr, none in ACP mode.
123+ Decisions: `-p` keeps the same default (the file decides;
124+ `AGENT_UNLOAD_ON_EXIT=false` for loops); only the agent's own model
125+ (mmConfigs agents unload their own when they stop; decision models not);
126+ independent of `unloadModels`; no lease (#223) — other users of the model
127+ are cut, documented.
128+ Live on mlx-serve 26.11.3 (E4B): `-p` → `🧹 unloaded …`, `loaded:false`;
129+ `=false` → stays loaded; SIGTERM mid-generation → exit 143 after the 3 s
130+ bound (server busy streaming), the unload then done by the server.
131+ Not checked live: llmman/ollama (not running), window, ACP, Ctrl-C in -p.
132+ **Behaviour change** for every existing agent file: release note needed.
133+ - id: 2
134+ author:
135+ name: k33g
136+ email: ph.charriere@gmail.com
137+ createdAt: 2026-11-24T16:59:50.000Z
138+ body: |
139+ Tested by the user; merged into `main`.
@@ -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: 2552 id: 255
3 title: Unload the model when mini-me exits (unloadOnExit, on by default)3 title: Unload the model when mini-me exits (unloadOnExit, on by default)
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-24T07:02:40.000Z8 createdAt: 2026-11-24T07:02:40.000Z
9-updatedAt: 2026-11-24T07:02:40.000Z9+updatedAt: 2026-11-24T16:59:50.000Z
10 labels:10 labels:
11 - enhancement11 - enhancement
12 - kind::feature12 - kind::feature
@@ -67,34 +67,73 @@ body: |
67 tasks:67 tasks:
68 - id: 168 - id: 1
69 title: Config key unloadOnExit (default true), validation, mm init writes it69 title: Config key unloadOnExit (default true), validation, mm init writes it
70- state: open70+ state: closed
71 priority: none71 priority: none
72 author:72 author:
73 name: k33g73 name: k33g
74 email: ph.charriere@gmail.com74 email: ph.charriere@gmail.com
75 createdAt: 2026-11-24T07:02:40.000Z75 createdAt: 2026-11-24T07:02:40.000Z
76+ updatedAt: 2026-11-24T16:57:13.000Z
77+ closedAt: 2026-11-24T16:57:13.000Z
76 - id: 278 - id: 2
77 title: Call Engine.Unload on every exit path (terminal, window, -p, ACP, signals) with a short timeout79 title: Call Engine.Unload on every exit path (terminal, window, -p, ACP, signals) with a short timeout
78- state: open80+ state: closed
79 priority: high81 priority: high
80 author:82 author:
81 name: k33g83 name: k33g
82 email: ph.charriere@gmail.com84 email: ph.charriere@gmail.com
83 createdAt: 2026-11-24T07:02:40.000Z85 createdAt: 2026-11-24T07:02:40.000Z
86+ updatedAt: 2026-11-24T16:57:13.000Z
87+ closedAt: 2026-11-24T16:57:13.000Z
84 - id: 388 - id: 3
85 title: Decide -p behaviour and other users of the same model (see #223)89 title: Decide -p behaviour and other users of the same model (see #223)
86- state: open90+ state: closed
87 priority: medium91 priority: medium
88 author:92 author:
89 name: k33g93 name: k33g
90 email: ph.charriere@gmail.com94 email: ph.charriere@gmail.com
91 createdAt: 2026-11-24T07:02:40.000Z95 createdAt: 2026-11-24T07:02:40.000Z
96+ updatedAt: 2026-11-24T16:57:13.000Z
97+ closedAt: 2026-11-24T16:57:13.000Z
92 - id: 498 - id: 4
93 title: Tests, EN+FR docs, release note (behaviour change)99 title: Tests, EN+FR docs, release note (behaviour change)
94- state: open100+ state: closed
95 priority: none101 priority: none
96 author:102 author:
97 name: k33g103 name: k33g
98 email: ph.charriere@gmail.com104 email: ph.charriere@gmail.com
99 createdAt: 2026-11-24T07:02:40.000Z105 createdAt: 2026-11-24T07:02:40.000Z
100-comments: []106+ updatedAt: 2026-11-24T16:57:13.000Z
107+ closedAt: 2026-11-24T16:57:13.000Z
108+comments:
109+ - id: 1
110+ author:
111+ name: k33g
112+ email: ph.charriere@gmail.com
113+ createdAt: 2026-11-24T16:57:13.000Z
114+ body: |
115+ Implemented on branch `feature/unload-on-exit` (not committed).
116+ - `unloadOnExit` (default true) + `AGENT_UNLOAD_ON_EXIT`; `mm init` writes it.
117+ - `Engine.UnloadOnExit`: silent when not loaded or when the server cannot
118+ unload (dmr, openai, single-model llama-server: new `errCannotUnload`).
119+ - `unload_exit.go`: `exitUnload.run` (once, 3 s bound even if the request
120+ ignores its context) on main's return, before each `os.Exit` of the -p
121+ paths, and on SIGTERM/SIGHUP (+ SIGINT during -p) → exit 128+sig.
122+ One `🧹` line on stderr, none in ACP mode.
123+ Decisions: `-p` keeps the same default (the file decides;
124+ `AGENT_UNLOAD_ON_EXIT=false` for loops); only the agent's own model
125+ (mmConfigs agents unload their own when they stop; decision models not);
126+ independent of `unloadModels`; no lease (#223) — other users of the model
127+ are cut, documented.
128+ Live on mlx-serve 26.11.3 (E4B): `-p` → `🧹 unloaded …`, `loaded:false`;
129+ `=false` → stays loaded; SIGTERM mid-generation → exit 143 after the 3 s
130+ bound (server busy streaming), the unload then done by the server.
131+ Not checked live: llmman/ollama (not running), window, ACP, Ctrl-C in -p.
132+ **Behaviour change** for every existing agent file: release note needed.
133+ - id: 2
134+ author:
135+ name: k33g
136+ email: ph.charriere@gmail.com
137+ createdAt: 2026-11-24T16:59:50.000Z
138+ body: |
139+ Tested by the user; merged into `main`.
modified docs/en/how-to/unload-a-model.md +18 -1
@@ -67,6 +67,23 @@ On every hand-off to `expert` (`ask_agent`, `/ask-expert`, `mm --ask expert`), m
6767
6868 The price is a reload of the expert's model on every question. `demos/coding-helpers-unload-option/` does it for two specialists; `demos/coding-helpers/` does the same with hooks.
6969
70+## When mm exits
71+
72+By default (`unloadOnExit: true`), mm unloads the agent's model as it 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:
73+
74+```text
75+> /quit
76+🧹 unloaded lmstudio-community/gemma-4-E4B-it-MLX-8bit
77+```
78+
79+Nothing is shown when the model was not loaded, or when the server cannot unload (dmr, openai, a single-model llama-server). A server that does not answer within 3 s is left as it is: the exit is not held. To keep the model loaded — another session or tool uses it, or a script runs `mm -p` in a loop and should not reload it each time:
80+
81+```yaml
82+unloadOnExit: false
83+```
84+
85+or, for one run, `AGENT_UNLOAD_ON_EXIT=false mm -p "…"`.
86+
7087 ## Variants
7188
7289 - **The agent's own model.** `unload_model` with an empty `model` unloads it, but only until the agent's next step: the agent needs its model to read the tool's result, and the server reloads it. Use `/unload` between two questions instead — or, to free it while another agent works, a `preAsk` hook that unloads the model named in its input (`"model": "<provider>/<model>"`) right before the asked agent starts: `demos/unload-models/hooks/unload.js self`.
@@ -77,4 +94,4 @@ The price is a reload of the expert's model on every question. `demos/coding-hel
7794 ## See also
7895
7996 - [`unload_model` reference](../reference/tools.md#unload_model) and [`/unload`](../reference/slash-commands.md#commands)
80-- [`unloadModels`](../reference/configuration.md)
97+- [`unloadModels`, `unloadOnExit`](../reference/configuration.md)
@@ -67,6 +67,23 @@ On every hand-off to `expert` (`ask_agent`, `/ask-expert`, `mm --ask expert`), m
67 67
68 The price is a reload of the expert's model on every question. `demos/coding-helpers-unload-option/` does it for two specialists; `demos/coding-helpers/` does the same with hooks.68 The price is a reload of the expert's model on every question. `demos/coding-helpers-unload-option/` does it for two specialists; `demos/coding-helpers/` does the same with hooks.
69 69
70+## When mm exits
71+
72+By default (`unloadOnExit: true`), mm unloads the agent's model as it 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:
73+
74+```text
75+> /quit
76+🧹 unloaded lmstudio-community/gemma-4-E4B-it-MLX-8bit
77+```
78+
79+Nothing is shown when the model was not loaded, or when the server cannot unload (dmr, openai, a single-model llama-server). A server that does not answer within 3 s is left as it is: the exit is not held. To keep the model loaded — another session or tool uses it, or a script runs `mm -p` in a loop and should not reload it each time:
80+
81+```yaml
82+unloadOnExit: false
83+```
84+
85+or, for one run, `AGENT_UNLOAD_ON_EXIT=false mm -p "…"`.
86+
70 ## Variants87 ## Variants
71 88
72 - **The agent's own model.** `unload_model` with an empty `model` unloads it, but only until the agent's next step: the agent needs its model to read the tool's result, and the server reloads it. Use `/unload` between two questions instead — or, to free it while another agent works, a `preAsk` hook that unloads the model named in its input (`"model": "<provider>/<model>"`) right before the asked agent starts: `demos/unload-models/hooks/unload.js self`.89 - **The agent's own model.** `unload_model` with an empty `model` unloads it, but only until the agent's next step: the agent needs its model to read the tool's result, and the server reloads it. Use `/unload` between two questions instead — or, to free it while another agent works, a `preAsk` hook that unloads the model named in its input (`"model": "<provider>/<model>"`) right before the asked agent starts: `demos/unload-models/hooks/unload.js self`.
@@ -77,4 +94,4 @@ The price is a reload of the expert's model on every question. `demos/coding-hel
77 ## See also94 ## See also
78 95
79 - [`unload_model` reference](../reference/tools.md#unload_model) and [`/unload`](../reference/slash-commands.md#commands)96 - [`unload_model` reference](../reference/tools.md#unload_model) and [`/unload`](../reference/slash-commands.md#commands)
80-- [`unloadModels`](../reference/configuration.md)97+- [`unloadModels`, `unloadOnExit`](../reference/configuration.md)
modified docs/en/reference/cli.md +1 -0
@@ -83,6 +83,7 @@ The rule depends on where the file is, not on how it was found: `-config`, `AGEN
8383 | `AGENT_SESSIONS` | `off` turns session persistence off for this run, whatever `sessions.enabled` says. Set by `/ask` on the agents it starts. |
8484 | `AGENT_TRACE` | Overrides `trace.enabled`: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Inherited by the agents `/ask` and `ask_agent` start. |
8585 | `AGENT_YOLO` | Overrides the `yolo` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Set to `false` by `/ask` and `ask_agent` on the agents they start, so the asking side decides (the agent's `mmConfigs` entry `yolo`, else the asking agent's). |
86+| `AGENT_UNLOAD_ON_EXIT` | Overrides the `unloadOnExit` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). `AGENT_UNLOAD_ON_EXIT=false mm -p …` in a loop keeps the model loaded between the runs. |
8687 | `AGENT_ASK_USER` | Overrides the `askUserTool` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Set by `/ask` and `ask_agent` on the agent they start when the asker's `mmConfigs` entry has `askUser`; the asker's own value is never passed on. |
8788 | `MM_BIN` | Set by `mm` in its own environment, so every process it starts inherits it — the commands its `bash` tool runs, its hooks: the path of the running `mm` binary. |
8889 | `MM_CONFIG` | Set by `mm` in its own environment, like `MM_BIN`, when a configuration file was read: the absolute path of its configuration file. Read by `--ask` / `--ask-with-context` when no `-config` and no positional path are given. |
@@ -83,6 +83,7 @@ The rule depends on where the file is, not on how it was found: `-config`, `AGEN
83 | `AGENT_SESSIONS` | `off` turns session persistence off for this run, whatever `sessions.enabled` says. Set by `/ask` on the agents it starts. |83 | `AGENT_SESSIONS` | `off` turns session persistence off for this run, whatever `sessions.enabled` says. Set by `/ask` on the agents it starts. |
84 | `AGENT_TRACE` | Overrides `trace.enabled`: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Inherited by the agents `/ask` and `ask_agent` start. |84 | `AGENT_TRACE` | Overrides `trace.enabled`: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Inherited by the agents `/ask` and `ask_agent` start. |
85 | `AGENT_YOLO` | Overrides the `yolo` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Set to `false` by `/ask` and `ask_agent` on the agents they start, so the asking side decides (the agent's `mmConfigs` entry `yolo`, else the asking agent's). |85 | `AGENT_YOLO` | Overrides the `yolo` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Set to `false` by `/ask` and `ask_agent` on the agents they start, so the asking side decides (the agent's `mmConfigs` entry `yolo`, else the asking agent's). |
86+| `AGENT_UNLOAD_ON_EXIT` | Overrides the `unloadOnExit` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). `AGENT_UNLOAD_ON_EXIT=false mm -p …` in a loop keeps the model loaded between the runs. |
86 | `AGENT_ASK_USER` | Overrides the `askUserTool` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Set by `/ask` and `ask_agent` on the agent they start when the asker's `mmConfigs` entry has `askUser`; the asker's own value is never passed on. |87 | `AGENT_ASK_USER` | Overrides the `askUserTool` key: `true` or `false` (any `strconv.ParseBool` spelling; anything else is a configuration error). Set by `/ask` and `ask_agent` on the agent they start when the asker's `mmConfigs` entry has `askUser`; the asker's own value is never passed on. |
87 | `MM_BIN` | Set by `mm` in its own environment, so every process it starts inherits it — the commands its `bash` tool runs, its hooks: the path of the running `mm` binary. |88 | `MM_BIN` | Set by `mm` in its own environment, so every process it starts inherits it — the commands its `bash` tool runs, its hooks: the path of the running `mm` binary. |
88 | `MM_CONFIG` | Set by `mm` in its own environment, like `MM_BIN`, when a configuration file was read: the absolute path of its configuration file. Read by `--ask` / `--ask-with-context` when no `-config` and no positional path are given. |89 | `MM_CONFIG` | Set by `mm` in its own environment, like `MM_BIN`, when a configuration file was read: the absolute path of its configuration file. Read by `--ask` / `--ask-with-context` when no `-config` and no positional path are given. |
modified docs/en/reference/configuration.md +1 -0
@@ -36,6 +36,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
3636 | `askUserTool` | bool | `true` | Declare `ask_user`, through which the model asks the user questions (pick one, pick several, type a text, yes or no) and waits for the answers. `false` removes it: the model cannot ask. Never declared beside a `structuredOutput`. Overridden by `AGENT_ASK_USER`; for an agent asked by another one, also by the asker's `mmConfigs.<name>.askUser`. See [tools](tools.md#ask_user). |
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). |
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). |
3940 | `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. |
4041 | `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`). |
4142 | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. |
@@ -36,6 +36,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
36 | `askUserTool` | bool | `true` | Declare `ask_user`, through which the model asks the user questions (pick one, pick several, type a text, yes or no) and waits for the answers. `false` removes it: the model cannot ask. Never declared beside a `structuredOutput`. Overridden by `AGENT_ASK_USER`; for an agent asked by another one, also by the asker's `mmConfigs.<name>.askUser`. See [tools](tools.md#ask_user). |36 | `askUserTool` | bool | `true` | Declare `ask_user`, through which the model asks the user questions (pick one, pick several, type a text, yes or no) and waits for the answers. `false` removes it: the model cannot ask. Never declared beside a `structuredOutput`. Overridden by `AGENT_ASK_USER`; for an agent asked by another one, also by the asker's `mmConfigs.<name>.askUser`. See [tools](tools.md#ask_user). |
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 | `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. |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. |
40 | `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`). |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`). |
41 | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. |42 | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. |
modified docs/fr/how-to/unload-a-model.md +18 -1
@@ -67,6 +67,23 @@ mmConfigs:
6767
6868 Le prix : le modèle de l'expert est rechargé à chaque question. `demos/coding-helpers-unload-option/` le fait pour deux spécialistes ; `demos/coding-helpers/` fait la même chose avec des hooks.
6969
70+## Quand mm se termine
71+
72+Par défaut (`unloadOnExit: true`), mm décharge le modèle de l'agent en se terminant — `/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 :
73+
74+```text
75+> /quit
76+🧹 unloaded lmstudio-community/gemma-4-E4B-it-MLX-8bit
77+```
78+
79+Rien n'est affiché quand le modèle n'était pas chargé, ou quand le serveur ne sait pas décharger (dmr, openai, un llama-server mono-modèle). Un serveur qui ne répond pas en 3 s est laissé tel quel : la sortie n'est pas retenue. Pour garder le modèle chargé — une autre session ou un autre outil s'en sert, ou un script lance `mm -p` en boucle et ne doit pas le recharger à chaque fois :
80+
81+```yaml
82+unloadOnExit: false
83+```
84+
85+ou, pour une exécution, `AGENT_UNLOAD_ON_EXIT=false mm -p "…"`.
86+
7087 ## Variantes
7188
7289 - **Le modèle de l'agent lui-même.** `unload_model` avec un `model` vide le décharge, mais seulement jusqu'à l'étape suivante de l'agent : il a besoin de son modèle pour lire le résultat de l'outil, et le serveur le recharge. Utilisez plutôt `/unload` entre deux questions — ou, pour le libérer pendant qu'un autre agent travaille, un hook `preAsk` qui décharge le modèle nommé dans son entrée (`"model": "<fournisseur>/<modèle>"`) juste avant le lancement de l'agent interrogé : `demos/unload-models/hooks/unload.js self`.
@@ -77,4 +94,4 @@ Le prix : le modèle de l'expert est rechargé à chaque question. `demos/coding
7794 ## Voir aussi
7895
7996 - [Référence de `unload_model`](../reference/tools.md#unload_model) et de [`/unload`](../reference/slash-commands.md#commandes)
80-- [`unloadModels`](../reference/configuration.md)
97+- [`unloadModels`, `unloadOnExit`](../reference/configuration.md)
@@ -67,6 +67,23 @@ mmConfigs:
67 67
68 Le prix : le modèle de l'expert est rechargé à chaque question. `demos/coding-helpers-unload-option/` le fait pour deux spécialistes ; `demos/coding-helpers/` fait la même chose avec des hooks.68 Le prix : le modèle de l'expert est rechargé à chaque question. `demos/coding-helpers-unload-option/` le fait pour deux spécialistes ; `demos/coding-helpers/` fait la même chose avec des hooks.
69 69
70+## Quand mm se termine
71+
72+Par défaut (`unloadOnExit: true`), mm décharge le modèle de l'agent en se terminant — `/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 :
73+
74+```text
75+> /quit
76+🧹 unloaded lmstudio-community/gemma-4-E4B-it-MLX-8bit
77+```
78+
79+Rien n'est affiché quand le modèle n'était pas chargé, ou quand le serveur ne sait pas décharger (dmr, openai, un llama-server mono-modèle). Un serveur qui ne répond pas en 3 s est laissé tel quel : la sortie n'est pas retenue. Pour garder le modèle chargé — une autre session ou un autre outil s'en sert, ou un script lance `mm -p` en boucle et ne doit pas le recharger à chaque fois :
80+
81+```yaml
82+unloadOnExit: false
83+```
84+
85+ou, pour une exécution, `AGENT_UNLOAD_ON_EXIT=false mm -p "…"`.
86+
70 ## Variantes87 ## Variantes
71 88
72 - **Le modèle de l'agent lui-même.** `unload_model` avec un `model` vide le décharge, mais seulement jusqu'à l'étape suivante de l'agent : il a besoin de son modèle pour lire le résultat de l'outil, et le serveur le recharge. Utilisez plutôt `/unload` entre deux questions — ou, pour le libérer pendant qu'un autre agent travaille, un hook `preAsk` qui décharge le modèle nommé dans son entrée (`"model": "<fournisseur>/<modèle>"`) juste avant le lancement de l'agent interrogé : `demos/unload-models/hooks/unload.js self`.89 - **Le modèle de l'agent lui-même.** `unload_model` avec un `model` vide le décharge, mais seulement jusqu'à l'étape suivante de l'agent : il a besoin de son modèle pour lire le résultat de l'outil, et le serveur le recharge. Utilisez plutôt `/unload` entre deux questions — ou, pour le libérer pendant qu'un autre agent travaille, un hook `preAsk` qui décharge le modèle nommé dans son entrée (`"model": "<fournisseur>/<modèle>"`) juste avant le lancement de l'agent interrogé : `demos/unload-models/hooks/unload.js self`.
@@ -77,4 +94,4 @@ Le prix : le modèle de l'expert est rechargé à chaque question. `demos/coding
77 ## Voir aussi94 ## Voir aussi
78 95
79 - [Référence de `unload_model`](../reference/tools.md#unload_model) et de [`/unload`](../reference/slash-commands.md#commandes)96 - [Référence de `unload_model`](../reference/tools.md#unload_model) et de [`/unload`](../reference/slash-commands.md#commandes)
80-- [`unloadModels`](../reference/configuration.md)97+- [`unloadModels`, `unloadOnExit`](../reference/configuration.md)
modified docs/fr/reference/cli.md +1 -0
@@ -83,6 +83,7 @@ La règle dépend de l'emplacement du fichier, pas de la façon dont il a été
8383 | `AGENT_SESSIONS` | `off` désactive l'enregistrement des sessions pour cette exécution, quoi que dise `sessions.enabled`. Posée par `/ask` sur les agents qu'il lance. |
8484 | `AGENT_TRACE` | Surcharge `trace.enabled` : `true` ou `false` (toute graphie acceptée par `strconv.ParseBool` ; toute autre valeur est une erreur de configuration). Héritée par les agents que lancent `/ask` et `ask_agent`. |
8585 | `AGENT_YOLO` | Surcharge la clé `yolo` : `true` ou `false` (toute graphie acceptée par `strconv.ParseBool` ; toute autre valeur est une erreur de configuration). Posée à `false` par `/ask` et `ask_agent` sur les agents qu'ils lancent, pour que le côté qui interroge décide (le `yolo` de l'entrée `mmConfigs` de l'agent, sinon celui de l'agent qui interroge). |
86+| `AGENT_UNLOAD_ON_EXIT` | Surcharge la clé `unloadOnExit` : `true` ou `false` (toute écriture acceptée par `strconv.ParseBool` ; autre chose est une erreur de configuration). `AGENT_UNLOAD_ON_EXIT=false mm -p …` dans une boucle garde le modèle chargé entre les exécutions. |
8687 | `AGENT_ASK_USER` | Surcharge la clé `askUserTool` : `true` ou `false` (toute écriture acceptée par `strconv.ParseBool` ; autre chose est une erreur de configuration). Positionnée par `/ask` et `ask_agent` sur l'agent qu'ils démarrent quand l'entrée `mmConfigs` de celui qui interroge a `askUser` ; la valeur propre de celui qui interroge n'est jamais transmise. |
8788 | `MM_BIN` | Posée par `mm` dans son propre environnement, dont héritent tous les processus qu'il lance — les commandes de son outil `bash`, ses hooks : le chemin du binaire `mm` en cours. |
8889 | `MM_CONFIG` | Posée par `mm` dans son propre environnement, comme `MM_BIN`, quand un fichier de configuration a été lu : le chemin absolu de son fichier de configuration. Lue par `--ask` / `--ask-with-context` quand ni `-config` ni chemin positionnel ne sont donnés. |
@@ -83,6 +83,7 @@ La règle dépend de l'emplacement du fichier, pas de la façon dont il a été
83 | `AGENT_SESSIONS` | `off` désactive l'enregistrement des sessions pour cette exécution, quoi que dise `sessions.enabled`. Posée par `/ask` sur les agents qu'il lance. |83 | `AGENT_SESSIONS` | `off` désactive l'enregistrement des sessions pour cette exécution, quoi que dise `sessions.enabled`. Posée par `/ask` sur les agents qu'il lance. |
84 | `AGENT_TRACE` | Surcharge `trace.enabled` : `true` ou `false` (toute graphie acceptée par `strconv.ParseBool` ; toute autre valeur est une erreur de configuration). Héritée par les agents que lancent `/ask` et `ask_agent`. |84 | `AGENT_TRACE` | Surcharge `trace.enabled` : `true` ou `false` (toute graphie acceptée par `strconv.ParseBool` ; toute autre valeur est une erreur de configuration). Héritée par les agents que lancent `/ask` et `ask_agent`. |
85 | `AGENT_YOLO` | Surcharge la clé `yolo` : `true` ou `false` (toute graphie acceptée par `strconv.ParseBool` ; toute autre valeur est une erreur de configuration). Posée à `false` par `/ask` et `ask_agent` sur les agents qu'ils lancent, pour que le côté qui interroge décide (le `yolo` de l'entrée `mmConfigs` de l'agent, sinon celui de l'agent qui interroge). |85 | `AGENT_YOLO` | Surcharge la clé `yolo` : `true` ou `false` (toute graphie acceptée par `strconv.ParseBool` ; toute autre valeur est une erreur de configuration). Posée à `false` par `/ask` et `ask_agent` sur les agents qu'ils lancent, pour que le côté qui interroge décide (le `yolo` de l'entrée `mmConfigs` de l'agent, sinon celui de l'agent qui interroge). |
86+| `AGENT_UNLOAD_ON_EXIT` | Surcharge la clé `unloadOnExit` : `true` ou `false` (toute écriture acceptée par `strconv.ParseBool` ; autre chose est une erreur de configuration). `AGENT_UNLOAD_ON_EXIT=false mm -p …` dans une boucle garde le modèle chargé entre les exécutions. |
86 | `AGENT_ASK_USER` | Surcharge la clé `askUserTool` : `true` ou `false` (toute écriture acceptée par `strconv.ParseBool` ; autre chose est une erreur de configuration). Positionnée par `/ask` et `ask_agent` sur l'agent qu'ils démarrent quand l'entrée `mmConfigs` de celui qui interroge a `askUser` ; la valeur propre de celui qui interroge n'est jamais transmise. |87 | `AGENT_ASK_USER` | Surcharge la clé `askUserTool` : `true` ou `false` (toute écriture acceptée par `strconv.ParseBool` ; autre chose est une erreur de configuration). Positionnée par `/ask` et `ask_agent` sur l'agent qu'ils démarrent quand l'entrée `mmConfigs` de celui qui interroge a `askUser` ; la valeur propre de celui qui interroge n'est jamais transmise. |
87 | `MM_BIN` | Posée par `mm` dans son propre environnement, dont héritent tous les processus qu'il lance — les commandes de son outil `bash`, ses hooks : le chemin du binaire `mm` en cours. |88 | `MM_BIN` | Posée par `mm` dans son propre environnement, dont héritent tous les processus qu'il lance — les commandes de son outil `bash`, ses hooks : le chemin du binaire `mm` en cours. |
88 | `MM_CONFIG` | Posée par `mm` dans son propre environnement, comme `MM_BIN`, quand un fichier de configuration a été lu : le chemin absolu de son fichier de configuration. Lue par `--ask` / `--ask-with-context` quand ni `-config` ni chemin positionnel ne sont donnés. |89 | `MM_CONFIG` | Posée par `mm` dans son propre environnement, comme `MM_BIN`, quand un fichier de configuration a été lu : le chemin absolu de son fichier de configuration. Lue par `--ask` / `--ask-with-context` quand ni `-config` ni chemin positionnel ne sont donnés. |
modified docs/fr/reference/configuration.md +1 -0
@@ -36,6 +36,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
3636 | `askUserTool` | booléen | `true` | Déclare `ask_user`, par lequel le modèle pose des questions à l'utilisateur (choisir une option, en choisir plusieurs, taper un texte, oui ou non) et attend les réponses. `false` le retire : le modèle ne peut pas demander. Jamais déclaré à côté d'un `structuredOutput`. Surchargé par `AGENT_ASK_USER` ; pour un agent interrogé par un autre, aussi par le `mmConfigs.<nom>.askUser` de celui qui l'interroge. Voir [outils](tools.md#ask_user). |
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). |
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). |
3940 | `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. |
4041 | `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`). |
4142 | `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é. |
@@ -36,6 +36,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
36 | `askUserTool` | booléen | `true` | Déclare `ask_user`, par lequel le modèle pose des questions à l'utilisateur (choisir une option, en choisir plusieurs, taper un texte, oui ou non) et attend les réponses. `false` le retire : le modèle ne peut pas demander. Jamais déclaré à côté d'un `structuredOutput`. Surchargé par `AGENT_ASK_USER` ; pour un agent interrogé par un autre, aussi par le `mmConfigs.<nom>.askUser` de celui qui l'interroge. Voir [outils](tools.md#ask_user). |36 | `askUserTool` | booléen | `true` | Déclare `ask_user`, par lequel le modèle pose des questions à l'utilisateur (choisir une option, en choisir plusieurs, taper un texte, oui ou non) et attend les réponses. `false` le retire : le modèle ne peut pas demander. Jamais déclaré à côté d'un `structuredOutput`. Surchargé par `AGENT_ASK_USER` ; pour un agent interrogé par un autre, aussi par le `mmConfigs.<nom>.askUser` de celui qui l'interroge. Voir [outils](tools.md#ask_user). |
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 | `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. |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. |
40 | `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`). |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`). |
41 | `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é. |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é. |
modified internal/agentinit/decide.go +1 -0
@@ -152,6 +152,7 @@ func (s *Settings) decideTop() {
152152 if u.JSON || u.Coordinator {
153153 s.add("unloadModels", "false", "no unload_model tool: this agent "+map[bool]string{true: "answers in JSON, which forbids tools", false: "only hands questions to other agents"}[u.JSON])
154154 }
155+ s.add("unloadOnExit", "true", "unload the model from the server's memory when mm exits; false keeps it loaded (faster next start, or another tool uses it)")
155156 if f := s.Family.ToolFormat; f != "" && s.anyTool() {
156157 s.add("toolFormat", f, "family "+s.Family.Name+": its chat template reads the tools from "+f+" and writes its calls as <tool_call> text — mm sends them there and reads the calls back")
157158 }
@@ -152,6 +152,7 @@ func (s *Settings) decideTop() {
152 if u.JSON || u.Coordinator {152 if u.JSON || u.Coordinator {
153 s.add("unloadModels", "false", "no unload_model tool: this agent "+map[bool]string{true: "answers in JSON, which forbids tools", false: "only hands questions to other agents"}[u.JSON])153 s.add("unloadModels", "false", "no unload_model tool: this agent "+map[bool]string{true: "answers in JSON, which forbids tools", false: "only hands questions to other agents"}[u.JSON])
154 }154 }
155+ s.add("unloadOnExit", "true", "unload the model from the server's memory when mm exits; false keeps it loaded (faster next start, or another tool uses it)")
155 if f := s.Family.ToolFormat; f != "" && s.anyTool() {156 if f := s.Family.ToolFormat; f != "" && s.anyTool() {
156 s.add("toolFormat", f, "family "+s.Family.Name+": its chat template reads the tools from "+f+" and writes its calls as <tool_call> text — mm sends them there and reads the calls back")157 s.add("toolFormat", f, "family "+s.Family.Name+": its chat template reads the tools from "+f+" and writes its calls as <tool_call> text — mm sends them there and reads the calls back")
157 }158 }
modified internal/agentinit/testdata/preview-developer.yaml +3 -0
@@ -34,6 +34,9 @@ bashTool: true
3434 editTools: true
3535 planTool: true
3636 askUserTool: true
37+# unload the model from the server's memory when mm exits; false keeps it
38+# loaded (faster next start, or another tool uses it)
39+unloadOnExit: true
3740 # no skills: add a skills/ folder and set skillsDir to use some (see
3841 # https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)
3942 skillsDir: no-skills
@@ -34,6 +34,9 @@ bashTool: true
34 editTools: true34 editTools: true
35 planTool: true35 planTool: true
36 askUserTool: true36 askUserTool: true
37+# unload the model from the server's memory when mm exits; false keeps it
38+# loaded (faster next start, or another tool uses it)
39+unloadOnExit: true
37 # no skills: add a skills/ folder and set skillsDir to use some (see40 # no skills: add a skills/ folder and set skillsDir to use some (see
38 # https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)41 # https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)
39 skillsDir: no-skills42 skillsDir: no-skills
modified internal/agentinit/testdata/preview-researcher.yaml +3 -0
@@ -36,6 +36,9 @@ planTool: false
3636 askUserTool: true
3737 fetchContentTool: true
3838 saveAnswerTool: true
39+# unload the model from the server's memory when mm exits; false keeps it
40+# loaded (faster next start, or another tool uses it)
41+unloadOnExit: true
3942 # no skills: add a skills/ folder and set skillsDir to use some (see
4043 # https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)
4144 skillsDir: no-skills
@@ -36,6 +36,9 @@ planTool: false
36 askUserTool: true36 askUserTool: true
37 fetchContentTool: true37 fetchContentTool: true
38 saveAnswerTool: true38 saveAnswerTool: true
39+# unload the model from the server's memory when mm exits; false keeps it
40+# loaded (faster next start, or another tool uses it)
41+unloadOnExit: true
39 # no skills: add a skills/ folder and set skillsDir to use some (see42 # no skills: add a skills/ folder and set skillsDir to use some (see
40 # https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)43 # https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)
41 skillsDir: no-skills44 skillsDir: no-skills
modified internal/config/config.go +27 -0
@@ -189,6 +189,16 @@ type Config struct {
189189 // structuredOutput, like ask_user.
190190 UnloadModels bool `yaml:"unloadModels"`
191191
192+ // UnloadOnExit: when mm exits — /quit, Ctrl-C at the prompt, Ctrl-D,
193+ // the window closed, the end of a -p run, the editor closing the ACP
194+ // session, SIGTERM, SIGHUP — unload the agent's model from the server's
195+ // memory (ticket 255), so it does not keep GB of RAM after the session.
196+ // On by default. Bounded (UnloadOnExitTimeout): a server that does not
197+ // answer never holds the exit. Independent of unloadModels; a provider
198+ // that cannot unload (dmr, openai, a single-model llama-server) says
199+ // nothing. Override: AGENT_UNLOAD_ON_EXIT.
200+ UnloadOnExit bool `yaml:"unloadOnExit"`
201+
192202 // Sampling: generation settings (OpenAI API keys; the plugin converts them.)
193203 Sampling map[string]any `yaml:"sampling"`
194204
@@ -311,6 +321,15 @@ const YoloEnv = "AGENT_YOLO"
311321 // mmConfigs entry says `askUser`.
312322 const AskUserEnv = "AGENT_ASK_USER"
313323
324+// UnloadOnExitEnv names the variable that overrides `unloadOnExit` for one
325+// run — `AGENT_UNLOAD_ON_EXIT=false mm -p …` in a loop keeps the model
326+// loaded between the runs.
327+const UnloadOnExitEnv = "AGENT_UNLOAD_ON_EXIT"
328+
329+// UnloadOnExitTimeout bounds the unload at exit: past it, mm exits and the
330+// model stays loaded.
331+const UnloadOnExitTimeout = 3 * time.Second
332+
314333 // The two values of Permissions (MCP's, and the deprecated top-level key).
315334 const (
316335 PermissionsAuto = "auto"
@@ -727,6 +746,7 @@ var Cfg = Config{
727746 PlanTool: true,
728747 AskUserTool: true,
729748 UnloadModels: true,
749+ UnloadOnExit: true,
730750 // FetchContentTool stays false (the zero value): see its field comment.
731751 System: `You are a coding agent working in a terminal.
732752 You have a "bash" tool to run shell commands.
@@ -913,6 +933,13 @@ func applyEnv() error {
913933 }
914934 Cfg.AskUserTool = on
915935 }
936+ if v := os.Getenv(UnloadOnExitEnv); v != "" {
937+ on, err := strconv.ParseBool(v)
938+ if err != nil {
939+ return fmt.Errorf("%s=%q: must be true or false", UnloadOnExitEnv, v)
940+ }
941+ Cfg.UnloadOnExit = on
942+ }
916943 // AGENT_TRACE: trace one run without editing the file. Not removed from
917944 // the environment of an agent started by /ask or ask_agent: tracing a
918945 // coordinator traces the agents it asks too, each under its own name.
@@ -189,6 +189,16 @@ type Config struct {
189 // structuredOutput, like ask_user.189 // structuredOutput, like ask_user.
190 UnloadModels bool `yaml:"unloadModels"`190 UnloadModels bool `yaml:"unloadModels"`
191 191
192+ // UnloadOnExit: when mm exits — /quit, Ctrl-C at the prompt, Ctrl-D,
193+ // the window closed, the end of a -p run, the editor closing the ACP
194+ // session, SIGTERM, SIGHUP — unload the agent's model from the server's
195+ // memory (ticket 255), so it does not keep GB of RAM after the session.
196+ // On by default. Bounded (UnloadOnExitTimeout): a server that does not
197+ // answer never holds the exit. Independent of unloadModels; a provider
198+ // that cannot unload (dmr, openai, a single-model llama-server) says
199+ // nothing. Override: AGENT_UNLOAD_ON_EXIT.
200+ UnloadOnExit bool `yaml:"unloadOnExit"`
201+
192 // Sampling: generation settings (OpenAI API keys; the plugin converts them.)202 // Sampling: generation settings (OpenAI API keys; the plugin converts them.)
193 Sampling map[string]any `yaml:"sampling"`203 Sampling map[string]any `yaml:"sampling"`
194 204
@@ -311,6 +321,15 @@ const YoloEnv = "AGENT_YOLO"
311 // mmConfigs entry says `askUser`.321 // mmConfigs entry says `askUser`.
312 const AskUserEnv = "AGENT_ASK_USER"322 const AskUserEnv = "AGENT_ASK_USER"
313 323
324+// UnloadOnExitEnv names the variable that overrides `unloadOnExit` for one
325+// run — `AGENT_UNLOAD_ON_EXIT=false mm -p …` in a loop keeps the model
326+// loaded between the runs.
327+const UnloadOnExitEnv = "AGENT_UNLOAD_ON_EXIT"
328+
329+// UnloadOnExitTimeout bounds the unload at exit: past it, mm exits and the
330+// model stays loaded.
331+const UnloadOnExitTimeout = 3 * time.Second
332+
314 // The two values of Permissions (MCP's, and the deprecated top-level key).333 // The two values of Permissions (MCP's, and the deprecated top-level key).
315 const (334 const (
316 PermissionsAuto = "auto"335 PermissionsAuto = "auto"
@@ -727,6 +746,7 @@ var Cfg = Config{
727 PlanTool: true,746 PlanTool: true,
728 AskUserTool: true,747 AskUserTool: true,
729 UnloadModels: true,748 UnloadModels: true,
749+ UnloadOnExit: true,
730 // FetchContentTool stays false (the zero value): see its field comment.750 // FetchContentTool stays false (the zero value): see its field comment.
731 System: `You are a coding agent working in a terminal.751 System: `You are a coding agent working in a terminal.
732 You have a "bash" tool to run shell commands.752 You have a "bash" tool to run shell commands.
@@ -913,6 +933,13 @@ func applyEnv() error {
913 }933 }
914 Cfg.AskUserTool = on934 Cfg.AskUserTool = on
915 }935 }
936+ if v := os.Getenv(UnloadOnExitEnv); v != "" {
937+ on, err := strconv.ParseBool(v)
938+ if err != nil {
939+ return fmt.Errorf("%s=%q: must be true or false", UnloadOnExitEnv, v)
940+ }
941+ Cfg.UnloadOnExit = on
942+ }
916 // AGENT_TRACE: trace one run without editing the file. Not removed from943 // AGENT_TRACE: trace one run without editing the file. Not removed from
917 // the environment of an agent started by /ask or ask_agent: tracing a944 // the environment of an agent started by /ask or ask_agent: tracing a
918 // coordinator traces the agents it asks too, each under its own name.945 // coordinator traces the agents it asks too, each under its own name.
modified internal/engine/kronk.go +1 -1
@@ -174,7 +174,7 @@ func unloadKronk(ctx context.Context, b Backend, model string) (string, error) {
174174 var status *httpStatusError
175175 switch {
176176 case errors.As(err, &status) && status.code == http.StatusNotFound:
177- return fmt.Sprintf("%s was not loaded: nothing to unload", model), nil
177+ return notLoaded(model), nil
178178 case err != nil:
179179 return "", err
180180 case reply.Status != "unloaded":
@@ -174,7 +174,7 @@ func unloadKronk(ctx context.Context, b Backend, model string) (string, error) {
174 var status *httpStatusError174 var status *httpStatusError
175 switch {175 switch {
176 case errors.As(err, &status) && status.code == http.StatusNotFound:176 case errors.As(err, &status) && status.code == http.StatusNotFound:
177- return fmt.Sprintf("%s was not loaded: nothing to unload", model), nil177+ return notLoaded(model), nil
178 case err != nil:178 case err != nil:
179 return "", err179 return "", err
180 case reply.Status != "unloaded":180 case reply.Status != "unloaded":
modified internal/engine/mlxserve.go +1 -1
@@ -104,7 +104,7 @@ func unloadMlxServe(ctx context.Context, b Backend, model string) (string, error
104104 return "", err
105105 }
106106 if m, found := list.find(model); !found || !m.Loaded {
107- return fmt.Sprintf("%s was not loaded: nothing to unload", model), nil
107+ return notLoaded(model), nil
108108 }
109109 var reply struct {
110110 Model struct {
@@ -104,7 +104,7 @@ func unloadMlxServe(ctx context.Context, b Backend, model string) (string, error
104 return "", err104 return "", err
105 }105 }
106 if m, found := list.find(model); !found || !m.Loaded {106 if m, found := list.find(model); !found || !m.Loaded {
107- return fmt.Sprintf("%s was not loaded: nothing to unload", model), nil107+ return notLoaded(model), nil
108 }108 }
109 var reply struct {109 var reply struct {
110 Model struct {110 Model struct {
modified internal/engine/unload.go +37 -3
@@ -60,6 +60,40 @@ func (e *Engine) Unload(ctx context.Context, model string) string {
6060 return line
6161 }
6262
63+// errCannotUnload marks a server that has no way to unload a model (a
64+// provider with no unload, a single-model llama-server): not a failure of
65+// this unload, a fact about the server — UnloadOnExit says nothing about it.
66+var errCannotUnload = errors.New("cannot unload a model")
67+
68+// notLoaded is the line of an unload that found the model not loaded.
69+func notLoaded(model string) string {
70+ return model + " was not loaded: nothing to unload"
71+}
72+
73+// UnloadOnExit unloads this engine's model as mm exits (config
74+// unloadOnExit, ticket 255) and returns the line to show, or "" when there
75+// is nothing worth saying at exit: the model was not loaded, or the server
76+// has no way to unload one. ctx bounds it — the caller gives it
77+// config.UnloadOnExitTimeout, so a server that does not answer never holds
78+// the exit.
79+//
80+// fmt.Println(e.UnloadOnExit(ctx)) // "unloaded hf.co/…:Q4_K_M"
81+func (e *Engine) UnloadOnExit(ctx context.Context) string {
82+ u, ok := e.Provider.(Unloader)
83+ if !ok {
84+ return ""
85+ }
86+ model := e.Backend.Model
87+ line, err := u.Unload(ctx, e.Backend, model)
88+ switch {
89+ case errors.Is(err, errCannotUnload), err == nil && line == notLoaded(model):
90+ return ""
91+ case err != nil:
92+ return fmt.Sprintf("cannot unload %s: %v", model, err)
93+ }
94+ return line
95+}
96+
6397 // UnloadAgent unloads the model of ANOTHER agent's config file, on that
6498 // agent's server: its provider, baseUrl (or fallback) and key, resolved like
6599 // a decider's — without AGENT_BASE_URL, which names the running agent's
@@ -95,7 +129,7 @@ func UnloadAgent(ctx context.Context, configPath string) string {
95129 // Unload implements Unloader with the server's own way, when it has one.
96130 func (p *openaiCompat) Unload(ctx context.Context, b Backend, model string) (string, error) {
97131 if p.unload == nil {
98- return "", fmt.Errorf("the %s provider cannot unload a model", p.name)
132+ return "", fmt.Errorf("the %s provider %w", p.name, errCannotUnload)
99133 }
100134 return p.unload(ctx, b, model)
101135 }
@@ -117,7 +151,7 @@ func unloadKeepAlive(ctx context.Context, b Backend, model string) (string, erro
117151 return "", err
118152 }
119153 if !slices.Contains(loaded, model) {
120- return fmt.Sprintf("%s was not loaded: nothing to unload", model), nil
154+ return notLoaded(model), nil
121155 }
122156 var reply struct {
123157 DoneReason string `json:"done_reason"`
@@ -164,7 +198,7 @@ func unloadRouter(ctx context.Context, b Backend, model string) (string, error)
164198 var status *httpStatusError
165199 switch {
166200 case errors.As(err, &status) && status.code == http.StatusNotFound:
167- return "", fmt.Errorf("this llama-server serves a single model and has no unload route — start it in router mode (no -m), or with --sleep-idle-seconds N to free memory when idle, or stop it")
201+ return "", fmt.Errorf("this llama-server serves a single model and has no unload route — start it in router mode (no -m), or with --sleep-idle-seconds N to free memory when idle, or stop it (%w)", errCannotUnload)
168202 case err != nil:
169203 return "", err
170204 case !reply.Success:
@@ -60,6 +60,40 @@ func (e *Engine) Unload(ctx context.Context, model string) string {
60 return line60 return line
61 }61 }
62 62
63+// errCannotUnload marks a server that has no way to unload a model (a
64+// provider with no unload, a single-model llama-server): not a failure of
65+// this unload, a fact about the server — UnloadOnExit says nothing about it.
66+var errCannotUnload = errors.New("cannot unload a model")
67+
68+// notLoaded is the line of an unload that found the model not loaded.
69+func notLoaded(model string) string {
70+ return model + " was not loaded: nothing to unload"
71+}
72+
73+// UnloadOnExit unloads this engine's model as mm exits (config
74+// unloadOnExit, ticket 255) and returns the line to show, or "" when there
75+// is nothing worth saying at exit: the model was not loaded, or the server
76+// has no way to unload one. ctx bounds it — the caller gives it
77+// config.UnloadOnExitTimeout, so a server that does not answer never holds
78+// the exit.
79+//
80+// fmt.Println(e.UnloadOnExit(ctx)) // "unloaded hf.co/…:Q4_K_M"
81+func (e *Engine) UnloadOnExit(ctx context.Context) string {
82+ u, ok := e.Provider.(Unloader)
83+ if !ok {
84+ return ""
85+ }
86+ model := e.Backend.Model
87+ line, err := u.Unload(ctx, e.Backend, model)
88+ switch {
89+ case errors.Is(err, errCannotUnload), err == nil && line == notLoaded(model):
90+ return ""
91+ case err != nil:
92+ return fmt.Sprintf("cannot unload %s: %v", model, err)
93+ }
94+ return line
95+}
96+
63 // UnloadAgent unloads the model of ANOTHER agent's config file, on that97 // UnloadAgent unloads the model of ANOTHER agent's config file, on that
64 // agent's server: its provider, baseUrl (or fallback) and key, resolved like98 // agent's server: its provider, baseUrl (or fallback) and key, resolved like
65 // a decider's — without AGENT_BASE_URL, which names the running agent's99 // a decider's — without AGENT_BASE_URL, which names the running agent's
@@ -95,7 +129,7 @@ func UnloadAgent(ctx context.Context, configPath string) string {
95 // Unload implements Unloader with the server's own way, when it has one.129 // Unload implements Unloader with the server's own way, when it has one.
96 func (p *openaiCompat) Unload(ctx context.Context, b Backend, model string) (string, error) {130 func (p *openaiCompat) Unload(ctx context.Context, b Backend, model string) (string, error) {
97 if p.unload == nil {131 if p.unload == nil {
98- return "", fmt.Errorf("the %s provider cannot unload a model", p.name)132+ return "", fmt.Errorf("the %s provider %w", p.name, errCannotUnload)
99 }133 }
100 return p.unload(ctx, b, model)134 return p.unload(ctx, b, model)
101 }135 }
@@ -117,7 +151,7 @@ func unloadKeepAlive(ctx context.Context, b Backend, model string) (string, erro
117 return "", err151 return "", err
118 }152 }
119 if !slices.Contains(loaded, model) {153 if !slices.Contains(loaded, model) {
120- return fmt.Sprintf("%s was not loaded: nothing to unload", model), nil154+ return notLoaded(model), nil
121 }155 }
122 var reply struct {156 var reply struct {
123 DoneReason string `json:"done_reason"`157 DoneReason string `json:"done_reason"`
@@ -164,7 +198,7 @@ func unloadRouter(ctx context.Context, b Backend, model string) (string, error)
164 var status *httpStatusError198 var status *httpStatusError
165 switch {199 switch {
166 case errors.As(err, &status) && status.code == http.StatusNotFound:200 case errors.As(err, &status) && status.code == http.StatusNotFound:
167- return "", fmt.Errorf("this llama-server serves a single model and has no unload route — start it in router mode (no -m), or with --sleep-idle-seconds N to free memory when idle, or stop it")201+ return "", fmt.Errorf("this llama-server serves a single model and has no unload route — start it in router mode (no -m), or with --sleep-idle-seconds N to free memory when idle, or stop it (%w)", errCannotUnload)
168 case err != nil:202 case err != nil:
169 return "", err203 return "", err
170 case !reply.Success:204 case !reply.Success:
modified internal/engine/unload_test.go +35 -0
@@ -169,3 +169,38 @@ func TestUnloadAgentUsesTheOtherAgentsFile(t *testing.T) {
169169 t.Errorf("absent: %q", got)
170170 }
171171 }
172+
173+// UnloadOnExit (ticket 255) says only what is worth a line at exit: the
174+// model unloaded, or why it could not be. A model that was not loaded, a
175+// provider with no unload and a single-model llama-server say nothing.
176+func TestUnloadOnExitLines(t *testing.T) {
177+ f := &fakeOllama{loaded: []string{"own"}}
178+ srv := f.server(t)
179+ llmman, _ := Lookup("llmman")
180+ e := &Engine{Provider: llmman, Backend: Backend{Provider: "llmman", BaseURL: srv.URL + "/v1", Model: "own"}}
181+ if got := e.UnloadOnExit(context.Background()); got != "unloaded own" {
182+ t.Errorf("loaded: %q, want unloaded own", got)
183+ }
184+ if got := e.UnloadOnExit(context.Background()); got != "" {
185+ t.Errorf("not loaded: %q, want nothing", got)
186+ }
187+
188+ dmr, _ := Lookup("dmr")
189+ e = &Engine{Provider: dmr, Backend: Backend{Provider: "dmr", Model: "m"}}
190+ if got := e.UnloadOnExit(context.Background()); got != "" {
191+ t.Errorf("dmr: %q, want nothing", got)
192+ }
193+
194+ single := httptest.NewServer(http.NotFoundHandler())
195+ t.Cleanup(single.Close)
196+ llamacpp, _ := Lookup("llamacpp")
197+ e = &Engine{Provider: llamacpp, Backend: Backend{Provider: "llamacpp", BaseURL: single.URL + "/v1", Model: "m"}}
198+ if got := e.UnloadOnExit(context.Background()); got != "" {
199+ t.Errorf("single-model llama-server: %q, want nothing", got)
200+ }
201+
202+ e = &Engine{Provider: llmman, Backend: Backend{Provider: "llmman", BaseURL: "http://127.0.0.1:1/v1", Model: "m"}}
203+ if got := e.UnloadOnExit(context.Background()); !strings.HasPrefix(got, "cannot unload m:") {
204+ t.Errorf("unreachable: %q, want cannot unload", got)
205+ }
206+}
@@ -169,3 +169,38 @@ func TestUnloadAgentUsesTheOtherAgentsFile(t *testing.T) {
169 t.Errorf("absent: %q", got)169 t.Errorf("absent: %q", got)
170 }170 }
171 }171 }
172+
173+// UnloadOnExit (ticket 255) says only what is worth a line at exit: the
174+// model unloaded, or why it could not be. A model that was not loaded, a
175+// provider with no unload and a single-model llama-server say nothing.
176+func TestUnloadOnExitLines(t *testing.T) {
177+ f := &fakeOllama{loaded: []string{"own"}}
178+ srv := f.server(t)
179+ llmman, _ := Lookup("llmman")
180+ e := &Engine{Provider: llmman, Backend: Backend{Provider: "llmman", BaseURL: srv.URL + "/v1", Model: "own"}}
181+ if got := e.UnloadOnExit(context.Background()); got != "unloaded own" {
182+ t.Errorf("loaded: %q, want unloaded own", got)
183+ }
184+ if got := e.UnloadOnExit(context.Background()); got != "" {
185+ t.Errorf("not loaded: %q, want nothing", got)
186+ }
187+
188+ dmr, _ := Lookup("dmr")
189+ e = &Engine{Provider: dmr, Backend: Backend{Provider: "dmr", Model: "m"}}
190+ if got := e.UnloadOnExit(context.Background()); got != "" {
191+ t.Errorf("dmr: %q, want nothing", got)
192+ }
193+
194+ single := httptest.NewServer(http.NotFoundHandler())
195+ t.Cleanup(single.Close)
196+ llamacpp, _ := Lookup("llamacpp")
197+ e = &Engine{Provider: llamacpp, Backend: Backend{Provider: "llamacpp", BaseURL: single.URL + "/v1", Model: "m"}}
198+ if got := e.UnloadOnExit(context.Background()); got != "" {
199+ t.Errorf("single-model llama-server: %q, want nothing", got)
200+ }
201+
202+ e = &Engine{Provider: llmman, Backend: Backend{Provider: "llmman", BaseURL: "http://127.0.0.1:1/v1", Model: "m"}}
203+ if got := e.UnloadOnExit(context.Background()); !strings.HasPrefix(got, "cannot unload m:") {
204+ t.Errorf("unreachable: %q, want cannot unload", got)
205+ }
206+}
modified main.go +13 -2
@@ -278,6 +278,12 @@ func main() {
278278 fail("[engine error: %v ]", err)
279279 os.Exit(1)
280280 }
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 != "")()
286+
281287 // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this
282288 // agent's model before the hand-off, the asked agent's after it.
283289 asker.SetUnloads(ask.Unloads{
@@ -325,10 +331,14 @@ func main() {
325331 // Handle prompt mode: run a single prompt and exit
326332 if *promptMode != "" && e.IsDecider() {
327333 ui.Out = os.Stderr
328- os.Exit(runDecisionPrompt(ctx, e, *promptMode, os.Stdout))
334+ code := runDecisionPrompt(ctx, e, *promptMode, os.Stdout)
335+ exitU.run()
336+ os.Exit(code)
329337 }
330338 if *promptMode != "" && config.Cfg.OutputSchema != nil {
331- os.Exit(runStructuredPrompt(ctx, e, *promptMode))
339+ code := runStructuredPrompt(ctx, e, *promptMode)
340+ exitU.run()
341+ os.Exit(code)
332342 }
333343 if *promptMode != "" {
334344 // In prompt mode, no banner, no session persistence. A failed
@@ -337,6 +347,7 @@ func main() {
337347 if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {
338348 set.close()
339349 asker.Close()
350+ exitU.run()
340351 os.Exit(code)
341352 }
342353 return
@@ -278,6 +278,12 @@ func main() {
278 fail("[engine error: %v ]", err)278 fail("[engine error: %v ]", err)
279 os.Exit(1)279 os.Exit(1)
280 }280 }
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 != "")()
286+
281 // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this287 // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this
282 // agent's model before the hand-off, the asked agent's after it.288 // agent's model before the hand-off, the asked agent's after it.
283 asker.SetUnloads(ask.Unloads{289 asker.SetUnloads(ask.Unloads{
@@ -325,10 +331,14 @@ func main() {
325 // Handle prompt mode: run a single prompt and exit331 // Handle prompt mode: run a single prompt and exit
326 if *promptMode != "" && e.IsDecider() {332 if *promptMode != "" && e.IsDecider() {
327 ui.Out = os.Stderr333 ui.Out = os.Stderr
328- os.Exit(runDecisionPrompt(ctx, e, *promptMode, os.Stdout))334+ code := runDecisionPrompt(ctx, e, *promptMode, os.Stdout)
335+ exitU.run()
336+ os.Exit(code)
329 }337 }
330 if *promptMode != "" && config.Cfg.OutputSchema != nil {338 if *promptMode != "" && config.Cfg.OutputSchema != nil {
331- os.Exit(runStructuredPrompt(ctx, e, *promptMode))339+ code := runStructuredPrompt(ctx, e, *promptMode)
340+ exitU.run()
341+ os.Exit(code)
332 }342 }
333 if *promptMode != "" {343 if *promptMode != "" {
334 // In prompt mode, no banner, no session persistence. A failed344 // In prompt mode, no banner, no session persistence. A failed
@@ -337,6 +347,7 @@ func main() {
337 if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {347 if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {
338 set.close()348 set.close()
339 asker.Close()349 asker.Close()
350+ exitU.run()
340 os.Exit(code)351 os.Exit(code)
341 }352 }
342 return353 return
added unload_exit.go +111 -0
new file mode 100644
@@ -0,0 +1,111 @@
1+package main
2+
3+import (
4+ "context"
5+ "fmt"
6+ "io"
7+ "os"
8+ "os/signal"
9+ "sync"
10+ "syscall"
11+ "time"
12+
13+ "mm/internal/config"
14+ "mm/internal/engine"
15+)
16+
17+// Unloading the model when mm exits (config unloadOnExit, ticket 255). Every
18+// way out ends in exitUnload.run, at most once:
19+//
20+// - /quit, Ctrl-C at the prompt, Ctrl-D, the window closed, the editor
21+// closing the ACP session, the end of a -p run: main returns, its
22+// deferred run fires — or main calls run itself before an os.Exit,
23+// which skips the deferred calls;
24+// - SIGTERM, SIGHUP (the terminal closed), and Ctrl-C during a -p run,
25+// which nothing else catches: watchExitSignals runs it, then exits
26+// with the usual 128+signal code.
27+//
28+// A crash unloads nothing; the next start or the server's own idle timeout
29+// takes care of it.
30+
31+// exitUnload unloads the agent's model once, within timeout. A zero
32+// exitUnload (unloadOnExit: false) does nothing.
33+type exitUnload struct {
34+ once sync.Once
35+ model string
36+ unload func(ctx context.Context) string // "" = nothing to say
37+ timeout time.Duration
38+ out io.Writer // nil = say nothing (ACP mode: stderr is the editor's log)
39+}
40+
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 {
44+ if !config.Cfg.UnloadOnExit {
45+ return &exitUnload{}
46+ }
47+ u := &exitUnload{model: e.Backend.Model, unload: e.UnloadOnExit, timeout: config.UnloadOnExitTimeout}
48+ if !acpMode {
49+ u.out = os.Stderr
50+ }
51+ return u
52+}
53+
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.
57+func (u *exitUnload) run() {
58+ if u == nil || u.unload == nil {
59+ return
60+ }
61+ u.once.Do(func() {
62+ ctx, cancel := context.WithTimeout(context.Background(), u.timeout)
63+ defer cancel()
64+ done := make(chan string, 1)
65+ go func() { done <- u.unload(ctx) }()
66+ var line string
67+ select {
68+ case line = <-done:
69+ case <-ctx.Done():
70+ line = fmt.Sprintf("cannot unload %s: no answer within %s", u.model, u.timeout)
71+ }
72+ if line != "" && u.out != nil {
73+ _, _ = fmt.Fprintf(u.out, "🧹 %s\n", line)
74+ }
75+ })
76+}
77+
78+// watchExitSignals catches the signals that would end mm without main
79+// returning — SIGTERM, SIGHUP, and SIGINT when withInterrupt (a -p run: the
80+// line mode and the window handle Ctrl-C themselves) — runs u, and exits
81+// with 128 + the signal's number. The returned function stops watching.
82+func watchExitSignals(u *exitUnload, withInterrupt bool) (stop func()) {
83+ sigs := []os.Signal{syscall.SIGTERM, syscall.SIGHUP}
84+ if withInterrupt {
85+ sigs = append(sigs, os.Interrupt)
86+ }
87+ ch := make(chan os.Signal, 1)
88+ signal.Notify(ch, sigs...)
89+ quit := make(chan struct{})
90+ go func() {
91+ select {
92+ case sig := <-ch:
93+ // The signal may cut an answer mid-line: the 🧹 line starts
94+ // on a line of its own.
95+ if u.out != nil {
96+ _, _ = fmt.Fprintln(u.out)
97+ }
98+ u.run()
99+ code := 1
100+ if s, ok := sig.(syscall.Signal); ok {
101+ code = 128 + int(s)
102+ }
103+ os.Exit(code)
104+ case <-quit:
105+ }
106+ }()
107+ return func() {
108+ signal.Stop(ch)
109+ close(quit)
110+ }
111+}
new file mode 100644
@@ -0,0 +1,111 @@
1+package main
2+
3+import (
4+ "context"
5+ "fmt"
6+ "io"
7+ "os"
8+ "os/signal"
9+ "sync"
10+ "syscall"
11+ "time"
12+
13+ "mm/internal/config"
14+ "mm/internal/engine"
15+)
16+
17+// Unloading the model when mm exits (config unloadOnExit, ticket 255). Every
18+// way out ends in exitUnload.run, at most once:
19+//
20+// - /quit, Ctrl-C at the prompt, Ctrl-D, the window closed, the editor
21+// closing the ACP session, the end of a -p run: main returns, its
22+// deferred run fires — or main calls run itself before an os.Exit,
23+// which skips the deferred calls;
24+// - SIGTERM, SIGHUP (the terminal closed), and Ctrl-C during a -p run,
25+// which nothing else catches: watchExitSignals runs it, then exits
26+// with the usual 128+signal code.
27+//
28+// A crash unloads nothing; the next start or the server's own idle timeout
29+// takes care of it.
30+
31+// exitUnload unloads the agent's model once, within timeout. A zero
32+// exitUnload (unloadOnExit: false) does nothing.
33+type exitUnload struct {
34+ once sync.Once
35+ model string
36+ unload func(ctx context.Context) string // "" = nothing to say
37+ timeout time.Duration
38+ out io.Writer // nil = say nothing (ACP mode: stderr is the editor's log)
39+}
40+
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 {
44+ if !config.Cfg.UnloadOnExit {
45+ return &exitUnload{}
46+ }
47+ u := &exitUnload{model: e.Backend.Model, unload: e.UnloadOnExit, timeout: config.UnloadOnExitTimeout}
48+ if !acpMode {
49+ u.out = os.Stderr
50+ }
51+ return u
52+}
53+
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.
57+func (u *exitUnload) run() {
58+ if u == nil || u.unload == nil {
59+ return
60+ }
61+ u.once.Do(func() {
62+ ctx, cancel := context.WithTimeout(context.Background(), u.timeout)
63+ defer cancel()
64+ done := make(chan string, 1)
65+ go func() { done <- u.unload(ctx) }()
66+ var line string
67+ select {
68+ case line = <-done:
69+ case <-ctx.Done():
70+ line = fmt.Sprintf("cannot unload %s: no answer within %s", u.model, u.timeout)
71+ }
72+ if line != "" && u.out != nil {
73+ _, _ = fmt.Fprintf(u.out, "🧹 %s\n", line)
74+ }
75+ })
76+}
77+
78+// watchExitSignals catches the signals that would end mm without main
79+// returning — SIGTERM, SIGHUP, and SIGINT when withInterrupt (a -p run: the
80+// line mode and the window handle Ctrl-C themselves) — runs u, and exits
81+// with 128 + the signal's number. The returned function stops watching.
82+func watchExitSignals(u *exitUnload, withInterrupt bool) (stop func()) {
83+ sigs := []os.Signal{syscall.SIGTERM, syscall.SIGHUP}
84+ if withInterrupt {
85+ sigs = append(sigs, os.Interrupt)
86+ }
87+ ch := make(chan os.Signal, 1)
88+ signal.Notify(ch, sigs...)
89+ quit := make(chan struct{})
90+ go func() {
91+ select {
92+ case sig := <-ch:
93+ // The signal may cut an answer mid-line: the 🧹 line starts
94+ // on a line of its own.
95+ if u.out != nil {
96+ _, _ = fmt.Fprintln(u.out)
97+ }
98+ u.run()
99+ code := 1
100+ if s, ok := sig.(syscall.Signal); ok {
101+ code = 128 + int(s)
102+ }
103+ os.Exit(code)
104+ case <-quit:
105+ }
106+ }()
107+ return func() {
108+ signal.Stop(ch)
109+ close(quit)
110+ }
111+}
added unload_exit_test.go +56 -0
new file mode 100644
@@ -0,0 +1,56 @@
1+package main
2+
3+import (
4+ "bytes"
5+ "context"
6+ "strings"
7+ "testing"
8+ "time"
9+)
10+
11+// The exit unload (ticket 255) runs once whatever the number of ways out
12+// that reach it, prints its line, and a disabled one does nothing.
13+func TestExitUnloadRunsOnce(t *testing.T) {
14+ calls := 0
15+ var out bytes.Buffer
16+ u := &exitUnload{model: "m", timeout: time.Second, out: &out,
17+ unload: func(context.Context) string { calls++; return "unloaded m" }}
18+ u.run()
19+ u.run()
20+ if calls != 1 || out.String() != "🧹 unloaded m\n" {
21+ t.Errorf("calls %d, out %q, want one call and one line", calls, out.String())
22+ }
23+
24+ var off *exitUnload
25+ off.run()
26+ (&exitUnload{}).run() // unloadOnExit: false
27+}
28+
29+// Nothing to say (model not loaded, provider that cannot unload) prints
30+// nothing; ACP mode (no writer) prints nothing either.
31+func TestExitUnloadQuietLines(t *testing.T) {
32+ var out bytes.Buffer
33+ (&exitUnload{timeout: time.Second, out: &out, unload: func(context.Context) string { return "" }}).run()
34+ (&exitUnload{timeout: time.Second, unload: func(context.Context) string { return "unloaded m" }}).run()
35+ if out.Len() != 0 {
36+ t.Errorf("out %q, want nothing", out.String())
37+ }
38+}
39+
40+// A server that does not answer never holds the exit past the timeout, even
41+// when the unload ignores its context.
42+func TestExitUnloadTimeout(t *testing.T) {
43+ var out bytes.Buffer
44+ block := make(chan struct{})
45+ t.Cleanup(func() { close(block) })
46+ u := &exitUnload{model: "m", timeout: 50 * time.Millisecond, out: &out,
47+ unload: func(context.Context) string { <-block; return "unloaded m" }}
48+ start := time.Now()
49+ u.run()
50+ if d := time.Since(start); d > time.Second {
51+ t.Errorf("run took %s, want about the 50ms timeout", d)
52+ }
53+ if !strings.Contains(out.String(), "cannot unload m: no answer within 50ms") {
54+ t.Errorf("out %q, want the timeout line", out.String())
55+ }
56+}
new file mode 100644
@@ -0,0 +1,56 @@
1+package main
2+
3+import (
4+ "bytes"
5+ "context"
6+ "strings"
7+ "testing"
8+ "time"
9+)
10+
11+// The exit unload (ticket 255) runs once whatever the number of ways out
12+// that reach it, prints its line, and a disabled one does nothing.
13+func TestExitUnloadRunsOnce(t *testing.T) {
14+ calls := 0
15+ var out bytes.Buffer
16+ u := &exitUnload{model: "m", timeout: time.Second, out: &out,
17+ unload: func(context.Context) string { calls++; return "unloaded m" }}
18+ u.run()
19+ u.run()
20+ if calls != 1 || out.String() != "🧹 unloaded m\n" {
21+ t.Errorf("calls %d, out %q, want one call and one line", calls, out.String())
22+ }
23+
24+ var off *exitUnload
25+ off.run()
26+ (&exitUnload{}).run() // unloadOnExit: false
27+}
28+
29+// Nothing to say (model not loaded, provider that cannot unload) prints
30+// nothing; ACP mode (no writer) prints nothing either.
31+func TestExitUnloadQuietLines(t *testing.T) {
32+ var out bytes.Buffer
33+ (&exitUnload{timeout: time.Second, out: &out, unload: func(context.Context) string { return "" }}).run()
34+ (&exitUnload{timeout: time.Second, unload: func(context.Context) string { return "unloaded m" }}).run()
35+ if out.Len() != 0 {
36+ t.Errorf("out %q, want nothing", out.String())
37+ }
38+}
39+
40+// A server that does not answer never holds the exit past the timeout, even
41+// when the unload ignores its context.
42+func TestExitUnloadTimeout(t *testing.T) {
43+ var out bytes.Buffer
44+ block := make(chan struct{})
45+ t.Cleanup(func() { close(block) })
46+ u := &exitUnload{model: "m", timeout: 50 * time.Millisecond, out: &out,
47+ unload: func(context.Context) string { <-block; return "unloaded m" }}
48+ start := time.Now()
49+ u.run()
50+ if d := time.Since(start); d > time.Second {
51+ t.Errorf("run took %s, want about the 50ms timeout", d)
52+ }
53+ if !strings.Contains(out.String(), "cannot unload m: no answer within 50ms") {
54+ t.Errorf("out %q, want the timeout line", out.String())
55+ }
56+}