@octocodeai/freellama-mcp-server 0.1.0 → 0.5.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.
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +18 -0
- package/README.md +203 -33
- package/adapters/agent_context.py +216 -29
- package/adapters/agent_transport.py +131 -0
- package/adapters/bash_agent.py +67 -92
- package/adapters/octocode_agent.py +63 -53
- package/adapters/shell_sandbox.py +487 -0
- package/assets/logo.jpg +0 -0
- package/dist/index.js +1287 -412
- package/docs/ARCHITECTURE.md +169 -26
- package/docs/CLI.md +107 -17
- package/docs/CPU_GPU_ROUTING.md +65 -20
- package/docs/ECONOMICS.md +20 -15
- package/docs/INDEX.md +8 -2
- package/docs/MODEL_METADATA.md +106 -0
- package/docs/MODEL_SELECTION.md +15 -2
- package/docs/MONITORING.md +285 -0
- package/docs/OLLAMA_SIDECAR.md +8 -6
- package/docs/PRODUCTION.md +49 -18
- package/docs/PRODUCT_POSITIONING.md +86 -256
- package/docs/README.md +40 -0
- package/docs/SCOPES_AND_WARMING.md +226 -0
- package/docs/TESTING.md +118 -1
- package/docs/dev/FINDINGS_AND_POSITIONING.md +290 -0
- package/docs/dev/LOCAL_PERFORMANCE_TESTING.md +298 -0
- package/docs/{OLLAMA_SYSTEM_OPTIMIZATION.md → dev/OLLAMA_SYSTEM_OPTIMIZATION.md} +19 -18
- package/native/index.d.ts +31 -0
- package/package.json +13 -10
- /package/docs/{ADR_RESOURCE_AWARE_BACKEND_ROUTING.md → dev/ADR_RESOURCE_AWARE_BACKEND_ROUTING.md} +0 -0
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
# FreeLlama architecture
|
|
2
2
|
|
|
3
|
-
FreeLlama is
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
FreeLlama is the management layer between an AI agent and local Ollama models. Agents offload
|
|
4
|
+
bounded tasks through MCP, the CLI, or the control API. FreeLlama selects eligible models,
|
|
5
|
+
coordinates resources, and returns results with execution evidence.
|
|
6
|
+
|
|
7
|
+
The calling agent owns task decomposition, prompts, and answer verification. FreeLlama owns managed
|
|
8
|
+
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;
|
|
10
|
+
the operating system and drivers schedule physical work.
|
|
6
11
|
|
|
7
12
|
## Responsibility boundary
|
|
8
13
|
|
|
@@ -13,8 +18,9 @@ The following table defines the ownership boundary:
|
|
|
13
18
|
| Model files, runners, Metal, MLX, llama.cpp, and token generation | Ollama |
|
|
14
19
|
| Native `/api/*` and OpenAI-compatible `/v1/*` semantics | Ollama |
|
|
15
20
|
| Installed-model discovery and capability normalization | FreeLlama |
|
|
16
|
-
| Task routing, advertised-context compatibility, K/V
|
|
17
|
-
| Managed admission, session affinity, and model-transition coordination | FreeLlama |
|
|
21
|
+
| Task routing, advertised-context compatibility, advisory K/V estimates, evidence policy, and model rejection reasons | FreeLlama |
|
|
22
|
+
| Managed admission, session affinity, bounded scope history, and model-transition coordination | FreeLlama |
|
|
23
|
+
| Forecast memory reservations, host-pressure holds, and requests to unload idle unpinned models | FreeLlama managed execution |
|
|
18
24
|
| Explicit per-model CPU/GPU backend assignment | FreeLlama and separate Ollama processes |
|
|
19
25
|
| Grounded research adapters, citations, and verification verdicts | FreeLlama MCP server |
|
|
20
26
|
|
|
@@ -77,6 +83,8 @@ flowchart TD
|
|
|
77
83
|
C -->|"natural-routes"| INTENT["Run intent model, then route"]
|
|
78
84
|
C -->|"tasks"| RUN["Route, admit, and execute"]
|
|
79
85
|
C -->|"sessions"| SESSION["Create in-memory affinity id"]
|
|
86
|
+
C -->|"scopes"| SCOPES["Retain revision-protected messages"]
|
|
87
|
+
C -->|"warm"| RUN
|
|
80
88
|
```
|
|
81
89
|
|
|
82
90
|
The control API exposes these endpoints:
|
|
@@ -91,7 +99,16 @@ The control API exposes these endpoints:
|
|
|
91
99
|
| `POST /_freellama/v1/natural-routes` | Schema-bound intent interpretation followed by deterministic routing | Intent model only |
|
|
92
100
|
| `POST /_freellama/v1/sessions` | New model-affinity session | No |
|
|
93
101
|
| `DELETE /_freellama/v1/sessions/:session_id` | Release model-affinity session | No |
|
|
102
|
+
| `POST /_freellama/v1/scopes` | Create bounded message history | No |
|
|
103
|
+
| `GET /_freellama/v1/scopes/:id` | Scope metadata; optional explicit history inclusion | No |
|
|
104
|
+
| `POST /_freellama/v1/scopes/:id/fork` | Fork history at an expected revision | No |
|
|
105
|
+
| `DELETE /_freellama/v1/scopes/:id` | Delete retained history | No |
|
|
106
|
+
| `POST /_freellama/v1/warm` | Admitted load of an exact installed runner profile | Load only |
|
|
94
107
|
| `POST /_freellama/v1/tasks` | Managed chat, vision, tools, or embedding task | Yes |
|
|
108
|
+
| `GET /_freellama/v1/jobs` | Deferred job metadata without prompts or results | No |
|
|
109
|
+
| `GET /_freellama/v1/jobs/:id` | One deferred receipt and retained result | No |
|
|
110
|
+
| `POST /_freellama/v1/jobs/:id/cancel` | Cancel one deferred task and release its local permits | No new inference |
|
|
111
|
+
| `DELETE /_freellama/v1/jobs/:id` | Cancel active work, release local permits, and remove its retained record | No new inference |
|
|
95
112
|
|
|
96
113
|
The machine profile is host-derived rather than model-name-derived. It reports total physical
|
|
97
114
|
memory on macOS (`sysctl`), Linux (`/proc`), and Windows (system APIs), along with CPU, OS,
|
|
@@ -125,9 +142,19 @@ A failed `/api/show` response skips that model instead of failing the entire cat
|
|
|
125
142
|
configured backend fails catalog discovery closed because FreeLlama cannot prove the assigned model's
|
|
126
143
|
state.
|
|
127
144
|
|
|
145
|
+
### Public model metadata
|
|
146
|
+
|
|
147
|
+
Public model enrichment belongs to the MCP layer's `model-knowledge.ts` and `model-search.ts`.
|
|
148
|
+
Installed/detail requests can opt into GET-only Ollama family and full tag-page lookups. The layer
|
|
149
|
+
matches exact tags and digest prefixes, preserves local supported features, and attaches family-scoped
|
|
150
|
+
source excerpts and usage notes. Its bounded in-memory cache expires successes after one hour and
|
|
151
|
+
failures after one minute. Failed or unmatched lookups leave local inventory and evidence intact.
|
|
152
|
+
Public claims do not enter the Rust catalog, task policy, quality confidence, or routing decisions.
|
|
153
|
+
See [Ollama model metadata](MODEL_METADATA.md) for the public contract and request bounds.
|
|
154
|
+
|
|
128
155
|
## Deterministic routing
|
|
129
156
|
|
|
130
|
-
Routing
|
|
157
|
+
Routing defaults to ordinary `completion`; explicit profiles refine selection. Supported task kinds are `completion`, `coding`,
|
|
131
158
|
`code_repair`, `tools`, `browser`, `vision`, `embedding`, and `long_context`.
|
|
132
159
|
|
|
133
160
|
```mermaid
|
|
@@ -138,7 +165,7 @@ flowchart TD
|
|
|
138
165
|
X -->|"Yes"| E["Use exact model or refuse"]
|
|
139
166
|
X -->|"No"| O{"Objective"}
|
|
140
167
|
O -->|"fastest"| S["Rank local performance,<br/>residency, and deterministic ties"]
|
|
141
|
-
O -->|"balanced"| B["
|
|
168
|
+
O -->|"balanced"| B["Prefer policy-qualified candidates;<br/>otherwise use eligible models with low confidence"]
|
|
142
169
|
O -->|"quality"| Q["Require policy-qualified candidates,<br/>then prefer policy order"]
|
|
143
170
|
E --> H["Grade advertised-context compatibility and evidence"]
|
|
144
171
|
S --> H
|
|
@@ -154,7 +181,7 @@ reason so callers can distinguish capability, context, policy, and installation
|
|
|
154
181
|
|
|
155
182
|
`context_window_fit` means only that requested `num_ctx` fits the model's advertised context
|
|
156
183
|
window. It is not a live-memory, free-VRAM, K/V-cache, thermal, or runner-admission verdict.
|
|
157
|
-
Execution separately reports
|
|
184
|
+
Execution separately reports an advisory model-metadata K/V estimate and post-run
|
|
158
185
|
placement evidence; Ollama remains authoritative for actual runner allocation and admission.
|
|
159
186
|
|
|
160
187
|
### Confidence evidence
|
|
@@ -198,12 +225,23 @@ The natural route endpoint does not run the selected task. Submit a managed task
|
|
|
198
225
|
|
|
199
226
|
## Managed task execution
|
|
200
227
|
|
|
201
|
-
|
|
228
|
+
The implementation separates [admission scheduling](../packages/rust-core/src/platform/admission.rs),
|
|
229
|
+
[execution coordination](../packages/rust-core/src/platform/execution.rs),
|
|
230
|
+
[read-only readiness](../packages/rust-core/src/platform/readiness.rs), and
|
|
231
|
+
[typed errors](../packages/rust-core/src/platform/error.rs). The platform module wires HTTP endpoints,
|
|
232
|
+
configuration, discovery, and shared state; extracting these owners preserves the public routing API.
|
|
233
|
+
|
|
234
|
+
Managed tasks combine routing with admission and backend-aware transition coordination. With
|
|
235
|
+
`defer:true`, the server returns HTTP `202` and a process-local job handle, then runs the same task
|
|
236
|
+
path. The bounded registry owns receipts and cancellation, while the existing governor owns
|
|
237
|
+
admission. Batch items cannot defer. Per-task `timeout_seconds` bounds discovery, waiting, loading,
|
|
238
|
+
and inference together, capped by the server task timeout. See [CLI controls](CLI.md#execute-tasks)
|
|
239
|
+
for retention limits and [monitoring](MONITORING.md) for the observable lifecycle.
|
|
202
240
|
|
|
203
241
|
```mermaid
|
|
204
242
|
flowchart TD
|
|
205
243
|
T["POST /tasks or /task-batches"] --> R["Select eligible model + backend"]
|
|
206
|
-
R --> K["
|
|
244
|
+
R --> K["Estimate metadata-backed F16 K/V<br/>(or report unknown)"]
|
|
207
245
|
K --> A{"Acquire selected backend's<br/>3:2:1 fair weighted budget"}
|
|
208
246
|
A -->|"No"| E503["503 server busy"]
|
|
209
247
|
A -->|"Yes"| B{"Execution backend"}
|
|
@@ -219,7 +257,7 @@ flowchart TD
|
|
|
219
257
|
CR --> OQ
|
|
220
258
|
CX --> OQ
|
|
221
259
|
OQ --> SEND["Ollama schedules bounded request"]
|
|
222
|
-
SEND --> RETRY{"500, 502
|
|
260
|
+
SEND --> RETRY{"500, 502,<br/>or connection-establishment failure?"}
|
|
223
261
|
RETRY -->|"Retryable"| OQ
|
|
224
262
|
RETRY -->|"Success"| OBS["Query selected Ollama /api/ps"]
|
|
225
263
|
OBS --> OUT["Route, assignment, physical observation,<br/>admission, metrics, and response"]
|
|
@@ -228,40 +266,120 @@ flowchart TD
|
|
|
228
266
|
|
|
229
267
|
Admission is independent per backend and uses weighted fair round robin: interactive gets three
|
|
230
268
|
turns, normal two, and background one, preserving FIFO inside each class and preventing starvation.
|
|
231
|
-
The primary/GPU pool defaults to two weighted units
|
|
232
|
-
optional CPU pool defaults to one. A saturated GPU burst therefore cannot
|
|
233
|
-
for a small CPU helper.
|
|
234
|
-
|
|
269
|
+
The primary/GPU pool defaults to two weighted units per observed `OLLAMA_NUM_PARALLEL` slot,
|
|
270
|
+
falling back to two. The optional CPU pool defaults to one. A saturated GPU burst therefore cannot
|
|
271
|
+
consume the permit held for a small CPU helper. With one parallel slot, those values represent one
|
|
272
|
+
ordinary chat and one embedding. Operators can tune both budgets from queue-wait and resident-memory evidence.
|
|
235
273
|
After FreeLlama admission, each Ollama process applies its own `OLLAMA_MAX_QUEUE`, scheduler,
|
|
236
|
-
`OLLAMA_NUM_PARALLEL`, and loaded-model limit. Raw proxy requests bypass
|
|
237
|
-
|
|
274
|
+
`OLLAMA_NUM_PARALLEL`, and loaded-model limit. Raw proxy requests bypass weighted admission but
|
|
275
|
+
still pass the raw concurrency cap, backend exclusion, and host-pressure gate.
|
|
238
276
|
|
|
239
|
-
| Task |
|
|
277
|
+
| Task | Default cost |
|
|
240
278
|
|---|---:|
|
|
241
279
|
| Embedding | `ceil(input_items / 4)` |
|
|
242
280
|
| Chat, coding, tools, browser, or long context | 2 |
|
|
243
281
|
| Vision | 4 |
|
|
244
282
|
|
|
283
|
+
The runtime file's `[task_costs]` table overrides task-kind base costs. Embeddings multiply their
|
|
284
|
+
base by `ceil(input_items / 4)`; the acquired charge is capped to the backend's current capacity.
|
|
285
|
+
See [monitoring controls](MONITORING.md#adaptive-concurrency) for validation and reload behavior.
|
|
286
|
+
|
|
287
|
+
After six capacity bypasses, the scheduler reserves released capacity for the oldest blocked waiter,
|
|
288
|
+
so a stream of small requests cannot indefinitely starve a larger request. Cancellation releases
|
|
289
|
+
that reservation. Admission, resource waiting, and transition locking share one queue deadline.
|
|
290
|
+
|
|
291
|
+
A task waiting for host resources returns its execution slot after two seconds and continues
|
|
292
|
+
waiting within the same deadline. It remains counted against the backend's bounded queue, so
|
|
293
|
+
memory pressure cannot create an invisible backlog. Health reports slot and resource waiters
|
|
294
|
+
separately. Returning to slot admission transfers the existing queue registration atomically;
|
|
295
|
+
new arrivals and a smaller reloaded queue limit cannot displace accepted work. Expired deadlines
|
|
296
|
+
prevent admission even when an execution slot is free. Cancellation removes either waiter, and releasing a memory reservation wakes resource
|
|
297
|
+
waiters immediately; host telemetry still obeys the sampling and recovery policy below.
|
|
298
|
+
|
|
245
299
|
FreeLlama acquires the admission slot before a transition lock to avoid deadlock. A model marked
|
|
246
300
|
resident during discovery is checked again while the shared transition lock is held; stale or
|
|
247
301
|
unavailable residency falls back to the exclusive transition path. Session affinity is bound only
|
|
248
302
|
after successful upstream execution, so refused and failed tasks cannot change later routing.
|
|
303
|
+
An explicit `done:false` chat response or a reported upstream error is a failure, even with HTTP 200.
|
|
304
|
+
It cannot train runtime feedback or bind affinity. Completed failed exchanges retain the raw response
|
|
305
|
+
and honor a requested immediate unload. Transport failures also attempt that unload and return its
|
|
306
|
+
lifecycle receipt, but a disconnected inference response alone does not prove upstream cancellation.
|
|
307
|
+
Resource failures return a readable `error`, a stable `code`, and structured `resource_admission`
|
|
308
|
+
data, including per-item batch failures.
|
|
249
309
|
|
|
250
310
|
`POST /_freellama/v1/task-batches` is for caller-declared independent work only: every item has a
|
|
251
311
|
stable ID and `independent:true`; dependent workflow execution is rejected before any upstream call.
|
|
252
312
|
It bounds local dispatch and returns ordered per-item success/error receipts. Every child still
|
|
253
313
|
passes the same global admission and transition path above.
|
|
254
314
|
|
|
255
|
-
The K/V preflight derives F16 K+V bytes-per-token only
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
315
|
+
The K/V preflight derives single-sequence F16 K+V bytes-per-token only for supported model
|
|
316
|
+
architectures with sufficient metadata. Explicit key/value dimensions take precedence; sliding-window,
|
|
317
|
+
shared-KV, recurrent, and unknown layouts report unknown. F16 is advisory because quantized KV can
|
|
318
|
+
use less memory. The coarse model-file budget refuses files over 80% of local CPU/unified RAM only
|
|
319
|
+
for loopback backends. Forecasts use each backend's independently attributed parallelism and KV
|
|
320
|
+
cache settings where process inspection is available, with explicit fallback sources otherwise.
|
|
321
|
+
Process observations refresh on requests after five seconds; measurements made under different
|
|
322
|
+
settings cannot supply an exact-fit estimate. Ollama remains the live loader and final memory
|
|
323
|
+
authority. Configured settings alone do not prove physical processor placement.
|
|
324
|
+
|
|
325
|
+
The shared [resource governor](../packages/rust-core/src/platform/resources.rs) samples local
|
|
326
|
+
available-memory estimates, load per logical CPU, OS memory pressure, active swap-out growth, and
|
|
327
|
+
thermal throttling when reported. It holds new local work below the larger of 15% available RAM or
|
|
328
|
+
1 GiB, and requires two healthy samples above the larger of 20% or 2 GiB to resume. Historical swap
|
|
329
|
+
occupancy alone is not pressure. Samples are cached for two seconds; unavailable signals stay unknown.
|
|
330
|
+
Remote backends bypass this host gate.
|
|
331
|
+
|
|
332
|
+
Each pressure signal recovers independently after two fresh samples that meet its recovery
|
|
333
|
+
threshold. A recovered CPU-load signal therefore clears even while RAM remains low. That keeps
|
|
334
|
+
unchanged resident runners eligible under a memory-only hold while cold loads continue waiting.
|
|
335
|
+
|
|
336
|
+
The default `require_memory` telemetry policy holds local inference when available RAM is missing,
|
|
337
|
+
even when a raw request has no model-footprint estimate. `best_effort` is an explicit opt-in;
|
|
338
|
+
`require_all` additionally requires the collector's applicable load, OS-pressure, and thermal signals.
|
|
339
|
+
Unsupported Linux collector signals remain explicitly unavailable rather than being fabricated.
|
|
340
|
+
The pure `ResourceSnapshot::assess_capacity` calculation is shared by admission and previews.
|
|
341
|
+
Previews use the same footprint lookup, subtract existing reservations, and expose both queue and
|
|
342
|
+
resource readiness. An available weighted slot cannot by itself produce `runnable_now` when model
|
|
343
|
+
headroom is insufficient. Preview capacity is advisory and conservative, never a reservation.
|
|
344
|
+
|
|
345
|
+
Managed CPU/unified-memory tasks reserve estimated additional model-file and known F16 KV bytes
|
|
346
|
+
across both backends. Verified runner footprints replace that estimate only for the same backend,
|
|
347
|
+
immutable model digest, and equal-or-larger observed context. Exact resident digest/context matches
|
|
348
|
+
avoid double-counting existing allocations. The reservation is rechecked after transition locking;
|
|
349
|
+
an increased requirement that no longer fits refuses with 503, without waiting while holding the
|
|
350
|
+
backend lock. Permits release on completion or cancellation. On discrete-GPU hosts, observed free
|
|
351
|
+
VRAM discounts the estimated host-memory requirement by the bytes the GPU can hold. Missing VRAM
|
|
352
|
+
telemetry reserves the full estimated footprint in host RAM. The governor cannot constrain external
|
|
353
|
+
allocations or preempt an already-running model.
|
|
354
|
+
|
|
355
|
+
Managed text tasks without explicit `context_tokens` select the smallest 2K/4K/8K/16K/32K bucket
|
|
356
|
+
that covers the UTF-8 prompt/schema estimate, output reserve, and 512-token template margin, bounded
|
|
357
|
+
by the selected model's advertised limit. Larger requests require explicit context or compaction.
|
|
358
|
+
Multimodal and embedding requests retain their profiles. The execution receipt exposes
|
|
359
|
+
`context_sizing`; previews contain routing fields only and therefore retain task defaults.
|
|
360
|
+
Managed chat sends `truncate:false` and `shift:false` so supporting Ollama backends refuse overflow
|
|
361
|
+
instead of silently losing earlier instructions. Managed embeddings send `truncate:false` too.
|
|
362
|
+
Only the dedicated CPU backend supplies a thread default: half the logical CPU count on other
|
|
363
|
+
platforms, while macOS leaves Ollama to select its performance cores. `FREELLAMA_CPU_NUM_THREAD`
|
|
364
|
+
overrides that default; explicit request options take precedence. The primary backend leaves thread
|
|
365
|
+
selection to Ollama to avoid changing the options of a shared runner. `runtime_options` reports
|
|
366
|
+
forwarded values; runner support is not assumed.
|
|
259
367
|
|
|
260
368
|
Resident tasks share a backend lock. Nonresident tasks take that backend's exclusive lock so a cold
|
|
261
369
|
load cannot race another managed task on the same server. CPU and GPU backends have separate locks
|
|
262
370
|
and admission pools, so they can progress independently.
|
|
263
371
|
|
|
264
|
-
|
|
372
|
+
In `serve`, mutating raw proxy requests also take the primary backend's exclusive transition lock,
|
|
373
|
+
returning 503 when busy. The response body holds this guard through EOF or disconnect. Metadata
|
|
374
|
+
GET/HEAD and `/api/show` requests remain available. Raw inference waits at most 500 ms for host
|
|
375
|
+
pressure to clear, then returns 503 with `Retry-After`; empty `keep_alive:0` unload requests bypass
|
|
376
|
+
pressure. Raw request-body collection has the configured request deadline too; an incomplete upload
|
|
377
|
+
returns HTTP 408 and releases its guards without contacting Ollama. Admission receipts report
|
|
378
|
+
`queue_wait_ms`, `resource_wait_ms`, `transition_wait_ms`, and
|
|
379
|
+
their sum as `total_wait_ms`. Health and route receipts expose sampled pressure and reservations.
|
|
380
|
+
|
|
381
|
+
HTTP `500` and `502` status codes and connection-establishment failures use bounded retry with backoff.
|
|
382
|
+
HTTP `504`, transport timeouts and post-send disconnects are not replayed.
|
|
265
383
|
FreeLlama does not retry `503 Service Unavailable` because retrying while holding admission can
|
|
266
384
|
amplify overload. It does not retry a generation timeout because the first request might still run.
|
|
267
385
|
|
|
@@ -317,6 +435,7 @@ flowchart TD
|
|
|
317
435
|
TOOL -->|"doctor"| NAPI["Native core diagnostics"]
|
|
318
436
|
TOOL -->|"models"| MIX["Control API or direct Ollama/library HTTP"]
|
|
319
437
|
TOOL -->|"run_task"| TASK["Control API route or task"]
|
|
438
|
+
TOOL -->|"task_jobs"| JOB["Deferred receipts and per-task cancellation"]
|
|
320
439
|
TOOL -->|"ollama_manage"| LIFE["Direct Ollama pull or unload"]
|
|
321
440
|
TOOL -->|"ollama_delete"| DELETE["Explicit destructive Ollama delete"]
|
|
322
441
|
TOOL -->|"delegate_research"| AD["Confined adapter subprocess"]
|
|
@@ -355,14 +474,33 @@ shape.
|
|
|
355
474
|
|
|
356
475
|
The adapter loop preserves its control contract through four mechanisms:
|
|
357
476
|
|
|
358
|
-
- Pagination keeps complete output
|
|
477
|
+
- Pagination keeps complete output in adapter memory and writes it into the final result file,
|
|
478
|
+
while showing bounded pages. Oversized lines split losslessly; the final page ends pagination.
|
|
359
479
|
- Context fitting byte-preserves the system prompt and question by default, compacts older
|
|
360
480
|
observations, and fails before Ollama if pinned content cannot fit. The first estimate is
|
|
361
481
|
configurable; real `prompt_eval_count` values calibrate subsequent fits conservatively.
|
|
362
482
|
- JSON repair retains gathered evidence across a bounded format correction.
|
|
363
483
|
- Repeat suppression serves an identical earlier result without rerunning the subprocess command.
|
|
364
484
|
|
|
365
|
-
|
|
485
|
+
Overflow compaction targets 90% of the input budget using older observations, preserving head/tail
|
|
486
|
+
evidence and exact stored-page recovery actions. Already-fitting prefixes and existing breadcrumbs
|
|
487
|
+
remain unchanged. Compact observation ledgers preserve action, status, source, step, page recovery,
|
|
488
|
+
and untrusted-output provenance. Full observations and page offsets are stored in temporary files;
|
|
489
|
+
only the requested page enters the conversation. Final audit JSON streams the full results from disk
|
|
490
|
+
and is atomically replaced. Temporary files are cleaned on normal and exceptional exits.
|
|
491
|
+
Calibration keys include the endpoint, exact model tag and verified manifest digest, system-prompt
|
|
492
|
+
hash, estimator version, and settings. Unknown model identity disables persisted calibration while
|
|
493
|
+
retaining process-local calibration. Adapter retries cover explicit
|
|
494
|
+
503 overload and connection refusal, never uncertain timeouts or post-send disconnects.
|
|
495
|
+
|
|
496
|
+
Ollama's optional `prompt_eval_cached_count` is a subset of total `prompt_eval_count`. Prefill rate
|
|
497
|
+
uses uncached tokens only; unavailable cache counts produce null instead of invented zero hits.
|
|
498
|
+
Adapter cache totals remain null if any turn is unreported, with partial-report coverage in metadata.
|
|
499
|
+
See [Ollama usage](https://docs.ollama.com/api/usage) and
|
|
500
|
+
[the pinned prefix-cache implementation](https://github.com/ggml-org/llama.cpp/blob/74a7c897f049c17e7080423aa2111776eff6ebbf/tools/server/server-context.cpp#L3201).
|
|
501
|
+
|
|
502
|
+
For adapter implementation, defaults, and measured caveats, see the
|
|
503
|
+
[local adapter reference](../benchmark/local/docs/07-adapter-contracts.md).
|
|
366
504
|
|
|
367
505
|
## Context and token boundary
|
|
368
506
|
|
|
@@ -390,6 +528,7 @@ FreeLlama keeps these values in memory:
|
|
|
390
528
|
- Catalog metadata cache
|
|
391
529
|
- Current residency snapshots
|
|
392
530
|
- Session-to-model affinity
|
|
531
|
+
- Revision-protected scope message history and bounded adaptive residency measurements
|
|
393
532
|
- Independent GPU and CPU priority-fair weighted admission pools
|
|
394
533
|
- Per-task normalized warm latency and queue feedback for each backend, restored from an optional
|
|
395
534
|
versioned atomic snapshot
|
|
@@ -398,7 +537,11 @@ FreeLlama keeps these values in memory:
|
|
|
398
537
|
Sessions are bounded (default 1024) and expire after idle time (default one hour); they store only
|
|
399
538
|
model affinity, never prompts or Ollama KV. Restarting `freellama serve` clears sessions and the catalog cache. Persisted placement feedback is
|
|
400
539
|
reloaded; `--ephemeral-feedback` intentionally resets it. Ollama owns model residency, so loaded
|
|
401
|
-
models survive a FreeLlama restart.
|
|
540
|
+
models survive a FreeLlama restart. Scope histories and their revisions do not survive restart.
|
|
541
|
+
They store messages independently from affinity and append only a successful generation at the
|
|
542
|
+
expected revision. Warming uses ordinary admission and fit checks; omitted residency controls use
|
|
543
|
+
a finite measured policy. See [Scope history and model warming](SCOPES_AND_WARMING.md) for the
|
|
544
|
+
public contract and configured limits.
|
|
402
545
|
|
|
403
546
|
The design fails closed when it cannot establish a required contract. Examples include an
|
|
404
547
|
unreachable configured backend, an unknown confidence grade, a policy without qualified models, an
|
package/docs/CLI.md
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# CLI reference
|
|
2
2
|
|
|
3
|
-
The `freellama` command
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
The `freellama` command starts and inspects the local management layer that agents use to offload
|
|
4
|
+
work. It exposes diagnostics, model routing, managed execution, resource controls, benchmarking,
|
|
5
|
+
and Ollama-compatible passthrough. Use the [README quick start](../README.md#quick-start) for first
|
|
6
|
+
use and this reference to look up commands and controls.
|
|
6
7
|
|
|
7
8
|
## Choose a command
|
|
8
9
|
|
|
@@ -22,16 +23,22 @@ flowchart TD
|
|
|
22
23
|
|
|
23
24
|
| Command | Purpose | Needs `freellama serve` |
|
|
24
25
|
|---|---|---|
|
|
25
|
-
| `init` | Inspect prerequisites and print a side-effect-free first-run plan | No |
|
|
26
|
+
| `init` | Inspect prerequisites and print a side-effect-free first-run plan with readiness flags | No |
|
|
26
27
|
| `serve` | Run the control plane and Ollama-compatible proxy | Starts it |
|
|
27
28
|
| `auth-token` | Create a new mode-0600 bearer-token file without printing the secret | No |
|
|
28
29
|
| `models` | List installed models, capabilities, residency, and evidence | Yes |
|
|
29
30
|
| `machine` | Print portable host RAM, CPU, OS, architecture, disk, and the local Ollama endpoint | Yes |
|
|
30
|
-
| `
|
|
31
|
+
| `status` | Live queues (also as a page at `http://127.0.0.1:11435/_freellama/ui`), current and adaptive limits, circuit breakers, loaded models, host memory, Ollama's effective settings, today's usage | Yes |
|
|
32
|
+
| `usage` | Task and token totals per day and per model (`--days`, default 7) | Yes |
|
|
33
|
+
| `config` | Effective runtime settings and the source of each; `--reload` re-reads the runtime file | Yes |
|
|
34
|
+
| `session` | Create model affinity for related tasks | Yes |
|
|
35
|
+
| `scope` | Create, inspect, fork, or delete bounded message history | Yes |
|
|
36
|
+
| `warm` | Warm an installed model through managed admission | Yes |
|
|
31
37
|
| `route` | Choose a model and request profile without executing it | Yes |
|
|
32
38
|
| `recommend` | Return an installed route or a reviewed installation plan | Yes |
|
|
33
39
|
| `natural-route` | Convert natural language to a route intent locally, then route it | Yes |
|
|
34
40
|
| `task` | Route and execute one nonstreaming task | Yes |
|
|
41
|
+
| `jobs` | List, inspect, cancel, or remove deferred tasks and warming operations | Yes |
|
|
35
42
|
| `proxy` | Run only the Ollama-compatible retry and telemetry sidecar | No |
|
|
36
43
|
| `bench-all` | Measure installed models by capability group | No |
|
|
37
44
|
| `policy-from-eval` | Generate policy from quality-evaluation pass rates | No |
|
|
@@ -91,18 +98,70 @@ placement.
|
|
|
91
98
|
|
|
92
99
|
### Bound admission
|
|
93
100
|
|
|
94
|
-
`--max-concurrent-tasks` is the primary/GPU cost budget, not a request count
|
|
95
|
-
|
|
96
|
-
|
|
101
|
+
`--max-concurrent-tasks` is the primary/GPU cost budget, not a request count. Without a flag,
|
|
102
|
+
environment variable, or runtime-file value it defaults to 2 units per `OLLAMA_NUM_PARALLEL` slot of
|
|
103
|
+
the Ollama server (read from its process environment where visible; Ollama's own default is 1, so 2).
|
|
104
|
+
`freellama config` shows the effective value and where it came from.
|
|
105
|
+
`--cpu-max-concurrent-tasks` controls the independent CPU pool and defaults to 1. Default base costs
|
|
106
|
+
are embedding 1, chat 2, and vision 4. Embeddings multiply their base by `ceil(input_items/4)`;
|
|
107
|
+
the acquired charge is capped to the selected backend's pool. Configure overrides in `[task_costs]`;
|
|
108
|
+
see [monitoring controls](MONITORING.md#adaptive-concurrency). A saturated GPU pool does
|
|
97
109
|
not consume CPU permits. `--max-queue-wait-seconds` defaults to 120; when no permit becomes
|
|
98
|
-
available, FreeLlama refuses the task with HTTP 503 instead of waiting forever.
|
|
110
|
+
available, FreeLlama refuses the task with HTTP 503 (`admission_timeout`) instead of waiting forever.
|
|
111
|
+
A task can ask for a shorter wait with `max_wait_seconds` (`maxWaitSeconds` in MCP); it can never
|
|
112
|
+
exceed the configured one. Omit it to use the server's waiting budget.
|
|
113
|
+
That deadline covers weighted admission, host-resource waiting, and model-transition locking together.
|
|
114
|
+
`--max-queued-tasks` (default 16) and `--cpu-max-queued-tasks` (default 8) also bound how many
|
|
115
|
+
parsed requests can be retained per backend; a full queue receives 429 (`admission_queue_full`)
|
|
116
|
+
immediately, and cancelled clients release their waiter. Every capacity refusal carries a
|
|
117
|
+
`Retry-After` header and `retry_after_seconds`, estimated from queue depth and the backend's recent
|
|
118
|
+
task duration, so clients back off instead of retrying hot. Health exposes the queue depth, oldest wait, in-flight work, and
|
|
119
|
+
refusal/timeout/cancellation counters.
|
|
99
120
|
|
|
100
121
|
These are conservative workload-unit defaults, not detected core or RAM counts. Tune them from
|
|
101
122
|
queue-wait receipts and resident-memory observations on the target host. Ollama still controls
|
|
102
123
|
decoding concurrency with `OLLAMA_NUM_PARALLEL`. It also owns a separate internal queue through
|
|
103
124
|
`OLLAMA_MAX_QUEUE`: managed tasks enter that queue only after FreeLlama admission, while raw proxy
|
|
104
125
|
traffic enters it directly. Start an unmeasured deployment with one loaded model and one parallel
|
|
105
|
-
stream per Ollama process.
|
|
126
|
+
stream per Ollama process. In `serve`, raw passthrough defaults to one full-lifetime streaming
|
|
127
|
+
request; override with `--raw-proxy-max-concurrent-requests` only after measurement. A raw request
|
|
128
|
+
over the cap waits up to `--raw-queue-wait-seconds` (default 10) and is then refused with 429 and
|
|
129
|
+
`Retry-After`; `0` restores immediate refusal.
|
|
130
|
+
|
|
131
|
+
All of these, plus pinned models, idle eviction, adaptive concurrency, the circuit breaker, and
|
|
132
|
+
context sizing, can also live in a runtime file (`--runtime-config`) that `serve` re-reads when it
|
|
133
|
+
changes. See [Monitoring and live tuning](MONITORING.md). The standalone
|
|
134
|
+
`proxy` command keeps its cap opt-in for compatibility.
|
|
135
|
+
|
|
136
|
+
The local host-pressure gate defaults to holding below 15% available RAM and resuming above 20%
|
|
137
|
+
after two healthy samples; minimum reserves are 1 GiB and 2 GiB, respectively. Tune the percentages
|
|
138
|
+
with `--resource-hold-available-percent` and `--resource-resume-available-percent`; the hold value
|
|
139
|
+
must be lower than the resume value, and neither can exceed 100. Health reports the policy, sampled
|
|
140
|
+
signals, unknown measurements, and reserved memory. These flags do not change Ollama or OS settings.
|
|
141
|
+
|
|
142
|
+
The reserve applies to every new managed load, not only to the pressure gate: a task is admitted
|
|
143
|
+
when effective available RAM covers already-reserved bytes, the task's estimated bytes, and the
|
|
144
|
+
reserve (the hold reserve normally; the larger resume reserve while capacity is recovering).
|
|
145
|
+
Effective available RAM is free memory plus a bounded reclaimable estimate, so it can be far lower
|
|
146
|
+
than the OS "free" percentage. A refusal reports `assessment.status: "held_insufficient_capacity"`
|
|
147
|
+
with `required_with_reserve_bytes` and `effective_available_bytes`; free memory, choose a smaller
|
|
148
|
+
model, or lower the percentages deliberately.
|
|
149
|
+
Both `serve` and `proxy` accept `--resource-telemetry-policy`:
|
|
150
|
+
|
|
151
|
+
- `require-memory` (default): wait or refuse local inference when available RAM is unknown, including
|
|
152
|
+
raw requests with zero forecast bytes. Missing thermal data alone does not block this policy.
|
|
153
|
+
- `require-all`: require all signals applicable to the collector. The built-in Linux collector does
|
|
154
|
+
not provide OS pressure or thermal signals and marks those as unsupported; custom collectors must
|
|
155
|
+
provide them. Unsupported signals are not evidence of healthy hardware.
|
|
156
|
+
- `best-effort`: explicitly permit unknown telemetry unless an observed pressure hold is active.
|
|
157
|
+
|
|
158
|
+
Remote upstreams bypass local host policy. Raw metadata and empty unload requests remain available
|
|
159
|
+
during a hold. Route receipts separate `queue_readiness` from `resource_readiness`, and include
|
|
160
|
+
`resource_assessment` without acquiring a permit. Resource refusals return a human-readable `error`,
|
|
161
|
+
a stable `code`, and an object-valued `resource_admission`; timeout during metadata inspection reports
|
|
162
|
+
its phase and omits estimates that were not obtained.
|
|
163
|
+
|
|
164
|
+
See [resource admission](ARCHITECTURE.md#managed-task-execution) for scope and limitations.
|
|
106
165
|
|
|
107
166
|
`route`, `recommend`, and `task` accept
|
|
108
167
|
`--execution-preference auto|prefer-cpu|prefer-gpu`. This is a fallback-capable hint over models
|
|
@@ -115,6 +174,10 @@ placement; the default `configured` accepts the operator assignment and observes
|
|
|
115
174
|
|
|
116
175
|
Start with the read-only guided receipt, then inspect available models. `init` never pulls a model;
|
|
117
176
|
it stops at exact-tag approval and prints the next prerequisite, serve, managed-task, and MCP steps.
|
|
177
|
+
Its `status` is `blocked` when Ollama is unavailable, `setup_required` when the managed service or
|
|
178
|
+
installed models are missing, and `ready` when all three are present. Separate `readiness` flags
|
|
179
|
+
identify the missing part. Readiness does not qualify a model for a particular task; use a route
|
|
180
|
+
preview to inspect eligibility and rejection reasons.
|
|
118
181
|
|
|
119
182
|
```bash
|
|
120
183
|
npx @octocodeai/freellama init
|
|
@@ -135,7 +198,10 @@ npx @octocodeai/freellama route \
|
|
|
135
198
|
|
|
136
199
|
Task kinds are `completion`, `coding`, `code-repair`, `tools`, `browser`, `vision`, `embedding`, and
|
|
137
200
|
`long-context`. Objectives are `fastest`, `balanced`, and `quality`. `fastest` can use capability
|
|
138
|
-
and local benchmark evidence alone
|
|
201
|
+
and local benchmark evidence alone. Default `balanced` prefers eligible task-policy candidates;
|
|
202
|
+
without them it falls back to capability/context-compatible models and reports low confidence
|
|
203
|
+
and missing quality evidence. `quality` requires a policy unless you supply an explicit model.
|
|
204
|
+
An explicit minimum-confidence gate still refuses insufficient evidence in every objective.
|
|
139
205
|
|
|
140
206
|
`recommend` is side-effect-free. If no installed model qualifies, it can return an installation
|
|
141
207
|
plan from the reviewed recommendation catalog, but it never pulls a model.
|
|
@@ -157,19 +223,41 @@ Useful task options include:
|
|
|
157
223
|
|
|
158
224
|
- `--model` for an exact installed model.
|
|
159
225
|
- `--session` for affinity across related requests.
|
|
160
|
-
- `--
|
|
226
|
+
- `--scope-id` and `--scope-revision` together for bounded message history.
|
|
227
|
+
- `--keep-alive` for an explicit residency duration.
|
|
228
|
+
- `--context-tokens` for the complete input and output context window (`num_ctx`).
|
|
161
229
|
- repeatable `--required-capability` constraints.
|
|
162
230
|
- repeatable `--image` paths for vision tasks.
|
|
163
231
|
- `--input-file` for batched embedding input, one item per line.
|
|
164
232
|
- `--min-confidence low|medium` to refuse insufficiently evidenced routes before generation.
|
|
233
|
+
- `--priority interactive|normal|background` for fair admission scheduling.
|
|
234
|
+
- `--max-wait-seconds` for a shorter admission/resource wait budget.
|
|
235
|
+
- `--timeout-seconds` for a total deadline including discovery, waiting, loading, and inference.
|
|
236
|
+
- `--defer` to return a job ID immediately.
|
|
237
|
+
|
|
238
|
+
Inspect deferred work with `jobs`, retrieve a result with `jobs --id <uuid>`, and cancel one task
|
|
239
|
+
with `jobs --id <uuid> --cancel`. Remove one task with `jobs --id <uuid> --remove`: active work is
|
|
240
|
+
cancelled first, then its retained record and result are deleted. Use the exact ID returned at
|
|
241
|
+
submission; `--cancel` and `--remove` are mutually exclusive. The same operations are available
|
|
242
|
+
through MCP `task_jobs`.
|
|
243
|
+
Cancellation and removal wait for local execution permits to be released; they do not unload a shared model
|
|
244
|
+
or confirm that the physical runner has stopped.
|
|
245
|
+
|
|
246
|
+
Jobs stay in server memory: at most 64 receipts, 1 MiB per input, and 2 MiB per retained result or
|
|
247
|
+
error. Finished receipts expire after 10 minutes and can be evicted earlier to make room for new
|
|
248
|
+
work. A restart discards all jobs. Admission queue limits still apply, and deferred work can fail
|
|
249
|
+
after acceptance. See [monitoring](MONITORING.md) for states and waiting reasons.
|
|
165
250
|
|
|
166
251
|
Create a session with `session`, then pass its identifier to related `route` or `task` calls. A
|
|
167
252
|
route preview honors an existing affinity but does not create or change one. Only a successfully
|
|
168
253
|
admitted task execution binds the session to its selected model. Reuse never bypasses capability,
|
|
169
254
|
policy, or memory checks.
|
|
170
255
|
|
|
171
|
-
|
|
172
|
-
`"-1"`
|
|
256
|
+
`task --keep-alive` and MCP `run_task.keepAlive` control residency: `"0"` requests immediate
|
|
257
|
+
unload, `"-1"` requests indefinite retention, and omission selects finite adaptive retention.
|
|
258
|
+
`session` retains affinity only; use `scope` for revision-protected message history and `warm`
|
|
259
|
+
for an admitted runner load. See [Scope history and model warming](SCOPES_AND_WARMING.md) for
|
|
260
|
+
input shapes, limits, and CLI examples.
|
|
173
261
|
|
|
174
262
|
## Earn medium routing confidence
|
|
175
263
|
|
|
@@ -190,7 +278,7 @@ Generate the policy from correctness data and the benchmark report from local ru
|
|
|
190
278
|
|
|
191
279
|
```bash
|
|
192
280
|
npx @octocodeai/freellama policy-from-eval \
|
|
193
|
-
--aggregate benchmark/local/results
|
|
281
|
+
--aggregate benchmark/local/results/MODEL/aggregate.json \
|
|
194
282
|
--task coding \
|
|
195
283
|
--min-pass 0.8 \
|
|
196
284
|
--out platform.toml
|
|
@@ -202,6 +290,8 @@ npx @octocodeai/freellama serve --recommendation-catalog recommendations.example
|
|
|
202
290
|
`serve` discovers `platform.toml` and `benchmark-report.json` in its working directory. Explicit
|
|
203
291
|
`--policy-file` and `--benchmark-report` values take precedence.
|
|
204
292
|
|
|
293
|
+
Replace `MODEL` with the directory containing your completed quality-evaluation aggregate.
|
|
294
|
+
|
|
205
295
|
`policy-from-eval` reads `pass_at_1`, not the throughput produced by `bench-all`. It refuses expired
|
|
206
296
|
aggregates and fewer than three trials unless `--allow-smoke` is explicit, and it skips models that
|
|
207
297
|
are not installed. This prevents speed data from being mislabeled as quality evidence.
|
|
@@ -213,7 +303,7 @@ npx @octocodeai/freellama tools
|
|
|
213
303
|
```
|
|
214
304
|
|
|
215
305
|
The command prints the maintained parity map. MCP-only operations are `delegate_research` and the
|
|
216
|
-
online `models { view: "library" }` view. CLI-only operations include `serve`, `proxy`,
|
|
306
|
+
online `models { view: "library" }` view. CLI-only operations include `serve`, `proxy`,
|
|
217
307
|
`recommend`, `natural-route`, `bench-all`, `policy-from-eval`, `run`, and `eval`.
|
|
218
308
|
|
|
219
|
-
For the
|
|
309
|
+
For the MCP tool contracts, read the [MCP package reference](../packages/mcp/README.md).
|