@drakonkat/ai-helper 1.2.17 → 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.
package/src/manager.js CHANGED
@@ -9,6 +9,25 @@ 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
+ describeHealth,
15
+ dockerInfo,
16
+ dockerLogged,
17
+ hindsightConfigHash,
18
+ hindsightRunArgs,
19
+ hindsightUrls,
20
+ imageId,
21
+ inspectContainer,
22
+ normalizeHindsightConfig,
23
+ probeHindsightHealth,
24
+ readHindsightApiKey,
25
+ requiresApiKey,
26
+ saveHindsightApiKey,
27
+ validateHindsightApiKey,
28
+ HINDSIGHT_KEY_ENV,
29
+ dockerError,
30
+ } from "./hindsight.js";
12
31
  import { ensureDir, getAihDir, getLogsDir, getServiceLogPath, getStateFilePath } from "./utils/path.js";
13
32
  import {
14
33
  isPidRunning,
@@ -22,11 +41,29 @@ import {
22
41
  } from "./utils/process.js";
23
42
  import { formatBytes, formatUptime, gray, red, yellow, green, cyan } from "./utils/format.js";
24
43
 
44
+ const isDocker = id => SERVICES[id]?.runtime === "docker";
45
+
25
46
  export class ServiceManager {
26
47
  updatesInProgress = new Set();
48
+ /** Injectable for tests: (cmd, args, timeoutMs) => { exitCode, stdout, stderr }. */
49
+ runDocker = execCommand;
50
+ probeHealth = probeHindsightHealth;
51
+ hindsightStartTimeoutMs = 180000;
52
+ hindsightPollMs = 1000;
53
+ dockerRetryAt = 0;
54
+
55
+ /** Saved Hindsight settings; invalid saved values fall back to defaults unless strict. */
56
+ hindsightConfig(state = this.readState(), { strict = false } = {}) {
57
+ try { return normalizeHindsightConfig(state.config?.hindsight); }
58
+ catch (error) {
59
+ if (strict) throw error;
60
+ return normalizeHindsightConfig(HINDSIGHT_DEFAULTS);
61
+ }
62
+ }
27
63
 
28
64
  /** Explicit update: fresh check, stop if needed, install, verify, restore runtime state. */
29
65
  async updateService(serviceId, { getVersions = getServiceVersions, install = installServiceUpdate } = {}) {
66
+ if (isDocker(serviceId)) return this.updateDockerService(serviceId);
30
67
  if (!Object.hasOwn(SERVICE_PACKAGES, serviceId)) {
31
68
  return { success: false, message: serviceId === "proxy"
32
69
  ? "The built-in proxy is part of ai-helper; update ai-helper itself to update it."
@@ -143,6 +180,9 @@ export class ServiceManager {
143
180
  state = { services: {}, updatedAt: new Date().toISOString() };
144
181
  }
145
182
  }
183
+ state.services ||= {};
184
+ // agentmemory was replaced by Hindsight; never manage or stop a leftover entry.
185
+ delete state.services.agentmemory;
146
186
 
147
187
  for (const id of SERVICE_IDS) {
148
188
  const def = SERVICES[id];
@@ -171,6 +211,10 @@ export class ServiceManager {
171
211
  const discovered = await discoverRunningProcesses({ knownServices: state.services });
172
212
 
173
213
  for (const id of Object.keys(state.services)) {
214
+ if (isDocker(id)) {
215
+ if (await this.syncDockerService(state, id)) needsSave = true;
216
+ continue;
217
+ }
174
218
  const svc = state.services[id];
175
219
  const info = discovered[id];
176
220
 
@@ -210,6 +254,37 @@ export class ServiceManager {
210
254
  return state;
211
255
  }
212
256
 
257
+ /** Container state replaces PID tracking; Docker's port proxies are not the service. */
258
+ async syncDockerService(state, id) {
259
+ const svc = state.services[id] || {};
260
+ const config = this.hindsightConfig(state);
261
+ const urls = hindsightUrls(config);
262
+ let container = null;
263
+ let runtimeError;
264
+ if (Date.now() < this.dockerRetryAt) runtimeError = svc.runtimeError || "Docker not available";
265
+ else {
266
+ try { container = await inspectContainer(config.containerName, this.runDocker); }
267
+ catch (error) {
268
+ runtimeError = error.message;
269
+ // A stopped Docker Desktop must not stall every one-second dashboard refresh.
270
+ this.dockerRetryAt = Date.now() + 10000;
271
+ }
272
+ }
273
+ if (!runtimeError) this.dockerRetryAt = 0;
274
+ const next = {
275
+ id, name: SERVICES[id].name, runtime: "docker",
276
+ command: `docker container ${config.containerName} (${container?.image || config.image})`,
277
+ status: container?.running ? "running" : "stopped",
278
+ startedAt: container?.running ? container.startedAt : undefined,
279
+ url: urls.ui, apiUrl: urls.api, containerName: config.containerName,
280
+ containerId: container?.id, containerStatus: container ? container.status : runtimeError ? undefined : "missing",
281
+ managed: container ? container.managed : undefined, runtimeError,
282
+ };
283
+ if (JSON.stringify(next) === JSON.stringify(svc)) return false;
284
+ state.services[id] = next;
285
+ return true;
286
+ }
287
+
213
288
  /**
214
289
  * Synchronous load with PID liveness check.
215
290
  */
@@ -219,7 +294,7 @@ export class ServiceManager {
219
294
 
220
295
  for (const id of Object.keys(state.services)) {
221
296
  const svc = state.services[id];
222
- if (svc.status === "running") {
297
+ if (svc.status === "running" && !isDocker(id)) {
223
298
  if (!svc.pid || !isPidRunning(svc.pid)) {
224
299
  svc.status = "stopped";
225
300
  svc.pid = undefined;
@@ -336,6 +411,7 @@ export class ServiceManager {
336
411
  */
337
412
  async startService(serviceId, options) {
338
413
  if (serviceId === "proxy") return this.startProxyService(options);
414
+ if (isDocker(serviceId)) return this.startDockerService(serviceId);
339
415
  const def = SERVICES[serviceId];
340
416
  if (!def) {
341
417
  return { success: false, message: `Unknown service '${serviceId}'. Available: ${SERVICE_IDS.join(", ")}` };
@@ -398,6 +474,159 @@ export class ServiceManager {
398
474
  };
399
475
  }
400
476
 
477
+ /** Starts (or creates) the Hindsight container and reports success only after /health. */
478
+ async startDockerService(id) {
479
+ const state = this.readState();
480
+ let config;
481
+ try { config = this.hindsightConfig(state, { strict: true }); }
482
+ catch (error) { return { success: false, message: `Invalid Hindsight settings: ${error.message}. Fix them with 'aih status --ui' (c).` }; }
483
+ const urls = hindsightUrls(config);
484
+ const base = { url: urls.ui, apiUrl: urls.api, containerName: config.containerName };
485
+ const docker = await dockerInfo(this.runDocker);
486
+ if (!docker.available) return { ...base, success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
487
+ this.dockerRetryAt = 0;
488
+ const key = readHindsightApiKey();
489
+ const configHash = hindsightConfigHash(config, key.key);
490
+ let container;
491
+ try { container = await inspectContainer(config.containerName, this.runDocker, 10000); }
492
+ catch (error) { return { ...base, success: false, message: `Cannot inspect the Hindsight container: ${error.message}` }; }
493
+ if (container?.running) {
494
+ const health = await this.probeHealth(urls.api);
495
+ await this.syncState();
496
+ const pending = container.managed && container.configHash !== configHash ? " Saved settings differ: restart it to apply them." : "";
497
+ return { ...base, success: true, alreadyRunning: true, containerId: container.id, health,
498
+ message: `Hindsight container '${config.containerName}' already running | health: ${describeHealth(health)}.${pending}` };
499
+ }
500
+ let action;
501
+ if (container?.managed && container.configHash !== configHash) {
502
+ // Settings changed: recreate it. The named volume keeps the memory data.
503
+ const removed = await dockerLogged(id, ["rm", config.containerName], this.runDocker, 60000);
504
+ if (removed.exitCode !== 0) return { ...base, success: false, message: `Cannot recreate the Hindsight container: ${dockerError(removed)}` };
505
+ container = null;
506
+ action = "recreated";
507
+ }
508
+ if (container) {
509
+ const started = await dockerLogged(id, ["start", config.containerName], this.runDocker, 120000);
510
+ if (started.exitCode !== 0) return { ...base, success: false, message: `docker start failed: ${dockerError(started)}. See 'aih logs hindsight'.` };
511
+ action = "started";
512
+ } else {
513
+ if (!key.key && requiresApiKey(config)) {
514
+ 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}.` };
515
+ }
516
+ if (!(await imageId(config.image, this.runDocker))) {
517
+ const pulled = await dockerLogged(id, ["pull", config.image], this.runDocker, 30 * 60000);
518
+ if (pulled.exitCode !== 0) return { ...base, success: false, message: `docker pull ${config.image} failed: ${dockerError(pulled)}` };
519
+ }
520
+ const created = await dockerLogged(id, hindsightRunArgs(config, { configHash, keySource: key.source }), this.runDocker, 120000);
521
+ if (created.exitCode !== 0) return { ...base, success: false, message: `docker run failed: ${dockerError(created)}` };
522
+ action ||= "created";
523
+ }
524
+ const health = await this.waitForHindsight(config);
525
+ const synced = (await this.syncState()).services[id];
526
+ if (health.state !== "healthy") {
527
+ return { ...base, success: false, containerId: synced?.containerId, health,
528
+ message: `Hindsight container ${action}, but /health is ${describeHealth(health)}. Check 'aih logs hindsight'.` };
529
+ }
530
+ return { ...base, success: true, containerId: synced?.containerId, health,
531
+ message: `Hindsight container '${config.containerName}' ${action}; health: ${describeHealth(health)}` };
532
+ }
533
+
534
+ /** First boots initialize the database and download models: poll until healthy, exited or timed out. */
535
+ async waitForHindsight(config) {
536
+ const deadline = Date.now() + this.hindsightStartTimeoutMs;
537
+ const api = hindsightUrls(config).api;
538
+ for (let attempt = 0; ; attempt++) {
539
+ const health = await this.probeHealth(api);
540
+ if (health.state === "healthy" || Date.now() >= deadline) return health;
541
+ if (attempt % 5 === 4) {
542
+ const container = await inspectContainer(config.containerName, this.runDocker).catch(() => null);
543
+ if (!container?.running) return { ...health, state: "unreachable", error: `container ${container?.status || "missing"}` };
544
+ }
545
+ await sleep(this.hindsightPollMs);
546
+ }
547
+ }
548
+
549
+ async stopDockerService(id) {
550
+ const config = this.hindsightConfig();
551
+ // Never kill port owners: on Windows they are Docker Desktop's own processes.
552
+ const result = await dockerLogged(id, ["stop", config.containerName], this.runDocker, 60000);
553
+ await this.syncState();
554
+ if (result.exitCode !== 0 && !/no such container/i.test(result.stderr)) {
555
+ return { success: false, message: `docker stop ${config.containerName} failed: ${dockerError(result)}` };
556
+ }
557
+ return { success: true, message: `Hindsight container '${config.containerName}' stopped (data kept)` };
558
+ }
559
+
560
+ /** Pull, then recreate only containers aih created; other containers belong to their owner. */
561
+ async updateDockerService(id) {
562
+ if (this.updatesInProgress.has(id)) return { success: false, message: `An update for '${id}' is already in progress` };
563
+ this.updatesInProgress.add(id);
564
+ try {
565
+ const config = this.hindsightConfig(this.readState(), { strict: true });
566
+ const docker = await dockerInfo(this.runDocker);
567
+ if (!docker.available) return { success: false, message: `Docker is not available (${docker.error}). Start Docker Desktop and retry.` };
568
+ const container = await inspectContainer(config.containerName, this.runDocker, 10000);
569
+ if (container && !container.managed) {
570
+ return { success: false, message: `Container '${config.containerName}' was not created by aih${container.composeProject ? ` (docker compose project '${container.composeProject}')` : ""}; update it with the tool that created it, or remove it so aih can create its own.` };
571
+ }
572
+ const previousVersion = container?.running ? (await this.probeHealth(hindsightUrls(config).api)).version ?? null : null;
573
+ const pulled = await dockerLogged(id, ["pull", config.image], this.runDocker, 30 * 60000);
574
+ if (pulled.exitCode !== 0) return { success: false, previousVersion, message: `docker pull ${config.image} failed: ${dockerError(pulled)}` };
575
+ if (!container) return { success: true, updated: true, previousVersion, message: `Image ${config.image} pulled; the container is created on the next start` };
576
+ const pulledImage = await imageId(config.image, this.runDocker);
577
+ if (pulledImage && pulledImage === container.imageId) {
578
+ return { success: true, updated: false, alreadyUpToDate: true, previousVersion, version: previousVersion,
579
+ message: `'${id}' already uses the latest ${config.image}` };
580
+ }
581
+ const removed = await dockerLogged(id, ["rm", "-f", config.containerName], this.runDocker, 120000);
582
+ if (removed.exitCode !== 0) return { success: false, previousVersion, message: `Cannot replace the container: ${dockerError(removed)}` };
583
+ if (!container.running) {
584
+ await this.syncState();
585
+ return { success: true, updated: true, restarted: false, previousVersion,
586
+ message: `Image ${config.image} updated; the container is recreated on the next start (data volume kept)` };
587
+ }
588
+ const started = await this.startDockerService(id);
589
+ const version = started.health?.version ?? null;
590
+ return { ...started, updated: true, restarted: started.success, previousVersion, version,
591
+ message: started.success ? `'${id}' updated${previousVersion && version ? ` from ${previousVersion} to ${version}` : ""} and restarted`
592
+ : `Image updated, but restart failed: ${started.message}` };
593
+ } catch (error) {
594
+ return { success: false, message: `Update failed: ${error.message}` };
595
+ } finally {
596
+ this.updatesInProgress.delete(id);
597
+ }
598
+ }
599
+
600
+ /** Non-secret settings go to state.json; the key only to ~/.aih/hindsight.env. */
601
+ saveHindsightConfiguration({ config, apiKey = "" } = {}) {
602
+ const normalized = normalizeHindsightConfig(config);
603
+ if (apiKey) {
604
+ validateHindsightApiKey(apiKey);
605
+ saveHindsightApiKey(apiKey);
606
+ }
607
+ const state = this.readState();
608
+ state.config = { ...state.config, hindsight: normalized };
609
+ this.saveState(state);
610
+ return normalized;
611
+ }
612
+
613
+ /** Applies saved settings to a running aih-managed container by recreating it. */
614
+ async applyHindsightConfiguration() {
615
+ const config = this.hindsightConfig(this.readState());
616
+ let container;
617
+ try { container = await inspectContainer(config.containerName, this.runDocker, 10000); }
618
+ catch (error) { return { success: true, warning: true, message: `Hindsight settings saved; Docker not available (${error.message})` }; }
619
+ if (!container?.running) return { success: true, message: "Hindsight settings saved for its next start" };
620
+ if (!container.managed) {
621
+ return { success: true, warning: true, message: `Hindsight settings saved; container '${config.containerName}' was not created by aih and is left unchanged` };
622
+ }
623
+ if (container.configHash === hindsightConfigHash(config, readHindsightApiKey().key)) return { success: true, message: "Hindsight unchanged" };
624
+ const stopped = await this.stopDockerService("hindsight");
625
+ if (!stopped.success) return stopped;
626
+ const started = await this.startDockerService("hindsight");
627
+ return { ...started, message: started.success ? `Hindsight recreated with the new settings (${describeHealth(started.health)})` : started.message };
628
+ }
629
+
401
630
  async startProxyService(options) {
402
631
  const state = this.loadState();
403
632
  const current = state.services.proxy;
@@ -494,6 +723,7 @@ export class ServiceManager {
494
723
  * Stops a single service cleanly, executing stop commands and clearing ports/workers.
495
724
  */
496
725
  async stopService(serviceId) {
726
+ if (isDocker(serviceId)) return this.stopDockerService(serviceId);
497
727
  const def = SERVICES[serviceId];
498
728
  const state = await this.syncState();
499
729
  const current = state.services[serviceId];
@@ -569,23 +799,33 @@ export class ServiceManager {
569
799
  }
570
800
 
571
801
  /** Desired configuration is separate from the running worker's snapshot. */
572
- saveProxyConfiguration(options, { startServices } = {}) {
802
+ saveProxyConfiguration(options, { startServices, hindsight } = {}) {
573
803
  const config = normalizeProxyOptions(options);
574
804
  const startup = startServices === undefined ? undefined : normalizeStartServices(startServices);
805
+ // Validate everything before writing the key file or state.
806
+ if (hindsight) {
807
+ normalizeHindsightConfig(hindsight.config);
808
+ if (hindsight.apiKey) validateHindsightApiKey(hindsight.apiKey);
809
+ this.saveHindsightConfiguration(hindsight);
810
+ }
575
811
  const state = this.readState();
576
812
  state.config = { ...state.config, proxyOptions: savedProxyOptions(config) };
577
813
  if (startup) state.config.startServices = startup;
578
814
  this.saveState(state);
579
- return { success: true, message: "Configuration saved for the next start/restart. Current proxy unchanged." };
815
+ return { success: true, message: `Configuration saved for the next start/restart. Current proxy${hindsight ? " and Hindsight" : ""} unchanged.` };
580
816
  }
581
817
 
582
818
  /** Validate before stopping; recover the old worker if applying the draft fails. */
583
- async applyProxyConfiguration(options, { preflight = preflightProxy, startServices } = {}) {
819
+ async applyProxyConfiguration(options, { preflight = preflightProxy, startServices, hindsight } = {}) {
584
820
  if (this.proxySetupBusy) return { success: false, message: "Proxy setup already in progress" };
585
821
  this.proxySetupBusy = true;
586
822
  try {
587
823
  const config = normalizeProxyOptions(options);
588
824
  if (startServices !== undefined) startServices = normalizeStartServices(startServices);
825
+ if (hindsight) {
826
+ normalizeHindsightConfig(hindsight.config);
827
+ if (hindsight.apiKey) validateHindsightApiKey(hindsight.apiKey);
828
+ }
589
829
  const state = await this.syncState();
590
830
  const previous = state.services.proxy;
591
831
  const oldDesired = state.config?.proxyOptions;
@@ -594,7 +834,7 @@ export class ServiceManager {
594
834
  if (wasRunning) {
595
835
  const stopped = await this.stopService("proxy");
596
836
  if (!stopped.success) {
597
- this.saveProxyConfiguration(config, { startServices });
837
+ this.saveProxyConfiguration(config, { startServices, hindsight });
598
838
  return { ...stopped, saved: true, applied: false,
599
839
  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
840
  }
@@ -603,8 +843,10 @@ export class ServiceManager {
603
843
  try {
604
844
  const result = await this.startService("proxy", config);
605
845
  if (!result.success) throw new Error(result.message || "Startup failed");
606
- this.saveProxyConfiguration(config, { startServices });
607
- return { ...result, checks, message: ["Configuration applied and saved", ...(checks || []).filter(c => c.startsWith("Warning:"))].join(" | ") };
846
+ this.saveProxyConfiguration(config, { startServices, hindsight });
847
+ const memory = hindsight ? await this.applyHindsightConfiguration() : null;
848
+ return { ...result, checks, hindsight: memory, message: ["Configuration applied and saved", ...(memory ? [memory.message] : []),
849
+ ...(checks || []).filter(c => c.startsWith("Warning:"))].join(" | ") };
608
850
  } catch (error) {
609
851
  // A failed start may have persisted a runtime entry before a later error.
610
852
  try { await this.stopService("proxy"); } catch {}
@@ -649,6 +891,19 @@ export class ServiceManager {
649
891
  * Displays or follows logs for a service.
650
892
  */
651
893
  async showLogs(serviceId, lines = 50, follow = false) {
894
+ if (isDocker(serviceId)) {
895
+ const config = this.hindsightConfig();
896
+ const logPath = getServiceLogPath(serviceId);
897
+ if (existsSync(logPath)) console.log(gray(`[aih] Docker commands run by aih are logged in: ${logPath}`));
898
+ console.log(gray(`[aih] docker logs --tail ${lines}${follow ? " --follow" : ""} ${config.containerName}\n`));
899
+ await new Promise(resolve => {
900
+ const child = spawn("docker", ["logs", "--tail", String(lines), ...(follow ? ["--follow"] : []), config.containerName],
901
+ { stdio: "inherit", windowsHide: true });
902
+ child.once("error", error => { console.log(red(`[aih] Cannot run docker logs: ${error.message}`)); resolve(); });
903
+ child.once("exit", resolve);
904
+ });
905
+ return;
906
+ }
652
907
  const logPath = getServiceLogPath(serviceId);
653
908
  if (!existsSync(logPath)) {
654
909
  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;
@@ -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", "agentmemory", ...SERVICE_IDS.filter(id => !["ocx", "agentmemory"].includes(id)), "proxy",
4
+ "ocx", "hindsight", ...SERVICE_IDS.filter(id => !["ocx", "hindsight"].includes(id)), "proxy",
5
5
  ]);
6
- export const DEFAULT_START_SERVICES = Object.freeze(["ocx", "agentmemory", "proxy"]);
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
  }
@@ -1,18 +1,49 @@
1
1
  import { PROXY_FIELDS, proxySetupDraft, normalizeSetupDraft } from "./proxy-setup.js";
2
2
  import { STARTUP_SERVICE_IDS, normalizeStartServices } from "./startup-services.js";
3
+ import {
4
+ HINDSIGHT_DEFAULTS,
5
+ HINDSIGHT_KEY_ENV,
6
+ normalizeHindsightConfig,
7
+ readHindsightApiKey,
8
+ validateHindsightApiKey,
9
+ } from "./hindsight.js";
3
10
 
4
11
  const STARTUP_FIELD = { key: "startServices", group: "Startup", label: "Services started by aih start / up",
5
12
  choices: STARTUP_SERVICE_IDS, multiple: true,
6
- help: "Arrows move; Space toggles. Choose at least one service. Explicit CLI targets override this list. RTK is a filter; bundled pxpipe does not need its standalone service. Changes take effect on the next aih start/up." };
13
+ help: "Arrows move; Space toggles. Choose at least one service. Explicit CLI targets override this list. RTK is a filter; bundled pxpipe does not need its standalone service. Hindsight runs in Docker; selecting it adds its settings to this setup. Changes take effect on the next aih start/up." };
14
+
15
+ /** Shown only when Hindsight is selected for start/up. "config" maps to the saved settings. */
16
+ export const HINDSIGHT_FIELDS = Object.freeze([
17
+ { key: "hindsightContainer", config: "containerName", group: "Hindsight", label: "Hindsight container name", help: "Docker container started/stopped by aih. An existing container with this name is reused as is; the settings below apply only to containers aih creates." },
18
+ { key: "hindsightImage", config: "image", group: "Hindsight", label: "Docker image", help: "Default ghcr.io/vectorize-io/hindsight:latest. Pin a tag (e.g. :1.1.0) for repeatable installs." },
19
+ { key: "hindsightApiPort", config: "apiPort", group: "Hindsight", label: "API port", help: "Loopback port for the Hindsight API and its /health check. Default 8888." },
20
+ { key: "hindsightUiPort", config: "uiPort", group: "Hindsight", label: "Web UI port", help: "Loopback port of the Hindsight control plane, opened with o in the dashboard. Default 9999." },
21
+ { key: "hindsightVolume", config: "volume", group: "Hindsight", label: "Data volume", help: "Docker volume holding the memory database (/home/hindsight/.pg0). Kept when the container is recreated or updated." },
22
+ { key: "hindsightLlmProvider", config: "llmProvider", group: "Hindsight LLM", label: "LLM provider", help: "HINDSIGHT_API_LLM_PROVIDER, e.g. openai, anthropic, gemini, groq, ollama, lmstudio. OpenAI-compatible gateways use openai plus a base URL." },
23
+ { key: "hindsightLlmModel", config: "llmModel", group: "Hindsight LLM", label: "LLM model", help: "HINDSIGHT_API_LLM_MODEL. Empty = Hindsight's default for the provider." },
24
+ { key: "hindsightLlmBaseUrl", config: "llmBaseUrl", group: "Hindsight LLM", label: "LLM base URL", help: "Optional OpenAI-compatible endpoint. Inside the container use host.docker.internal instead of localhost, e.g. http://host.docker.internal:10100/v1. Empty = provider default." },
25
+ { key: "hindsightApiKey", secret: true, group: "Hindsight LLM", label: "LLM API key", help: `Saved to ~/.aih/hindsight.env and passed with docker --env-file; never stored in state.json or on command lines. Empty = keep the saved key (or ${HINDSIGHT_KEY_ENV} from the environment).` },
26
+ { key: "hindsightEnvFile", config: "envFile", group: "Hindsight advanced", label: "Extra environment file", help: "Optional docker --env-file with advanced HINDSIGHT_* settings (timeouts, failover models...). Empty = none." },
27
+ ]);
7
28
 
8
29
  const clean = value => String(value ?? "").replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
30
+ const isHindsightField = field => field.key.startsWith("hindsight");
31
+
32
+ function savedHindsight(state) {
33
+ try { return normalizeHindsightConfig(state.config?.hindsight); }
34
+ catch { return normalizeHindsightConfig(HINDSIGHT_DEFAULTS); }
35
+ }
9
36
 
10
37
  /** Pure wizard state; all process and disk actions belong to Dashboard/manager. */
11
38
  export class ProxySetupWizard {
12
- constructor(state) {
39
+ constructor(state, { keyStatus = readHindsightApiKey().source } = {}) {
13
40
  this.draft = proxySetupDraft(state);
14
41
  this.currentStartServices = normalizeStartServices(state.config?.startServices);
15
42
  this.draft.startServices = this.currentStartServices.join(",");
43
+ this.hindsightSaved = state.config?.hindsight ? savedHindsight(state) : null;
44
+ const hindsight = savedHindsight(state);
45
+ for (const f of HINDSIGHT_FIELDS) this.draft[f.key] = f.secret ? "" : String(hindsight[f.config] ?? "");
46
+ this.keyStatus = keyStatus;
16
47
  this.serviceIndex = 0;
17
48
  this.initial = { ...this.draft };
18
49
  this.active = state.services?.proxy?.proxyOptions;
@@ -28,13 +59,34 @@ export class ProxySetupWizard {
28
59
  this.pasting = false;
29
60
  }
30
61
 
31
- get fields() { return [...PROXY_FIELDS.filter(f => !f.stage || this.draft.preset.split("-").includes(f.stage)), STARTUP_FIELD]; }
62
+ get hindsightSelected() { return this.draft.startServices.split(",").includes("hindsight"); }
63
+ get fields() {
64
+ return [...PROXY_FIELDS.filter(f => !f.stage || this.draft.preset.split("-").includes(f.stage)), STARTUP_FIELD,
65
+ ...(this.hindsightSelected ? HINDSIGHT_FIELDS : [])];
66
+ }
32
67
  get field() { return this.fields[this.step]; }
33
68
  get summary() { return this.step >= this.fields.length; }
34
69
  get dirty() { return JSON.stringify(this.initial) !== JSON.stringify(this.draft); }
35
70
 
71
+ hindsightDraft() {
72
+ return Object.fromEntries(HINDSIGHT_FIELDS.filter(f => !f.secret).map(f => [f.config, this.draft[f.key]]));
73
+ }
74
+
75
+ /** null when Hindsight is not started by start/up: its settings are then left untouched. */
76
+ hindsightSettings() {
77
+ if (!this.hindsightSelected) return null;
78
+ const apiKey = this.draft.hindsightApiKey.trim();
79
+ if (apiKey) validateHindsightApiKey(apiKey);
80
+ return { config: normalizeHindsightConfig(this.hindsightDraft()), apiKey };
81
+ }
82
+
83
+ keyDescription() {
84
+ return this.keyStatus === "file" ? "saved" : this.keyStatus === "env" ? `from ${HINDSIGHT_KEY_ENV}` : "not set";
85
+ }
86
+
36
87
  validate() {
37
88
  normalizeStartServices(this.draft.startServices.split(","));
89
+ this.hindsightSettings();
38
90
  return normalizeSetupDraft(this.draft);
39
91
  }
40
92
 
@@ -42,6 +94,8 @@ export class ProxySetupWizard {
42
94
  const field = this.field;
43
95
  const value = this.draft[field.key];
44
96
  if (field.multiple) { normalizeStartServices(value.split(",")); return; }
97
+ if (field.secret) { validateHindsightApiKey(value.trim()); return; }
98
+ if (isHindsightField(field)) { normalizeHindsightConfig(this.hindsightDraft()); return; }
45
99
  // Validate only this field, against known valid defaults, without discarding other edits.
46
100
  const base = proxySetupDraft({ services: {} });
47
101
  base.upstream = "https://example.com";
@@ -147,7 +201,7 @@ export class ProxySetupWizard {
147
201
  if (line || !lines.length) lines.push(line);
148
202
  return lines;
149
203
  };
150
- const title = `PROXY SETUP | ${this.summary ? "Summary" : `${this.field.group} (${this.step + 1}/${this.fields.length})`}`;
204
+ const title = `AIH SETUP | ${this.summary ? "Summary" : `${this.field.group} (${this.step + 1}/${this.fields.length})`}`;
151
205
  let body = [];
152
206
  if (this.summary) {
153
207
  body = [...PROXY_FIELDS, STARTUP_FIELD].flatMap(f => {
@@ -155,6 +209,15 @@ export class ProxySetupWizard {
155
209
  const after = this.draft[f.key];
156
210
  return wrap(`${before !== after ? "* " : " "}${f.label}: ${after || (f.key === "models" ? "pxpipe defaults; RTK/Headroom on all" : "(none)")}${before !== after ? ` (previous: ${before || "empty"})` : ""}`);
157
211
  });
212
+ if (this.hindsightSelected) {
213
+ body.push(...HINDSIGHT_FIELDS.flatMap(f => {
214
+ if (f.secret) return wrap(this.draft[f.key].trim() ? `* ${f.label}: new key (hidden)` : ` ${f.label}: unchanged (${this.keyDescription()})`);
215
+ const before = this.initial[f.key];
216
+ const after = this.draft[f.key];
217
+ return wrap(`${before !== after ? "* " : " "}${f.label}: ${after || "(none)"}${before !== after ? ` (previous: ${before || "empty"})` : ""}`);
218
+ }));
219
+ body.push(...wrap("Hindsight: settings are saved; apply recreates a running container created by aih (data volume kept). Other containers are left unchanged."));
220
+ }
158
221
  body.push(...wrap(this.running ? "WARNING: apply now restarts the proxy and interrupts active requests/streams." : "Apply now starts the proxy. Save only leaves it stopped."));
159
222
  body.push(...this.checks.flatMap(wrap));
160
223
  if (this.error) body.push(...wrap(`Error: ${this.error}`));
@@ -166,12 +229,21 @@ export class ProxySetupWizard {
166
229
  : `${v === this.draft[f.key] ? ">" : " "} ${v.replaceAll("-", " -> ")}`));
167
230
  else {
168
231
  const value = this.draft[f.key];
232
+ const shown = f.secret ? "*".repeat(value.length) : value;
169
233
  const start = Math.max(0, this.cursor - width + 6);
170
- body.push(...wrap("> " + value.slice(start, this.cursor) + "|" + value.slice(this.cursor, start + width - 4)));
234
+ body.push(...wrap("> " + shown.slice(start, this.cursor) + "|" + shown.slice(this.cursor, start + width - 4)));
235
+ }
236
+ if (f.secret) {
237
+ body.push(...wrap("Initial value: (empty: keep the current key)"));
238
+ body.push(...wrap(`Current setting: key ${this.keyDescription()}`));
239
+ } else if (isHindsightField(f)) {
240
+ body.push(...wrap(`Initial value: ${this.initial[f.key] || "(empty)"}`));
241
+ body.push(...wrap(`Current setting: ${this.hindsightSaved ? String(this.hindsightSaved[f.config] ?? "") || "(empty)" : "(not configured: defaults)"}`));
242
+ } else {
243
+ body.push(...wrap(`Initial value: ${this.initial[f.key] || "(empty)"}`));
244
+ const current = f.multiple ? this.currentStartServices.join(",") : this.active ? String(this.active[f.key] ?? "") || "(empty)" : "(not configured)";
245
+ body.push(...wrap(`Current setting: ${current}${!f.multiple && !this.running && this.active ? " (proxy stopped)" : ""}`));
171
246
  }
172
- body.push(...wrap(`Initial value: ${this.initial[f.key] || "(empty)"}`));
173
- const current = f.multiple ? this.currentStartServices.join(",") : this.active ? String(this.active[f.key] ?? "") || "(empty)" : "(not configured)";
174
- body.push(...wrap(`Current setting: ${current}${!f.multiple && !this.running && this.active ? " (proxy stopped)" : ""}`));
175
247
  }
176
248
  const actions = ["Check", "Save only", "Save and apply now", "Edit", "Cancel"];
177
249
  const controls = this.summary
@@ -179,7 +251,7 @@ export class ProxySetupWizard {
179
251
  : wrap("Enter/Tab next | Shift+Tab back | Esc cancel").concat(wrap(this.field.multiple ? "Arrows move | Space toggle" : this.field.choices ? "Arrows/Space change" : "Ctrl+U clear | Home/End move cursor"));
180
252
  const hint = this.summary && this.action === 2
181
253
  ? this.running ? "RESTART: interrupts requests/streams." : "Apply starts the proxy."
182
- : this.summary ? "Arrows select | Enter confirm | Esc cancel" : "Local draft; proxy unchanged.";
254
+ : this.summary ? "Arrows select | Enter confirm | Esc cancel" : "Local draft; services unchanged.";
183
255
  const status = this.cancelPending ? "Discard draft? Enter/Esc confirms; any other key continues" : busy ? "Operation in progress..." : this.error || hint;
184
256
  const statusLines = wrap(status);
185
257
  const tail = [...controls.flatMap(wrap), ...statusLines.slice(0, 2)];