@octocodeai/freellama-mcp-server 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CONFIGURATION.md +82 -3
  2. package/DEVELOPING.md +40 -9
  3. package/README.md +316 -213
  4. package/dist/agent-cli.js +16963 -0
  5. package/dist/index.js +4896 -4036
  6. package/dist/research/bash-agent.js +287 -108
  7. package/dist/research/coder-agent.js +455 -127
  8. package/dist/research/github-agent.js +276 -94
  9. package/dist/research/octocode-agent.js +276 -94
  10. package/docs/AGENT_CLI.md +234 -0
  11. package/docs/API.md +160 -0
  12. package/docs/ARCHITECTURE.md +158 -50
  13. package/docs/ASSESSMENT.md +131 -0
  14. package/docs/BENCHMARK.md +381 -0
  15. package/docs/BUILD_AND_NOTES.md +12 -3
  16. package/docs/CLI.md +62 -17
  17. package/docs/CPU_GPU_ROUTING.md +22 -9
  18. package/docs/DEFERRED_JOBS.md +17 -4
  19. package/docs/FEATURES.md +97 -43
  20. package/docs/LLAMACPP.md +133 -0
  21. package/docs/LOCAL_MODELS.md +26 -20
  22. package/docs/MODEL_FORMS_AND_RESULTS.md +14 -6
  23. package/docs/MODEL_INTROSPECTION.md +9 -2
  24. package/docs/MODEL_SELECTION.md +38 -9
  25. package/docs/MONITORING.md +110 -12
  26. package/docs/OLLAMA_REVIEW.md +226 -0
  27. package/docs/PRODUCTION.md +68 -25
  28. package/docs/PROMPTS.md +119 -0
  29. package/docs/README.md +22 -6
  30. package/docs/RELIABILITY.md +207 -0
  31. package/docs/RUST_RESOURCE_AUDIT.md +65 -0
  32. package/docs/SCOPES_AND_WARMING.md +12 -5
  33. package/docs/TESTING.md +112 -6
  34. package/docs/TUNING.md +12 -8
  35. package/docs/assets/benchmark-results-2026-11-14.html +4 -0
  36. package/docs/assets/tool-calling-2026-11-14-bonsai-9b/TABLE.md +14 -0
  37. package/docs/assets/tool-calling-2026-11-14-lfm3-vl/TABLE.md +14 -0
  38. package/docs/assets/tool-calling-table.md +14 -0
  39. package/docs/cookbooks/README.md +9 -2
  40. package/docs/cookbooks/batch-text.md +4 -2
  41. package/docs/cookbooks/classify.md +19 -3
  42. package/docs/cookbooks/coding.md +13 -4
  43. package/docs/cookbooks/find-code.md +8 -3
  44. package/docs/cookbooks/jobs.md +8 -8
  45. package/docs/cookbooks/memory-and-caching.md +2 -2
  46. package/docs/cookbooks/ocr.md +3 -3
  47. package/docs/cookbooks/research-agent.md +32 -2
  48. package/docs/cookbooks/speech-to-text.md +1 -1
  49. package/docs/cookbooks/sweep.md +4 -1
  50. package/docs/octocode/GITHUB.md +4 -4
  51. package/docs/octocode/LOCAL.md +5 -4
  52. package/native/index.d.ts +1 -1
  53. package/package.json +6 -6
  54. package/docs/COMPARISON.md +0 -40
@@ -1,12 +1,16 @@
1
1
  # FreeLlama architecture
2
2
 
3
- FreeLlama is the management layer between an AI agent and local Ollama models. Agents offload
3
+ FreeLlama is the management layer between an AI agent and local inference servers. Agents offload
4
4
  bounded tasks through MCP, the CLI, or the control API. FreeLlama selects eligible models,
5
5
  coordinates resources, and returns results with execution evidence.
6
6
 
7
+ Ollama supports the complete managed model lifecycle. The [llama.cpp adapter](LLAMACPP.md) supports
8
+ explicitly selected bounded text tasks on an operator-run server, sharing core admission and
9
+ memory policy. Its unsupported capabilities are refused before generation.
10
+
7
11
  The calling agent owns task decomposition, prompts, and answer verification. FreeLlama owns managed
8
12
  admission, memory checks, residency coordination, and routing within operator-configured CPU/GPU
9
- backends. Ollama owns model storage, runner loading, inference engines, and token generation;
13
+ backends. The configured inference server owns model storage, runner loading, and token generation;
10
14
  the operating system and drivers schedule physical work.
11
15
 
12
16
  ## Responsibility boundary
@@ -16,15 +20,17 @@ This is the canonical ownership rule; other guides link here.
16
20
  | Responsibility | Owner |
17
21
  |---|---|
18
22
  | Goal decomposition, prompts, system messages, task dependencies, and answer verification | Calling agent |
19
- | Ollama processes and endpoints, exact `--cpu-model` assignments, runtime settings, and approval of pulls, stops, and deletes | Operator |
20
- | Prompt templates and model defaults | Ollama model metadata or a `Modelfile` |
23
+ | Inference processes and endpoints, exact Ollama `--cpu-model` assignments, llama.cpp limits, runtime settings, and approval of pulls, stops, and deletes | Operator |
24
+ | Prompt templates and model defaults | Inference-server configuration; Ollama model metadata or a `Modelfile` on the Ollama path |
21
25
  | Physical CPU/GPU scheduling and memory | OS, drivers, and accelerator runtime |
22
- | Model files, runners, Metal, MLX, llama.cpp, and token generation | Ollama |
23
- | Native `/api/*` and OpenAI-compatible `/v1/*` semantics | Ollama |
24
- | Installed-model discovery and capability normalization | FreeLlama |
26
+ | Model files, runner loading, inference kernels, and token generation | Configured inference server (Ollama or explicit llama.cpp adapter) |
27
+ | Native `/api/*` semantics | Ollama |
28
+ | OpenAI-compatible `/v1/*` semantics | Selected inference server, within its supported protocol |
29
+ | Ollama installed-model discovery and capability normalization | FreeLlama |
25
30
  | Task routing, advertised-context compatibility, advisory K/V estimates, evidence policy, and model rejection reasons | FreeLlama |
26
31
  | Managed admission, session affinity, bounded scope history, and model-transition coordination | FreeLlama |
27
- | Forecast memory reservations, host-pressure holds, and requests to unload idle unpinned models | FreeLlama managed execution |
32
+ | Forecast memory reservations and host-pressure holds | FreeLlama managed execution and native local raw Ollama loads; external raw upstreams have narrower pressure gating |
33
+ | Requests to unload idle unpinned Ollama models | FreeLlama Ollama lifecycle coordination |
28
34
  | Explicit per-model CPU/GPU backend assignment | FreeLlama and separate Ollama processes |
29
35
  | Grounded research adapters, citations, and verification verdicts | FreeLlama MCP server |
30
36
  | Bearer authentication of every route except the static `/_freellama/ui` shell | FreeLlama; external ingress owns TLS and tenant authorization |
@@ -46,6 +52,7 @@ flowchart LR
46
52
  F -->|"managed primary task"| G
47
53
  F -->|"managed assigned task"| U["Optional CPU Ollama"]
48
54
  F -->|"/v1 for an engine's model"| O["Optional OpenAI-compatible engines<br/>LM Studio, llama.cpp, vLLM, cloud"]
55
+ F -->|"explicit managed text task"| LC["Operator-run local llama.cpp"]
49
56
  G --> E["Metal, MLX, CUDA, ROCm, Vulkan, or CPU runner"]
50
57
  U --> E2["CPU runner"]
51
58
  ```
@@ -72,6 +79,7 @@ flowchart TB
72
79
  subgraph clients["Clients"]
73
80
  CLI["freellama CLI"]
74
81
  MCP["MCP client"]
82
+ FLL["freellama CLI / gateway"]
75
83
  RUST["Embedded Rust application"]
76
84
  RAW["Ollama-compatible client"]
77
85
  end
@@ -89,21 +97,29 @@ flowchart TB
89
97
 
90
98
  CLI --> CORE
91
99
  MCP --> CORE
100
+ FLL -->|"in-process MCP handlers"| API
101
+ FLL -->|"streamed rewrites"| PX
92
102
  RUST --> CORE
93
103
  CORE --> API
94
104
  RAW --> PX
95
105
  API --> GPU
96
106
  API --> CPU
107
+ API -->|"explicit bounded text"| LC["Local llama.cpp"]
108
+ PX -->|"configured /v1 model"| EXT["OpenAI-compatible engines"]
97
109
  PX --> GPU
98
110
  MCP --> ADAPTER
99
111
  ADAPTER --> FILES
100
112
  ADAPTER --> GPU
101
113
  ```
102
114
 
103
- The CLI and MCP server do not reimplement routing. CLI commands other than `serve`, `doctor`,
104
- `init`, and benchmarking are HTTP clients of a running `freellama serve`. The MCP server reaches the
105
- same control API through the feature-gated NAPI boundary, and unless `FREELLAMA_MCP_AUTOSTART_SERVE=0`
115
+ The CLI and MCP server do not reimplement routing. `freellama` commands other than `serve`, `proxy`,
116
+ `doctor`, `init`, `catalog` (it falls back to the shipped catalog), `auth-token`, `bench-all`, and
117
+ `policy from-eval` are HTTP clients of a running `freellama serve`. The MCP server reaches the same control API through the feature-gated NAPI boundary, and unless `FREELLAMA_MCP_AUTOSTART_SERVE=0`
106
118
  it starts the bundled `serve` in the background at launch when nothing answers on the default endpoint.
119
+ The agent commands (`freellama run`, `chat`, `gateway`…) call the same MCP tool handlers in-process. Its gateway runs a non-streamed Ollama or OpenAI
120
+ chat on a `freellama/<workflow|job|auto>` virtual model as managed `run_task`, rewrites streamed and
121
+ Anthropic or OpenAI Responses requests for serve's Ollama passthrough, and proxies everything else to
122
+ serve ([agent CLI](AGENT_CLI.md)).
107
123
 
108
124
  ## Request classification
109
125
 
@@ -113,7 +129,7 @@ The listener classifies requests by path before any model-aware work occurs:
113
129
  flowchart TD
114
130
  IN["Request to FreeLlama"] --> P{"Path starts with<br/>/_freellama/v1/?"}
115
131
  P -->|"No"| RAW["Stream through compatibility proxy"]
116
- RAW --> PRIMARY["Primary Ollama"]
132
+ RAW --> PRIMARY["Primary Ollama or configured /v1 upstream"]
117
133
  P -->|"Yes"| C{"Control endpoint"}
118
134
  C -->|"health, machine, models"| READ["Read local and Ollama state"]
119
135
  C -->|"routes"| DECIDE["Decide without inference"]
@@ -128,6 +144,7 @@ The control API exposes these endpoints:
128
144
  | Method and path | Purpose | Inference |
129
145
  |---|---|---|
130
146
  | `GET /_freellama/v1/health` | Health, admission capacity, and configured backends | No |
147
+ | `GET /_freellama/v1/ready` | 200 once the primary Ollama (and CPU backend, when configured) answers and its catalog reads; otherwise 503 naming what is missing | No |
131
148
  | `GET /_freellama/v1/machine` | Machine profile | No |
132
149
  | `GET /_freellama/v1/models` | Normalized installed catalog, evidence, residency, and execution backend | No |
133
150
  | `POST /_freellama/v1/routes` | Deterministic route decision | No |
@@ -139,6 +156,7 @@ The control API exposes these endpoints:
139
156
  | `POST /_freellama/v1/scopes/:id/fork` | Fork history at an expected revision | No |
140
157
  | `DELETE /_freellama/v1/scopes/:id` | Delete retained history | No |
141
158
  | `POST /_freellama/v1/warm` | Admitted load of an exact installed runner profile | Load only |
159
+ | `POST /_freellama/v1/unload` | Unload a resident model once its running tasks finish; a model that is not loaded reports `not_resident` | No |
142
160
  | `POST /_freellama/v1/tasks` | Managed chat, vision, tools, or embedding task (body shape under [Request shapes](#request-shapes)) | Yes |
143
161
  | `POST /_freellama/v1/task-batches` | Caller-declared independent tasks with ordered per-item receipts | Yes |
144
162
  | `GET /_freellama/v1/jobs` | Deferred job metadata without prompts or results | No |
@@ -146,10 +164,16 @@ The control API exposes these endpoints:
146
164
  | `POST /_freellama/v1/jobs/:id/cancel` | Cancel one deferred task and release its local permits | No new inference |
147
165
  | `DELETE /_freellama/v1/jobs/:id` | Cancel active work, release local permits, and remove its retained record | No new inference |
148
166
 
149
- Status, usage, metrics, and runtime-config endpoints are listed in [monitoring](MONITORING.md).
167
+ Status, usage, metrics, and runtime-config (`config`, `config/reload`) endpoints are listed in
168
+ [monitoring](MONITORING.md); [API](API.md) lists every surface.
150
169
 
151
170
  ### Request shapes
152
171
 
172
+ The fields and stream behavior below describe Ollama tasks. Explicit `name/model` requests for a
173
+ configured llama.cpp adapter use the narrower [text contract](LLAMACPP.md#supported-contract-and-limits);
174
+ unsupported controls are refused rather than forwarded or ignored. Its normalized receipt names
175
+ `execution.engine:"llamacpp"` and reports physical placement as unknown.
176
+
153
177
  The control API uses snake_case JSON. A managed task body is the routing fields plus the payload:
154
178
 
155
179
  ```json
@@ -170,13 +194,65 @@ installed tag of that family; an unknown or ambiguous name is refused with the i
170
194
  `request_options.options`. `stop_on_repetition` (on by default when no `num_predict` caps the output,
171
195
  `false` to turn it off) streams the chat from Ollama and stops as soon
172
196
  as the output repeats its unit twice after the first copy over 96+ characters: the connection
173
- closes, which cancels generation upstream, and everything generated is kept with
197
+ closes to request cancellation upstream, and everything generated is kept with
174
198
  `done_reason: "repetition"`. An Ollama "token repeat limit" abort is kept the same way
175
199
  (`done_reason: "repeat_limit"`). A stopped stream has no Ollama timing fields, so it trains no
176
200
  throughput feedback. The receipt holds `route`, `admission` (`queue_wait_ms`,
177
201
  `resource_wait_ms`, `transition_wait_ms`, `total_wait_ms`), `execution` (placement, observation,
178
- `resource_admission`, `context_sizing`, `memory_reservation`), `metrics`, `feedback` and
179
- `response`, which is Ollama's own answer (`message.content`, `eval_count`, durations).
202
+ `resource_admission`, `context_sizing`, `memory_reservation`), `metrics`, `feedback`, `timing` and
203
+ `response`, which is Ollama's own answer (`message.content`, `eval_count`, durations). `timing` says
204
+ where the task's time went inside `serve`, in milliseconds: `discover_ms`, `route_ms`,
205
+ `prepare_ms`, `admission_ms`, `dispatch_ms`, `upstream_ms` (Ollama's whole answer),
206
+ `placement_ms`, `learning_ms`, `persist_ms`, `receipt_ms`, `total_ms`, and `overhead_ms`
207
+ (everything except `upstream_ms`). Learned feedback is written to disk after the response
208
+ (`feedback.persistence.persisted: "queued"`); a failed write shows in health.
209
+
210
+ `stream: true` answers with server-sent events (`text/event-stream`) instead of one JSON body. The
211
+ task uses the same routing, fallback chain, admission, memory gate and receipt as a JSON response.
212
+
213
+ | Event | When | `data` |
214
+ |---|---|---|
215
+ | `route` | the model is chosen, before dispatch (once per fallback attempt) | `{selected_model, backend}` |
216
+ | `admission` | queued, waiting for memory, loading, running | `{status, reason, detail?}`, the deferred-job phases |
217
+ | `delta` | each generated piece | `{content}` or `{thinking}` |
218
+ | `done` | finished | the receipt a non-streaming call returns |
219
+ | `error` | refused or failed | the error body, `status` and `retry_safe` (false once a `delta` was sent) |
220
+
221
+ Only generating tasks stream (`completion`, `coding`, `code_repair`, `vision`, `long_context`),
222
+ without `defer`, `tools`, `questions`, `input` or `nearest`; anything else is refused before
223
+ admission with 422 `stream_unsupported`. Fallback models advance only before generation starts. A
224
+ client that disconnects aborts the task and closes the upstream request to request cancellation;
225
+ local permit release is not proof of physical stop, and nothing is replayed. `stop_on_repetition` keeps its meaning: streaming does not turn the
226
+ loop stop on. A deferred chat job without tools reads Ollama's output the same way and shows
227
+ `{generated_tokens, tokens_per_second}` in its status detail (reason `generating`), which MCP
228
+ `run_task` reports as progress.
229
+
230
+ Managed Ollama responses have a byte ceiling equal to `FREELLAMA_MAX_REQUEST_BYTES` (64 MiB by
231
+ default). It covers the complete JSON response or cumulative NDJSON bytes, including reasoning,
232
+ tools, log probabilities, malformed frames and error bodies. Crossing it closes the response and
233
+ returns `upstream_response_too_large` with `retry_safe:false`; any retained prefix is incomplete.
234
+ This is a per-response wire bound, not a process-wide heap limit. The raw compatibility proxy
235
+ continues forwarding response bytes without accumulating a complete answer.
236
+
237
+ Managed SSE uses bounded queues between execution and the response body. A slow reader applies
238
+ backpressure to generated text and route events; admission progress updates are best effort while
239
+ the queue is full. The execution worker continues enforcing the task deadline independently of
240
+ the reader and releases local permits on expiry. Streams without a caller deadline use the server
241
+ task timeout. Dropping the response aborts that worker; an unread bounded result may remain until
242
+ the client reads or closes the connection.
243
+
244
+ `fallback_models` (up to 4 tags) is an explicit fallback chain run in the core
245
+ (`platform/execution/fallback.rs`): the next model replaces `model` only when the attempt before it
246
+ was refused with a code that proves nothing executed (`resource_admission_unavailable`,
247
+ `context_window_exceeded`, `embedding_item_exceeds_context`, `model_exceeds_host_budget`,
248
+ `upstream_circuit_open`, `model_not_installed`, `model_not_eligible`), and only when no earlier
249
+ embedding slice of the same task ran. Any other error ends the chain. During each attempt the later
250
+ chain models are registered as busy, which keeps eviction from unloading them. An attempt without a
251
+ `model` records the model routing selected, so `attempts[].model` is never null for a routed pick and
252
+ that model is not tried again; the usage record of a failed chain names the last model tried.
253
+ A success adds `fallback: {used, attempts, selected}` to the receipt; a failure adds
254
+ `fallback: {used, exhausted, attempts, note}` to the error body. A deferred job validates the chain
255
+ at submission.
180
256
 
181
257
  A batch nests whole task bodies:
182
258
 
@@ -192,10 +268,12 @@ architecture, and disk. `memory_bytes` is portable host RAM. `memory_kind` is `u
192
268
  when host and accelerator memory are known to share a pool; host RAM must not be treated as
193
269
  discrete GPU VRAM. Ollama's `/api/ps` remains the placement authority.
194
270
 
195
- All other paths use the compatibility proxy. It buffers request bodies up to 64 MB so a retry can
196
- resend identical bytes, then streams the upstream response. It removes hop-by-hop headers, adds
197
- `x-freellama-proxy: 1`, always targets the primary upstream, and does not apply CPU model
198
- assignment. Existing Ollama clients keep predictable compatibility; clients that opt into the
271
+ All other paths use the compatibility proxy. It buffers request bodies up to 64 MiB by default for admission
272
+ and forwarding, then streams the upstream response. Requests are replayed only when execution
273
+ is proven not to have started; buffering bytes does not make an inference retry safe. It removes hop-by-hop headers, adds
274
+ `x-freellama-proxy: 1`, and does not apply CPU model assignments. Native Ollama paths target
275
+ the primary upstream; configured OpenAI-compatible `/v1/*` requests can route by model to other
276
+ engines, and `/v1/systemone` has asset translation. Existing Ollama clients keep predictable compatibility; clients that opt into the
199
277
  managed API receive routing and policy behavior.
200
278
 
201
279
  ## Model discovery
@@ -248,7 +326,7 @@ See [Model metadata](MODEL_SELECTION.md#model-metadata) for the public contract
248
326
  ## Deterministic routing
249
327
 
250
328
  Routing defaults to ordinary `completion`; explicit profiles refine selection. Supported task kinds are `completion`, `coding`,
251
- `code_repair`, `tools`, `browser`, `vision`, `embedding`, and `long_context`.
329
+ `code_repair`, `tools`, `browser`, `vision`, `embedding`, `long_context`, and `decision`.
252
330
 
253
331
  ```mermaid
254
332
  flowchart TD
@@ -289,6 +367,13 @@ placement evidence; Ollama remains authoritative for actual runner allocation an
289
367
 
290
368
  ### Confidence evidence
291
369
 
370
+ Ollama benchmark rankings qualify only when a schema-2 report matches the current host identity,
371
+ observed hardware profile, exact loopback endpoint and installed model digest. Missing identity,
372
+ legacy schema, a different machine/endpoint, or an ambiguous/mismatched model artifact supplies no
373
+ ranking evidence. A matching throughput report still does not establish task accuracy. Quality
374
+ policy evidence independently matches exact model digests and excludes smoke-only policies.
375
+ See [model selection](MODEL_SELECTION.md) for calibration and quality qualification.
376
+
292
377
  Confidence is a grade derived from independent evidence dimensions:
293
378
 
294
379
  | Policy evidence | Benchmark evidence | Confidence | Meaning |
@@ -312,10 +397,17 @@ configuration, discovery, and shared state; extracting these owners preserves th
312
397
  Managed tasks combine routing with admission and backend-aware transition coordination. With
313
398
  `defer:true`, the server returns HTTP `202` and a process-local job handle, then runs the same task
314
399
  path. The bounded registry owns receipts and cancellation, while the existing governor owns
315
- admission. Batch items cannot defer. Per-task `timeout_seconds` bounds discovery, waiting, loading,
400
+ admission. Optional durable storage retains terminal receipts without replaying unfinished work
401
+ ([deferred jobs](DEFERRED_JOBS.md)). Batch items cannot defer. Per-task `timeout_seconds` bounds discovery, waiting, loading,
316
402
  and inference together, capped by the server task timeout. See [CLI controls](CLI.md#execute-tasks)
317
403
  for retention limits and [monitoring](MONITORING.md) for the observable lifecycle.
318
404
 
405
+ The Ollama path below includes model discovery, context sizing, transition locks and placement
406
+ learning. The explicit [llama.cpp path](LLAMACPP.md) shares admission pools, the resource governor,
407
+ job/deadline handling and usage accounting, while using operator-set memory and output bounds.
408
+ It checks the ready single-model endpoint and never performs lifecycle operations, auto-selection,
409
+ physical-placement claims or Ollama feedback learning. It sends one generation POST with no retry.
410
+
319
411
  ```mermaid
320
412
  flowchart TD
321
413
  T["POST /tasks or /task-batches"] --> R["Select eligible model + backend"]
@@ -326,24 +418,25 @@ flowchart TD
326
418
  B -->|"Primary"| GL{"GPU runner resident<br/>at expected identity?"}
327
419
  B -->|"CPU assignment"| CO["Add num_gpu: 0"]
328
420
  CO --> CL{"CPU runner resident<br/>at expected identity?"}
329
- GL -->|"Yes"| GR["GPU shared lock"]
421
+ GL -->|"Yes"| GR["GPU model use lease; no load lock"]
330
422
  GL -->|"No"| GX["GPU load lock until runner observed"]
331
- CL -->|"Yes"| CR["CPU shared lock"]
423
+ CL -->|"Yes"| CR["CPU model use lease; no load lock"]
332
424
  CL -->|"No"| CX["CPU load lock until runner observed"]
333
425
  GR --> OQ["Send to selected Ollama queue"]
334
426
  GX --> OQ
335
427
  CR --> OQ
336
428
  CX --> OQ
337
429
  OQ --> SEND["Ollama schedules bounded request"]
338
- SEND --> RETRY{"500, 502,<br/>or connection-establishment failure?"}
430
+ SEND --> RETRY{"Connection establishment failed<br/>before execution?"}
339
431
  RETRY -->|"Retryable"| OQ
340
432
  RETRY -->|"Success"| OBS["Query selected Ollama /api/ps"]
341
433
  OBS --> OUT["Route, assignment, physical observation,<br/>admission, metrics, and response"]
342
- RETRY -->|"503, timeout, or final failure"| ERR["Return upstream error"]
434
+ RETRY -->|"HTTP error, timeout, or uncertain failure"| ERR["Return upstream error"]
343
435
  ```
344
436
 
345
437
  Admission is independent per backend and uses weighted fair round robin: interactive gets three
346
- turns, normal two, and background one, preserving FIFO inside each class and preventing starvation.
438
+ turns, normal two, and background one. Within a class, bounded model affinity can temporarily
439
+ reorder FIFO; capacity reservation and aging bound repeated bypasses.
347
440
  The primary/GPU pool defaults to two weighted units per observed `OLLAMA_NUM_PARALLEL` slot,
348
441
  falling back to two. The optional CPU pool defaults to one. A saturated GPU burst therefore cannot
349
442
  consume the permit held for a small CPU helper. With one parallel slot, those values represent one
@@ -375,8 +468,9 @@ times, or queued for two seconds, restores FIFO order for its class. Affinity us
375
468
  own record of admitted work, never an Ollama call. Each pool's receipt counts
376
469
  `affinity_promotions`; health reports the bounds under `admission.priority_fairness.model_affinity`.
377
470
 
378
- A task waiting for host resources returns its execution slot after two seconds and continues
379
- waiting within the same deadline. It remains counted against the backend's bounded queue, so
471
+ An Ollama task waiting for host resources returns its execution slot after at most two seconds
472
+ of slot-held resource waiting. A llama.cpp task yields after its initial bounded telemetry probe.
473
+ Both continue waiting within the same queue deadline and remain counted against the pool's bounded queue, so
380
474
  memory pressure cannot create an invisible backlog. Health reports slot and resource waiters
381
475
  separately. Returning to slot admission transfers the existing queue registration atomically;
382
476
  new arrivals and a smaller reloaded queue limit cannot displace accepted work. Expired deadlines
@@ -389,7 +483,8 @@ load, which takes the load lock and observes once more after winning it (a same-
389
483
  finished meanwhile is then shared).
390
484
  See [Load lock and use lease](CPU_GPU_ROUTING.md#load-lock-and-use-lease). Session affinity is bound only
391
485
  after successful upstream execution, so refused and failed tasks cannot change later routing.
392
- An explicit `done:false` chat response or a reported upstream error is a failure, even with HTTP 200.
486
+ An Ollama chat response requires boolean `done:true`; missing, non-boolean or false completion
487
+ markers and reported upstream errors are failures, even with HTTP 200.
393
488
  It cannot train runtime feedback or bind affinity. Completed failed exchanges retain the raw response
394
489
  and honor a requested immediate unload. Transport failures also attempt that unload and return its
395
490
  lifecycle receipt, but a disconnected inference response alone does not prove upstream cancellation.
@@ -399,7 +494,8 @@ data, including per-item batch failures.
399
494
  `POST /_freellama/v1/task-batches` is for caller-declared independent work only: every item has a
400
495
  stable ID and `independent:true`; dependent workflow execution is rejected before any upstream call.
401
496
  It bounds local dispatch and returns ordered per-item success/error receipts. Every child still
402
- passes the same global admission and transition path above.
497
+ passes its engine's capability checks and the shared admission/resource limits. Ollama children
498
+ also use the transition path above.
403
499
 
404
500
  The K/V preflight derives single-sequence F16 K+V bytes-per-token for any architecture whose
405
501
  metadata declares the block count and head counts. Explicit key/value dimensions take precedence
@@ -444,10 +540,11 @@ admits such a load with a `memory_advisory` instead, after unloading idle runner
444
540
  Each pressure signal recovers independently after two fresh samples that meet its recovery
445
541
  threshold. A recovered CPU-load signal therefore clears even while RAM remains low.
446
542
 
447
- On Linux and macOS the default `require_memory` telemetry policy holds local inference when
448
- available RAM is missing, even when a raw request has no model-footprint estimate. Windows and other
449
- platforms have no host collector, so they default to `best_effort` and admit with
450
- `admitted_telemetry_unknown`; elsewhere `best_effort` is an explicit opt-in;
543
+ On Linux, macOS and Windows the default `require_memory` telemetry policy holds local inference when
544
+ available RAM is missing, even when a raw request has no model-footprint estimate. Windows uses a
545
+ bounded PowerShell CIM query for total and available physical RAM; its CPU load, OS-pressure,
546
+ thermal, swap and GPU signals remain unavailable. Other platforms have no host collector, so they
547
+ default to `best_effort` and admit with `admitted_telemetry_unknown`; elsewhere `best_effort` is an explicit opt-in;
451
548
  `require_all` additionally requires the collector's applicable load, OS-pressure, and thermal signals.
452
549
  Unsupported Linux collector signals remain explicitly unavailable rather than being fabricated.
453
550
  The pure `ResourceSnapshot::assess_capacity` calculation is shared by admission and previews.
@@ -486,7 +583,7 @@ transition path rather than claiming verified runner compatibility.
486
583
  A compatible resident runner needs no backend lock: nonempty model digest and effective context must
487
584
  match the observed runner (a request that sends no `num_ctx` also accepts a runner whose context
488
585
  `/api/ps` omits). Name-only residency is insufficient, and `admission.reason` names the degraded
489
- identity. Every task holds a per-model use lease for its whole request, which keeps its runner from
586
+ identity. Every managed Ollama task holds a per-model use lease for its whole request, which keeps its runner from
490
587
  being evicted or unloaded. Forecast release invalidates the
491
588
  host sample generation so an older available-memory observation cannot spend released capacity.
492
589
  A task that must load or reload a runner takes that backend's load lock until the runner is
@@ -509,8 +606,10 @@ waits up to the raw queue wait (control API: the managed queue wait), then gets
509
606
  `queue_wait_ms`, `resource_wait_ms`, `transition_wait_ms`, and
510
607
  their sum as `total_wait_ms`. Health and route receipts expose sampled pressure and reservations.
511
608
 
512
- HTTP `500` and `502` status codes and connection-establishment failures use bounded retry with backoff.
513
- HTTP `504`, transport timeouts and post-send disconnects are not replayed.
609
+ Connection-establishment failures use bounded retry with backoff because they precede execution.
610
+ Managed inference and raw mutation/inference requests are not replayed after HTTP `500` or `502`: an
611
+ Ollama error may arrive after the runner has already performed work. Raw read-only GET/HEAD status
612
+ failures may still be retried. HTTP `504`, transport timeouts and post-send disconnects are not replayed.
514
613
  FreeLlama does not retry `503 Service Unavailable` because retrying while holding admission can
515
614
  amplify overload. It does not retry a generation timeout because the first request might still run.
516
615
 
@@ -561,16 +660,18 @@ Execution receipts expose `completion_planning`, including estimated costs and w
561
660
  influenced selection. Ollama's cached-token counts inform prefill-rate learning; FreeLlama does not
562
661
  export or manage KV tensors.
563
662
 
564
- Raw proxy traffic always uses the primary upstream. For setup and runtime verification, see
663
+ Raw Ollama traffic uses the primary upstream; configured OpenAI-compatible upstreams are the
664
+ separate `/v1/*` model-routing exception. For setup and runtime verification, see
565
665
  [Run models on CPU and GPU](CPU_GPU_ROUTING.md).
566
666
 
567
667
  ## MCP tool flow
568
668
 
569
669
  The MCP server keeps general model work (`run_task`), file-backed research (`delegate_research`, a
570
- confined adapter subprocess), and destructive lifecycle operations (`ollama_manage`,
571
- `ollama_delete`) in separate tools, so `run_task` never acquires file access and lifecycle
572
- operations are not hidden inside a generic action. The canonical tool table, schemas, and security
573
- annotations are in the [MCP server reference](https://github.com/bgauryy/FreeLlama/blob/main/packages/mcp/README.md#tools).
670
+ confined adapter subprocess), and lifecycle operations (`ollama_manage`, `ollama_delete`) in
671
+ separate tools. `run_task` can read caller-named `files` through its input handler; it does not gain
672
+ the research adapter's tool loop. Lifecycle mutation is not hidden inside generic task execution. Tool schemas and security annotations
673
+ are registered in `packages/mcp/src/tools/registrations.ts`; the tool list is in
674
+ [API](API.md#mcp-tools). `freellama tool NAME JSON` calls the same handlers from a shell.
574
675
 
575
676
  ## Grounded research flow
576
677
 
@@ -643,7 +744,8 @@ flowchart LR
643
744
 
644
745
  Raw source, images, and embedding vectors do not need to enter the frontier model's context.
645
746
  Embedding vectors are withheld by default because they are large and not human-readable. For the
646
- measured accounting, see [Token economics](https://github.com/bgauryy/FreeLlama/blob/main/packages/mcp/README.md#token-economics).
747
+ compact receipts, saved response files, and the avoided-cost estimate, see
748
+ [Small agent context](FEATURES.md#small-agent-context).
647
749
 
648
750
  ## State and failure behavior
649
751
 
@@ -660,21 +762,27 @@ FreeLlama keeps these values in memory:
660
762
 
661
763
  Sessions are bounded (default 1024) and expire after idle time (default one hour); they store only
662
764
  model affinity, never prompts or Ollama KV. Restarting `freellama serve` clears sessions and the catalog cache. Persisted placement feedback is
663
- reloaded; `--ephemeral` intentionally resets it. Ollama owns model residency, so loaded
664
- models survive a FreeLlama restart. Scope histories and their revisions do not survive restart.
765
+ reloaded; `--ephemeral` intentionally resets it. Inference servers own model residency, so
766
+ restarting only FreeLlama does not itself unload their models. Scope histories and their revisions do not survive restart.
665
767
  They store messages independently from affinity and append only a successful generation at the
666
768
  expected revision. Warming uses ordinary admission and fit checks; omitted residency controls use
667
769
  a finite measured policy. See [Scope history and model warming](SCOPES_AND_WARMING.md) for the
668
770
  public contract and configured limits.
669
771
 
670
- In `serve`, raw generation traffic shares the primary load lock and use leases and receives
671
- host-pressure gating, while managed tasks also reserve forecast memory. Direct Ollama callers bypass
772
+ In `serve`, native local raw generation traffic shares the primary load lock, use leases and governor;
773
+ cold loads require forecast memory reservations and resident reuse receives host-pressure gating.
774
+ External raw upstreams have a narrower pressure gate because local telemetry cannot reserve remote
775
+ memory. Managed tasks also apply model selection and context controls. Direct Ollama callers bypass
672
776
  these controls. FreeLlama cannot preempt inference or constrain other processes. A configured but
673
- unreachable CPU backend makes managed catalog discovery fail closed; raw primary passthrough remains
674
- usable. Runtime feedback is task-specific, token-normalized, and warm-only: it can steer unpinned
777
+ unreachable CPU backend makes managed Ollama catalog discovery fail closed; raw primary
778
+ passthrough and explicit configured llama.cpp tasks remain usable independently of that catalog. Runtime feedback is task-specific, token-normalized, and warm-only: it can steer unpinned
675
779
  `fastest` or `balanced` work after three samples per backend and a greater-than-10% advantage, but
676
780
  cannot change CPU eligibility or steer quality routing.
677
781
 
782
+ Admission pools, use leases and memory reservations are process-local. Sharing SQLite shares
783
+ records and learned evidence, not a distributed execution lock or a host-wide reservation ledger.
784
+ The governor cannot control direct engine clients or allocations made by other processes.
785
+
678
786
  The design fails closed when it cannot establish a required contract. Examples include an
679
787
  unreachable configured backend, an unknown confidence grade, a policy without qualified models, an
680
788
  explicit model that is not installed, or a task that exceeds the advertised context window.
@@ -0,0 +1,131 @@
1
+ # FreeLlama assessment
2
+
3
+ **Overall: 7/10 for bounded local work on a shared workstation.** FreeLlama has a coherent Rust
4
+ management core, substantial deterministic contracts and useful local measurements. The largest
5
+ remaining gap is evidence that local answers and tool calls are reliable across representative
6
+ tasks and machines. The second engine works for a deliberately small text surface; release and
7
+ hardware qualification are incomplete.
8
+
9
+ These ratings were established on **2026-11-14** and reviewed again on **2026-11-15**, including
10
+ unreleased changes. The [end-to-end Ollama review](OLLAMA_REVIEW.md) records the follow-up research,
11
+ feature coverage, implemented repairs and current verification. Scores remain unchanged because
12
+ regression fixes do not supply missing representative model or hardware evidence.
13
+ Astra reviewed runtime architecture, APIs and production behavior; two Sol reviews covered
14
+ calibration/reliability and CI/Windows/maintenance. The orchestrator reconciled their findings and
15
+ reviewed the entry points, agent instructions and documentation. Scores are engineering judgments,
16
+ not measured accuracy percentages, a competitive ranking, or a promise that unreleased features
17
+ are already in npm. The overall score weighs the intended workstation use; it is not an arithmetic
18
+ average of implemented features and optional future work.
19
+
20
+ ## Rating scale
21
+
22
+ | Score | Meaning |
23
+ |---|---|
24
+ | 0 | Absent |
25
+ | 2 | Design or scaffolding only |
26
+ | 4 | Narrow implementation or evidence |
27
+ | 6 | Working implementation with meaningful contracts and limited live proof |
28
+ | 8 | Broad repeatable contracts, clear ownership and bounded live evidence; qualification gaps remain |
29
+ | 10 | Representative repeated workloads, supported platforms and failure modes qualified in production |
30
+
31
+ Half points distinguish a substantial remaining qualification gap. A high architecture score does
32
+ not compensate for weak answer-accuracy evidence.
33
+
34
+ ## The five implementation priorities
35
+
36
+ | Priority | Rating | Implemented and demonstrated | What keeps it below 9–10 |
37
+ |---|---:|---|---|
38
+ | 1. CI and test coverage | **7.5/10** | [Three-OS workflow](../.github/workflows/ci.yml), strict local Rust lint, build/type checks, 781 passing Rust tests, 1,474 passing JavaScript/evaluation checks and 51 packaging contracts | Hosted lanes have not been observed; Windows selects portable JavaScript contracts and does not qualify POSIX research/coder adapters. Full live integration, hardware and all-platform release gates remain separate. [Validation scope](TESTING.md) |
39
+ | 2. Second engine: llama.cpp | **7/10** | Explicit loopback `name/model` text execution shares Rust admission and resource reservations; nine engine contracts and a [retained live smoke](assets/llamacpp-managed-smoke-2026-11-14.json) with Ollama unavailable | No automatic discovery/selection, streaming, tool calls, embeddings, vision, lifecycle management or observed placement for this engine. The caller supplies a bounded context/output/memory configuration. [Engine contract](LLAMACPP.md) |
40
+ | 3. Per-machine calibration | **7/10** | Schema-2 reports bind throughput to host/hardware, local endpoint and artifact digest; job selection consumes the qualifying Rust route before catalog fallbacks | Throughput is not correctness. Capable jobs and OCR still need task-quality evidence; calibration is Ollama-specific and lacks a representative multi-machine study. Runtime/settings changes require an operator rerun. [Selection](MODEL_SELECTION.md#turn-measurements-into-routing-evidence) |
41
+ | 4a. Accuracy of `check:` lines | **5/10** | A reproducible 30-case labeled corpus retains misses and false alarms; tool arguments receive bounded structural validation. Numeric matching and malformed tool-call handling were repaired in the follow-up | Synthetic, implementation-visible examples are regression evidence. The original source-risk recall was 25%; the repaired numeric-token checker reaches 37.5% on the same exposed cases. Injection-risk recall remains 50%, dropped-value recall 33.3%. Clean checks do not prove correctness. [Versioned corpus and limits](RELIABILITY.md#accuracy-of-result-checks) |
42
+ | 4b. Public tool-calling evidence | **4/10** | Exact model identities, prompts, settings, raw turns and graders are retained; two models ran seven cases once, scoring 6/7 and 5/7 strictly | Ten other installed audit tags remain unmeasured. The public single-trial suite cannot rank models or estimate general reliability; the observed failures were formatting. [Table and transcripts](RELIABILITY.md#measured-on-2026-11-14) |
43
+ | 5. Panic/lock audit and large files | **8/10** | Focused poison, sampler-panic and subprocess-cleanup coverage; production lint census found no `unwrap_used` or `await_holding_lock` hits; large production files split into helpers/tests | Thirty explicit `expect` sites were counted, not all formally proved. Lock ordering, contention and OS thread exhaustion need broader qualification. Large test modules remain. [Audit](RUST_RESOURCE_AUDIT.md) |
44
+
45
+ The earlier approximate count of 426 `unwrap` calls mixed production and test code. It was a
46
+ review starting point, not a production panic count; retaining clear test assertions is appropriate.
47
+ Likewise, splitting files improves review boundaries without proving runtime correctness.
48
+
49
+ ## Other product areas
50
+
51
+ | Area | Rating | Evidence and remaining constraint |
52
+ |---|---:|---|
53
+ | Architecture and ownership | **8/10** | Routing and resource policy stay in Rust; callers own prompts, dependencies and verification. Engine-specific operations are now explicit, but discovery, warming and feedback remain centered on Ollama. [Architecture](ARCHITECTURE.md) |
54
+ | Resource scheduler | **8/10** | Bounded weighted queues, reservations, cancellation and resource waits have contracts; waiting tasks yield execution units while retaining bounded queue tickets. Budgets and leases are process-local, so multiple authorities do not share them. Physical GPU/host contention needs broader testing. [Monitoring](MONITORING.md), [production boundary](PRODUCTION.md) |
55
+ | APIs and agent ergonomics | **8/10** | MCP, shell, operator CLI and HTTP reuse core contracts, receipts and explicit preview. Different engines and protocol doors support different controls; the agent CLI and global readiness still require Ollama. [API](API.md), [agent CLI](AGENT_CLI.md) |
56
+ | Installation and packaging | **8/10** | Node 22 npm/npx installs select one of five prebuilt native packages; standalone operators can use the Rust binary without Node. Source builds need Rust. Optional dependencies must remain enabled; Intel macOS and musl Linux lack prebuilt targets, and current all-target packed-install qualification is outstanding. [Build/install](BUILD_AND_NOTES.md), [packaging checks](TESTING.md#verify-release-packages) |
57
+ | Windows support | **6.5/10** | Bounded CIM physical-memory sampling and `require-memory` defaults have invalid/overflow/zero fixtures. Native Rust and selected portable JavaScript contracts are configured in CI but unobserved here; POSIX research/coder paths are not qualified for native Windows. CPU load, pressure, swap, thermal and GPU observations remain unknown. [Windows audit](RUST_RESOURCE_AUDIT.md#windows-memory-contract), [CI scope](TESTING.md) |
58
+ | Research/coder boundaries | **7/10** | Read-only lookup, bounded observations and caller verification are explicit; coder is opt-in, returns a patch from an isolated copy and permits only selected commands. Real coding-outcome and sandbox-platform evidence is limited; this remains substantial scope alongside the resource manager. [Research recipe](cookbooks/research-agent.md) |
59
+ | Performance evidence | **7/10** | Retained single-machine data covers overhead, concurrency, cold observations and selected workflows. It does not predict other hardware or broad answer quality; the historical workflow denominator is incomplete. [Benchmark](BENCHMARK.md) |
60
+ | Deployment and recovery | **6.5/10** | Loopback/auth boundaries, bounded durable receipts, unknown-outcome recovery and refusal-before-execution fallback are documented and tested. Managed-engine changes now conflict with retained input identity without moving the lookup namespace. No complete current production gate or hardware matrix is recorded. [Production](PRODUCTION.md), [durable jobs](DEFERRED_JOBS.md) |
61
+ | Documentation | **8/10** | Guides, recipes, agent skill, package READMEs and source examples were reconciled with code, with links and example schemas checked. Historical external claims remain dated; this was not a fresh audit of every upstream URL or a clean-machine usability study. [Index](README.md) |
62
+
63
+ The research/coder boundary rating measures containment and authority, not whether those adapters
64
+ belong in the default product. Making them a separately installed feature remains a scope and
65
+ maintenance decision; they have not been extracted by this change.
66
+
67
+ ## Availability and ambitious options
68
+
69
+ | Capability | Status | Consequence |
70
+ |---|---|---|
71
+ | Explicit fallback before execution | Implemented | Up to four caller-named candidates; attempts and refusal reasons stay in the receipt. Ambiguous inference outcomes are not replayed. [Fallback rules](FEATURES.md#fallback-chains) |
72
+ | Engine-neutral automatic failover | **Not implemented (0/10)** | Shared admission is a foundation, but engine discovery, capabilities, health/readiness and takeover are not a complete neutral scheduler. A second text adapter alone does not provide availability failover. |
73
+ | Local-first automatic cloud escalation after failed checks | **Not implemented (0/10)** | The caller decides whether to rerun locally or use a hosted model. Existing external-upstream transport does not supply this policy, data-transfer authorization, cost limits or correctness evaluation. |
74
+ | Multi-machine pool | Deliberately excluded | One coordinating FreeLlama authority per inference topology remains the supported resource model. |
75
+
76
+ Failover safety is stronger than failover availability: refusing to replay an uncertain POST avoids
77
+ duplicate work, but does not make a failed request succeed. Do not describe the current fallback
78
+ chain as automatic cross-engine recovery.
79
+
80
+ For retained durable keys, changed managed-engine mappings now produce an explicit conflict.
81
+ Original receipts remain readable; inspect them before intentionally starting work with a new key.
82
+ The [migration and conservative invalidation rules](DEFERRED_JOBS.md#idempotency) are explicit.
83
+
84
+ ## Next work, in order
85
+
86
+ 1. **Observe CI and complete release qualification** (small to medium). Run the configured lanes,
87
+ packed installs on supported targets and relevant live tiers; retain their versions, results and
88
+ skips. Configuration and local success are not cross-platform qualification.
89
+ 2. **Broaden correctness evidence** (large). Add unseen, representative factual/extraction cases
90
+ with independent labels; report precision/recall and abstentions. Repeat tool cases across exact
91
+ model artifacts, context lengths and machines; include semantic grading alongside strict format
92
+ grading and preserve every attempted denominator. This is the largest route to a stronger product.
93
+ 3. **Extend the engine contract deliberately** (medium to large). Choose the next real client need
94
+ such as streaming or tools, add a capability matrix and failure tests, and qualify it live before
95
+ broadening default routing. Keep uncertain execution out of automatic replay.
96
+ 4. **Validate calibration across machines** (medium). Pair host-local performance with digest-bound
97
+ task-quality evaluations, document rerun triggers and measure whether picks improve actual jobs.
98
+ 5. **Finish operational qualification and scope reduction** (medium). Measure lock contention and
99
+ sustained load, exercise Windows CIM and supported drivers, and decide whether research/coder
100
+ should install separately. Prebuilt packages already remove the end-user Rust requirement.
101
+
102
+ These are effort estimates. Automatic cloud escalation is optional future work after check quality
103
+ and explicit data-transfer/cost policy are established; a multi-machine pool is outside this plan.
104
+
105
+ ## Historical documentation review and validation
106
+
107
+ The review covered the root README/changelog/agent instructions, every operator guide, all 15
108
+ cookbook pages, both Octocode instruction sheets, the FreeLlama skill and references, package
109
+ guides and README generation, the benchmark harness guide, and the example policy. Five cookbook
110
+ pages and the skill's output format required no semantic change. Raw measurement files and
111
+ generated evidence tables were retained; their scope and denominators were corrected in the guides.
112
+
113
+ Before the final 2026-11-14 documentation edits, the implementation's local macOS validation passed `yarn build`, `yarn typecheck`,
114
+ `yarn lint:rust`, `yarn test` and `yarn test:release`. That historical snapshot included 1,292 Vitest,
115
+ 112 benchmark/grader and 10 reliability checks; one JavaScript test was skipped and four Rust
116
+ tests ignored. A read-only macOS host-resource smoke ran separately. The retained llama.cpp and
117
+ two-model tool-calling runs are bounded live evidence, not the full inference test suite.
118
+
119
+ For this documentation pass, all 18 cookbook schema/resource integration checks and all 31
120
+ cookbook JSON examples passed; the FreeLlama skill review reported no errors or warnings.
121
+ The two compact Octocode sheets were checked against installed version 20.2.0: 23 query examples
122
+ matched 12 local tool schemas, using only help/schema commands.
123
+ The JavaScript build refreshed the packaged guides, synchronized package READMEs matched their
124
+ source, and all 51 packaging contracts passed again. The repository-wide link pass checked 64
125
+ Markdown files, 589 local/repository links and 178 heading anchors without errors. No new model
126
+ inference or download was needed to update this assessment. External URLs were not rechecked.
127
+
128
+ The 2026-11-15 full baseline found two failures: the Octocode documentation had changed without
129
+ updating its embedded prompt copies. The follow-up removed that duplicate source through build-time
130
+ Markdown imports and restored the existing equality and 30-line checks. Current validation and
131
+ the freshly checked primary Ollama sources are recorded in the [follow-up review](OLLAMA_REVIEW.md).