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