@drakonkat/ai-helper 1.2.16 → 1.2.18

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.
@@ -0,0 +1,256 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, writeFileSync, chmodSync, appendFileSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { createServer } from "node:net";
5
+ import { ensureDir, getAihDir, getLogsDir, getServiceLogPath } from "./utils/path.js";
6
+ import { execCommand } from "./utils/process.js";
7
+
8
+ /** Hindsight runs in Docker; these defaults match the upstream quick start. */
9
+ export const HINDSIGHT_DEFAULTS = Object.freeze({
10
+ containerName: "hindsight",
11
+ image: "ghcr.io/vectorize-io/hindsight:latest",
12
+ apiPort: 8888,
13
+ uiPort: 9999,
14
+ volume: "hindsight-data",
15
+ llmProvider: "openai",
16
+ llmModel: "",
17
+ llmBaseUrl: "",
18
+ envFile: "",
19
+ });
20
+ export const HINDSIGHT_RELEASES_URL = "https://api.github.com/repos/vectorize-io/hindsight/releases/latest";
21
+ export const HINDSIGHT_KEY_ENV = "HINDSIGHT_API_LLM_API_KEY";
22
+ const API_PORT = 8888;
23
+ const UI_PORT = 9999;
24
+ const DATA_DIR = "/home/hindsight/.pg0";
25
+ const NO_KEY_PROVIDERS = new Set(["ollama", "lmstudio"]);
26
+ const DOCKER_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/;
27
+ const CONTROL = /[\x00-\x1f\x7f-\x9f]/;
28
+
29
+ function port(value, label) {
30
+ const text = String(value ?? "").trim();
31
+ const number = Number(text);
32
+ if (!/^\d+$/.test(text) || !Number.isInteger(number) || number < 1 || number > 65535) {
33
+ throw new Error(label + ": enter a port between 1 and 65535");
34
+ }
35
+ return number;
36
+ }
37
+
38
+ /** Validates the non-secret settings; the API key never belongs in this object. */
39
+ export function normalizeHindsightConfig(input = {}) {
40
+ const value = { ...HINDSIGHT_DEFAULTS, ...Object.fromEntries(Object.entries(input || {}).filter(([, v]) => v !== undefined && v !== null)) };
41
+ const text = key => String(value[key] ?? "").trim();
42
+ const config = {
43
+ containerName: text("containerName"), image: text("image"), volume: text("volume"),
44
+ apiPort: port(value.apiPort, "Hindsight API port"), uiPort: port(value.uiPort, "Hindsight UI port"),
45
+ llmProvider: text("llmProvider").toLowerCase(), llmModel: text("llmModel"), llmBaseUrl: text("llmBaseUrl"),
46
+ envFile: text("envFile"),
47
+ };
48
+ if (!DOCKER_NAME.test(config.containerName)) throw new Error("Hindsight container name: letters, digits, '_', '.', '-' (max 128)");
49
+ if (!DOCKER_NAME.test(config.volume)) throw new Error("Hindsight data volume: letters, digits, '_', '.', '-' (max 128)");
50
+ if (!/^[a-z0-9][a-z0-9._\/:@-]{0,254}$/i.test(config.image)) throw new Error("Hindsight image: invalid Docker image reference");
51
+ if (config.apiPort === config.uiPort) throw new Error("Hindsight API and UI ports must differ");
52
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(config.llmProvider)) throw new Error("Hindsight LLM provider: lowercase letters, digits, '_' or '-'");
53
+ if (CONTROL.test(config.llmModel) || /\s/.test(config.llmModel) || config.llmModel.length > 200) throw new Error("Hindsight LLM model: no spaces or control characters");
54
+ if (config.llmBaseUrl) {
55
+ let url;
56
+ try { url = new URL(config.llmBaseUrl); } catch { throw new Error("Hindsight LLM base URL: enter an http(s) URL or leave empty"); }
57
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password) throw new Error("Hindsight LLM base URL: http(s) without credentials");
58
+ }
59
+ if (CONTROL.test(config.envFile)) throw new Error("Hindsight environment file: invalid path");
60
+ return config;
61
+ }
62
+
63
+ export function hindsightUrls(config) {
64
+ return { api: "http://127.0.0.1:" + config.apiPort, ui: "http://localhost:" + config.uiPort };
65
+ }
66
+
67
+ export function hindsightKeyFile() {
68
+ return join(getAihDir(), "hindsight.env");
69
+ }
70
+
71
+ /** Saved key first, then the environment of the process that runs docker. */
72
+ export function readHindsightApiKey({ file = hindsightKeyFile(), env = process.env } = {}) {
73
+ try {
74
+ if (existsSync(file)) {
75
+ const line = readFileSync(file, "utf8").split(/\r?\n/).find(l => l.startsWith(HINDSIGHT_KEY_ENV + "="));
76
+ const key = line?.slice(HINDSIGHT_KEY_ENV.length + 1);
77
+ if (key) return { key, source: "file" };
78
+ }
79
+ } catch {}
80
+ return env[HINDSIGHT_KEY_ENV] ? { key: env[HINDSIGHT_KEY_ENV], source: "env" } : { key: "", source: null };
81
+ }
82
+
83
+ export function validateHindsightApiKey(key) {
84
+ if (CONTROL.test(key) || /\s/.test(key)) throw new Error("Hindsight API key: no spaces or control characters");
85
+ return key;
86
+ }
87
+
88
+ /** Docker --env-file format: one KEY=value line, no quoting. Readable by the user only where supported. */
89
+ export function saveHindsightApiKey(key, file = hindsightKeyFile()) {
90
+ validateHindsightApiKey(key);
91
+ ensureDir(getAihDir());
92
+ writeFileSync(file, HINDSIGHT_KEY_ENV + "=" + key + "\n", { encoding: "utf8", mode: 0o600 });
93
+ try { chmodSync(file, 0o600); } catch {}
94
+ }
95
+
96
+ /** Fingerprint of everything that requires recreating the container (secrets are hashed). */
97
+ export function hindsightConfigHash(config, key = "") {
98
+ let extra = "";
99
+ try { if (config.envFile) extra = readFileSync(config.envFile, "utf8"); } catch {}
100
+ return createHash("sha256").update(JSON.stringify([config, key, extra])).digest("hex").slice(0, 16);
101
+ }
102
+
103
+ export function hindsightRunArgs(config, { configHash, keySource }) {
104
+ const args = ["run", "-d", "--name", config.containerName, "--restart", "unless-stopped", "--shm-size", "1g",
105
+ "-p", "127.0.0.1:" + config.apiPort + ":" + API_PORT, "-p", "127.0.0.1:" + config.uiPort + ":" + UI_PORT,
106
+ "-v", config.volume + ":" + DATA_DIR,
107
+ "--label", "io.aih.managed=true", "--label", "io.aih.config=" + configHash,
108
+ "-e", "HINDSIGHT_CP_DATAPLANE_API_URL=http://localhost:" + API_PORT,
109
+ "-e", "HINDSIGHT_API_LLM_PROVIDER=" + config.llmProvider];
110
+ if (config.llmModel) args.push("-e", "HINDSIGHT_API_LLM_MODEL=" + config.llmModel);
111
+ if (config.llmBaseUrl) args.push("-e", "HINDSIGHT_API_LLM_BASE_URL=" + config.llmBaseUrl);
112
+ if (config.envFile) args.push("--env-file", config.envFile);
113
+ // Never put the key on the command line: docker reads it from a file or its own environment.
114
+ if (keySource === "file") args.push("--env-file", hindsightKeyFile());
115
+ else if (keySource === "env") args.push("-e", HINDSIGHT_KEY_ENV);
116
+ args.push(config.image);
117
+ return args;
118
+ }
119
+
120
+ export function requiresApiKey(config) {
121
+ return !NO_KEY_PROVIDERS.has(config.llmProvider);
122
+ }
123
+
124
+ const firstLine = text => String(text || "").trim().split(/\r?\n/).find(Boolean) || "";
125
+
126
+ export function dockerError(result) {
127
+ return firstLine(result.stderr) || firstLine(result.stdout) || "docker exited with code " + result.exitCode;
128
+ }
129
+
130
+ export async function dockerInfo(run = execCommand) {
131
+ const result = await run("docker", ["version", "--format", "{{.Server.Version}}"], 10000);
132
+ const version = result.stdout.trim();
133
+ return result.exitCode === 0 && version ? { available: true, version }
134
+ : { available: false, error: /ENOENT/.test(result.stderr) ? "docker CLI not found" : dockerError(result) };
135
+ }
136
+
137
+ /** null when the container does not exist; throws when Docker itself is unavailable. */
138
+ export async function inspectContainer(name, run = execCommand, timeout = 5000) {
139
+ const result = await run("docker", ["container", "inspect", name], timeout);
140
+ if (result.exitCode !== 0) {
141
+ if (/no such (container|object)/i.test(result.stderr)) return null;
142
+ throw new Error(/ENOENT/.test(result.stderr) ? "docker CLI not found" : dockerError(result));
143
+ }
144
+ const [container] = JSON.parse(result.stdout);
145
+ const labels = container?.Config?.Labels || {};
146
+ const started = Date.parse(container?.State?.StartedAt);
147
+ return {
148
+ id: String(container?.Id || "").slice(0, 12),
149
+ imageId: container?.Image || null,
150
+ image: container?.Config?.Image || null,
151
+ status: container?.State?.Status || "unknown",
152
+ running: container?.State?.Running === true,
153
+ startedAt: Number.isFinite(started) && started > 0 ? new Date(started).toISOString() : undefined,
154
+ managed: labels["io.aih.managed"] === "true",
155
+ configHash: labels["io.aih.config"] || null,
156
+ composeProject: labels["com.docker.compose.project"] || null,
157
+ };
158
+ }
159
+
160
+ export async function imageId(image, run = execCommand) {
161
+ const result = await run("docker", ["image", "inspect", "--format", "{{.Id}}", image], 10000);
162
+ return result.exitCode === 0 ? result.stdout.trim() || null : null;
163
+ }
164
+
165
+ /** Long-running docker commands keep their output in the service log, not the terminal. */
166
+ export async function dockerLogged(id, args, run = execCommand, timeout = 0) {
167
+ ensureDir(getLogsDir());
168
+ const result = await run("docker", args, timeout);
169
+ try {
170
+ appendFileSync(getServiceLogPath(id), "\n[aih] " + new Date().toISOString() + " docker " + args[0] + " " + (args[0] === "run" ? "(" + args.at(-1) + ")" : args.slice(1).join(" "))
171
+ + " -> exit " + result.exitCode + "\n" + result.stdout + result.stderr, "utf8");
172
+ } catch {}
173
+ return result;
174
+ }
175
+
176
+ const str = value => typeof value === "string" ? value : null;
177
+
178
+ /**
179
+ * Reads /health (readiness, includes the database) and /health/live (version, uptime).
180
+ * HTTP 200 = healthy, any other HTTP answer = degraded, no answer = unreachable.
181
+ */
182
+ export async function probeHindsightHealth(apiUrl, { fetchImpl = fetch, timeoutMs = 2000, now = Date.now } = {}) {
183
+ const checkedAt = now();
184
+ const get = async path => {
185
+ const response = await fetchImpl(new URL(path, apiUrl).href, { signal: AbortSignal.timeout(timeoutMs) });
186
+ let body = null;
187
+ try { body = await response.json(); } catch {}
188
+ return { status: response.status, ok: response.ok, body: body && typeof body === "object" ? body : {} };
189
+ };
190
+ try {
191
+ const [ready, live] = await Promise.all([get("/health"), get("/health/live").catch(() => null)]);
192
+ const healthy = ready.ok && (ready.body.status === undefined || ready.body.status === "healthy");
193
+ return {
194
+ state: healthy ? "healthy" : "degraded", httpStatus: ready.status,
195
+ status: str(ready.body.status), database: str(ready.body.database),
196
+ version: str(live?.body?.version), uptimeSeconds: Number.isFinite(live?.body?.uptime_seconds) ? live.body.uptime_seconds : null,
197
+ url: new URL("/health", apiUrl).href, checkedAt,
198
+ };
199
+ } catch (error) {
200
+ return { state: "unreachable", error: error?.name === "TimeoutError" ? "timeout" : error?.cause?.code || error?.message || String(error),
201
+ url: new URL("/health", apiUrl).href, checkedAt };
202
+ }
203
+ }
204
+
205
+ export function describeHealth(health) {
206
+ if (!health) return "not checked";
207
+ if (health.state === "healthy") return "healthy" + (health.version ? " v" + health.version : "") + (health.database ? ", database " + health.database : "");
208
+ if (health.state === "degraded") return "unhealthy (HTTP " + health.httpStatus + (health.database ? ", database " + health.database : "") + ")";
209
+ return "unreachable (" + health.error + ")";
210
+ }
211
+
212
+ function portFree(port) {
213
+ return new Promise(resolve => {
214
+ const server = createServer();
215
+ server.once("error", () => resolve(false));
216
+ server.listen(port, "127.0.0.1", () => server.close(() => resolve(true)));
217
+ });
218
+ }
219
+
220
+ /** Read-only checks for the setup wizard; nothing is created, pulled or started. */
221
+ export async function preflightHindsight(config, { newKey = "", run = execCommand, probe = probeHindsightHealth, readKey = readHindsightApiKey, isPortFree = portFree } = {}) {
222
+ const checks = [];
223
+ const docker = await dockerInfo(run);
224
+ if (!docker.available) {
225
+ checks.push("Warning: Docker not available (" + docker.error + "); start Docker Desktop before starting Hindsight");
226
+ return checks;
227
+ }
228
+ checks.push("Docker " + docker.version + " available");
229
+ const saved = readKey();
230
+ if (newKey) checks.push("Hindsight API key: new value will be saved");
231
+ else if (saved.key) checks.push("Hindsight API key: " + (saved.source === "file" ? "saved" : "from " + HINDSIGHT_KEY_ENV));
232
+ else if (requiresApiKey(config)) checks.push("Warning: Hindsight API key missing; provider '" + config.llmProvider + "' requires one");
233
+ if (config.envFile) {
234
+ try {
235
+ if (!statSync(config.envFile).isFile()) throw new Error();
236
+ checks.push("Hindsight environment file readable");
237
+ } catch { checks.push("Warning: Hindsight environment file not found: " + config.envFile); }
238
+ }
239
+ let container = null;
240
+ try { container = await inspectContainer(config.containerName, run); } catch (error) { checks.push("Warning: " + error.message); }
241
+ if (container) {
242
+ const owner = container.managed ? "created by aih" : "not created by aih" + (container.composeProject ? " (compose project '" + container.composeProject + "')" : "") + "; it is reused as is and the settings above do not change it";
243
+ checks.push("Container '" + config.containerName + "' " + container.status + ", " + owner);
244
+ if (container.managed && container.configHash !== hindsightConfigHash(config, newKey || saved.key)) {
245
+ checks.push("Settings changed: aih recreates the container on its next start (data volume kept)");
246
+ }
247
+ if (container.running) checks.push("Health: " + describeHealth(await probe(hindsightUrls(config).api)));
248
+ } else {
249
+ checks.push("Container '" + config.containerName + "' not found: aih creates it on start");
250
+ checks.push(await imageId(config.image, run) ? "Image " + config.image + " present" : "Image " + config.image + " not present: pulled on first start (may take minutes)");
251
+ for (const [label, port] of [["API", config.apiPort], ["UI", config.uiPort]]) {
252
+ checks.push(await isPortFree(port) ? label + " port " + port + " available" : "Warning: " + label + " port " + port + " already in use");
253
+ }
254
+ }
255
+ return checks;
256
+ }
package/src/index.js CHANGED
@@ -34,7 +34,7 @@ ${bold("COMMANDS:")}
34
34
  ${yellow("status")}, ${yellow("ps")} [services...] Show status, PID, uptime, dashboards and repositories
35
35
  ${yellow("status -ui")} Interactive live dashboard: manage services and watch the AI pipeline
36
36
  ${yellow("open")}, ${yellow("dash")} [services...] Open web dashboard(s) directly in your default browser
37
- ${yellow("start")}, ${yellow("up")} [services...] Start ocx, agentmemory and the pxpipe proxy, or specified services
37
+ ${yellow("start")}, ${yellow("up")} [services...] Start ocx, hindsight and the pxpipe proxy, or specified services
38
38
  ${yellow("start proxy")} [upstream] Start HTTP/SSE/WebSocket proxy; first start requires upstream
39
39
  ${yellow("stop")}, ${yellow("down")} [services...] Stop all or specified services
40
40
  ${yellow("restart")} [services...] Restart all or specified services
@@ -50,7 +50,7 @@ ${bold("COMMANDS:")}
50
50
  ${yellow("help")}, ${yellow("-h")}, ${yellow("--help")} Show this help message
51
51
 
52
52
  Other aliases: status = ls/list; open = dashboard; logs = log.
53
- Service lists use spaces: ocx agentmemory. Omitting the command shows status.
53
+ Service lists use spaces: ocx hindsight. Omitting the command shows status.
54
54
 
55
55
  ${bold("SERVICES MANAGED:")}
56
56
  ${SERVICE_IDS.map(id => {
@@ -59,6 +59,15 @@ ${SERVICE_IDS.map(id => {
59
59
  }).join("\n")}
60
60
  ${cyan("proxy".padEnd(14))} Built-in HTTP/SSE/WebSocket proxy (no web dashboard)
61
61
 
62
+ ${bold("HINDSIGHT (DOCKER):")}
63
+ hindsight runs as a Docker container (default name: hindsight, image ghcr.io/vectorize-io/hindsight).
64
+ Requires Docker Desktop/Engine. start creates or starts the container and waits for /health;
65
+ stop runs docker stop (data stays in the hindsight-data volume); logs shows docker logs.
66
+ Configure container, ports, LLM provider/model/base URL and API key in status --ui (c),
67
+ after selecting hindsight in the Startup step. The key is kept in ~/.aih/hindsight.env;
68
+ HINDSIGHT_API_LLM_API_KEY from the environment is used when no key is saved.
69
+ update pulls the image and recreates only containers created by aih.
70
+
62
71
  ${bold("OPTIONS:")}
63
72
  ${gray("-n, --lines <num>")} Number of log lines to show (logs only; default: 50)
64
73
  ${gray("-f, --follow")} Follow log output in real-time (logs only)
@@ -84,7 +93,7 @@ ${bold("PROXY OPTIONS (start/up/restart proxy):")}
84
93
 
85
94
  ${bold("START DEFAULTS AND MODEL VALUES:")}
86
95
  Without service targets, start/up uses the Startup selection saved in status --ui setup.
87
- Until configured, it launches ocx, agentmemory, then proxy with:
96
+ Until configured, it launches ocx, hindsight, then proxy with:
88
97
  upstream: http://127.0.0.1:10100/ listen: http://127.0.0.1:10102 preset: pxpipe
89
98
  models: gpt-6-astra,google-antigravity/gemini-3.8*,anthropic/claude-fable*
90
99
  config pxpipe-models=<list> saves a replacement list; --models overrides it.
@@ -98,7 +107,7 @@ ${bold("START DEFAULTS AND MODEL VALUES:")}
98
107
  ${bold("SELF AND SERVICE UPDATES:")}
99
108
  'update' without targets updates aih's global npm installation, not managed services.
100
109
  Standalone executables must be rebuilt; npm updates do not replace them.
101
- To update all managed services: aih update pxpipe ocx agentmemory headroom
110
+ To update all managed services: aih update pxpipe ocx hindsight headroom
102
111
  In the live dashboard, select a service with up/down and press u to update it.
103
112
  Only running services are restarted; stopped services stay stopped.
104
113
 
@@ -110,7 +119,7 @@ ${bold("EXAMPLES - STATUS, DASHBOARDS AND LOGS:")}
110
119
  ${dim("$")} ${cyan("npx @drakonkat/ai-helper")} status
111
120
  ${dim("$")} ${cyan(CLI_NAME)} status ocx proxy --json
112
121
  ${dim("$")} ${cyan(CLI_NAME)} status --ui
113
- ${dim("$")} ${cyan(CLI_NAME)} open agentmemory
122
+ ${dim("$")} ${cyan(CLI_NAME)} open hindsight
114
123
  ${dim("$")} ${cyan(CLI_NAME)} open ocx proxy --repo
115
124
  ${dim("$")} ${cyan(CLI_NAME)} logs proxy --lines 100 --follow
116
125
  ${dim("$")} ${cyan(CLI_NAME)} logs ocx -n=20
@@ -123,12 +132,12 @@ ${bold("EXAMPLES - START, STOP AND UPDATE:")}
123
132
  ${dim("$")} ${cyan(CLI_NAME)} start --models "gpt-6-astra,anthropic/claude-fable*" --json
124
133
  ${dim("$")} ${cyan(CLI_NAME)} up --models="google-antigravity/gemini-3.8*"
125
134
  ${dim("$")} ${cyan(CLI_NAME)} start --models= ${dim("# Use pxpipe's default model selection")}
126
- ${dim("$")} ${cyan(CLI_NAME)} start ocx agentmemory
127
- ${dim("$")} ${cyan(CLI_NAME)} stop ocx agentmemory proxy
135
+ ${dim("$")} ${cyan(CLI_NAME)} start ocx hindsight
136
+ ${dim("$")} ${cyan(CLI_NAME)} stop ocx hindsight proxy
128
137
  ${dim("$")} ${cyan(CLI_NAME)} restart ocx --json
129
138
  ${dim("$")} ${cyan(CLI_NAME)} update ${dim("# Update aih itself from npm")}
130
139
  ${dim("$")} ${cyan(CLI_NAME)} ocx update
131
- ${dim("$")} ${cyan(CLI_NAME)} update ocx agentmemory --json
140
+ ${dim("$")} ${cyan(CLI_NAME)} update ocx hindsight --json
132
141
  ${dim("$")} ${cyan(CLI_NAME)} install ${dim("# Build/install standalone binary; requires Bun")}
133
142
 
134
143
  ${bold("EXAMPLES - PROXY CONFIGURATION:")}
@@ -151,6 +160,12 @@ function printCodexConfig(result) {
151
160
  if (config?.message) console.log((config.status === "warning" ? yellow : dim)(` ${config.message}`));
152
161
  }
153
162
 
163
+ /** Host processes have a PID; Docker services have a container and a health result. */
164
+ function startedDetail(result) {
165
+ if (result.pid) return `PID: ${result.pid}`;
166
+ return [result.containerId && `container ${result.containerId}`, result.health?.state && `health: ${result.health.state}`].filter(Boolean).join(", ") || "-";
167
+ }
168
+
154
169
  async function runInstall() {
155
170
  printBanner();
156
171
  console.log(cyan("⚙ Building standalone binary and installing to ~/.local/bin...\n"));
@@ -479,9 +494,9 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
479
494
  if (jsonOutput) continue;
480
495
  if (res.success) {
481
496
  if (res.alreadyRunning) {
482
- console.log(yellow(`already running (PID: ${res.pid})`));
497
+ console.log(yellow(`already running (${startedDetail(res)})`));
483
498
  } else {
484
- console.log(green(`started (PID: ${res.pid})`));
499
+ console.log(green(`started (${startedDetail(res)})`));
485
500
  }
486
501
  } else {
487
502
  console.log(red(`failed: ${res.message}`));
@@ -523,7 +538,7 @@ export async function main({ updateSelfImpl = updateSelf } = {}) {
523
538
  results.push({ id, ...res });
524
539
  if (jsonOutput) continue;
525
540
  if (res.success) {
526
- console.log(green(`started (PID: ${res.pid})`));
541
+ console.log(green(`started (${startedDetail(res)})`));
527
542
  } else {
528
543
  console.log(red(`failed: ${res.message}`));
529
544
  }