@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/src/index.js CHANGED
@@ -70,6 +70,8 @@ ${bold("HINDSIGHT (DOCKER):")}
70
70
  again), archives the data volume in ~/.aih/backups and recreates the container. A container
71
71
  not created by aih (e.g. docker compose) is left alone until adopted: update hindsight --adopt
72
72
  imports its image, ports, volume and environment and recreates it on the same volume.
73
+ Optional local LLM (hindsight-llm, llama.cpp server): enable it in status --ui (c); start/stop
74
+ hindsight also start it first and stop it last. Its image tag is pinned: update re-pulls it only.
73
75
 
74
76
  ${bold("OPTIONS:")}
75
77
  ${gray("-n, --lines <num>")} Number of log lines to show (logs only; default: 50)
package/src/manager.js CHANGED
@@ -12,7 +12,10 @@ import { configureCodexForProxy } from "./codex-routing.js";
12
12
  import {
13
13
  HINDSIGHT_DEFAULTS,
14
14
  HINDSIGHT_REPOSITORY,
15
+ HINDSIGHT_NETWORK,
16
+ LOCAL_LLM_ID,
15
17
  adoptedHindsightSettings,
18
+ adoptedLocalLlmSettings,
16
19
  describeHealth,
17
20
  dockerInfo,
18
21
  dockerLogged,
@@ -21,11 +24,16 @@ import {
21
24
  hindsightUrls,
22
25
  imageId,
23
26
  inspectContainer,
27
+ localLlmConfigHash,
28
+ localLlmRunArgs,
29
+ localLlmUrls,
24
30
  normalizeHindsightConfig,
25
31
  probeHindsightHealth,
32
+ probeLocalLlmHealth,
26
33
  readHindsightApiKey,
27
34
  requiresApiKey,
28
35
  saveHindsightApiKey,
36
+ smokeTestLocalLlm,
29
37
  validateHindsightApiKey,
30
38
  HINDSIGHT_KEY_ENV,
31
39
  dockerError,
@@ -44,13 +52,19 @@ import {
44
52
  import { formatBytes, formatUptime, gray, red, yellow, green, cyan } from "./utils/format.js";
45
53
 
46
54
  const isDocker = id => SERVICES[id]?.runtime === "docker";
55
+ const LLM_DISABLED = "The Hindsight local LLM is disabled; enable it in 'aih status --ui' (c), Hindsight local LLM step.";
47
56
 
48
57
  export class ServiceManager {
49
58
  updatesInProgress = new Set();
50
59
  /** Injectable for tests: (cmd, args, timeoutMs) => { exitCode, stdout, stderr }. */
51
60
  runDocker = execCommand;
52
61
  probeHealth = probeHindsightHealth;
62
+ probeLlmHealth = probeLocalLlmHealth;
63
+ smokeTestLlm = smokeTestLocalLlm;
64
+ fileExists = existsSync;
53
65
  hindsightStartTimeoutMs = 180000;
66
+ /** Loading a model into GPU memory can take minutes on first start. */
67
+ localLlmStartTimeoutMs = 300000;
54
68
  hindsightPollMs = 1000;
55
69
  dockerRetryAt = 0;
56
70
 
@@ -185,8 +199,12 @@ export class ServiceManager {
185
199
  state.services ||= {};
186
200
  // agentmemory was replaced by Hindsight; never manage or stop a leftover entry.
187
201
  delete state.services.agentmemory;
202
+ // The local LLM row exists only while it is enabled.
203
+ const localLlm = state.config?.hindsight?.localLlm?.enabled === true;
204
+ if (!localLlm) delete state.services[LOCAL_LLM_ID];
188
205
 
189
206
  for (const id of SERVICE_IDS) {
207
+ if (id === LOCAL_LLM_ID && !localLlm) continue;
190
208
  const def = SERVICES[id];
191
209
  if (!state.services[id]) {
192
210
  state.services[id] = {
@@ -260,12 +278,12 @@ export class ServiceManager {
260
278
  async syncDockerService(state, id) {
261
279
  const svc = state.services[id] || {};
262
280
  const config = this.hindsightConfig(state);
263
- const urls = hindsightUrls(config);
281
+ const target = this.dockerTarget(id, config);
264
282
  let container = null;
265
283
  let runtimeError;
266
284
  if (Date.now() < this.dockerRetryAt) runtimeError = svc.runtimeError || "Docker not available";
267
285
  else {
268
- try { container = await inspectContainer(config.containerName, this.runDocker); }
286
+ try { container = await inspectContainer(target.containerName, this.runDocker); }
269
287
  catch (error) {
270
288
  runtimeError = error.message;
271
289
  // A stopped Docker Desktop must not stall every one-second dashboard refresh.
@@ -275,10 +293,10 @@ export class ServiceManager {
275
293
  if (!runtimeError) this.dockerRetryAt = 0;
276
294
  const next = {
277
295
  id, name: SERVICES[id].name, runtime: "docker",
278
- command: `docker container ${config.containerName} (${container?.image || config.image})`,
296
+ command: `docker container ${target.containerName} (${container?.image || target.image})`,
279
297
  status: container?.running ? "running" : "stopped",
280
298
  startedAt: container?.running ? container.startedAt : undefined,
281
- url: urls.ui, apiUrl: urls.api, containerName: config.containerName,
299
+ url: target.url, apiUrl: target.apiUrl, containerName: target.containerName,
282
300
  containerId: container?.id, containerStatus: container ? container.status : runtimeError ? undefined : "missing",
283
301
  managed: container ? container.managed : undefined, runtimeError,
284
302
  };
@@ -476,28 +494,65 @@ export class ServiceManager {
476
494
  };
477
495
  }
478
496
 
479
- /** Starts (or creates) the Hindsight container and reports success only after /health. */
497
+ /** Container name and URLs of a Docker service. */
498
+ dockerTarget(id, config) {
499
+ if (id === LOCAL_LLM_ID) {
500
+ const urls = localLlmUrls(config.localLlm);
501
+ return { containerName: config.localLlm.containerName, image: config.localLlm.image, url: urls.ui, apiUrl: urls.api };
502
+ }
503
+ const urls = hindsightUrls(config);
504
+ return { containerName: config.containerName, image: config.image, url: urls.ui, apiUrl: urls.api };
505
+ }
506
+
507
+ /**
508
+ * Starts (or creates) a Docker service and reports success only after /health.
509
+ * Hindsight starts its local LLM first, when enabled: the operations routed to it need it.
510
+ */
480
511
  async startDockerService(id) {
481
512
  const state = this.readState();
482
513
  let config;
483
514
  try { config = this.hindsightConfig(state, { strict: true }); }
484
515
  catch (error) { return { success: false, message: `Invalid Hindsight settings: ${error.message}. Fix them with 'aih status --ui' (c).` }; }
516
+ const llmEnabled = config.localLlm.enabled;
517
+ if (id === LOCAL_LLM_ID && !llmEnabled) return { success: false, message: LLM_DISABLED };
485
518
  const urls = hindsightUrls(config);
486
519
  const base = { url: urls.ui, apiUrl: urls.api, containerName: config.containerName };
487
520
  const docker = await dockerInfo(this.runDocker);
488
521
  if (!docker.available) return { ...base, success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
489
522
  this.dockerRetryAt = 0;
523
+ if (id === LOCAL_LLM_ID) {
524
+ const result = await this.startLocalLlm(config);
525
+ await this.syncState();
526
+ return result;
527
+ }
490
528
  const key = readHindsightApiKey();
491
529
  const configHash = hindsightConfigHash(config, key.key);
492
530
  let container;
493
531
  try { container = await inspectContainer(config.containerName, this.runDocker, 10000); }
494
532
  catch (error) { return { ...base, success: false, message: `Cannot inspect the Hindsight container: ${error.message}` }; }
533
+ if (!container?.running) {
534
+ // Two Hindsight servers on one database corrupt it: never start next to a foreign one.
535
+ const [rival] = await this.foreignOnVolume(config, { running: true });
536
+ if (rival) {
537
+ const project = rival.container.composeProject ? `, compose project '${rival.container.composeProject}'` : "";
538
+ return { ...base, success: false, message: `Container '${rival.name}' (not created by aih${project}) is running on data volume '${config.volume}'. Stop it, or adopt it with 'aih update hindsight --adopt'.` };
539
+ }
540
+ }
541
+ let llm = null;
542
+ if (llmEnabled) {
543
+ llm = await this.startLocalLlm(config);
544
+ if (!llm.success) {
545
+ await this.syncState();
546
+ return { ...base, success: false, localLlm: llm, message: `${llm.message} Hindsight was not started.` };
547
+ }
548
+ }
549
+ const withLlm = message => llm ? `${message} | local LLM: ${describeHealth(llm.health)}` : message;
495
550
  if (container?.running) {
496
551
  const health = await this.probeHealth(urls.api);
497
552
  await this.syncState();
498
553
  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}` };
554
+ return { ...base, success: true, alreadyRunning: true, containerId: container.id, health, localLlm: llm,
555
+ message: withLlm(`Hindsight container '${config.containerName}' already running | health: ${describeHealth(health)}.${pending}`) };
501
556
  }
502
557
  let action;
503
558
  if (container?.managed && container.configHash !== configHash) {
@@ -526,37 +581,127 @@ export class ServiceManager {
526
581
  const health = await this.waitForHindsight(config);
527
582
  const synced = (await this.syncState()).services[id];
528
583
  if (health.state !== "healthy") {
529
- return { ...base, success: false, containerId: synced?.containerId, health,
584
+ return { ...base, success: false, containerId: synced?.containerId, health, localLlm: llm,
530
585
  message: `Hindsight container ${action}, but /health is ${describeHealth(health)}. Check 'aih logs hindsight'.` };
531
586
  }
532
- return { ...base, success: true, containerId: synced?.containerId, health,
533
- message: `Hindsight container '${config.containerName}' ${action}; health: ${describeHealth(health)}` };
587
+ return { ...base, success: true, containerId: synced?.containerId, health, localLlm: llm,
588
+ message: withLlm(`Hindsight container '${config.containerName}' ${action}; health: ${describeHealth(health)}`) };
534
589
  }
535
590
 
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;
591
+ /** Starts or creates the local LLM container; success only after /health, plus a test completion when it is new. */
592
+ async startLocalLlm(config) {
593
+ const llm = config.localLlm;
594
+ const id = LOCAL_LLM_ID;
595
+ const name = llm.containerName;
596
+ const urls = localLlmUrls(llm);
597
+ const base = { url: urls.ui, apiUrl: urls.api, containerName: name };
598
+ const configHash = localLlmConfigHash(llm);
599
+ let container;
600
+ try { container = await inspectContainer(name, this.runDocker, 10000); }
601
+ catch (error) { return { ...base, success: false, message: `Cannot inspect the local LLM container: ${error.message}` }; }
602
+ if (container && !container.managed) {
603
+ return { ...base, success: false, message: `Container '${name}' was not created by aih: rename or remove it, or adopt the Hindsight stack with 'aih update hindsight --adopt'.` };
604
+ }
605
+ if (container?.running) {
606
+ const health = await this.probeLlmHealth(urls.api);
607
+ const pending = container.configHash !== configHash ? ` Saved settings differ: restart ${id} to apply them.` : "";
608
+ return { ...base, success: true, alreadyRunning: true, containerId: container.id, health,
609
+ message: `Local LLM '${name}' already running | health: ${describeHealth(health)}.${pending}` };
610
+ }
611
+ const network = await this.ensureHindsightNetwork();
612
+ if (!network.success) return { ...base, ...network };
613
+ let action;
614
+ if (container && container.configHash !== configHash) {
615
+ const removed = await dockerLogged(id, ["rm", name], this.runDocker, 60000);
616
+ if (removed.exitCode !== 0) return { ...base, success: false, message: `Cannot recreate the local LLM container: ${dockerError(removed)}` };
617
+ container = null;
618
+ action = "recreated";
619
+ }
620
+ if (container) {
621
+ const started = await dockerLogged(id, ["start", name], this.runDocker, 120000);
622
+ if (started.exitCode !== 0) return { ...base, success: false, message: `docker start ${name} failed: ${dockerError(started)}. See 'aih logs ${id}'.` };
623
+ action = "started";
624
+ } else {
625
+ const missing = [llm.model, llm.lora].filter(Boolean).map(file => join(llm.modelsDir, file)).filter(path => !this.fileExists(path));
626
+ if (missing.length) return { ...base, success: false, message: `Local LLM file not found: ${missing.join(", ")}. Fix the models folder in 'aih status --ui' (c).` };
627
+ if (!(await imageId(llm.image, this.runDocker))) {
628
+ const pulled = await dockerLogged(id, ["pull", llm.image], this.runDocker, 30 * 60000);
629
+ if (pulled.exitCode !== 0) return { ...base, success: false, message: `docker pull ${llm.image} failed: ${dockerError(pulled)}` };
630
+ }
631
+ const created = await dockerLogged(id, localLlmRunArgs(llm, { configHash }), this.runDocker, 120000, llm.image);
632
+ if (created.exitCode !== 0) return { ...base, success: false, message: `docker run ${llm.image} failed: ${dockerError(created)}` };
633
+ action ||= "created";
634
+ }
635
+ const health = await this.waitForContainerHealth(name, () => this.probeLlmHealth(urls.api), this.localLlmStartTimeoutMs);
636
+ if (health.state !== "healthy") {
637
+ return { ...base, success: false, health, message: `Local LLM container ${action}, but /health is ${describeHealth(health)}. Check 'aih logs ${id}'.` };
638
+ }
639
+ if (action !== "started") {
640
+ // A new image or new settings: prove that the model and adapter generate, not only that the server is up.
641
+ const smoke = await this.smokeTestLlm(urls.api, llm.alias);
642
+ if (!smoke.ok) return { ...base, success: false, health, message: `Local LLM ${action} and healthy, but a test completion failed (${smoke.error}). Check 'aih logs ${id}'.` };
643
+ }
644
+ return { ...base, success: true, health, message: `Local LLM '${name}' ${action}; health: ${describeHealth(health)}` };
645
+ }
646
+
647
+ /** The user-defined network on which Hindsight reaches the local LLM by container name. */
648
+ async ensureHindsightNetwork() {
649
+ const found = await this.runDocker("docker", ["network", "inspect", "--format", "{{.Name}}", HINDSIGHT_NETWORK], 10000);
650
+ if (found.exitCode === 0) return { success: true };
651
+ const created = await dockerLogged(LOCAL_LLM_ID, ["network", "create", HINDSIGHT_NETWORK], this.runDocker, 30000);
652
+ return created.exitCode === 0 ? { success: true }
653
+ : { success: false, message: `Cannot create the Docker network '${HINDSIGHT_NETWORK}': ${dockerError(created)}` };
654
+ }
655
+
656
+ /** First boots initialize the database, download or load models: poll until healthy, exited or timed out. */
657
+ async waitForContainerHealth(name, probe, timeoutMs) {
658
+ const deadline = Date.now() + timeoutMs;
540
659
  for (let attempt = 0; ; attempt++) {
541
- const health = await this.probeHealth(api);
660
+ const health = await probe();
542
661
  if (health.state === "healthy" || Date.now() >= deadline) return health;
543
662
  if (attempt % 5 === 4) {
544
- const container = await inspectContainer(config.containerName, this.runDocker).catch(() => null);
663
+ const container = await inspectContainer(name, this.runDocker).catch(() => null);
545
664
  if (!container?.running) return { ...health, state: "unreachable", error: `container ${container?.status || "missing"}` };
546
665
  }
547
666
  await sleep(this.hindsightPollMs);
548
667
  }
549
668
  }
550
669
 
670
+ async waitForHindsight(config) {
671
+ return this.waitForContainerHealth(config.containerName, () => this.probeHealth(hindsightUrls(config).api), this.hindsightStartTimeoutMs);
672
+ }
673
+
674
+ /** Containers not created by aih that mount the Hindsight data volume (only running ones if asked). */
675
+ async foreignOnVolume(config, { running = false } = {}) {
676
+ const listed = await this.runDocker("docker", ["ps", "-a", "--filter", "volume=" + config.volume, "--format", "{{.Names}}"], 10000);
677
+ if (listed.exitCode !== 0) return [];
678
+ const found = [];
679
+ for (const name of listed.stdout.split(/\r?\n/).map(line => line.trim()).filter(line => line && line !== config.containerName)) {
680
+ const container = await inspectContainer(name, this.runDocker, 10000).catch(() => null);
681
+ if (container && !container.managed && (!running || container.running)) found.push({ name, container });
682
+ }
683
+ return found;
684
+ }
685
+
551
686
  async stopDockerService(id) {
552
687
  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)}` };
688
+ const llm = config.localLlm;
689
+ // Hindsight first, then the server it calls. Never kill port owners: on Windows they are Docker Desktop's own processes.
690
+ const names = id === LOCAL_LLM_ID ? [llm.containerName] : [config.containerName, ...(llm.enabled ? [llm.containerName] : [])];
691
+ for (const name of names) {
692
+ const result = await dockerLogged(id, ["stop", name], this.runDocker, 60000);
693
+ if (result.exitCode !== 0 && !/no such container/i.test(result.stderr)) {
694
+ await this.syncState();
695
+ return { success: false, message: `docker stop ${name} failed: ${dockerError(result)}` };
696
+ }
697
+ }
698
+ const state = await this.syncState();
699
+ if (id === LOCAL_LLM_ID) {
700
+ const warning = state.services.hindsight?.status === "running"
701
+ ? `; Hindsight is still running and its ${llm.operations.join(", ")} calls fail until the local LLM is started again` : "";
702
+ return { success: true, warning: Boolean(warning), message: `Local LLM '${llm.containerName}' stopped${warning}` };
558
703
  }
559
- return { success: true, message: `Hindsight container '${config.containerName}' stopped (data kept)` };
704
+ return { success: true, message: `Hindsight container '${config.containerName}' stopped (data kept)${llm.enabled ? `; local LLM '${llm.containerName}' stopped` : ""}` };
560
705
  }
561
706
 
562
707
  /**
@@ -567,14 +712,18 @@ export class ServiceManager {
567
712
  if (this.updatesInProgress.has(id)) return { success: false, message: `An update for '${id}' is already in progress` };
568
713
  this.updatesInProgress.add(id);
569
714
  try {
715
+ if (id === LOCAL_LLM_ID) return await this.updateLocalLlm(id);
570
716
  const config = this.hindsightConfig(this.readState(), { strict: true });
571
717
  const name = config.containerName;
572
718
  const docker = await dockerInfo(this.runDocker);
573
719
  if (!docker.available) return { success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
574
720
  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.` };
721
+ // A foreign container with aih's name, or a running one on the same data (e.g. a compose stack under other names).
722
+ const foreign = container && !container.managed ? { name, container } : (await this.foreignOnVolume(config, { running: true }))[0];
723
+ if (foreign) {
724
+ if (adopt) return await this.adoptDockerService(id, foreign.name, foreign.container, config);
725
+ const project = foreign.container.composeProject ? ` (docker compose project '${foreign.container.composeProject}')` : "";
726
+ return { success: false, adoptable: true, message: `Container '${foreign.name}' was not created by aih${project}. To adopt it run 'aih update ${id} --adopt' (dashboard: press u again): aih imports its settings, and those of the local LLM container it calls, and recreates them on the same data volume.` };
578
727
  }
579
728
  const previousVersion = container?.running ? (await this.probeHealth(hindsightUrls(config).api)).version ?? null : null;
580
729
  // A release tag of the official image moves to the latest GitHub release; any other tag is pulled again.
@@ -647,40 +796,134 @@ export class ServiceManager {
647
796
  return { success: true, path: join(dir, file) };
648
797
  }
649
798
 
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) {
799
+ /**
800
+ * The llama.cpp build is pinned and changed by hand (image tag in setup). u pulls the same tag again and
801
+ * replaces the container only if the image changed, going back to the previous image if the new one fails.
802
+ */
803
+ async updateLocalLlm(id) {
804
+ const config = this.hindsightConfig(this.readState(), { strict: true });
805
+ const llm = config.localLlm;
806
+ if (!llm.enabled) return { success: false, message: LLM_DISABLED };
807
+ const docker = await dockerInfo(this.runDocker);
808
+ if (!docker.available) return { success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
809
+ const name = llm.containerName;
810
+ const container = await inspectContainer(name, this.runDocker, 10000);
811
+ if (container && !container.managed) return { success: false, message: `Container '${name}' was not created by aih; adopt the Hindsight stack with 'aih update hindsight --adopt'.` };
812
+ const pinned = "The llama.cpp build is pinned: to move to another build, change the local LLM image tag in 'aih status --ui' (c).";
813
+ const pulled = await dockerLogged(id, ["pull", llm.image], this.runDocker, 30 * 60000);
814
+ if (pulled.exitCode !== 0) return { success: false, message: `docker pull ${llm.image} failed: ${dockerError(pulled)}` };
815
+ const image = await imageId(llm.image, this.runDocker);
816
+ if (!container) return { success: true, updated: true, message: `Image ${llm.image} pulled; the container is created on the next start. ${pinned}` };
817
+ if (image && image === container.imageId) {
818
+ return { success: true, updated: false, alreadyUpToDate: true, message: `'${id}' already uses the latest ${llm.image}. ${pinned}` };
819
+ }
820
+ // The container keeps no data: no backup, and the previous image stays local for a rollback.
821
+ const stopped = await dockerLogged(id, ["stop", name], this.runDocker, 60000);
822
+ const removed = stopped.exitCode === 0 ? await dockerLogged(id, ["rm", name], this.runDocker, 60000) : stopped;
823
+ if (removed.exitCode !== 0) {
824
+ if (container.running) await dockerLogged(id, ["start", name], this.runDocker, 120000);
825
+ await this.syncState();
826
+ return { success: false, message: `Cannot replace the local LLM container: ${dockerError(removed)}; the current container is kept` };
827
+ }
828
+ if (!container.running) {
829
+ await this.syncState();
830
+ return { success: true, updated: true, restarted: false, message: `Image ${llm.image} updated; the container is recreated on the next start` };
831
+ }
832
+ const started = await this.startLocalLlm(config);
833
+ if (started.success) {
834
+ await this.syncState();
835
+ return { ...started, updated: true, restarted: true, message: `'${id}' updated to the new ${llm.image} and restarted (${describeHealth(started.health)})` };
836
+ }
837
+ await dockerLogged(id, ["rm", "-f", name], this.runDocker, 60000);
838
+ const tagged = await dockerLogged(id, ["tag", container.imageId, llm.image], this.runDocker, 30000);
839
+ const restored = tagged.exitCode === 0 ? await this.startLocalLlm(config) : { success: false, message: dockerError(tagged) };
840
+ await this.syncState();
841
+ return { success: false, updated: false, rolledBack: restored.success,
842
+ message: `The new ${llm.image} failed (${started.message}); ${restored.success ? "rolled back to the previous image" : `rollback failed: ${restored.message}`}` };
843
+ }
844
+
845
+ /**
846
+ * Takes over a container aih did not create, and the local LLM container it calls, if any: imports
847
+ * their settings, archives the data volume, then recreates them under aih's names on the same volume.
848
+ */
849
+ async adoptDockerService(id, name, container, current = this.hindsightConfig()) {
652
850
  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));
851
+ // Variables already defined by an image are not settings: importing them would pin them across updates.
852
+ const imageEnv = async image => {
853
+ const result = await this.runDocker("docker", ["image", "inspect", "--format", "{{json .Config.Env}}", image], 10000);
854
+ if (result.exitCode !== 0) throw new Error(dockerError(result));
855
+ return JSON.parse(result.stdout) || [];
856
+ };
656
857
  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`);
858
+ let config;
859
+ let llmName = null;
860
+ let llmContainer = null;
861
+ try {
862
+ adopted = adoptedHindsightSettings(current.containerName, container, await imageEnv(container.imageId));
863
+ let localLlm = { ...current.localLlm, enabled: false };
864
+ if (adopted.route) {
865
+ llmName = adopted.route.host;
866
+ llmContainer = await inspectContainer(llmName, this.runDocker, 10000);
867
+ if (!llmContainer) throw new Error(`its ${adopted.route.operations.join(", ")} calls go to '${llmName}', which is not a container`);
868
+ localLlm = adoptedLocalLlmSettings(llmContainer, await imageEnv(llmContainer.imageId), adopted.route, current.localLlm.containerName);
869
+ }
870
+ config = normalizeHindsightConfig({ ...adopted.config, localLlm });
871
+ } catch (error) { return refuse(error.message); }
872
+ if (!adopted.key && !readHindsightApiKey().key && requiresApiKey(config)) {
873
+ return refuse(`it has no LLM API key for provider '${config.llmProvider}'; save one in setup (c) first`);
874
+ }
875
+ // aih's names must be free, or belong to stopped aih containers that are replaced.
876
+ const adopting = [name, ...(llmName ? [llmName] : [])];
877
+ const stale = [];
878
+ for (const target of [config.containerName, ...(llmName ? [config.localLlm.containerName] : [])].filter(t => !adopting.includes(t))) {
879
+ let existing;
880
+ try { existing = await inspectContainer(target, this.runDocker, 10000); } catch (error) { return refuse(error.message); }
881
+ if (!existing) continue;
882
+ if (!existing.managed) return refuse(`the name '${target}' is taken by another container not created by aih`);
883
+ if (existing.running) return refuse(`aih's container '${target}' is running; stop it first`);
884
+ stale.push(target);
661
885
  }
886
+ const wasRunning = { [name]: container.running, ...(llmName ? { [llmName]: llmContainer.running } : {}) };
887
+ const restore = async () => {
888
+ for (const target of [...adopting].reverse()) if (wasRunning[target]) await dockerLogged(id, ["start", target], this.runDocker, 120000);
889
+ await this.syncState();
890
+ };
891
+ // Hindsight first, then its LLM; the archive needs a quiet database.
892
+ for (const target of adopting) {
893
+ const stopped = await dockerLogged(id, ["stop", target], this.runDocker, 60000);
894
+ if (stopped.exitCode !== 0) { await restore(); return refuse(`docker stop ${target} failed: ${dockerError(stopped)}`); }
895
+ }
896
+ const backup = await this.backupHindsightVolume(id, config.volume, container.imageId);
897
+ if (!backup.success) { await restore(); return refuse(`data backup failed: ${backup.message}`); }
662
898
  const envFile = adopted.extra.length ? join(getAihDir(), "hindsight-extra.env") : "";
663
899
  if (envFile) {
664
900
  ensureDir(getAihDir());
665
901
  writeFileSync(envFile, adopted.extra.join("\n") + "\n", { encoding: "utf8", mode: 0o600 });
666
902
  }
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;
903
+ this.saveHindsightConfiguration({ config: { ...config, envFile }, apiKey: adopted.key });
904
+ const removed = await dockerLogged(id, ["rm", name], this.runDocker, 60000);
670
905
  if (removed.exitCode !== 0) {
671
- if (container.running) await dockerLogged(id, ["start", name], this.runDocker, 120000);
672
- await this.syncState();
906
+ await restore();
673
907
  return { success: false, message: `Settings imported, but the container could not be replaced: ${dockerError(removed)}` };
674
908
  }
675
- const kept = `data volume '${adopted.config.volume}' kept`;
909
+ const leftovers = [];
910
+ for (const target of [...adopting.slice(1), ...stale]) {
911
+ const result = await dockerLogged(id, ["rm", target], this.runDocker, 60000);
912
+ if (result.exitCode !== 0) leftovers.push(`${target} (${dockerError(result)})`);
913
+ }
914
+ const what = llmName ? `Containers '${name}' and '${llmName}'` : `Container '${name}'`;
915
+ const names = llmName ? `'${config.containerName}' and '${config.localLlm.containerName}'` : `'${config.containerName}'`;
916
+ const kept = `data volume '${config.volume}' kept, backup ${backup.path}`;
917
+ const notes = (leftovers.length ? ` Could not remove: ${leftovers.join(", ")}.` : "")
918
+ + (container.composeProject ? ` Do not run 'docker compose up' for project '${container.composeProject}' again: it would start a second Hindsight on the same data.` : "");
676
919
  if (!container.running) {
677
920
  await this.syncState();
678
- return { success: true, adopted: true, message: `Container '${name}' adopted; aih recreates it on the next start (${kept})` };
921
+ return { success: true, adopted: true, backup: backup.path, message: `${what} adopted; aih creates ${names} on the next start (${kept}).${notes}` };
679
922
  }
680
923
  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}` };
924
+ return { ...started, adopted: true, backup: backup.path, message: started.success
925
+ ? `${what} adopted and recreated by aih as ${names} (${kept}; ${describeHealth(started.health)}).${notes} Update with u or 'aih update ${id}'.`
926
+ : `Settings imported and old containers removed, but the new ones failed: ${started.message}${notes}` };
684
927
  }
685
928
 
686
929
  /** Non-secret settings go to state.json; the key only to ~/.aih/hindsight.env. */
@@ -696,21 +939,35 @@ export class ServiceManager {
696
939
  return normalized;
697
940
  }
698
941
 
699
- /** Applies saved settings to a running aih-managed container by recreating it. */
942
+ /** Applies saved settings to running aih-managed containers by recreating them; a disabled local LLM is stopped. */
700
943
  async applyHindsightConfiguration() {
701
944
  const config = this.hindsightConfig(this.readState());
945
+ const llm = config.localLlm;
702
946
  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" };
947
+ let llmContainer;
948
+ try {
949
+ container = await inspectContainer(config.containerName, this.runDocker, 10000);
950
+ llmContainer = await inspectContainer(llm.containerName, this.runDocker, 10000);
951
+ } catch (error) { return { success: true, warning: true, message: `Hindsight settings saved; Docker not available (${error.message})` }; }
952
+ const orphan = !llm.enabled && llmContainer?.managed && llmContainer.running;
953
+ if (orphan) await dockerLogged(LOCAL_LLM_ID, ["stop", llm.containerName], this.runDocker, 60000);
954
+ const note = orphan ? `; local LLM '${llm.containerName}' stopped (disabled)` : "";
955
+ if (!container?.running) {
956
+ if (orphan) await this.syncState();
957
+ return { success: true, message: `Hindsight settings saved for its next start${note}` };
958
+ }
706
959
  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)` };
960
+ 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)${note}` };
961
+ }
962
+ const llmChanged = llm.enabled && (!llmContainer?.running || (llmContainer.managed && llmContainer.configHash !== localLlmConfigHash(llm)));
963
+ if (container.configHash === hindsightConfigHash(config, readHindsightApiKey().key) && !llmChanged) {
964
+ if (orphan) await this.syncState();
965
+ return { success: true, message: `Hindsight unchanged${note}` };
708
966
  }
709
- if (container.configHash === hindsightConfigHash(config, readHindsightApiKey().key)) return { success: true, message: "Hindsight unchanged" };
710
967
  const stopped = await this.stopDockerService("hindsight");
711
968
  if (!stopped.success) return stopped;
712
969
  const started = await this.startDockerService("hindsight");
713
- return { ...started, message: started.success ? `Hindsight recreated with the new settings (${describeHealth(started.health)})` : started.message };
970
+ return { ...started, message: started.success ? `Hindsight recreated with the new settings (${describeHealth(started.health)})${note}` : started.message };
714
971
  }
715
972
 
716
973
  async startProxyService(options) {
@@ -978,12 +1235,12 @@ export class ServiceManager {
978
1235
  */
979
1236
  async showLogs(serviceId, lines = 50, follow = false) {
980
1237
  if (isDocker(serviceId)) {
981
- const config = this.hindsightConfig();
1238
+ const { containerName } = this.dockerTarget(serviceId, this.hindsightConfig());
982
1239
  const logPath = getServiceLogPath(serviceId);
983
1240
  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`));
1241
+ console.log(gray(`[aih] docker logs --tail ${lines}${follow ? " --follow" : ""} ${containerName}\n`));
985
1242
  await new Promise(resolve => {
986
- const child = spawn("docker", ["logs", "--tail", String(lines), ...(follow ? ["--follow"] : []), config.containerName],
1243
+ const child = spawn("docker", ["logs", "--tail", String(lines), ...(follow ? ["--follow"] : []), containerName],
987
1244
  { stdio: "inherit", windowsHide: true });
988
1245
  child.once("error", error => { console.log(red(`[aih] Cannot run docker logs: ${error.message}`)); resolve(); });
989
1246
  child.once("exit", resolve);