@drakonkat/ai-helper 1.0.0

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,160 @@
1
+ import { VERSION, APP_NAME } from "../config.js";
2
+
3
+ const isColorSupported = !process.env.NO_COLOR && (process.stdout.isTTY || process.env.FORCE_COLOR);
4
+
5
+ function wrap(code, close) {
6
+ return (text) =>
7
+ isColorSupported ? `\x1b[${code}m${text}\x1b[${close}m` : String(text);
8
+ }
9
+
10
+ export const bold = wrap(1, 22);
11
+ export const dim = wrap(2, 22);
12
+ export const italic = wrap(3, 23);
13
+ export const underline = wrap(4, 24);
14
+
15
+ export const black = wrap(30, 39);
16
+ export const red = wrap(31, 39);
17
+ export const green = wrap(32, 39);
18
+ export const yellow = wrap(33, 39);
19
+ export const blue = wrap(34, 39);
20
+ export const magenta = wrap(35, 39);
21
+ export const cyan = wrap(36, 39);
22
+ export const white = wrap(37, 39);
23
+ export const gray = wrap(90, 39);
24
+
25
+ export const bgGreen = wrap(42, 49);
26
+ export const bgRed = wrap(41, 49);
27
+ export const bgYellow = wrap(43, 49);
28
+ export const bgCyan = wrap(46, 49);
29
+
30
+ /**
31
+ * Removes ANSI escape sequences for calculating display length.
32
+ * @param {string} str
33
+ * @returns {string}
34
+ */
35
+ export function stripAnsi(str) {
36
+ // eslint-disable-next-line no-control-regex
37
+ return str.replace(/\x1b\[[0-9;]*m/g, "");
38
+ }
39
+
40
+ /**
41
+ * Returns formatted status badge.
42
+ * @param {"running" | "stopped" | "error"} status
43
+ * @returns {string}
44
+ */
45
+ export function badgeStatus(status) {
46
+ switch (status) {
47
+ case "running":
48
+ return green(bold("● RUNNING"));
49
+ case "stopped":
50
+ return gray("○ STOPPED");
51
+ case "error":
52
+ return red(bold("✖ ERROR"));
53
+ default:
54
+ return gray("? UNKNOWN");
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Formats uptime from an ISO timestamp.
60
+ * @param {string} [startedAtIso]
61
+ * @returns {string}
62
+ */
63
+ export function formatUptime(startedAtIso) {
64
+ if (!startedAtIso) return "-";
65
+ const start = new Date(startedAtIso).getTime();
66
+ if (isNaN(start)) return "-";
67
+
68
+ const elapsedSeconds = Math.max(0, Math.floor((Date.now() - start) / 1000));
69
+ if (elapsedSeconds < 60) {
70
+ return `${elapsedSeconds}s`;
71
+ }
72
+ const minutes = Math.floor(elapsedSeconds / 60);
73
+ const seconds = elapsedSeconds % 60;
74
+ if (minutes < 60) {
75
+ return `${minutes}m ${seconds}s`;
76
+ }
77
+ const hours = Math.floor(minutes / 60);
78
+ const remMinutes = minutes % 60;
79
+ if (hours < 24) {
80
+ return `${hours}h ${remMinutes}m`;
81
+ }
82
+ const days = Math.floor(hours / 24);
83
+ const remHours = hours % 24;
84
+ return `${days}d ${remHours}h`;
85
+ }
86
+
87
+ /**
88
+ * Formats byte counts into human readable strings.
89
+ * @param {number} [bytes]
90
+ * @returns {string}
91
+ */
92
+ export function formatBytes(bytes) {
93
+ if (bytes === undefined || bytes === null || isNaN(bytes)) return "-";
94
+ if (bytes === 0) return "0 B";
95
+ const k = 1024;
96
+ const sizes = ["B", "KB", "MB", "GB"];
97
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
98
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
99
+ }
100
+
101
+ /**
102
+ * Renders a clean aligned terminal table.
103
+ * @param {Array<string | { header: string; align?: "left" | "right" | "center" }>} headers
104
+ * @param {Array<Array<string | number>>} rows
105
+ * @returns {string}
106
+ */
107
+ export function renderTable(headers, rows) {
108
+ const colDefs = headers.map(h =>
109
+ typeof h === "string" ? { header: h, align: "left" } : h
110
+ );
111
+
112
+ const colWidths = colDefs.map((col, colIdx) => {
113
+ let max = stripAnsi(col.header).length;
114
+ for (const row of rows) {
115
+ const cell = row[colIdx] !== undefined ? String(row[colIdx]) : "";
116
+ const len = stripAnsi(cell).length;
117
+ if (len > max) max = len;
118
+ }
119
+ return max;
120
+ });
121
+
122
+ function pad(text, width, align = "left") {
123
+ const rawLen = stripAnsi(text).length;
124
+ const diff = Math.max(0, width - rawLen);
125
+ if (align === "right") {
126
+ return " ".repeat(diff) + text;
127
+ } else if (align === "center") {
128
+ const left = Math.floor(diff / 2);
129
+ const right = diff - left;
130
+ return " ".repeat(left) + text + " ".repeat(right);
131
+ }
132
+ return text + " ".repeat(diff);
133
+ }
134
+
135
+ const headerLine = colDefs
136
+ .map((col, idx) => bold(cyan(pad(col.header, colWidths[idx], col.align))))
137
+ .join(" ");
138
+
139
+ const dividerLine = colWidths
140
+ .map(w => gray("─".repeat(w)))
141
+ .join(" ");
142
+
143
+ const bodyLines = rows.map(row => {
144
+ return colDefs
145
+ .map((col, idx) => {
146
+ const cell = row[idx] !== undefined ? String(row[idx]) : "";
147
+ return pad(cell, colWidths[idx], col.align);
148
+ })
149
+ .join(" ");
150
+ });
151
+
152
+ return [headerLine, dividerLine, ...bodyLines].join("\n");
153
+ }
154
+
155
+ export function printBanner() {
156
+ console.log(
157
+ `${bold(cyan(APP_NAME))} ${gray(`v${VERSION}`)} ${dim("— Background AI Ecosystem Service Manager")}\n`
158
+ );
159
+ }
160
+
@@ -0,0 +1,63 @@
1
+ import { homedir } from "os";
2
+ import { join, resolve, normalize } from "path";
3
+ import { existsSync, mkdirSync } from "fs";
4
+
5
+ export function getAihDir() {
6
+ const custom = process.env.AIH_HOME;
7
+ if (custom && custom.trim().length > 0) {
8
+ return resolve(custom);
9
+ }
10
+ return join(homedir(), ".aih");
11
+ }
12
+
13
+ export function getStateFilePath() {
14
+ return join(getAihDir(), "state.json");
15
+ }
16
+
17
+ export function getLogsDir() {
18
+ return join(getAihDir(), "logs");
19
+ }
20
+
21
+ export function getServiceLogPath(serviceId) {
22
+ return join(getLogsDir(), `${serviceId}.log`);
23
+ }
24
+
25
+ export function getLocalBinDir() {
26
+ return join(homedir(), ".local", "bin");
27
+ }
28
+
29
+ export function ensureDir(dirPath) {
30
+ if (!existsSync(dirPath)) {
31
+ mkdirSync(dirPath, { recursive: true });
32
+ }
33
+ }
34
+
35
+ export function isLocalBinInPath() {
36
+ const localBin = normalize(resolve(getLocalBinDir())).toLowerCase();
37
+ const pathEnv = process.env.PATH || "";
38
+ const delimiter = process.platform === "win32" ? ";" : ":";
39
+
40
+ const entries = pathEnv
41
+ .split(delimiter)
42
+ .map(p => p.trim())
43
+ .filter(p => p.length > 0)
44
+ .map(p => {
45
+ try {
46
+ return normalize(resolve(p)).toLowerCase();
47
+ } catch {
48
+ return p.toLowerCase();
49
+ }
50
+ });
51
+
52
+ return entries.includes(localBin);
53
+ }
54
+
55
+ export function getAddToPathInstructions() {
56
+ const localBin = getLocalBinDir();
57
+ return {
58
+ powershell: `[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";${localBin}", "User")`,
59
+ cmd: `setx PATH "%PATH%;${localBin}"`,
60
+ bash: `echo 'export PATH="${localBin}:$PATH"' >> ~/.bashrc && source ~/.bashrc`,
61
+ };
62
+ }
63
+
@@ -0,0 +1,369 @@
1
+ import { spawn } from "node:child_process";
2
+ import { openSync, closeSync, appendFileSync } from "node:fs";
3
+ import { ensureDir, getLogsDir } from "./path.js";
4
+
5
+ /**
6
+ * Async sleep utility compatible with Node.js and Bun.
7
+ * @param {number} ms
8
+ * @returns {Promise<void>}
9
+ */
10
+ export function sleep(ms) {
11
+ return new Promise(resolve => setTimeout(resolve, ms));
12
+ }
13
+
14
+ /**
15
+ * Helper to run a command and return stdout/stderr asynchronously.
16
+ * @param {string} cmd
17
+ * @param {string[]} args
18
+ * @returns {Promise<{ exitCode: number; stdout: string; stderr: string }>}
19
+ */
20
+ export function execCommand(cmd, args) {
21
+ return new Promise(resolve => {
22
+ try {
23
+ const proc = spawn(cmd, args, {
24
+ stdio: ["ignore", "pipe", "pipe"],
25
+ windowsHide: true,
26
+ });
27
+
28
+ let stdout = "";
29
+ let stderr = "";
30
+
31
+ proc.stdout?.on("data", d => (stdout += d.toString()));
32
+ proc.stderr?.on("data", d => (stderr += d.toString()));
33
+
34
+ proc.on("close", exitCode => {
35
+ resolve({ exitCode: exitCode ?? 0, stdout, stderr });
36
+ });
37
+
38
+ proc.on("error", err => {
39
+ resolve({ exitCode: 1, stdout: "", stderr: err.message });
40
+ });
41
+ } catch (err) {
42
+ resolve({ exitCode: 1, stdout: "", stderr: err.message });
43
+ }
44
+ });
45
+ }
46
+
47
+ /**
48
+ * Checks if a process with the given PID is currently active.
49
+ * @param {number} [pid]
50
+ * @returns {boolean}
51
+ */
52
+ export function isPidRunning(pid) {
53
+ if (!pid || pid <= 0) return false;
54
+ try {
55
+ return process.kill(pid, 0);
56
+ } catch (err) {
57
+ if (err?.code === "ESRCH") {
58
+ return false;
59
+ }
60
+ if (err?.code === "EPERM") {
61
+ return true;
62
+ }
63
+ return false;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Opens a URL in the user's default web browser cross-platform.
69
+ * @param {string} url
70
+ */
71
+ export function openBrowser(url) {
72
+ if (!url) return;
73
+ try {
74
+ if (process.platform === "win32") {
75
+ const proc = spawn("cmd.exe", ["/c", "start", "", url], {
76
+ detached: true,
77
+ stdio: "ignore",
78
+ windowsHide: true,
79
+ });
80
+ proc.unref();
81
+ } else if (process.platform === "darwin") {
82
+ const proc = spawn("open", [url], {
83
+ detached: true,
84
+ stdio: "ignore",
85
+ });
86
+ proc.unref();
87
+ } else {
88
+ const proc = spawn("xdg-open", [url], {
89
+ detached: true,
90
+ stdio: "ignore",
91
+ });
92
+ proc.unref();
93
+ }
94
+ } catch {}
95
+ }
96
+
97
+ /**
98
+ * Kills a process and its entire child process tree.
99
+ * @param {number} pid
100
+ * @returns {Promise<{ success: boolean; message: string }>}
101
+ */
102
+ export async function killProcessTree(pid) {
103
+ if (!isPidRunning(pid)) {
104
+ return { success: true, message: `Process ${pid} is not running` };
105
+ }
106
+
107
+ if (process.platform === "win32") {
108
+ try {
109
+ const res = await execCommand("taskkill.exe", ["/pid", String(pid), "/T", "/F"]);
110
+ await sleep(200);
111
+
112
+ if (!isPidRunning(pid)) {
113
+ return { success: true, message: `Terminated process tree for PID ${pid}` };
114
+ }
115
+
116
+ try {
117
+ process.kill(pid, "SIGKILL");
118
+ } catch {}
119
+
120
+ return {
121
+ success: !isPidRunning(pid),
122
+ message: res.stdout.trim() || res.stderr.trim() || `Killed process ${pid}`,
123
+ };
124
+ } catch (err) {
125
+ try {
126
+ process.kill(pid, "SIGKILL");
127
+ return { success: true, message: `Killed process ${pid} via signal fallback` };
128
+ } catch {
129
+ return { success: false, message: err?.message || String(err) };
130
+ }
131
+ }
132
+ } else {
133
+ try {
134
+ try {
135
+ process.kill(-pid, "SIGTERM");
136
+ } catch {
137
+ process.kill(pid, "SIGTERM");
138
+ }
139
+
140
+ for (let i = 0; i < 5; i++) {
141
+ if (!isPidRunning(pid)) break;
142
+ await sleep(100);
143
+ }
144
+
145
+ if (isPidRunning(pid)) {
146
+ try {
147
+ process.kill(-pid, "SIGKILL");
148
+ } catch {
149
+ process.kill(pid, "SIGKILL");
150
+ }
151
+ }
152
+
153
+ await sleep(100);
154
+ const stopped = !isPidRunning(pid);
155
+ return {
156
+ success: stopped,
157
+ message: stopped ? `Terminated process ${pid}` : `Failed to terminate process ${pid}`,
158
+ };
159
+ } catch (err) {
160
+ return { success: false, message: err?.message || String(err) };
161
+ }
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Spawns a background detached service and redirects output to a log file.
167
+ * @param {string} command
168
+ * @param {string} logFilePath
169
+ * @param {{ env?: Record<string, string>; cwd?: string }} [options]
170
+ * @returns {{ pid: number }}
171
+ */
172
+ export function spawnDetachedProcess(command, logFilePath, options) {
173
+ ensureDir(getLogsDir());
174
+
175
+ const timestamp = new Date().toISOString();
176
+ const banner = `\n[aih] ========================================\n[aih] Service started at: ${timestamp}\n[aih] Command: ${command}\n[aih] ========================================\n\n`;
177
+
178
+ try {
179
+ appendFileSync(logFilePath, banner, "utf-8");
180
+ } catch {}
181
+
182
+ const fd = openSync(logFilePath, "a");
183
+
184
+ let proc;
185
+ if (process.platform === "win32") {
186
+ proc = spawn("cmd.exe", ["/c", command], {
187
+ detached: true,
188
+ stdio: ["ignore", fd, fd],
189
+ env: { ...process.env, ...options?.env },
190
+ cwd: options?.cwd,
191
+ windowsHide: true,
192
+ });
193
+ } else {
194
+ proc = spawn("sh", ["-c", command], {
195
+ detached: true,
196
+ stdio: ["ignore", fd, fd],
197
+ env: { ...process.env, ...options?.env },
198
+ cwd: options?.cwd,
199
+ });
200
+ }
201
+
202
+ proc.unref();
203
+ try {
204
+ closeSync(fd);
205
+ } catch {}
206
+
207
+ return { pid: proc.pid };
208
+ }
209
+
210
+ /**
211
+ * Scans the OS process table and listening ports to discover active services and their URLs.
212
+ * @returns {Promise<Record<string, { pid: number; command: string; startedAt?: string; url?: string }>>}
213
+ */
214
+ export async function discoverRunningProcesses() {
215
+ const discovered = {};
216
+
217
+ if (process.platform === "win32") {
218
+ try {
219
+ const script = `
220
+ $procs = Get-CimInstance Win32_Process | Where-Object {
221
+ $_.CommandLine -and
222
+ ($_.CommandLine -match 'pxpipe|ocx|agentmemory|iii') -and
223
+ ($_.CommandLine -notmatch 'ai-helper|Get-CimInstance|Where-Object|Select-Object')
224
+ } | Select-Object ProcessId, ParentProcessId, Name, CommandLine, CreationDate
225
+
226
+ $ports = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Select-Object LocalPort, OwningProcess
227
+
228
+ @{ Procs = $procs; Ports = $ports } | ConvertTo-Json -Depth 3
229
+ `;
230
+
231
+ const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
232
+ if (!res.stdout.trim()) return discovered;
233
+
234
+ let data;
235
+ try {
236
+ data = JSON.parse(res.stdout.trim());
237
+ } catch {
238
+ return discovered;
239
+ }
240
+
241
+ const procList = data?.Procs ? (Array.isArray(data.Procs) ? data.Procs : [data.Procs]) : [];
242
+ const portList = data?.Ports ? (Array.isArray(data.Ports) ? data.Ports : [data.Ports]) : [];
243
+
244
+ const pidToPorts = {};
245
+ for (const p of portList) {
246
+ if (p?.OwningProcess && p?.LocalPort) {
247
+ if (!pidToPorts[p.OwningProcess]) pidToPorts[p.OwningProcess] = [];
248
+ pidToPorts[p.OwningProcess].push(p.LocalPort);
249
+ }
250
+ }
251
+
252
+ for (const item of procList) {
253
+ const cmd = item.CommandLine || "";
254
+ const pid = item.ProcessId;
255
+ if (!pid || !isPidRunning(pid)) continue;
256
+
257
+ let startedAt;
258
+ if (item.CreationDate) {
259
+ const match = String(item.CreationDate).match(/\/Date\((\d+)\)\//);
260
+ if (match) {
261
+ startedAt = new Date(parseInt(match[1], 10)).toISOString();
262
+ } else {
263
+ const d = new Date(item.CreationDate);
264
+ if (!isNaN(d.getTime())) {
265
+ startedAt = d.toISOString();
266
+ }
267
+ }
268
+ }
269
+
270
+ const ports = pidToPorts[pid] || [];
271
+
272
+ // 1. pxpipe
273
+ if (cmd.includes("pxpipe-proxy") || (cmd.toLowerCase().includes("pxpipe") && !cmd.includes("@agentmemory"))) {
274
+ if (!discovered.pxpipe || (item.Name && item.Name.toLowerCase() === "node.exe" && cmd.includes("cli.js"))) {
275
+ const webPort = ports.find(p => p > 1000 && p < 65000) || (discovered.pxpipe?.port);
276
+ discovered.pxpipe = {
277
+ pid,
278
+ command: cmd,
279
+ startedAt,
280
+ port: webPort,
281
+ url: webPort ? `http://localhost:${webPort}` : "http://localhost:47821",
282
+ };
283
+ }
284
+ }
285
+
286
+ // 2. ocx
287
+ if (cmd.includes("ocx.mjs") || cmd.includes("opencodex") || cmd.includes("ocx start")) {
288
+ const webPort = ports.find(p => p === 10100 || (p > 1000 && p < 65000));
289
+ if (!discovered.ocx || cmd.includes("ocx.mjs start")) {
290
+ discovered.ocx = {
291
+ pid,
292
+ command: cmd,
293
+ startedAt,
294
+ port: webPort || 10100,
295
+ url: `http://localhost:${webPort || 10100}`,
296
+ };
297
+ }
298
+ }
299
+
300
+ // 3. agentmemory
301
+ if (
302
+ cmd.includes("@agentmemory/agentmemory") ||
303
+ cmd.includes("agentmemory\\dist\\cli.mjs") ||
304
+ cmd.includes("agentmemory/dist/cli.mjs") ||
305
+ cmd.includes("iii-config.yaml") ||
306
+ (cmd.includes("agentmemory") && !cmd.includes("@agentmemory/mcp"))
307
+ ) {
308
+ const webPort = ports.find(p => p === 3113 || p === 43210 || (p > 1000 && p < 65000));
309
+ if (!discovered.agentmemory || cmd.includes("agentmemory/agentmemory")) {
310
+ discovered.agentmemory = {
311
+ pid,
312
+ command: cmd,
313
+ startedAt,
314
+ port: webPort || 3113,
315
+ url: `http://localhost:${webPort || 3113}`,
316
+ };
317
+ }
318
+ }
319
+ }
320
+
321
+ for (const p of procList) {
322
+ const ports = pidToPorts[p.ProcessId] || [];
323
+ if (ports.length > 0) {
324
+ if (ports.includes(47821) && discovered.pxpipe) {
325
+ discovered.pxpipe.url = "http://localhost:47821";
326
+ }
327
+ if (ports.includes(10100) && discovered.ocx) {
328
+ discovered.ocx.url = "http://localhost:10100";
329
+ }
330
+ if (ports.includes(3113) && discovered.agentmemory) {
331
+ discovered.agentmemory.url = "http://localhost:3113";
332
+ }
333
+ }
334
+ }
335
+ } catch {}
336
+ } else {
337
+ try {
338
+ const res = await execCommand("ps", ["-eo", "pid,command"]);
339
+ const lines = res.stdout.split("\n");
340
+
341
+ for (const line of lines) {
342
+ const trimmed = line.trim();
343
+ if (!trimmed || trimmed.includes("ps -eo") || trimmed.includes("ai-helper")) continue;
344
+
345
+ const parts = trimmed.split(/\s+/);
346
+ const pid = parseInt(parts[0], 10);
347
+ const cmd = parts.slice(1).join(" ");
348
+ if (!pid || !isPidRunning(pid)) continue;
349
+
350
+ if (cmd.includes("pxpipe-proxy") || (cmd.includes("pxpipe") && !cmd.includes("@agentmemory"))) {
351
+ if (!discovered.pxpipe) discovered.pxpipe = { pid, command: cmd, url: "http://localhost:47821" };
352
+ }
353
+ if (cmd.includes("ocx start") || cmd.includes("ocx.mjs") || cmd.includes("opencodex")) {
354
+ if (!discovered.ocx) discovered.ocx = { pid, command: cmd, url: "http://localhost:10100" };
355
+ }
356
+ if (
357
+ cmd.includes("@agentmemory/agentmemory") ||
358
+ cmd.includes("iii-config.yaml") ||
359
+ (cmd.includes("agentmemory") && !cmd.includes("@agentmemory/mcp"))
360
+ ) {
361
+ if (!discovered.agentmemory) discovered.agentmemory = { pid, command: cmd, url: "http://localhost:3113" };
362
+ }
363
+ }
364
+ } catch {}
365
+ }
366
+
367
+ return discovered;
368
+ }
369
+