@drakonkat/ai-helper 1.2.17 → 1.2.19
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 +21 -4
- package/CHANGELOG.md +28 -0
- package/README.md +131 -40
- package/package.json +5 -4
- package/src/config.js +12 -12
- package/src/health.js +81 -0
- package/src/hindsight.js +285 -0
- package/src/index.js +34 -14
- package/src/manager.js +350 -9
- package/src/proxy.js +10 -0
- package/src/startup-services.js +5 -2
- package/src/tui-proxy-setup.js +81 -9
- package/src/tui.js +155 -93
- package/src/utils/metrics.js +3 -3
- package/src/utils/process.js +7 -65
- package/src/utils/versions.js +16 -3
package/src/manager.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, readFileSync, writeFileSync, statSync, openSync, readSync, closeSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync, statSync, openSync, readSync, closeSync, readdirSync, rmSync } from "node:fs";
|
|
2
2
|
import { execFileSync, spawn } from "node:child_process";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { join } from "node:path";
|
|
@@ -9,6 +9,27 @@ import { SERVICES, SERVICE_IDS, SERVICE_PACKAGES, APP_REPOSITORY_URL } from "./c
|
|
|
9
9
|
import { compareVersions, getServiceVersions } from "./utils/versions.js";
|
|
10
10
|
import { installServiceUpdate, serviceStartCommand } from "./service-updates.js";
|
|
11
11
|
import { configureCodexForProxy } from "./codex-routing.js";
|
|
12
|
+
import {
|
|
13
|
+
HINDSIGHT_DEFAULTS,
|
|
14
|
+
HINDSIGHT_REPOSITORY,
|
|
15
|
+
adoptedHindsightSettings,
|
|
16
|
+
describeHealth,
|
|
17
|
+
dockerInfo,
|
|
18
|
+
dockerLogged,
|
|
19
|
+
hindsightConfigHash,
|
|
20
|
+
hindsightRunArgs,
|
|
21
|
+
hindsightUrls,
|
|
22
|
+
imageId,
|
|
23
|
+
inspectContainer,
|
|
24
|
+
normalizeHindsightConfig,
|
|
25
|
+
probeHindsightHealth,
|
|
26
|
+
readHindsightApiKey,
|
|
27
|
+
requiresApiKey,
|
|
28
|
+
saveHindsightApiKey,
|
|
29
|
+
validateHindsightApiKey,
|
|
30
|
+
HINDSIGHT_KEY_ENV,
|
|
31
|
+
dockerError,
|
|
32
|
+
} from "./hindsight.js";
|
|
12
33
|
import { ensureDir, getAihDir, getLogsDir, getServiceLogPath, getStateFilePath } from "./utils/path.js";
|
|
13
34
|
import {
|
|
14
35
|
isPidRunning,
|
|
@@ -22,11 +43,29 @@ import {
|
|
|
22
43
|
} from "./utils/process.js";
|
|
23
44
|
import { formatBytes, formatUptime, gray, red, yellow, green, cyan } from "./utils/format.js";
|
|
24
45
|
|
|
46
|
+
const isDocker = id => SERVICES[id]?.runtime === "docker";
|
|
47
|
+
|
|
25
48
|
export class ServiceManager {
|
|
26
49
|
updatesInProgress = new Set();
|
|
50
|
+
/** Injectable for tests: (cmd, args, timeoutMs) => { exitCode, stdout, stderr }. */
|
|
51
|
+
runDocker = execCommand;
|
|
52
|
+
probeHealth = probeHindsightHealth;
|
|
53
|
+
hindsightStartTimeoutMs = 180000;
|
|
54
|
+
hindsightPollMs = 1000;
|
|
55
|
+
dockerRetryAt = 0;
|
|
56
|
+
|
|
57
|
+
/** Saved Hindsight settings; invalid saved values fall back to defaults unless strict. */
|
|
58
|
+
hindsightConfig(state = this.readState(), { strict = false } = {}) {
|
|
59
|
+
try { return normalizeHindsightConfig(state.config?.hindsight); }
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (strict) throw error;
|
|
62
|
+
return normalizeHindsightConfig(HINDSIGHT_DEFAULTS);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
27
65
|
|
|
28
66
|
/** Explicit update: fresh check, stop if needed, install, verify, restore runtime state. */
|
|
29
|
-
async updateService(serviceId, { getVersions = getServiceVersions, install = installServiceUpdate } = {}) {
|
|
67
|
+
async updateService(serviceId, { getVersions = getServiceVersions, install = installServiceUpdate, adopt = false } = {}) {
|
|
68
|
+
if (isDocker(serviceId)) return this.updateDockerService(serviceId, { getVersions, adopt });
|
|
30
69
|
if (!Object.hasOwn(SERVICE_PACKAGES, serviceId)) {
|
|
31
70
|
return { success: false, message: serviceId === "proxy"
|
|
32
71
|
? "The built-in proxy is part of ai-helper; update ai-helper itself to update it."
|
|
@@ -143,6 +182,9 @@ export class ServiceManager {
|
|
|
143
182
|
state = { services: {}, updatedAt: new Date().toISOString() };
|
|
144
183
|
}
|
|
145
184
|
}
|
|
185
|
+
state.services ||= {};
|
|
186
|
+
// agentmemory was replaced by Hindsight; never manage or stop a leftover entry.
|
|
187
|
+
delete state.services.agentmemory;
|
|
146
188
|
|
|
147
189
|
for (const id of SERVICE_IDS) {
|
|
148
190
|
const def = SERVICES[id];
|
|
@@ -171,6 +213,10 @@ export class ServiceManager {
|
|
|
171
213
|
const discovered = await discoverRunningProcesses({ knownServices: state.services });
|
|
172
214
|
|
|
173
215
|
for (const id of Object.keys(state.services)) {
|
|
216
|
+
if (isDocker(id)) {
|
|
217
|
+
if (await this.syncDockerService(state, id)) needsSave = true;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
174
220
|
const svc = state.services[id];
|
|
175
221
|
const info = discovered[id];
|
|
176
222
|
|
|
@@ -210,6 +256,37 @@ export class ServiceManager {
|
|
|
210
256
|
return state;
|
|
211
257
|
}
|
|
212
258
|
|
|
259
|
+
/** Container state replaces PID tracking; Docker's port proxies are not the service. */
|
|
260
|
+
async syncDockerService(state, id) {
|
|
261
|
+
const svc = state.services[id] || {};
|
|
262
|
+
const config = this.hindsightConfig(state);
|
|
263
|
+
const urls = hindsightUrls(config);
|
|
264
|
+
let container = null;
|
|
265
|
+
let runtimeError;
|
|
266
|
+
if (Date.now() < this.dockerRetryAt) runtimeError = svc.runtimeError || "Docker not available";
|
|
267
|
+
else {
|
|
268
|
+
try { container = await inspectContainer(config.containerName, this.runDocker); }
|
|
269
|
+
catch (error) {
|
|
270
|
+
runtimeError = error.message;
|
|
271
|
+
// A stopped Docker Desktop must not stall every one-second dashboard refresh.
|
|
272
|
+
this.dockerRetryAt = Date.now() + 10000;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (!runtimeError) this.dockerRetryAt = 0;
|
|
276
|
+
const next = {
|
|
277
|
+
id, name: SERVICES[id].name, runtime: "docker",
|
|
278
|
+
command: `docker container ${config.containerName} (${container?.image || config.image})`,
|
|
279
|
+
status: container?.running ? "running" : "stopped",
|
|
280
|
+
startedAt: container?.running ? container.startedAt : undefined,
|
|
281
|
+
url: urls.ui, apiUrl: urls.api, containerName: config.containerName,
|
|
282
|
+
containerId: container?.id, containerStatus: container ? container.status : runtimeError ? undefined : "missing",
|
|
283
|
+
managed: container ? container.managed : undefined, runtimeError,
|
|
284
|
+
};
|
|
285
|
+
if (JSON.stringify(next) === JSON.stringify(svc)) return false;
|
|
286
|
+
state.services[id] = next;
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
|
|
213
290
|
/**
|
|
214
291
|
* Synchronous load with PID liveness check.
|
|
215
292
|
*/
|
|
@@ -219,7 +296,7 @@ export class ServiceManager {
|
|
|
219
296
|
|
|
220
297
|
for (const id of Object.keys(state.services)) {
|
|
221
298
|
const svc = state.services[id];
|
|
222
|
-
if (svc.status === "running") {
|
|
299
|
+
if (svc.status === "running" && !isDocker(id)) {
|
|
223
300
|
if (!svc.pid || !isPidRunning(svc.pid)) {
|
|
224
301
|
svc.status = "stopped";
|
|
225
302
|
svc.pid = undefined;
|
|
@@ -336,6 +413,7 @@ export class ServiceManager {
|
|
|
336
413
|
*/
|
|
337
414
|
async startService(serviceId, options) {
|
|
338
415
|
if (serviceId === "proxy") return this.startProxyService(options);
|
|
416
|
+
if (isDocker(serviceId)) return this.startDockerService(serviceId);
|
|
339
417
|
const def = SERVICES[serviceId];
|
|
340
418
|
if (!def) {
|
|
341
419
|
return { success: false, message: `Unknown service '${serviceId}'. Available: ${SERVICE_IDS.join(", ")}` };
|
|
@@ -398,6 +476,243 @@ export class ServiceManager {
|
|
|
398
476
|
};
|
|
399
477
|
}
|
|
400
478
|
|
|
479
|
+
/** Starts (or creates) the Hindsight container and reports success only after /health. */
|
|
480
|
+
async startDockerService(id) {
|
|
481
|
+
const state = this.readState();
|
|
482
|
+
let config;
|
|
483
|
+
try { config = this.hindsightConfig(state, { strict: true }); }
|
|
484
|
+
catch (error) { return { success: false, message: `Invalid Hindsight settings: ${error.message}. Fix them with 'aih status --ui' (c).` }; }
|
|
485
|
+
const urls = hindsightUrls(config);
|
|
486
|
+
const base = { url: urls.ui, apiUrl: urls.api, containerName: config.containerName };
|
|
487
|
+
const docker = await dockerInfo(this.runDocker);
|
|
488
|
+
if (!docker.available) return { ...base, success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
|
|
489
|
+
this.dockerRetryAt = 0;
|
|
490
|
+
const key = readHindsightApiKey();
|
|
491
|
+
const configHash = hindsightConfigHash(config, key.key);
|
|
492
|
+
let container;
|
|
493
|
+
try { container = await inspectContainer(config.containerName, this.runDocker, 10000); }
|
|
494
|
+
catch (error) { return { ...base, success: false, message: `Cannot inspect the Hindsight container: ${error.message}` }; }
|
|
495
|
+
if (container?.running) {
|
|
496
|
+
const health = await this.probeHealth(urls.api);
|
|
497
|
+
await this.syncState();
|
|
498
|
+
const pending = container.managed && container.configHash !== configHash ? " Saved settings differ: restart it to apply them." : "";
|
|
499
|
+
return { ...base, success: true, alreadyRunning: true, containerId: container.id, health,
|
|
500
|
+
message: `Hindsight container '${config.containerName}' already running | health: ${describeHealth(health)}.${pending}` };
|
|
501
|
+
}
|
|
502
|
+
let action;
|
|
503
|
+
if (container?.managed && container.configHash !== configHash) {
|
|
504
|
+
// Settings changed: recreate it. The named volume keeps the memory data.
|
|
505
|
+
const removed = await dockerLogged(id, ["rm", config.containerName], this.runDocker, 60000);
|
|
506
|
+
if (removed.exitCode !== 0) return { ...base, success: false, message: `Cannot recreate the Hindsight container: ${dockerError(removed)}` };
|
|
507
|
+
container = null;
|
|
508
|
+
action = "recreated";
|
|
509
|
+
}
|
|
510
|
+
if (container) {
|
|
511
|
+
const started = await dockerLogged(id, ["start", config.containerName], this.runDocker, 120000);
|
|
512
|
+
if (started.exitCode !== 0) return { ...base, success: false, message: `docker start failed: ${dockerError(started)}. See 'aih logs hindsight'.` };
|
|
513
|
+
action = "started";
|
|
514
|
+
} else {
|
|
515
|
+
if (!key.key && requiresApiKey(config)) {
|
|
516
|
+
return { ...base, success: false, message: `Hindsight needs an LLM API key for provider '${config.llmProvider}': set it with 'aih status --ui' (c) or export ${HINDSIGHT_KEY_ENV}.` };
|
|
517
|
+
}
|
|
518
|
+
if (!(await imageId(config.image, this.runDocker))) {
|
|
519
|
+
const pulled = await dockerLogged(id, ["pull", config.image], this.runDocker, 30 * 60000);
|
|
520
|
+
if (pulled.exitCode !== 0) return { ...base, success: false, message: `docker pull ${config.image} failed: ${dockerError(pulled)}` };
|
|
521
|
+
}
|
|
522
|
+
const created = await dockerLogged(id, hindsightRunArgs(config, { configHash, keySource: key.source }), this.runDocker, 120000);
|
|
523
|
+
if (created.exitCode !== 0) return { ...base, success: false, message: `docker run failed: ${dockerError(created)}` };
|
|
524
|
+
action ||= "created";
|
|
525
|
+
}
|
|
526
|
+
const health = await this.waitForHindsight(config);
|
|
527
|
+
const synced = (await this.syncState()).services[id];
|
|
528
|
+
if (health.state !== "healthy") {
|
|
529
|
+
return { ...base, success: false, containerId: synced?.containerId, health,
|
|
530
|
+
message: `Hindsight container ${action}, but /health is ${describeHealth(health)}. Check 'aih logs hindsight'.` };
|
|
531
|
+
}
|
|
532
|
+
return { ...base, success: true, containerId: synced?.containerId, health,
|
|
533
|
+
message: `Hindsight container '${config.containerName}' ${action}; health: ${describeHealth(health)}` };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** First boots initialize the database and download models: poll until healthy, exited or timed out. */
|
|
537
|
+
async waitForHindsight(config) {
|
|
538
|
+
const deadline = Date.now() + this.hindsightStartTimeoutMs;
|
|
539
|
+
const api = hindsightUrls(config).api;
|
|
540
|
+
for (let attempt = 0; ; attempt++) {
|
|
541
|
+
const health = await this.probeHealth(api);
|
|
542
|
+
if (health.state === "healthy" || Date.now() >= deadline) return health;
|
|
543
|
+
if (attempt % 5 === 4) {
|
|
544
|
+
const container = await inspectContainer(config.containerName, this.runDocker).catch(() => null);
|
|
545
|
+
if (!container?.running) return { ...health, state: "unreachable", error: `container ${container?.status || "missing"}` };
|
|
546
|
+
}
|
|
547
|
+
await sleep(this.hindsightPollMs);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
async stopDockerService(id) {
|
|
552
|
+
const config = this.hindsightConfig();
|
|
553
|
+
// Never kill port owners: on Windows they are Docker Desktop's own processes.
|
|
554
|
+
const result = await dockerLogged(id, ["stop", config.containerName], this.runDocker, 60000);
|
|
555
|
+
await this.syncState();
|
|
556
|
+
if (result.exitCode !== 0 && !/no such container/i.test(result.stderr)) {
|
|
557
|
+
return { success: false, message: `docker stop ${config.containerName} failed: ${dockerError(result)}` };
|
|
558
|
+
}
|
|
559
|
+
return { success: true, message: `Hindsight container '${config.containerName}' stopped (data kept)` };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Pull, back up the data, then recreate. Only containers aih created are replaced:
|
|
564
|
+
* any other container belongs to its owner until the user explicitly adopts it.
|
|
565
|
+
*/
|
|
566
|
+
async updateDockerService(id, { getVersions = getServiceVersions, adopt = false } = {}) {
|
|
567
|
+
if (this.updatesInProgress.has(id)) return { success: false, message: `An update for '${id}' is already in progress` };
|
|
568
|
+
this.updatesInProgress.add(id);
|
|
569
|
+
try {
|
|
570
|
+
const config = this.hindsightConfig(this.readState(), { strict: true });
|
|
571
|
+
const name = config.containerName;
|
|
572
|
+
const docker = await dockerInfo(this.runDocker);
|
|
573
|
+
if (!docker.available) return { success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
|
|
574
|
+
const container = await inspectContainer(name, this.runDocker, 10000);
|
|
575
|
+
if (container && !container.managed) {
|
|
576
|
+
if (adopt) return await this.adoptDockerService(id, name, container);
|
|
577
|
+
return { success: false, adoptable: true, message: `Container '${name}' was not created by aih${container.composeProject ? ` (docker compose project '${container.composeProject}')` : ""}. To adopt it run 'aih update ${id} --adopt' (dashboard: press u again): aih imports its settings and recreates it on the same data volume.` };
|
|
578
|
+
}
|
|
579
|
+
const previousVersion = container?.running ? (await this.probeHealth(hindsightUrls(config).api)).version ?? null : null;
|
|
580
|
+
// A release tag of the official image moves to the latest GitHub release; any other tag is pulled again.
|
|
581
|
+
const tag = config.image.startsWith(HINDSIGHT_REPOSITORY + ":") ? config.image.slice(HINDSIGHT_REPOSITORY.length + 1) : "";
|
|
582
|
+
let image = config.image;
|
|
583
|
+
if (compareVersions(tag, tag) !== null) {
|
|
584
|
+
const latest = (await getVersions([{ id }]))[id]?.latestVersion;
|
|
585
|
+
const comparison = compareVersions(tag, latest);
|
|
586
|
+
if (comparison === null) return { success: false, previousVersion, message: "Cannot determine the latest Hindsight release; no changes made. Check your connection and retry." };
|
|
587
|
+
if (comparison >= 0) {
|
|
588
|
+
return { success: true, updated: false, alreadyUpToDate: true, previousVersion, version: previousVersion,
|
|
589
|
+
message: `'${id}' is already up to date (${config.image})` };
|
|
590
|
+
}
|
|
591
|
+
image = HINDSIGHT_REPOSITORY + ":" + latest;
|
|
592
|
+
}
|
|
593
|
+
const pulled = await dockerLogged(id, ["pull", image], this.runDocker, 30 * 60000);
|
|
594
|
+
if (pulled.exitCode !== 0) return { success: false, previousVersion, message: `docker pull ${image} failed: ${dockerError(pulled)}` };
|
|
595
|
+
const saveImage = () => { if (image !== config.image) this.saveHindsightConfiguration({ config: { ...config, image } }); };
|
|
596
|
+
if (!container) {
|
|
597
|
+
saveImage();
|
|
598
|
+
return { success: true, updated: true, previousVersion, message: `Image ${image} pulled; the container is created on the next start` };
|
|
599
|
+
}
|
|
600
|
+
const pulledImage = await imageId(image, this.runDocker);
|
|
601
|
+
if (image === config.image && pulledImage && pulledImage === container.imageId) {
|
|
602
|
+
return { success: true, updated: false, alreadyUpToDate: true, previousVersion, version: previousVersion,
|
|
603
|
+
message: `'${id}' already uses the latest ${image}` };
|
|
604
|
+
}
|
|
605
|
+
// Stop first: the archive needs a quiet database, and 'rm -f' would SIGKILL it.
|
|
606
|
+
const stopped = await dockerLogged(id, ["stop", name], this.runDocker, 60000);
|
|
607
|
+
const backup = stopped.exitCode === 0 ? await this.backupHindsightVolume(id, config.volume, container.imageId)
|
|
608
|
+
: { success: false, message: dockerError(stopped) };
|
|
609
|
+
const removed = backup.success ? await dockerLogged(id, ["rm", name], this.runDocker, 60000) : null;
|
|
610
|
+
if (removed?.exitCode !== 0) {
|
|
611
|
+
if (container.running) await dockerLogged(id, ["start", name], this.runDocker, 120000);
|
|
612
|
+
await this.syncState();
|
|
613
|
+
return { success: false, previousVersion, message: (backup.success ? `Cannot replace the container: ${dockerError(removed)}`
|
|
614
|
+
: `Data backup failed: ${backup.message}`) + "; the current container is kept" };
|
|
615
|
+
}
|
|
616
|
+
saveImage();
|
|
617
|
+
if (!container.running) {
|
|
618
|
+
await this.syncState();
|
|
619
|
+
return { success: true, updated: true, restarted: false, previousVersion, backup: backup.path,
|
|
620
|
+
message: `Image ${image} updated; the container is recreated on the next start (data backup: ${backup.path})` };
|
|
621
|
+
}
|
|
622
|
+
const started = await this.startDockerService(id);
|
|
623
|
+
const version = started.health?.version ?? null;
|
|
624
|
+
return { ...started, updated: true, restarted: started.success, previousVersion, version, backup: backup.path,
|
|
625
|
+
message: (started.success ? `'${id}' updated${previousVersion && version ? ` from ${previousVersion} to ${version}` : ""} and restarted`
|
|
626
|
+
: `Image updated, but restart failed: ${started.message}`) + ` (data backup: ${backup.path})` };
|
|
627
|
+
} catch (error) {
|
|
628
|
+
return { success: false, message: `Update failed: ${error.message}` };
|
|
629
|
+
} finally {
|
|
630
|
+
this.updatesInProgress.delete(id);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Archives a stopped container's data volume in ~/.aih/backups, keeping the two most recent archives. */
|
|
635
|
+
async backupHindsightVolume(id, volume, image) {
|
|
636
|
+
const dir = join(getAihDir(), "backups");
|
|
637
|
+
ensureDir(dir);
|
|
638
|
+
const file = `hindsight-${new Date().toISOString().replace(/[-:]|\..*/g, "")}.tgz`;
|
|
639
|
+
// The container's own image already has tar: nothing else to pull. Root, so the archive is writable on Linux.
|
|
640
|
+
const result = await dockerLogged(id, ["run", "--rm", "--user", "0", "--entrypoint", "tar", "-v", volume + ":/d:ro", "-v", dir + ":/b",
|
|
641
|
+
image, "czf", "/b/" + file, "-C", "/d", "."], this.runDocker, 30 * 60000);
|
|
642
|
+
if (result.exitCode !== 0) {
|
|
643
|
+
rmSync(join(dir, file), { force: true });
|
|
644
|
+
return { success: false, message: dockerError(result) };
|
|
645
|
+
}
|
|
646
|
+
for (const old of readdirSync(dir).filter(f => /^hindsight-.*\.tgz$/.test(f)).sort().slice(0, -2)) rmSync(join(dir, old), { force: true });
|
|
647
|
+
return { success: true, path: join(dir, file) };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Takes over a container aih did not create: imports its settings, then recreates it on the same volume. */
|
|
651
|
+
async adoptDockerService(id, name, container) {
|
|
652
|
+
const refuse = reason => ({ success: false, message: `Cannot adopt container '${name}': ${reason}. Nothing was changed.` });
|
|
653
|
+
// Variables already defined by the image are not settings: importing them would pin them across updates.
|
|
654
|
+
const imageEnv = await this.runDocker("docker", ["image", "inspect", "--format", "{{json .Config.Env}}", container.imageId], 10000);
|
|
655
|
+
if (imageEnv.exitCode !== 0) return refuse(dockerError(imageEnv));
|
|
656
|
+
let adopted;
|
|
657
|
+
try { adopted = adoptedHindsightSettings(name, container, JSON.parse(imageEnv.stdout) || []); }
|
|
658
|
+
catch (error) { return refuse(error.message); }
|
|
659
|
+
if (!adopted.key && !readHindsightApiKey().key && requiresApiKey(adopted.config)) {
|
|
660
|
+
return refuse(`it has no LLM API key for provider '${adopted.config.llmProvider}'; save one in setup (c) first`);
|
|
661
|
+
}
|
|
662
|
+
const envFile = adopted.extra.length ? join(getAihDir(), "hindsight-extra.env") : "";
|
|
663
|
+
if (envFile) {
|
|
664
|
+
ensureDir(getAihDir());
|
|
665
|
+
writeFileSync(envFile, adopted.extra.join("\n") + "\n", { encoding: "utf8", mode: 0o600 });
|
|
666
|
+
}
|
|
667
|
+
this.saveHindsightConfiguration({ config: { ...adopted.config, envFile }, apiKey: adopted.key });
|
|
668
|
+
const stopped = await dockerLogged(id, ["stop", name], this.runDocker, 60000);
|
|
669
|
+
const removed = stopped.exitCode === 0 ? await dockerLogged(id, ["rm", name], this.runDocker, 60000) : stopped;
|
|
670
|
+
if (removed.exitCode !== 0) {
|
|
671
|
+
if (container.running) await dockerLogged(id, ["start", name], this.runDocker, 120000);
|
|
672
|
+
await this.syncState();
|
|
673
|
+
return { success: false, message: `Settings imported, but the container could not be replaced: ${dockerError(removed)}` };
|
|
674
|
+
}
|
|
675
|
+
const kept = `data volume '${adopted.config.volume}' kept`;
|
|
676
|
+
if (!container.running) {
|
|
677
|
+
await this.syncState();
|
|
678
|
+
return { success: true, adopted: true, message: `Container '${name}' adopted; aih recreates it on the next start (${kept})` };
|
|
679
|
+
}
|
|
680
|
+
const started = await this.startDockerService(id);
|
|
681
|
+
return { ...started, adopted: true, message: started.success
|
|
682
|
+
? `Container '${name}' adopted and recreated by aih (${kept}; ${describeHealth(started.health)}). Update it with u or 'aih update ${id}'.`
|
|
683
|
+
: `Settings imported and old container removed, but the new one failed: ${started.message}` };
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Non-secret settings go to state.json; the key only to ~/.aih/hindsight.env. */
|
|
687
|
+
saveHindsightConfiguration({ config, apiKey = "" } = {}) {
|
|
688
|
+
const normalized = normalizeHindsightConfig(config);
|
|
689
|
+
if (apiKey) {
|
|
690
|
+
validateHindsightApiKey(apiKey);
|
|
691
|
+
saveHindsightApiKey(apiKey);
|
|
692
|
+
}
|
|
693
|
+
const state = this.readState();
|
|
694
|
+
state.config = { ...state.config, hindsight: normalized };
|
|
695
|
+
this.saveState(state);
|
|
696
|
+
return normalized;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** Applies saved settings to a running aih-managed container by recreating it. */
|
|
700
|
+
async applyHindsightConfiguration() {
|
|
701
|
+
const config = this.hindsightConfig(this.readState());
|
|
702
|
+
let container;
|
|
703
|
+
try { container = await inspectContainer(config.containerName, this.runDocker, 10000); }
|
|
704
|
+
catch (error) { return { success: true, warning: true, message: `Hindsight settings saved; Docker not available (${error.message})` }; }
|
|
705
|
+
if (!container?.running) return { success: true, message: "Hindsight settings saved for its next start" };
|
|
706
|
+
if (!container.managed) {
|
|
707
|
+
return { success: true, warning: true, message: `Hindsight settings saved; container '${config.containerName}' was not created by aih and is left unchanged (adopt it with u on the dashboard)` };
|
|
708
|
+
}
|
|
709
|
+
if (container.configHash === hindsightConfigHash(config, readHindsightApiKey().key)) return { success: true, message: "Hindsight unchanged" };
|
|
710
|
+
const stopped = await this.stopDockerService("hindsight");
|
|
711
|
+
if (!stopped.success) return stopped;
|
|
712
|
+
const started = await this.startDockerService("hindsight");
|
|
713
|
+
return { ...started, message: started.success ? `Hindsight recreated with the new settings (${describeHealth(started.health)})` : started.message };
|
|
714
|
+
}
|
|
715
|
+
|
|
401
716
|
async startProxyService(options) {
|
|
402
717
|
const state = this.loadState();
|
|
403
718
|
const current = state.services.proxy;
|
|
@@ -494,6 +809,7 @@ export class ServiceManager {
|
|
|
494
809
|
* Stops a single service cleanly, executing stop commands and clearing ports/workers.
|
|
495
810
|
*/
|
|
496
811
|
async stopService(serviceId) {
|
|
812
|
+
if (isDocker(serviceId)) return this.stopDockerService(serviceId);
|
|
497
813
|
const def = SERVICES[serviceId];
|
|
498
814
|
const state = await this.syncState();
|
|
499
815
|
const current = state.services[serviceId];
|
|
@@ -569,23 +885,33 @@ export class ServiceManager {
|
|
|
569
885
|
}
|
|
570
886
|
|
|
571
887
|
/** Desired configuration is separate from the running worker's snapshot. */
|
|
572
|
-
saveProxyConfiguration(options, { startServices } = {}) {
|
|
888
|
+
saveProxyConfiguration(options, { startServices, hindsight } = {}) {
|
|
573
889
|
const config = normalizeProxyOptions(options);
|
|
574
890
|
const startup = startServices === undefined ? undefined : normalizeStartServices(startServices);
|
|
891
|
+
// Validate everything before writing the key file or state.
|
|
892
|
+
if (hindsight) {
|
|
893
|
+
normalizeHindsightConfig(hindsight.config);
|
|
894
|
+
if (hindsight.apiKey) validateHindsightApiKey(hindsight.apiKey);
|
|
895
|
+
this.saveHindsightConfiguration(hindsight);
|
|
896
|
+
}
|
|
575
897
|
const state = this.readState();
|
|
576
898
|
state.config = { ...state.config, proxyOptions: savedProxyOptions(config) };
|
|
577
899
|
if (startup) state.config.startServices = startup;
|
|
578
900
|
this.saveState(state);
|
|
579
|
-
return { success: true, message:
|
|
901
|
+
return { success: true, message: `Configuration saved for the next start/restart. Current proxy${hindsight ? " and Hindsight" : ""} unchanged.` };
|
|
580
902
|
}
|
|
581
903
|
|
|
582
904
|
/** Validate before stopping; recover the old worker if applying the draft fails. */
|
|
583
|
-
async applyProxyConfiguration(options, { preflight = preflightProxy, startServices } = {}) {
|
|
905
|
+
async applyProxyConfiguration(options, { preflight = preflightProxy, startServices, hindsight } = {}) {
|
|
584
906
|
if (this.proxySetupBusy) return { success: false, message: "Proxy setup already in progress" };
|
|
585
907
|
this.proxySetupBusy = true;
|
|
586
908
|
try {
|
|
587
909
|
const config = normalizeProxyOptions(options);
|
|
588
910
|
if (startServices !== undefined) startServices = normalizeStartServices(startServices);
|
|
911
|
+
if (hindsight) {
|
|
912
|
+
normalizeHindsightConfig(hindsight.config);
|
|
913
|
+
if (hindsight.apiKey) validateHindsightApiKey(hindsight.apiKey);
|
|
914
|
+
}
|
|
589
915
|
const state = await this.syncState();
|
|
590
916
|
const previous = state.services.proxy;
|
|
591
917
|
const oldDesired = state.config?.proxyOptions;
|
|
@@ -594,7 +920,7 @@ export class ServiceManager {
|
|
|
594
920
|
if (wasRunning) {
|
|
595
921
|
const stopped = await this.stopService("proxy");
|
|
596
922
|
if (!stopped.success) {
|
|
597
|
-
this.saveProxyConfiguration(config, { startServices });
|
|
923
|
+
this.saveProxyConfiguration(config, { startServices, hindsight });
|
|
598
924
|
return { ...stopped, saved: true, applied: false,
|
|
599
925
|
message: `Configuration saved, but not applied: could not stop the current proxy. ${stopped.message} If access is denied, stop/restart the proxy from a terminal with the same permissions (Administrator if it was started elevated), then retry. Saved settings will be used on the next start/restart.` };
|
|
600
926
|
}
|
|
@@ -603,8 +929,10 @@ export class ServiceManager {
|
|
|
603
929
|
try {
|
|
604
930
|
const result = await this.startService("proxy", config);
|
|
605
931
|
if (!result.success) throw new Error(result.message || "Startup failed");
|
|
606
|
-
this.saveProxyConfiguration(config, { startServices });
|
|
607
|
-
|
|
932
|
+
this.saveProxyConfiguration(config, { startServices, hindsight });
|
|
933
|
+
const memory = hindsight ? await this.applyHindsightConfiguration() : null;
|
|
934
|
+
return { ...result, checks, hindsight: memory, message: ["Configuration applied and saved", ...(memory ? [memory.message] : []),
|
|
935
|
+
...(checks || []).filter(c => c.startsWith("Warning:"))].join(" | ") };
|
|
608
936
|
} catch (error) {
|
|
609
937
|
// A failed start may have persisted a runtime entry before a later error.
|
|
610
938
|
try { await this.stopService("proxy"); } catch {}
|
|
@@ -649,6 +977,19 @@ export class ServiceManager {
|
|
|
649
977
|
* Displays or follows logs for a service.
|
|
650
978
|
*/
|
|
651
979
|
async showLogs(serviceId, lines = 50, follow = false) {
|
|
980
|
+
if (isDocker(serviceId)) {
|
|
981
|
+
const config = this.hindsightConfig();
|
|
982
|
+
const logPath = getServiceLogPath(serviceId);
|
|
983
|
+
if (existsSync(logPath)) console.log(gray(`[aih] Docker commands run by aih are logged in: ${logPath}`));
|
|
984
|
+
console.log(gray(`[aih] docker logs --tail ${lines}${follow ? " --follow" : ""} ${config.containerName}\n`));
|
|
985
|
+
await new Promise(resolve => {
|
|
986
|
+
const child = spawn("docker", ["logs", "--tail", String(lines), ...(follow ? ["--follow"] : []), config.containerName],
|
|
987
|
+
{ stdio: "inherit", windowsHide: true });
|
|
988
|
+
child.once("error", error => { console.log(red(`[aih] Cannot run docker logs: ${error.message}`)); resolve(); });
|
|
989
|
+
child.once("exit", resolve);
|
|
990
|
+
});
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
652
993
|
const logPath = getServiceLogPath(serviceId);
|
|
653
994
|
if (!existsSync(logPath)) {
|
|
654
995
|
console.log(yellow(`[aih] No log file exists yet for '${serviceId}' at: ${logPath}`));
|
package/src/proxy.js
CHANGED
|
@@ -10,6 +10,8 @@ import { normalizePresetOptions, createPresetHooks } from "./proxy-presets.js";
|
|
|
10
10
|
|
|
11
11
|
const HOP_HEADERS = ["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"];
|
|
12
12
|
const HOOKS = ["onRequest", "onResponse", "onResponseBody", "onResponseChunk", "onWebSocketMessage"];
|
|
13
|
+
/** Reserved path answered by the proxy itself (aih status --ui health); never forwarded. */
|
|
14
|
+
export const PROXY_HEALTH_PATH = "/__aih/health";
|
|
13
15
|
|
|
14
16
|
function parseUrl(value) {
|
|
15
17
|
return new URL(String(value).replace(/^(https?):\/*/i, "$1://"));
|
|
@@ -176,6 +178,14 @@ export async function startProxy(options) {
|
|
|
176
178
|
}
|
|
177
179
|
|
|
178
180
|
const server = http.createServer(async (request, response) => {
|
|
181
|
+
// aih's own readiness probe; never forwarded, recorded or passed to hooks.
|
|
182
|
+
if (request.url === PROXY_HEALTH_PATH && (request.method === "GET" || request.method === "HEAD")) {
|
|
183
|
+
const body = JSON.stringify({ service: "aih-proxy", status: "ok", pid: process.pid,
|
|
184
|
+
uptime_seconds: Math.round(process.uptime() * 10) / 10, upstream: target.origin, preset: config.preset });
|
|
185
|
+
response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
|
|
186
|
+
response.end(request.method === "HEAD" ? undefined : body);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
179
189
|
const started = performance.now();
|
|
180
190
|
let upstream;
|
|
181
191
|
let context;
|
package/src/startup-services.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { SERVICE_IDS } from "./config.js";
|
|
2
2
|
|
|
3
3
|
export const STARTUP_SERVICE_IDS = Object.freeze([
|
|
4
|
-
"ocx", "
|
|
4
|
+
"ocx", "hindsight", ...SERVICE_IDS.filter(id => !["ocx", "hindsight"].includes(id)), "proxy",
|
|
5
5
|
]);
|
|
6
|
-
export const DEFAULT_START_SERVICES = Object.freeze(["ocx", "
|
|
6
|
+
export const DEFAULT_START_SERVICES = Object.freeze(["ocx", "hindsight", "proxy"]);
|
|
7
|
+
/** Saved selections from older releases name services that were replaced. */
|
|
8
|
+
const REPLACED_SERVICES = { agentmemory: "hindsight" };
|
|
7
9
|
|
|
8
10
|
export function normalizeStartServices(value = DEFAULT_START_SERVICES) {
|
|
11
|
+
if (Array.isArray(value)) value = value.map(id => REPLACED_SERVICES[id] || id);
|
|
9
12
|
if (!Array.isArray(value) || !value.length || value.some(id => !STARTUP_SERVICE_IDS.includes(id))) {
|
|
10
13
|
throw new Error(`Select at least one startup service from: ${STARTUP_SERVICE_IDS.join(", ")}`);
|
|
11
14
|
}
|