@drakonkat/ai-helper 1.2.19 → 1.2.21
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/ARCHITECTURE.md +9 -0
- package/CHANGELOG.md +19 -0
- package/README.md +50 -4
- package/package.json +1 -1
- package/src/config.js +12 -0
- package/src/health.js +2 -1
- package/src/hindsight.js +334 -13
- package/src/index.js +2 -0
- package/src/manager.js +311 -54
- package/src/proxy-presets.js +89 -35
- package/src/pxpipe-pool.js +69 -15
- package/src/startup-services.js +2 -1
- package/src/tui-proxy-setup.js +51 -10
- package/src/tui.js +3 -1
- package/src/utils/versions.js +8 -1
package/ARCHITECTURE.md
CHANGED
|
@@ -99,6 +99,15 @@ the environment it adds to its image become aih's settings, and aih recreates it
|
|
|
99
99
|
Update stops the container, archives its volume to `~/.aih/backups` and only then
|
|
100
100
|
removes it; it never uses `docker rm -f`, which would SIGKILL the embedded database.
|
|
101
101
|
|
|
102
|
+
The optional local LLM (`hindsight-llm`, a llama.cpp server) is part of the Hindsight
|
|
103
|
+
settings (`state.config.hindsight.localLlm`) and is listed as a service only while enabled.
|
|
104
|
+
Both containers join the `aih-hindsight` network. Its container carries `io.aih.role=llm`
|
|
105
|
+
and its own fingerprint (server settings only); the routing settings (operations,
|
|
106
|
+
timeouts, budgets) are part of Hindsight's fingerprint, so changing them recreates
|
|
107
|
+
Hindsight but not the model server. Without a local LLM, Hindsight's fingerprint is
|
|
108
|
+
computed as before, so upgrading aih does not recreate it. Start order is LLM then
|
|
109
|
+
Hindsight, stop order the reverse. aih never advances its image tag.
|
|
110
|
+
|
|
102
111
|
---
|
|
103
112
|
|
|
104
113
|
## 4. State Synchronization
|
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,25 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.21] - 2026-11-23
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- **Local LLM for Hindsight** (`hindsight-llm`): an optional llama.cpp server container managed by aih, configured in setup (step *Hindsight local LLM*): image, models folder, model, LoRA adapter, alias, GPUs, context, parallel slots, extra arguments, and the Hindsight operations sent to it (reflect, retain, consolidation, mental model refresh). Both containers share the `aih-hindsight` network. `start hindsight` starts the LLM first and waits for its `/health` and, for a new container, a test completion; `stop hindsight` stops it after Hindsight. It has its own dashboard row with llama.cpp health and build.
|
|
11
|
+
- Adopting Hindsight also imports the local LLM container its operations call, so a docker compose stack becomes `hindsight` + `hindsight-llm` in one step. Adoption now archives the data volume first.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
- The llama.cpp build is pinned: `aih update hindsight-llm` pulls the same tag again and rolls back to the previous image if the new one fails; the tag is changed by hand in setup.
|
|
15
|
+
- `aih start hindsight` refuses to start while a container not created by aih runs on the same data volume; `u` offers to adopt it.
|
|
16
|
+
|
|
17
|
+
## [1.2.20] - 2026-11-13
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
- **pxpipe overload no longer fails requests**: when the worker queue is full, a request waits more than 10 s, or the body exceeds 64 MiB, the proxy forwards it without pxpipe (stage reason `queue_full`, `queue_timeout`, `body_too_large`) instead of answering HTTP 503. pxpipe-only requests are checked before the JSON body is parsed.
|
|
21
|
+
- The worker queue is limited per worker (4 waiting requests) and by waiting time; the byte cap is now a memory guard of 4 × `--max-body-bytes` instead of a single request's size.
|
|
22
|
+
- Worker affinity follows the Codex thread instead of the session, so forked subagents no longer queue behind their parent and each other.
|
|
23
|
+
- A client disconnect no longer terminates the active pxpipe worker: its result is discarded and the warm worker is kept (replaced only if still busy after 120 s).
|
|
24
|
+
- Compressed requests that decompress beyond `--max-body-bytes` are forwarded unchanged instead of failing; unchanged bodies are no longer re-serialized before pxpipe.
|
|
25
|
+
|
|
7
26
|
## [1.2.19] - 2026-11-10
|
|
8
27
|
|
|
9
28
|
### Added
|
package/README.md
CHANGED
|
@@ -93,6 +93,7 @@ bun add -g @drakonkat/ai-helper
|
|
|
93
93
|
| **`pxpipe`** | `npx pxpipe-proxy` | [`http://localhost:47821`](http://localhost:47821) | [teamchong/pxpipe](https://github.com/teamchong/pxpipe) | AI LLM & MCP protocol reverse proxy bridge |
|
|
94
94
|
| **`ocx`** | `ocx start` | [`http://localhost:10100`](http://localhost:10100) | [lidge-jun/opencodex](https://github.com/lidge-jun/opencodex) | OpenCode interpreter execution daemon |
|
|
95
95
|
| **`hindsight`** | Docker container `hindsight` (`ghcr.io/vectorize-io/hindsight`) | [`http://localhost:9999`](http://localhost:9999) (UI), API `http://127.0.0.1:8888` | [vectorize-io/hindsight](https://github.com/vectorize-io/hindsight) | Long-term agent memory; requires Docker; health from `/health` |
|
|
96
|
+
| **`hindsight-llm`** | Docker container `hindsight-llm` (`ghcr.io/ggml-org/llama.cpp` server) | API `http://127.0.0.1:8085` | [ggml-org/llama.cpp](https://github.com/ggml-org/llama.cpp) | Optional local LLM for selected Hindsight operations; listed only when enabled |
|
|
96
97
|
| **`headroom`** | `headroom proxy` | [`http://localhost:8787/dashboard`](http://localhost:8787/dashboard) | [headroomlabs-ai/headroom](https://github.com/headroomlabs-ai/headroom) | Context optimization & LLM compression proxy |
|
|
97
98
|
| **`proxy`** | `aih start proxy <upstream>` | `http://127.0.0.1:10101` | [drakonkat/ai-helper](https://github.com/drakonkat/ai-helper) | HTTP/SSE/WebSocket forwarding with optional presets; **no web dashboard** |
|
|
98
99
|
|
|
@@ -138,6 +139,44 @@ not by PID, and never kills processes on its ports (on Windows they belong to Do
|
|
|
138
139
|
through `/health`. To go back, restore the archive into the volume with the container
|
|
139
140
|
stopped and set the previous tag in the settings:
|
|
140
141
|
`docker run --rm -v hindsight-data:/d -v ~/.aih/backups:/b alpine sh -c "rm -rf /d/* /d/.[!.]* && tar xzf /b/<file> -C /d"`.
|
|
142
|
+
- aih refuses to start its container while another container not created by aih is
|
|
143
|
+
running on the same data volume (two Hindsight servers would corrupt the database);
|
|
144
|
+
`u` on hindsight then offers to adopt that container.
|
|
145
|
+
|
|
146
|
+
#### Local LLM (`hindsight-llm`)
|
|
147
|
+
|
|
148
|
+
Hindsight can send some operations to a local model while the others keep the LLM
|
|
149
|
+
above. When enabled in setup (step **Hindsight local LLM**), aih also manages a
|
|
150
|
+
llama.cpp server container, `hindsight-llm`:
|
|
151
|
+
|
|
152
|
+
- Both containers join the Docker network `aih-hindsight` (created when needed);
|
|
153
|
+
Hindsight calls `http://hindsight-llm:8080/v1`. The server is also published on
|
|
154
|
+
`127.0.0.1:8085` for its health check and your own tests.
|
|
155
|
+
- Settings: image (pin a build, e.g. `server-cuda-b12282`), models folder (mounted read-only at
|
|
156
|
+
`/models`), model file, optional LoRA adapter, alias, GPUs (`--gpus all` by default,
|
|
157
|
+
`none` for CPU), context size, parallel slots, extra llama-server arguments, the
|
|
158
|
+
operations to route (`reflect`, `retain`, `consolidation`, `mental_model_refresh`;
|
|
159
|
+
mental model refresh follows reflect unless chosen), max concurrent requests, timeout
|
|
160
|
+
and the reflect token budgets. aih writes the matching `HINDSIGHT_API_<OPERATION>_LLM_*`
|
|
161
|
+
variables; they override the same names in the extra env file. Setup refuses a reflect
|
|
162
|
+
budget (context + completion) larger than one slot.
|
|
163
|
+
- **start hindsight** starts the local LLM first and starts Hindsight only after the LLM
|
|
164
|
+
answers `/health` (up to 5 minutes while the model loads) and, when its container is new
|
|
165
|
+
or was recreated, a one-token test completion. **stop hindsight** stops Hindsight, then
|
|
166
|
+
the LLM. `hindsight-llm` can also be started, stopped and restarted on its own; stopping
|
|
167
|
+
it while Hindsight runs makes the routed operations fail until it is back.
|
|
168
|
+
- The dashboard shows it as its own row: health from llama.cpp `/health` (`degraded` while
|
|
169
|
+
loading), `VERSION` is the llama.cpp build and `UPDATE` shows `pinned`.
|
|
170
|
+
- **The llama.cpp build is changed by hand**: edit the image tag in setup. `u` /
|
|
171
|
+
`aih update hindsight-llm` only pulls the same tag again; if the image changed it
|
|
172
|
+
recreates the container, and if the new image fails its health check or test completion
|
|
173
|
+
it goes back to the previous image. The container holds no data, so there is no backup.
|
|
174
|
+
- Adopting works for a whole docker compose stack: `aih update hindsight --adopt` on a
|
|
175
|
+
Hindsight container whose operations call another container (e.g.
|
|
176
|
+
`http://lfm3-hindsight:8080/v1`) imports that container's image, models folder,
|
|
177
|
+
arguments and GPUs as the local LLM settings, archives the data volume, and recreates
|
|
178
|
+
both as `hindsight` and `hindsight-llm`. A stopped container left by aih under one of
|
|
179
|
+
those names is replaced. Afterwards do not run `docker compose up` for that project again.
|
|
141
180
|
|
|
142
181
|
Settings are edited in `aih status --ui` → **`c`** after selecting **hindsight** in the
|
|
143
182
|
Startup step: container name, image (default `ghcr.io/vectorize-io/hindsight:latest`),
|
|
@@ -466,10 +505,17 @@ tokenization costs and worker-thread experiments.
|
|
|
466
505
|
|
|
467
506
|
Pxpipe transformations and their token estimates run in up to **two persistent
|
|
468
507
|
CPU workers**. Excluded models bypass the worker queue; HTTP and SSE streaming
|
|
469
|
-
remain on the main thread.
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
508
|
+
remain on the main thread. Each Codex thread keeps a stable worker to reuse caches;
|
|
509
|
+
a new thread (for example a forked subagent) starts on its parent's worker only when
|
|
510
|
+
that worker is idle, otherwise on the least busy one. Each worker accepts up to 4
|
|
511
|
+
waiting requests, each waiting at most 10 s, and all waiting input is capped at
|
|
512
|
+
4 × `--max-body-bytes`. Requests over these limits, or with bodies over 64 MiB, are
|
|
513
|
+
**forwarded without pxpipe** (stage reason `queue_full`, `queue_timeout` or
|
|
514
|
+
`body_too_large`) instead of failing; pxpipe-only requests are checked before
|
|
515
|
+
parsing. Compressed bodies that decompress beyond `--max-body-bytes` are forwarded
|
|
516
|
+
unchanged. Disconnecting cancels queued work; an active transformation finishes on
|
|
517
|
+
its warm worker and its result is discarded (a worker still busy after 120 s is
|
|
518
|
+
replaced). Shutdown closes both workers.
|
|
473
519
|
|
|
474
520
|
Installation applies a version-checked correction to pxpipe 0.14.0: diagnostic
|
|
475
521
|
composition counts exclude encrypted reasoning, opaque compaction and media data,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.21",
|
|
4
4
|
"description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, hindsight, headroom)",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"module": "src/index.js",
|
package/src/config.js
CHANGED
|
@@ -42,6 +42,18 @@ export const SERVICES = {
|
|
|
42
42
|
defaultUrl: "http://localhost:9999",
|
|
43
43
|
ports: [],
|
|
44
44
|
},
|
|
45
|
+
"hindsight-llm": {
|
|
46
|
+
id: "hindsight-llm",
|
|
47
|
+
name: "hindsight-llm",
|
|
48
|
+
// Optional: listed only when the Hindsight local LLM is enabled. Started and stopped with hindsight.
|
|
49
|
+
runtime: "docker",
|
|
50
|
+
command: "docker container hindsight-llm",
|
|
51
|
+
repositoryUrl: "https://github.com/ggml-org/llama.cpp",
|
|
52
|
+
description: "Local LLM for Hindsight (llama.cpp server in Docker; API :8085; enable it in setup)",
|
|
53
|
+
defaultPort: 8085,
|
|
54
|
+
defaultUrl: "http://localhost:8085",
|
|
55
|
+
ports: [],
|
|
56
|
+
},
|
|
45
57
|
headroom: {
|
|
46
58
|
id: "headroom",
|
|
47
59
|
name: "headroom",
|
package/src/health.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { baseUrl } from "./utils/metrics.js";
|
|
2
|
-
import { probeHindsightHealth } from "./hindsight.js";
|
|
2
|
+
import { LOCAL_LLM_ID, probeHindsightHealth, probeLocalLlmHealth } from "./hindsight.js";
|
|
3
3
|
import { PROXY_HEALTH_PATH } from "./proxy.js";
|
|
4
4
|
|
|
5
5
|
export { PROXY_HEALTH_PATH };
|
|
@@ -76,6 +76,7 @@ export async function probeHttpHealth(id, url, { fetchImpl = fetch, timeoutMs =
|
|
|
76
76
|
|
|
77
77
|
/** One entry point for every service status object shown in the dashboard. */
|
|
78
78
|
export function probeServiceHealth(svc, options) {
|
|
79
|
+
if (svc.id === LOCAL_LLM_ID) return probeLocalLlmHealth(svc.apiUrl, options);
|
|
79
80
|
if (svc.runtime === "docker") return probeHindsightHealth(svc.apiUrl, options);
|
|
80
81
|
return probeHttpHealth(svc.id, svc.url, options);
|
|
81
82
|
}
|
package/src/hindsight.js
CHANGED
|
@@ -26,6 +26,43 @@ const DATA_DIR = "/home/hindsight/.pg0";
|
|
|
26
26
|
const NO_KEY_PROVIDERS = new Set(["ollama", "lmstudio"]);
|
|
27
27
|
const DOCKER_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/;
|
|
28
28
|
const CONTROL = /[\x00-\x1f\x7f-\x9f]/;
|
|
29
|
+
const IMAGE_REF = /^[a-z0-9][a-z0-9._\/:@-]{0,254}$/i;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Optional local LLM (llama.cpp server) that Hindsight calls for selected operations.
|
|
33
|
+
* Both containers join one Docker network; Hindsight reaches it by container name.
|
|
34
|
+
*/
|
|
35
|
+
export const LOCAL_LLM_ID = "hindsight-llm";
|
|
36
|
+
export const HINDSIGHT_NETWORK = "aih-hindsight";
|
|
37
|
+
export const LOCAL_LLM_REPOSITORY = "ghcr.io/ggml-org/llama.cpp";
|
|
38
|
+
/** Hindsight operations with their own LLM settings; mental model refresh falls back to reflect. */
|
|
39
|
+
export const LOCAL_LLM_OPERATIONS = Object.freeze(["reflect", "retain", "consolidation", "mental_model_refresh"]);
|
|
40
|
+
const LLM_PORT = 8080;
|
|
41
|
+
const MODELS_DIR = "/models";
|
|
42
|
+
/** llama-server options set by aih; extra arguments may not repeat them. */
|
|
43
|
+
const LLM_ARG_NAMES = { "-m": "--model", "--model": "--model", "--lora": "--lora", "-a": "--alias", "--alias": "--alias",
|
|
44
|
+
"--host": "--host", "--port": "--port", "-c": "--ctx-size", "--ctx-size": "--ctx-size", "-np": "--parallel", "--parallel": "--parallel" };
|
|
45
|
+
export const LOCAL_LLM_DEFAULTS = Object.freeze({
|
|
46
|
+
enabled: false,
|
|
47
|
+
containerName: LOCAL_LLM_ID,
|
|
48
|
+
image: LOCAL_LLM_REPOSITORY + ":server-cuda",
|
|
49
|
+
port: 8085,
|
|
50
|
+
modelsDir: "",
|
|
51
|
+
model: "",
|
|
52
|
+
lora: "",
|
|
53
|
+
alias: "local-llm",
|
|
54
|
+
gpus: "all",
|
|
55
|
+
ctxSize: 65536,
|
|
56
|
+
parallel: 1,
|
|
57
|
+
extraArgs: "--jinja --n-gpu-layers 999 --flash-attn on --metrics",
|
|
58
|
+
operations: Object.freeze(["reflect"]),
|
|
59
|
+
maxConcurrent: 1,
|
|
60
|
+
timeout: 180,
|
|
61
|
+
maxContextTokens: 48000,
|
|
62
|
+
maxCompletionTokens: 8192,
|
|
63
|
+
});
|
|
64
|
+
/** Fields that only change how Hindsight calls the server, not the server itself. */
|
|
65
|
+
const LLM_ROUTING_FIELDS = ["containerName", "alias", "operations", "maxConcurrent", "timeout", "maxContextTokens", "maxCompletionTokens"];
|
|
29
66
|
|
|
30
67
|
function port(value, label) {
|
|
31
68
|
const text = String(value ?? "").trim();
|
|
@@ -36,19 +73,94 @@ function port(value, label) {
|
|
|
36
73
|
return number;
|
|
37
74
|
}
|
|
38
75
|
|
|
76
|
+
function integer(value, label, min, max) {
|
|
77
|
+
const text = String(value ?? "").trim();
|
|
78
|
+
const number = Number(text);
|
|
79
|
+
if (!/^\d+$/.test(text) || number < min || number > max) throw new Error(label + ": enter a whole number between " + min + " and " + max);
|
|
80
|
+
return number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const defined = input => Object.fromEntries(Object.entries(input || {}).filter(([, v]) => v !== undefined && v !== null));
|
|
84
|
+
|
|
85
|
+
/** A file inside the models folder, as a forward-slash relative path. */
|
|
86
|
+
function modelFile(value, label, required) {
|
|
87
|
+
const text = String(value ?? "").trim().replaceAll("\\", "/");
|
|
88
|
+
if (!text) {
|
|
89
|
+
if (required) throw new Error(label + ": required when the local LLM is enabled");
|
|
90
|
+
return "";
|
|
91
|
+
}
|
|
92
|
+
if (CONTROL.test(text) || /[,"]/.test(text) || text.startsWith("/") || /^[a-z]:/i.test(text) || text.split("/").some(p => !p || p === "." || p === "..")) {
|
|
93
|
+
throw new Error(label + ": a file inside the models folder (no absolute path, '..', commas or quotes)");
|
|
94
|
+
}
|
|
95
|
+
return text;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function splitLlmArgs(text) {
|
|
99
|
+
return String(text ?? "").trim().split(/\s+/).filter(Boolean);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Validates the local LLM settings; required fields are enforced only when it is enabled. */
|
|
103
|
+
export function normalizeLocalLlmConfig(input = {}) {
|
|
104
|
+
const value = { ...LOCAL_LLM_DEFAULTS, ...defined(input) };
|
|
105
|
+
const text = key => String(value[key] ?? "").trim();
|
|
106
|
+
const enabled = value.enabled === true || /^(true|on|yes|1)$/i.test(String(value.enabled));
|
|
107
|
+
const operations = (Array.isArray(value.operations) ? value.operations : String(value.operations).split(","))
|
|
108
|
+
.map(op => String(op).trim().toLowerCase()).filter(Boolean);
|
|
109
|
+
const unknown = operations.find(op => !LOCAL_LLM_OPERATIONS.includes(op));
|
|
110
|
+
if (unknown) throw new Error("Local LLM operations: '" + unknown + "' is not one of " + LOCAL_LLM_OPERATIONS.join(", "));
|
|
111
|
+
const gpus = text("gpus").toLowerCase() === "none" ? "" : text("gpus");
|
|
112
|
+
const config = {
|
|
113
|
+
enabled,
|
|
114
|
+
containerName: text("containerName"),
|
|
115
|
+
image: text("image"),
|
|
116
|
+
port: port(value.port, "Local LLM port"),
|
|
117
|
+
modelsDir: text("modelsDir").replace(/(.)[\\/]+$/, "$1"),
|
|
118
|
+
model: modelFile(value.model, "Local LLM model file", enabled),
|
|
119
|
+
lora: modelFile(value.lora, "Local LLM LoRA adapter", false),
|
|
120
|
+
alias: text("alias"),
|
|
121
|
+
gpus,
|
|
122
|
+
ctxSize: integer(value.ctxSize, "Local LLM context size", 512, 4194304),
|
|
123
|
+
parallel: integer(value.parallel, "Local LLM parallel slots", 1, 64),
|
|
124
|
+
extraArgs: splitLlmArgs(value.extraArgs).join(" "),
|
|
125
|
+
operations: LOCAL_LLM_OPERATIONS.filter(op => operations.includes(op)),
|
|
126
|
+
maxConcurrent: integer(value.maxConcurrent, "Local LLM max concurrent requests", 1, 64),
|
|
127
|
+
timeout: integer(value.timeout, "Local LLM timeout (seconds)", 1, 3600),
|
|
128
|
+
maxContextTokens: integer(value.maxContextTokens, "Reflect max context tokens", 256, 4194304),
|
|
129
|
+
maxCompletionTokens: integer(value.maxCompletionTokens, "Reflect max completion tokens", 16, 4194304),
|
|
130
|
+
};
|
|
131
|
+
if (!DOCKER_NAME.test(config.containerName)) throw new Error("Local LLM container name: letters, digits, '_', '.', '-' (max 128)");
|
|
132
|
+
if (!IMAGE_REF.test(config.image)) throw new Error("Local LLM image: invalid Docker image reference");
|
|
133
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:\/-]{0,127}$/.test(config.alias)) throw new Error("Local LLM model alias: letters, digits, '.', '_', ':', '/', '-'");
|
|
134
|
+
if (!/^(all|\d{1,2}|device=[A-Za-z0-9,._-]+)?$/.test(config.gpus)) throw new Error("Local LLM GPUs: all, none, a count or device=<ids>");
|
|
135
|
+
if (CONTROL.test(config.extraArgs)) throw new Error("Local LLM extra arguments: no control characters");
|
|
136
|
+
const managed = splitLlmArgs(config.extraArgs).find(arg => LLM_ARG_NAMES[arg.split("=")[0]]);
|
|
137
|
+
if (managed) throw new Error("Local LLM extra arguments: " + managed.split("=")[0] + " is set by aih from the other fields");
|
|
138
|
+
if (CONTROL.test(config.modelsDir) || /[,"]/.test(config.modelsDir)) throw new Error("Local LLM models folder: no commas, quotes or control characters");
|
|
139
|
+
if (!enabled) return config;
|
|
140
|
+
if (!/^([a-z]:[\\/]|\/)/i.test(config.modelsDir)) throw new Error("Local LLM models folder: enter an absolute path");
|
|
141
|
+
if (!config.operations.length) throw new Error("Local LLM operations: choose at least one of " + LOCAL_LLM_OPERATIONS.join(", "));
|
|
142
|
+
if (config.maxConcurrent > config.parallel) throw new Error("Local LLM max concurrent requests cannot exceed its " + config.parallel + " parallel slots");
|
|
143
|
+
const slot = Math.floor(config.ctxSize / config.parallel);
|
|
144
|
+
if (config.operations.includes("reflect") && config.maxContextTokens + config.maxCompletionTokens > slot) {
|
|
145
|
+
throw new Error("Reflect context (" + config.maxContextTokens + ") + completion (" + config.maxCompletionTokens + ") tokens exceed the "
|
|
146
|
+
+ slot + " tokens of each local LLM slot (context size / parallel slots)");
|
|
147
|
+
}
|
|
148
|
+
return config;
|
|
149
|
+
}
|
|
150
|
+
|
|
39
151
|
/** Validates the non-secret settings; the API key never belongs in this object. */
|
|
40
152
|
export function normalizeHindsightConfig(input = {}) {
|
|
41
|
-
const value = { ...HINDSIGHT_DEFAULTS, ...
|
|
153
|
+
const value = { ...HINDSIGHT_DEFAULTS, ...defined(input) };
|
|
42
154
|
const text = key => String(value[key] ?? "").trim();
|
|
43
155
|
const config = {
|
|
44
156
|
containerName: text("containerName"), image: text("image"), volume: text("volume"),
|
|
45
157
|
apiPort: port(value.apiPort, "Hindsight API port"), uiPort: port(value.uiPort, "Hindsight UI port"),
|
|
46
158
|
llmProvider: text("llmProvider").toLowerCase(), llmModel: text("llmModel"), llmBaseUrl: text("llmBaseUrl"),
|
|
47
|
-
envFile: text("envFile"),
|
|
159
|
+
envFile: text("envFile"), localLlm: normalizeLocalLlmConfig(value.localLlm),
|
|
48
160
|
};
|
|
49
161
|
if (!DOCKER_NAME.test(config.containerName)) throw new Error("Hindsight container name: letters, digits, '_', '.', '-' (max 128)");
|
|
50
162
|
if (!DOCKER_NAME.test(config.volume)) throw new Error("Hindsight data volume: letters, digits, '_', '.', '-' (max 128)");
|
|
51
|
-
if (
|
|
163
|
+
if (!IMAGE_REF.test(config.image)) throw new Error("Hindsight image: invalid Docker image reference");
|
|
52
164
|
if (config.apiPort === config.uiPort) throw new Error("Hindsight API and UI ports must differ");
|
|
53
165
|
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(config.llmProvider)) throw new Error("Hindsight LLM provider: lowercase letters, digits, '_' or '-'");
|
|
54
166
|
if (CONTROL.test(config.llmModel) || /\s/.test(config.llmModel) || config.llmModel.length > 200) throw new Error("Hindsight LLM model: no spaces or control characters");
|
|
@@ -58,6 +170,10 @@ export function normalizeHindsightConfig(input = {}) {
|
|
|
58
170
|
if (!/^https?:$/.test(url.protocol) || url.username || url.password) throw new Error("Hindsight LLM base URL: http(s) without credentials");
|
|
59
171
|
}
|
|
60
172
|
if (CONTROL.test(config.envFile)) throw new Error("Hindsight environment file: invalid path");
|
|
173
|
+
if (config.localLlm.enabled) {
|
|
174
|
+
if ([config.apiPort, config.uiPort].includes(config.localLlm.port)) throw new Error("Local LLM port must differ from the Hindsight API and UI ports");
|
|
175
|
+
if (config.localLlm.containerName === config.containerName) throw new Error("Local LLM and Hindsight container names must differ");
|
|
176
|
+
}
|
|
61
177
|
return config;
|
|
62
178
|
}
|
|
63
179
|
|
|
@@ -98,11 +214,42 @@ export function saveHindsightApiKey(key, file = hindsightKeyFile()) {
|
|
|
98
214
|
export function hindsightConfigHash(config, key = "") {
|
|
99
215
|
let extra = "";
|
|
100
216
|
try { if (config.envFile) extra = readFileSync(config.envFile, "utf8"); } catch {}
|
|
101
|
-
|
|
217
|
+
// Without a local LLM the fingerprint matches older releases: no needless recreation on upgrade.
|
|
218
|
+
const { localLlm, ...base } = config;
|
|
219
|
+
const parts = [base, key, extra];
|
|
220
|
+
if (localLlm?.enabled) parts.push(Object.fromEntries(LLM_ROUTING_FIELDS.map(field => [field, localLlm[field]])));
|
|
221
|
+
return createHash("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 16);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Fingerprint of the settings that require recreating the local LLM container. */
|
|
225
|
+
export function localLlmConfigHash(llm) {
|
|
226
|
+
const server = Object.fromEntries(Object.entries(llm).filter(([field]) => field === "containerName" || field === "alias"
|
|
227
|
+
|| !LLM_ROUTING_FIELDS.includes(field) && field !== "enabled"));
|
|
228
|
+
return createHash("sha256").update(JSON.stringify(server)).digest("hex").slice(0, 16);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function localLlmUrls(llm) {
|
|
232
|
+
return { api: "http://127.0.0.1:" + llm.port, ui: "http://localhost:" + llm.port };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Variables that send the selected Hindsight operations to the local server. */
|
|
236
|
+
export function localLlmEnv(llm) {
|
|
237
|
+
if (!llm?.enabled) return [];
|
|
238
|
+
const url = "http://" + llm.containerName + ":" + LLM_PORT + "/v1";
|
|
239
|
+
const env = llm.operations.flatMap(op => {
|
|
240
|
+
const prefix = "HINDSIGHT_API_" + op.toUpperCase() + "_LLM_";
|
|
241
|
+
return [prefix + "PROVIDER=openai", prefix + "BASE_URL=" + url, prefix + "MODEL=" + llm.alias, prefix + "API_KEY=local",
|
|
242
|
+
prefix + "MAX_CONCURRENT=" + llm.maxConcurrent, prefix + "TIMEOUT=" + llm.timeout];
|
|
243
|
+
});
|
|
244
|
+
if (llm.operations.includes("reflect")) {
|
|
245
|
+
env.push("HINDSIGHT_API_REFLECT_MAX_CONTEXT_TOKENS=" + llm.maxContextTokens, "HINDSIGHT_API_REFLECT_MAX_COMPLETION_TOKENS=" + llm.maxCompletionTokens);
|
|
246
|
+
}
|
|
247
|
+
return env;
|
|
102
248
|
}
|
|
103
249
|
|
|
104
250
|
export function hindsightRunArgs(config, { configHash, keySource }) {
|
|
105
251
|
const args = ["run", "-d", "--name", config.containerName, "--restart", "unless-stopped", "--shm-size", "1g",
|
|
252
|
+
...(config.localLlm?.enabled ? ["--network", HINDSIGHT_NETWORK] : []),
|
|
106
253
|
"-p", "127.0.0.1:" + config.apiPort + ":" + API_PORT, "-p", "127.0.0.1:" + config.uiPort + ":" + UI_PORT,
|
|
107
254
|
"-v", config.volume + ":" + DATA_DIR,
|
|
108
255
|
"--label", "io.aih.managed=true", "--label", "io.aih.config=" + configHash,
|
|
@@ -110,6 +257,8 @@ export function hindsightRunArgs(config, { configHash, keySource }) {
|
|
|
110
257
|
"-e", "HINDSIGHT_API_LLM_PROVIDER=" + config.llmProvider];
|
|
111
258
|
if (config.llmModel) args.push("-e", "HINDSIGHT_API_LLM_MODEL=" + config.llmModel);
|
|
112
259
|
if (config.llmBaseUrl) args.push("-e", "HINDSIGHT_API_LLM_BASE_URL=" + config.llmBaseUrl);
|
|
260
|
+
// -e wins over --env-file: the local routing cannot be overridden by the extra file by mistake.
|
|
261
|
+
for (const line of localLlmEnv(config.localLlm)) args.push("-e", line);
|
|
113
262
|
if (config.envFile) args.push("--env-file", config.envFile);
|
|
114
263
|
// Never put the key on the command line: docker reads it from a file or its own environment.
|
|
115
264
|
if (keySource === "file") args.push("--env-file", hindsightKeyFile());
|
|
@@ -118,6 +267,20 @@ export function hindsightRunArgs(config, { configHash, keySource }) {
|
|
|
118
267
|
return args;
|
|
119
268
|
}
|
|
120
269
|
|
|
270
|
+
/** llama-server in Docker: models mounted read-only, API published on loopback only. */
|
|
271
|
+
export function localLlmRunArgs(llm, { configHash }) {
|
|
272
|
+
const args = ["run", "-d", "--name", llm.containerName, "--restart", "unless-stopped", "--network", HINDSIGHT_NETWORK,
|
|
273
|
+
"-p", "127.0.0.1:" + llm.port + ":" + LLM_PORT,
|
|
274
|
+
"--mount", "type=bind,source=" + llm.modelsDir + ",target=" + MODELS_DIR + ",readonly",
|
|
275
|
+
"--label", "io.aih.managed=true", "--label", "io.aih.role=llm", "--label", "io.aih.config=" + configHash];
|
|
276
|
+
if (llm.gpus) args.push("--gpus", llm.gpus);
|
|
277
|
+
args.push(llm.image, "--model", MODELS_DIR + "/" + llm.model);
|
|
278
|
+
if (llm.lora) args.push("--lora", MODELS_DIR + "/" + llm.lora);
|
|
279
|
+
args.push("--alias", llm.alias, "--host", "0.0.0.0", "--port", String(LLM_PORT),
|
|
280
|
+
"--ctx-size", String(llm.ctxSize), "--parallel", String(llm.parallel), ...splitLlmArgs(llm.extraArgs));
|
|
281
|
+
return args;
|
|
282
|
+
}
|
|
283
|
+
|
|
121
284
|
export function requiresApiKey(config) {
|
|
122
285
|
return !NO_KEY_PROVIDERS.has(config.llmProvider);
|
|
123
286
|
}
|
|
@@ -153,18 +316,52 @@ export async function inspectContainer(name, run = execCommand, timeout = 5000)
|
|
|
153
316
|
running: container?.State?.Running === true,
|
|
154
317
|
startedAt: Number.isFinite(started) && started > 0 ? new Date(started).toISOString() : undefined,
|
|
155
318
|
managed: labels["io.aih.managed"] === "true",
|
|
319
|
+
role: labels["io.aih.role"] || null,
|
|
156
320
|
configHash: labels["io.aih.config"] || null,
|
|
157
321
|
composeProject: labels["com.docker.compose.project"] || null,
|
|
158
322
|
// Read only to adopt a container aih did not create.
|
|
159
323
|
env: container?.Config?.Env || [],
|
|
160
|
-
|
|
324
|
+
cmd: container?.Config?.Cmd || [],
|
|
325
|
+
mounts: (container?.Mounts || []).map(m => ({ type: m.Type, name: m.Name, source: m.Source, destination: m.Destination })),
|
|
161
326
|
ports: container?.HostConfig?.PortBindings || {},
|
|
327
|
+
gpus: container?.HostConfig?.DeviceRequests || [],
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Operations whose LLM calls go to one OpenAI-compatible server addressed by container name. */
|
|
332
|
+
function localLlmRoute(env) {
|
|
333
|
+
const routes = LOCAL_LLM_OPERATIONS.map(op => {
|
|
334
|
+
const prefix = "HINDSIGHT_API_" + op.toUpperCase() + "_LLM_";
|
|
335
|
+
const url = /^http:\/\/([A-Za-z0-9_-]+):(\d+)\/v1\/?$/.exec(env.get(prefix + "BASE_URL") || "");
|
|
336
|
+
const provider = env.get(prefix + "PROVIDER") || "openai";
|
|
337
|
+
return url && url[1] !== "localhost" && provider === "openai" ? { op, prefix, host: url[1], port: Number(url[2]), model: env.get(prefix + "MODEL") || "" } : null;
|
|
338
|
+
}).filter(Boolean);
|
|
339
|
+
if (!routes.length) return null;
|
|
340
|
+
if (routes.some(r => r.host !== routes[0].host || r.port !== routes[0].port || r.model !== routes[0].model)) {
|
|
341
|
+
throw new Error("its operations use different local servers or models; aih manages a single local LLM");
|
|
342
|
+
}
|
|
343
|
+
const values = field => routes.map(r => env.get(r.prefix + field)).filter(v => v !== undefined);
|
|
344
|
+
const one = (field, label) => {
|
|
345
|
+
const found = [...new Set(values(field))];
|
|
346
|
+
if (found.length > 1) throw new Error("its operations use different " + label + " values for the local LLM");
|
|
347
|
+
return found[0];
|
|
162
348
|
};
|
|
349
|
+
const route = { host: routes[0].host, port: routes[0].port, alias: routes[0].model, operations: routes.map(r => r.op),
|
|
350
|
+
maxConcurrent: one("MAX_CONCURRENT", "max concurrent"), timeout: one("TIMEOUT", "timeout"),
|
|
351
|
+
maxContextTokens: env.get("HINDSIGHT_API_REFLECT_MAX_CONTEXT_TOKENS"), maxCompletionTokens: env.get("HINDSIGHT_API_REFLECT_MAX_COMPLETION_TOKENS") };
|
|
352
|
+
// These variables are regenerated from the local LLM settings.
|
|
353
|
+
for (const r of routes) for (const field of ["PROVIDER", "BASE_URL", "MODEL", "API_KEY", "MAX_CONCURRENT", "TIMEOUT"]) env.delete(r.prefix + field);
|
|
354
|
+
if (route.operations.includes("reflect")) {
|
|
355
|
+
env.delete("HINDSIGHT_API_REFLECT_MAX_CONTEXT_TOKENS");
|
|
356
|
+
env.delete("HINDSIGHT_API_REFLECT_MAX_COMPLETION_TOKENS");
|
|
357
|
+
}
|
|
358
|
+
return route;
|
|
163
359
|
}
|
|
164
360
|
|
|
165
361
|
/**
|
|
166
362
|
* Settings that let aih recreate a container it did not create: image, ports, data volume and
|
|
167
|
-
* the variables set on top of its image. Throws when something would be lost.
|
|
363
|
+
* the variables set on top of its image. Throws when something would be lost. "route" describes
|
|
364
|
+
* a local LLM container the operations are sent to, if any.
|
|
168
365
|
*/
|
|
169
366
|
export function adoptedHindsightSettings(containerName, container, imageEnv) {
|
|
170
367
|
const data = container.mounts.find(m => m.destination === DATA_DIR);
|
|
@@ -177,13 +374,53 @@ export function adoptedHindsightSettings(containerName, container, imageEnv) {
|
|
|
177
374
|
const hostPort = port => container.ports[port + "/tcp"]?.[0]?.HostPort;
|
|
178
375
|
take("HINDSIGHT_CP_DATAPLANE_API_URL"); // always set by aih
|
|
179
376
|
const key = validateHindsightApiKey(take(HINDSIGHT_KEY_ENV) || "");
|
|
377
|
+
const route = localLlmRoute(env);
|
|
180
378
|
const config = normalizeHindsightConfig({
|
|
181
379
|
containerName, image: container.image, volume: data.name, apiPort: hostPort(API_PORT), uiPort: hostPort(UI_PORT),
|
|
182
380
|
llmProvider: take("HINDSIGHT_API_LLM_PROVIDER"), llmModel: take("HINDSIGHT_API_LLM_MODEL"), llmBaseUrl: take("HINDSIGHT_API_LLM_BASE_URL"),
|
|
183
381
|
});
|
|
184
382
|
const extra = [...env].map(([name, value]) => name + "=" + value);
|
|
185
383
|
if (extra.some(line => /[\r\n]/.test(line))) throw new Error("a multi-line environment value cannot be written to an env file");
|
|
186
|
-
return { config, key, extra };
|
|
384
|
+
return { config, key, extra, route };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Local LLM settings read from an existing llama.cpp server container. Throws when something would be lost. */
|
|
388
|
+
export function adoptedLocalLlmSettings(container, imageEnv, route, containerName = LOCAL_LLM_ID) {
|
|
389
|
+
const inherited = new Set(imageEnv);
|
|
390
|
+
const own = container.env.filter(line => !inherited.has(line)).map(line => line.split("=")[0]);
|
|
391
|
+
if (own.length) throw new Error("local LLM container '" + route.host + "' sets environment variables (" + own.join(", ") + "); pass them as llama-server arguments instead");
|
|
392
|
+
const models = container.mounts[0];
|
|
393
|
+
if (container.mounts.length !== 1 || models.type !== "bind") throw new Error("local LLM container '" + route.host + "' must bind-mount one models folder and nothing else");
|
|
394
|
+
const dir = models.destination.replace(/\/+$/, "");
|
|
395
|
+
const values = {};
|
|
396
|
+
const extra = [];
|
|
397
|
+
const args = container.cmd;
|
|
398
|
+
for (let i = 0; i < args.length; i++) {
|
|
399
|
+
const [flag, inline] = args[i].split(/=(.*)/s);
|
|
400
|
+
const name = LLM_ARG_NAMES[flag];
|
|
401
|
+
if (name) values[name] = inline ?? args[++i];
|
|
402
|
+
else extra.push(args[i]);
|
|
403
|
+
}
|
|
404
|
+
if (extra.some(arg => /\s/.test(arg))) throw new Error("a llama-server argument of '" + route.host + "' contains spaces");
|
|
405
|
+
const inModels = (path, label) => {
|
|
406
|
+
if (!path) return "";
|
|
407
|
+
if (!path.startsWith(dir + "/")) throw new Error(label + " " + path + " is not inside the mounted folder " + dir);
|
|
408
|
+
return path.slice(dir.length + 1);
|
|
409
|
+
};
|
|
410
|
+
const internal = Number(values["--port"] || LLM_PORT);
|
|
411
|
+
if (internal !== route.port) throw new Error("Hindsight calls port " + route.port + " but '" + route.host + "' listens on " + internal);
|
|
412
|
+
if (!values["--ctx-size"]) throw new Error("'" + route.host + "' has no --ctx-size; set one so the reflect token budget can be checked");
|
|
413
|
+
const alias = values["--alias"] || route.alias;
|
|
414
|
+
if (route.alias && alias !== route.alias) throw new Error("Hindsight asks for model '" + route.alias + "' but '" + route.host + "' serves '" + alias + "'");
|
|
415
|
+
const gpu = container.gpus.find(d => d.Driver === "nvidia" || (d.Capabilities || []).flat().includes("gpu"));
|
|
416
|
+
const gpus = !gpu ? "" : gpu.DeviceIDs?.length ? "device=" + gpu.DeviceIDs.join(",") : gpu.Count === -1 ? "all" : String(gpu.Count);
|
|
417
|
+
const parallel = values["--parallel"] ?? 1;
|
|
418
|
+
return normalizeLocalLlmConfig({
|
|
419
|
+
enabled: true, containerName, image: container.image, port: container.ports[internal + "/tcp"]?.[0]?.HostPort ?? LOCAL_LLM_DEFAULTS.port,
|
|
420
|
+
modelsDir: models.source, model: inModels(values["--model"], "the model"), lora: inModels(values["--lora"], "the LoRA adapter"),
|
|
421
|
+
alias, gpus, ctxSize: values["--ctx-size"], parallel, extraArgs: extra.join(" "), operations: route.operations,
|
|
422
|
+
maxConcurrent: route.maxConcurrent ?? parallel, timeout: route.timeout, maxContextTokens: route.maxContextTokens, maxCompletionTokens: route.maxCompletionTokens,
|
|
423
|
+
});
|
|
187
424
|
}
|
|
188
425
|
|
|
189
426
|
export async function imageId(image, run = execCommand) {
|
|
@@ -191,12 +428,12 @@ export async function imageId(image, run = execCommand) {
|
|
|
191
428
|
return result.exitCode === 0 ? result.stdout.trim() || null : null;
|
|
192
429
|
}
|
|
193
430
|
|
|
194
|
-
/** Long-running docker commands keep their output in the service log, not the terminal. */
|
|
195
|
-
export async function dockerLogged(id, args, run = execCommand, timeout = 0) {
|
|
431
|
+
/** Long-running docker commands keep their output in the service log, not the terminal. "run" logs only its image. */
|
|
432
|
+
export async function dockerLogged(id, args, run = execCommand, timeout = 0, image = args.at(-1)) {
|
|
196
433
|
ensureDir(getLogsDir());
|
|
197
434
|
const result = await run("docker", args, timeout);
|
|
198
435
|
try {
|
|
199
|
-
appendFileSync(getServiceLogPath(id), "\n[aih] " + new Date().toISOString() + " docker " + args[0] + " " + (args[0] === "run" ? "(" +
|
|
436
|
+
appendFileSync(getServiceLogPath(id), "\n[aih] " + new Date().toISOString() + " docker " + args[0] + " " + (args[0] === "run" ? "(" + image + ")" : args.slice(1).join(" "))
|
|
200
437
|
+ " -> exit " + result.exitCode + "\n" + result.stdout + result.stderr, "utf8");
|
|
201
438
|
} catch {}
|
|
202
439
|
return result;
|
|
@@ -233,11 +470,56 @@ export async function probeHindsightHealth(apiUrl, { fetchImpl = fetch, timeoutM
|
|
|
233
470
|
|
|
234
471
|
export function describeHealth(health) {
|
|
235
472
|
if (!health) return "not checked";
|
|
236
|
-
|
|
237
|
-
if (health.state === "
|
|
473
|
+
const llm = health.build || health.model ? " (" + [health.build && "llama.cpp " + health.build, health.model && "model " + health.model].filter(Boolean).join(", ") + ")" : "";
|
|
474
|
+
if (health.state === "healthy") return "healthy" + (health.version ? " v" + health.version : "") + llm + (health.database ? ", database " + health.database : "");
|
|
475
|
+
if (health.state === "degraded") return "unhealthy (HTTP " + health.httpStatus + (health.database ? ", database " + health.database : "") + (health.detail ? ", " + health.detail : "") + ")";
|
|
238
476
|
return "unreachable (" + health.error + ")";
|
|
239
477
|
}
|
|
240
478
|
|
|
479
|
+
/**
|
|
480
|
+
* llama.cpp server: /health answers 200 {"status":"ok"} once the model is loaded and 503 while
|
|
481
|
+
* loading; /props adds the build and the served model alias.
|
|
482
|
+
*/
|
|
483
|
+
export async function probeLocalLlmHealth(apiUrl, { fetchImpl = fetch, timeoutMs = 2000, now = Date.now } = {}) {
|
|
484
|
+
const checkedAt = now();
|
|
485
|
+
const url = new URL("/health", apiUrl).href;
|
|
486
|
+
const get = async path => {
|
|
487
|
+
const response = await fetchImpl(new URL(path, apiUrl).href, { signal: AbortSignal.timeout(timeoutMs) });
|
|
488
|
+
let body = null;
|
|
489
|
+
try { body = await response.json(); } catch {}
|
|
490
|
+
return { status: response.status, ok: response.ok, body: body && typeof body === "object" ? body : {} };
|
|
491
|
+
};
|
|
492
|
+
try {
|
|
493
|
+
const ready = await get("/health");
|
|
494
|
+
const healthy = ready.ok && (ready.body.status === undefined || ready.body.status === "ok");
|
|
495
|
+
const props = healthy ? await get("/props").catch(() => null) : null;
|
|
496
|
+
return {
|
|
497
|
+
state: healthy ? "healthy" : "degraded", httpStatus: ready.status, status: str(ready.body.status),
|
|
498
|
+
detail: healthy ? null : str(ready.body.error?.message)?.toLowerCase() || null,
|
|
499
|
+
version: null, build: str(props?.body?.build_info)?.split("-")[0] || null, model: str(props?.body?.model_alias),
|
|
500
|
+
url, checkedAt,
|
|
501
|
+
};
|
|
502
|
+
} catch (error) {
|
|
503
|
+
return { state: "unreachable", error: error?.name === "TimeoutError" ? "timeout" : error?.cause?.code || error?.message || String(error), url, checkedAt };
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** One-token completion: proves the model and adapter actually generate, not just that the server is up. */
|
|
508
|
+
export async function smokeTestLocalLlm(apiUrl, alias, { fetchImpl = fetch, timeoutMs = 120000 } = {}) {
|
|
509
|
+
try {
|
|
510
|
+
const response = await fetchImpl(new URL("/v1/chat/completions", apiUrl).href, {
|
|
511
|
+
method: "POST", headers: { "content-type": "application/json" }, signal: AbortSignal.timeout(timeoutMs),
|
|
512
|
+
body: JSON.stringify({ model: alias, messages: [{ role: "user", content: "ping" }], max_tokens: 1 }),
|
|
513
|
+
});
|
|
514
|
+
let body = null;
|
|
515
|
+
try { body = await response.json(); } catch {}
|
|
516
|
+
if (response.ok && Array.isArray(body?.choices)) return { ok: true };
|
|
517
|
+
return { ok: false, error: "HTTP " + response.status + (str(body?.error?.message) ? ": " + body.error.message : "") };
|
|
518
|
+
} catch (error) {
|
|
519
|
+
return { ok: false, error: error?.name === "TimeoutError" ? "timeout" : error?.cause?.code || error?.message || String(error) };
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
241
523
|
function portFree(port) {
|
|
242
524
|
return new Promise(resolve => {
|
|
243
525
|
const server = createServer();
|
|
@@ -247,7 +529,8 @@ function portFree(port) {
|
|
|
247
529
|
}
|
|
248
530
|
|
|
249
531
|
/** Read-only checks for the setup wizard; nothing is created, pulled or started. */
|
|
250
|
-
export async function preflightHindsight(config, { newKey = "", run = execCommand, probe = probeHindsightHealth,
|
|
532
|
+
export async function preflightHindsight(config, { newKey = "", run = execCommand, probe = probeHindsightHealth, probeLlm = probeLocalLlmHealth,
|
|
533
|
+
readKey = readHindsightApiKey, isPortFree = portFree, fileExists = existsSync } = {}) {
|
|
251
534
|
const checks = [];
|
|
252
535
|
const docker = await dockerInfo(run);
|
|
253
536
|
if (!docker.available) {
|
|
@@ -281,5 +564,43 @@ export async function preflightHindsight(config, { newKey = "", run = execComman
|
|
|
281
564
|
checks.push(await isPortFree(port) ? label + " port " + port + " available" : "Warning: " + label + " port " + port + " already in use");
|
|
282
565
|
}
|
|
283
566
|
}
|
|
567
|
+
if (config.localLlm?.enabled) checks.push(...await preflightLocalLlm(config, { run, probeLlm, isPortFree, fileExists }));
|
|
568
|
+
return checks;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async function preflightLocalLlm(config, { run, probeLlm, isPortFree, fileExists }) {
|
|
572
|
+
const llm = config.localLlm;
|
|
573
|
+
const checks = [];
|
|
574
|
+
for (const [label, file] of [["model", llm.model], ["LoRA adapter", llm.lora]]) {
|
|
575
|
+
if (!file) continue;
|
|
576
|
+
const path = join(llm.modelsDir, file);
|
|
577
|
+
checks.push(fileExists(path) ? "Local LLM " + label + " found: " + file : "Warning: local LLM " + label + " not found: " + path);
|
|
578
|
+
}
|
|
579
|
+
const refresh = llm.operations.includes("reflect") && !llm.operations.includes("mental_model_refresh") ? " (mental model refresh follows reflect)" : "";
|
|
580
|
+
checks.push("Local LLM handles: " + llm.operations.join(", ") + refresh + "; other operations use " + config.llmProvider + (config.llmModel ? " " + config.llmModel : ""));
|
|
581
|
+
if (llm.gpus) checks.push("Local LLM GPUs: --gpus " + llm.gpus + " (needs NVIDIA GPU support in Docker)");
|
|
582
|
+
if (config.envFile) {
|
|
583
|
+
let names = [];
|
|
584
|
+
try {
|
|
585
|
+
const managed = new Set(localLlmEnv(llm).map(line => line.split("=")[0]));
|
|
586
|
+
names = readFileSync(config.envFile, "utf8").split(/\r?\n/).map(line => line.split("=")[0].trim()).filter(name => managed.has(name));
|
|
587
|
+
} catch {}
|
|
588
|
+
if (names.length) checks.push("Warning: " + names.join(", ") + " in the extra environment file are replaced by the local LLM settings; remove them there");
|
|
589
|
+
}
|
|
590
|
+
let container = null;
|
|
591
|
+
try { container = await inspectContainer(llm.containerName, run); } catch (error) { checks.push("Warning: " + error.message); return checks; }
|
|
592
|
+
if (container) {
|
|
593
|
+
if (!container.managed) {
|
|
594
|
+
checks.push("Warning: container '" + llm.containerName + "' exists and was not created by aih; aih will not use it. Rename/remove it, or adopt the stack: 'aih update hindsight --adopt'");
|
|
595
|
+
return checks;
|
|
596
|
+
}
|
|
597
|
+
checks.push("Local LLM container '" + llm.containerName + "' " + container.status + ", created by aih");
|
|
598
|
+
if (container.configHash !== localLlmConfigHash(llm)) checks.push("Local LLM settings changed: aih recreates its container on the next start");
|
|
599
|
+
if (container.running) checks.push("Local LLM health: " + describeHealth(await probeLlm(localLlmUrls(llm).api)));
|
|
600
|
+
} else {
|
|
601
|
+
checks.push("Local LLM container '" + llm.containerName + "' not found: aih creates it on start");
|
|
602
|
+
checks.push(await imageId(llm.image, run) ? "Image " + llm.image + " present" : "Image " + llm.image + " not present: pulled on first start (may take minutes)");
|
|
603
|
+
checks.push(await isPortFree(llm.port) ? "Local LLM port " + llm.port + " available" : "Warning: local LLM port " + llm.port + " already in use");
|
|
604
|
+
}
|
|
284
605
|
return checks;
|
|
285
606
|
}
|