@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.
package/src/index.js ADDED
@@ -0,0 +1,326 @@
1
+ import { APP_NAME, CLI_NAME, SERVICES, SERVICE_IDS, VERSION } from "./config.js";
2
+ import { manager } from "./manager.js";
3
+ import {
4
+ badgeStatus,
5
+ bold,
6
+ cyan,
7
+ dim,
8
+ gray,
9
+ green,
10
+ printBanner,
11
+ red,
12
+ renderTable,
13
+ yellow,
14
+ underline,
15
+ } from "./utils/format.js";
16
+ import { isLocalBinInPath, getAddToPathInstructions, getLocalBinDir, ensureDir } from "./utils/path.js";
17
+ import { join } from "node:path";
18
+ import { copyFileSync } from "node:fs";
19
+
20
+ function printHelp() {
21
+ printBanner();
22
+ console.log(`${bold("USAGE:")}
23
+ ${cyan(CLI_NAME)} ${yellow("<command>")} [options] [services...]
24
+
25
+ ${bold("COMMANDS:")}
26
+ ${yellow("status")}, ${yellow("ps")} Show status, PID, uptime, and web dashboard URLs
27
+ ${yellow("open")}, ${yellow("dash")} [services...] Open web dashboard(s) directly in your default browser
28
+ ${yellow("start")}, ${yellow("up")} [services...] Start all or specified services (pxpipe, ocx, agentmemory)
29
+ ${yellow("stop")}, ${yellow("down")} [services...] Stop all or specified services
30
+ ${yellow("restart")} [services...] Restart all or specified services
31
+ ${yellow("logs")} <service> [-n 50] [-f] View or stream live logs for a service
32
+ ${yellow("install")} Build standalone binary to ~/.local/bin and verify PATH
33
+ ${yellow("version")}, ${yellow("-v")} Show version information
34
+ ${yellow("help")}, ${yellow("-h")} Show this help message
35
+
36
+ ${bold("SERVICES MANAGED:")}
37
+ ${SERVICE_IDS.map(id => {
38
+ const svc = SERVICES[id];
39
+ return ` ${cyan(svc.id.padEnd(14))} ${svc.description} ${dim(`(${svc.defaultUrl})`)}`;
40
+ }).join("\n")}
41
+
42
+ ${bold("OPTIONS:")}
43
+ ${gray("-n, --lines <num>")} Number of log lines to show (default: 50)
44
+ ${gray("-f, --follow")} Follow log output in real-time
45
+ ${gray("--json")} Output results in JSON format
46
+
47
+ ${bold("EXAMPLES:")}
48
+ ${dim("$")} ${cyan("npx ai-helper")} status
49
+ ${dim("$")} ${cyan(CLI_NAME)} open ${dim("# Opens all running dashboards in browser")}
50
+ ${dim("$")} ${cyan(CLI_NAME)} open agentmemory ${dim("# Opens agentmemory dashboard")}
51
+ ${dim("$")} ${cyan(CLI_NAME)} start
52
+ ${dim("$")} ${cyan(CLI_NAME)} stop pxpipe
53
+ ${dim("$")} ${cyan(CLI_NAME)} restart ocx
54
+ ${dim("$")} ${cyan(CLI_NAME)} logs pxpipe -f
55
+ `);
56
+ }
57
+
58
+ function printVersion() {
59
+ const runtime = typeof Bun !== "undefined" ? `Bun ${Bun.version}` : `Node ${process.version}`;
60
+ console.log(`${bold(cyan(CLI_NAME))} version ${bold(VERSION)} (${runtime}, ${process.platform}-${process.arch})`);
61
+ }
62
+
63
+ async function runInstall() {
64
+ printBanner();
65
+ console.log(cyan("āš™ Building standalone binary and installing to ~/.local/bin...\n"));
66
+
67
+ if (typeof Bun === "undefined") {
68
+ console.log(yellow("Notice: Standalone compilation via 'install' uses Bun."));
69
+ console.log("If you are using npm/Node, you can install globally with:\n");
70
+ console.log(cyan(" npm install -g ai-helper\n"));
71
+ return;
72
+ }
73
+
74
+ const localBinDir = getLocalBinDir();
75
+ const isWindows = process.platform === "win32";
76
+ const binaryName = isWindows ? `${CLI_NAME}.exe` : CLI_NAME;
77
+ const targetPath = join(localBinDir, binaryName);
78
+ const tempBuildPath = join(process.cwd(), "dist", binaryName);
79
+
80
+ try {
81
+ const buildProc = Bun.spawn(
82
+ [
83
+ process.execPath,
84
+ "build",
85
+ "--compile",
86
+ "--minify",
87
+ `--outfile=${tempBuildPath}`,
88
+ join(import.meta.dir, "index.js"),
89
+ ],
90
+ { stdout: "pipe", stderr: "pipe" }
91
+ );
92
+
93
+ const exitCode = await buildProc.exited;
94
+ if (exitCode !== 0) {
95
+ const err = await new Response(buildProc.stderr).text();
96
+ console.log(red(`āœ– Build failed: ${err}`));
97
+ process.exit(1);
98
+ }
99
+
100
+ console.log(green(`āœ“ Built standalone executable: ${tempBuildPath}`));
101
+
102
+ ensureDir(localBinDir);
103
+ copyFileSync(tempBuildPath, targetPath);
104
+ console.log(green(`āœ“ Installed binary to: ${targetPath}`));
105
+
106
+ console.log(dim("\nChecking PATH configuration..."));
107
+ if (isLocalBinInPath()) {
108
+ console.log(green(`\nšŸŽ‰ Success! '${localBinDir}' is already in your PATH.`));
109
+ console.log(dim(`You can now run '${CLI_NAME}' from any terminal window.\n`));
110
+ } else {
111
+ console.log(yellow(`\n⚠ Notice: '${localBinDir}' is NOT in your current PATH.`));
112
+ console.log(`To make '${CLI_NAME}' available everywhere, run the following command:\n`);
113
+
114
+ const instructions = getAddToPathInstructions();
115
+ if (isWindows) {
116
+ console.log(bold("PowerShell (User Environment):"));
117
+ console.log(cyan(` ${instructions.powershell}\n`));
118
+ console.log(bold("Command Prompt (CMD):"));
119
+ console.log(cyan(` ${instructions.cmd}\n`));
120
+ } else {
121
+ console.log(bold("Bash / Zsh:"));
122
+ console.log(cyan(` ${instructions.bash}\n`));
123
+ }
124
+ console.log(dim("After running the command above, restart your terminal to apply changes.\n"));
125
+ }
126
+ } catch (err) {
127
+ console.log(red(`āœ– Installation error: ${err?.message || err}`));
128
+ process.exit(1);
129
+ }
130
+ }
131
+
132
+ export async function main() {
133
+ const rawArgs = process.argv.slice(2);
134
+
135
+ let jsonOutput = false;
136
+ let follow = false;
137
+ let lines = 50;
138
+ const positionalArgs = [];
139
+
140
+ for (let i = 0; i < rawArgs.length; i++) {
141
+ const arg = rawArgs[i];
142
+ if (arg === "--json") {
143
+ jsonOutput = true;
144
+ } else if (arg === "-f" || arg === "--follow") {
145
+ follow = true;
146
+ } else if (arg === "-n" || arg === "--lines") {
147
+ const next = rawArgs[i + 1];
148
+ if (next && !next.startsWith("-")) {
149
+ lines = parseInt(next, 10) || 50;
150
+ i++;
151
+ }
152
+ } else if (arg.startsWith("-n=")) {
153
+ lines = parseInt(arg.slice(3), 10) || 50;
154
+ } else if (arg.startsWith("--lines=")) {
155
+ lines = parseInt(arg.slice(8), 10) || 50;
156
+ } else if (arg === "-h" || arg === "--help" || arg === "help") {
157
+ printHelp();
158
+ return;
159
+ } else if (arg === "-v" || arg === "--version" || arg === "version") {
160
+ printVersion();
161
+ return;
162
+ } else if (!arg.startsWith("-")) {
163
+ positionalArgs.push(arg);
164
+ }
165
+ }
166
+
167
+ const command = positionalArgs[0]?.toLowerCase() || "status";
168
+ const targets = positionalArgs.slice(1);
169
+
170
+ switch (command) {
171
+ case "status":
172
+ case "ps":
173
+ case "ls":
174
+ case "list": {
175
+ const statuses = await manager.getStatus(targets.length > 0 ? targets : undefined);
176
+
177
+ if (jsonOutput) {
178
+ console.log(JSON.stringify(statuses, null, 2));
179
+ return;
180
+ }
181
+
182
+ printBanner();
183
+
184
+ const headers = [
185
+ "SERVICE",
186
+ "STATUS",
187
+ { header: "PID", align: "right" },
188
+ { header: "UPTIME", align: "right" },
189
+ "DASHBOARD / URL",
190
+ "COMMAND",
191
+ ];
192
+
193
+ const rows = statuses.map(s => [
194
+ bold(s.id),
195
+ badgeStatus(s.status),
196
+ s.pid ? String(s.pid) : dim("-"),
197
+ s.status === "running" ? s.uptime : dim("-"),
198
+ s.status === "running" && s.url && s.url !== "-"
199
+ ? cyan(underline(s.url))
200
+ : dim(s.url || "-"),
201
+ dim(s.command),
202
+ ]);
203
+
204
+ console.log(renderTable(headers, rows));
205
+ console.log("");
206
+ console.log(dim(`Use '${CLI_NAME} open [service]' to open dashboards in browser or '${CLI_NAME} start' to launch.`));
207
+ break;
208
+ }
209
+
210
+ case "open":
211
+ case "dashboard":
212
+ case "dash": {
213
+ printBanner();
214
+ const svcsToOpen = targets.length > 0 ? targets : undefined;
215
+ const opened = await manager.openDashboard(svcsToOpen);
216
+
217
+ if (opened.length === 0) {
218
+ console.log(yellow("⚠ No dashboard URLs available to open."));
219
+ console.log(dim(`Run '${CLI_NAME} status' to check running services.\n`));
220
+ return;
221
+ }
222
+
223
+ console.log(green(`🌐 Opening ${opened.length} dashboard(s) in your default browser:\n`));
224
+ for (const item of opened) {
225
+ console.log(` • ${bold(item.name)}: ${cyan(underline(item.url))} ${item.status === "running" ? green("(Running)") : dim("(Stopped)")}`);
226
+ }
227
+ console.log("");
228
+ break;
229
+ }
230
+
231
+ case "start":
232
+ case "up": {
233
+ printBanner();
234
+ const svcsToStart = targets.length > 0 ? targets : SERVICE_IDS;
235
+ console.log(cyan(`Starting service(s): ${svcsToStart.join(", ")}...\n`));
236
+
237
+ for (const id of svcsToStart) {
238
+ process.stdout.write(` Launching ${bold(id)}... `);
239
+ const res = await manager.startService(id);
240
+ if (res.success) {
241
+ if (res.alreadyRunning) {
242
+ console.log(yellow(`already running (PID: ${res.pid})`));
243
+ } else {
244
+ console.log(green(`started (PID: ${res.pid})`));
245
+ }
246
+ } else {
247
+ console.log(red(`failed: ${res.message}`));
248
+ }
249
+ }
250
+ console.log("");
251
+ break;
252
+ }
253
+
254
+ case "stop":
255
+ case "down": {
256
+ printBanner();
257
+ const svcsToStop = targets.length > 0 ? targets : SERVICE_IDS;
258
+ console.log(cyan(`Stopping service(s): ${svcsToStop.join(", ")}...\n`));
259
+
260
+ for (const id of svcsToStop) {
261
+ process.stdout.write(` Stopping ${bold(id)}... `);
262
+ const res = await manager.stopService(id);
263
+ if (res.success) {
264
+ console.log(green(res.message));
265
+ } else {
266
+ console.log(red(res.message));
267
+ }
268
+ }
269
+ console.log("");
270
+ break;
271
+ }
272
+
273
+ case "restart": {
274
+ printBanner();
275
+ const svcsToRestart = targets.length > 0 ? targets : SERVICE_IDS;
276
+ console.log(cyan(`Restarting service(s): ${svcsToRestart.join(", ")}...\n`));
277
+
278
+ for (const id of svcsToRestart) {
279
+ process.stdout.write(` Restarting ${bold(id)}... `);
280
+ const res = await manager.restartService(id);
281
+ if (res.success) {
282
+ console.log(green(`started (PID: ${res.pid})`));
283
+ } else {
284
+ console.log(red(`failed: ${res.message}`));
285
+ }
286
+ }
287
+ console.log("");
288
+ break;
289
+ }
290
+
291
+ case "logs":
292
+ case "log": {
293
+ const targetService = targets[0];
294
+ if (!targetService) {
295
+ console.log(red("āœ– Error: Please specify a service name for logs."));
296
+ console.log(`Available services: ${SERVICE_IDS.join(", ")}`);
297
+ console.log(`Example: ${cyan(`${CLI_NAME} logs pxpipe -f`)}\n`);
298
+ process.exit(1);
299
+ }
300
+
301
+ if (!SERVICE_IDS.includes(targetService)) {
302
+ console.log(yellow(`⚠ Warning: '${targetService}' is not a standard service. Looking for log file anyway...`));
303
+ }
304
+
305
+ await manager.showLogs(targetService, lines, follow);
306
+ break;
307
+ }
308
+
309
+ case "install": {
310
+ await runInstall();
311
+ break;
312
+ }
313
+
314
+ default: {
315
+ console.log(red(`āœ– Unknown command: '${command}'\n`));
316
+ printHelp();
317
+ process.exit(1);
318
+ }
319
+ }
320
+ }
321
+
322
+ main().catch(err => {
323
+ console.error(red(`[aih] Fatal error: ${err?.message || err}`));
324
+ process.exit(1);
325
+ });
326
+
package/src/manager.js ADDED
@@ -0,0 +1,380 @@
1
+ import { existsSync, readFileSync, writeFileSync, statSync, openSync, readSync, closeSync } from "node:fs";
2
+ import { SERVICES, SERVICE_IDS } from "./config.js";
3
+ import { ensureDir, getAihDir, getLogsDir, getServiceLogPath, getStateFilePath } from "./utils/path.js";
4
+ import { isPidRunning, killProcessTree, spawnDetachedProcess, discoverRunningProcesses, openBrowser, sleep } from "./utils/process.js";
5
+ import { formatBytes, formatUptime, gray, red, yellow, green, cyan } from "./utils/format.js";
6
+
7
+ export class ServiceManager {
8
+ /**
9
+ * Reads raw state from disk without discovery.
10
+ */
11
+ readState() {
12
+ ensureDir(getAihDir());
13
+ const statePath = getStateFilePath();
14
+ let state = {
15
+ services: {},
16
+ updatedAt: new Date().toISOString(),
17
+ };
18
+
19
+ if (existsSync(statePath)) {
20
+ try {
21
+ const raw = readFileSync(statePath, "utf-8");
22
+ state = JSON.parse(raw);
23
+ } catch {
24
+ state = { services: {}, updatedAt: new Date().toISOString() };
25
+ }
26
+ }
27
+
28
+ for (const id of SERVICE_IDS) {
29
+ const def = SERVICES[id];
30
+ if (!state.services[id]) {
31
+ state.services[id] = {
32
+ id: def.id,
33
+ name: def.name,
34
+ command: def.command,
35
+ status: "stopped",
36
+ url: def.defaultUrl,
37
+ };
38
+ }
39
+ }
40
+
41
+ return state;
42
+ }
43
+
44
+ /**
45
+ * Synchronizes state with active OS processes and auto-discovers externally launched services.
46
+ */
47
+ async syncState() {
48
+ const state = this.readState();
49
+ let needsSave = false;
50
+
51
+ // 1. Verify liveness of currently recorded PIDs
52
+ for (const id of Object.keys(state.services)) {
53
+ const svc = state.services[id];
54
+ if (svc.status === "running") {
55
+ if (!svc.pid || !isPidRunning(svc.pid)) {
56
+ svc.status = "stopped";
57
+ svc.pid = undefined;
58
+ svc.startedAt = undefined;
59
+ needsSave = true;
60
+ }
61
+ }
62
+ }
63
+
64
+ // 2. Discover externally started processes
65
+ const discovered = await discoverRunningProcesses();
66
+ for (const id of Object.keys(discovered)) {
67
+ const info = discovered[id];
68
+ const svc = state.services[id];
69
+ if (svc) {
70
+ if (svc.status !== "running" || !svc.pid || !isPidRunning(svc.pid)) {
71
+ svc.status = "running";
72
+ svc.pid = info.pid;
73
+ svc.startedAt = info.startedAt || new Date().toISOString();
74
+ svc.url = info.url || SERVICES[id]?.defaultUrl;
75
+ needsSave = true;
76
+ } else if (info.url && svc.url !== info.url) {
77
+ svc.url = info.url;
78
+ needsSave = true;
79
+ }
80
+ }
81
+ }
82
+
83
+ if (needsSave) {
84
+ this.saveState(state);
85
+ }
86
+
87
+ return state;
88
+ }
89
+
90
+ /**
91
+ * Synchronous load with PID liveness check.
92
+ */
93
+ loadState() {
94
+ const state = this.readState();
95
+ let needsSave = false;
96
+
97
+ for (const id of Object.keys(state.services)) {
98
+ const svc = state.services[id];
99
+ if (svc.status === "running") {
100
+ if (!svc.pid || !isPidRunning(svc.pid)) {
101
+ svc.status = "stopped";
102
+ svc.pid = undefined;
103
+ svc.startedAt = undefined;
104
+ needsSave = true;
105
+ }
106
+ }
107
+ }
108
+
109
+ if (needsSave) {
110
+ this.saveState(state);
111
+ }
112
+
113
+ return state;
114
+ }
115
+
116
+ /**
117
+ * Saves state to disk.
118
+ */
119
+ saveState(state) {
120
+ ensureDir(getAihDir());
121
+ state.updatedAt = new Date().toISOString();
122
+ writeFileSync(getStateFilePath(), JSON.stringify(state, null, 2), "utf-8");
123
+ }
124
+
125
+ /**
126
+ * Gets current status for all or specific services (with auto-discovery and URL resolution).
127
+ */
128
+ async getStatus(targetServices) {
129
+ const state = await this.syncState();
130
+ const targets = targetServices && targetServices.length > 0 ? targetServices : SERVICE_IDS;
131
+
132
+ return targets.map(id => {
133
+ const def = SERVICES[id] || {
134
+ id,
135
+ name: id,
136
+ command: "custom",
137
+ description: "Custom service",
138
+ defaultUrl: "http://localhost",
139
+ };
140
+ const svcState = state.services[id] || {
141
+ id,
142
+ name: def.name,
143
+ command: def.command,
144
+ status: "stopped",
145
+ url: def.defaultUrl,
146
+ };
147
+
148
+ const logPath = getServiceLogPath(id);
149
+ let logSize = 0;
150
+ if (existsSync(logPath)) {
151
+ try {
152
+ logSize = statSync(logPath).size;
153
+ } catch {}
154
+ }
155
+
156
+ const url = svcState.url || def.defaultUrl || "-";
157
+
158
+ return {
159
+ ...svcState,
160
+ description: def.description,
161
+ uptime: svcState.status === "running" ? formatUptime(svcState.startedAt) : "-",
162
+ url,
163
+ logPath,
164
+ logSize,
165
+ };
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Opens service dashboard in browser.
171
+ */
172
+ async openDashboard(targetServices) {
173
+ const statuses = await this.getStatus(targetServices);
174
+ const opened = [];
175
+
176
+ for (const svc of statuses) {
177
+ const url = svc.url || SERVICES[svc.id]?.defaultUrl;
178
+ if (url && url !== "-") {
179
+ openBrowser(url);
180
+ opened.push({ id: svc.id, name: svc.name, url, status: svc.status });
181
+ }
182
+ }
183
+
184
+ return opened;
185
+ }
186
+
187
+ /**
188
+ * Starts a single service by ID.
189
+ */
190
+ async startService(serviceId) {
191
+ const def = SERVICES[serviceId];
192
+ if (!def) {
193
+ return { success: false, message: `Unknown service '${serviceId}'. Available: ${SERVICE_IDS.join(", ")}` };
194
+ }
195
+
196
+ const state = await this.syncState();
197
+ const current = state.services[serviceId];
198
+
199
+ if (current && current.status === "running" && current.pid && isPidRunning(current.pid)) {
200
+ return {
201
+ success: true,
202
+ message: `Service '${serviceId}' is already running (PID: ${current.pid})`,
203
+ pid: current.pid,
204
+ alreadyRunning: true,
205
+ url: current.url || def.defaultUrl,
206
+ };
207
+ }
208
+
209
+ const logPath = getServiceLogPath(serviceId);
210
+ const { pid } = spawnDetachedProcess(def.command, logPath, {
211
+ env: def.env,
212
+ cwd: def.workingDir,
213
+ });
214
+
215
+ state.services[serviceId] = {
216
+ id: def.id,
217
+ name: def.name,
218
+ command: def.command,
219
+ status: "running",
220
+ pid,
221
+ startedAt: new Date().toISOString(),
222
+ url: def.defaultUrl,
223
+ };
224
+ this.saveState(state);
225
+
226
+ await sleep(600);
227
+
228
+ if (!isPidRunning(pid)) {
229
+ state.services[serviceId].status = "error";
230
+ state.services[serviceId].pid = undefined;
231
+ state.services[serviceId].lastError = "Process exited immediately after spawn";
232
+ this.saveState(state);
233
+
234
+ return {
235
+ success: false,
236
+ message: `Service '${serviceId}' exited immediately. Check logs with 'aih logs ${serviceId}'`,
237
+ pid,
238
+ };
239
+ }
240
+
241
+ return {
242
+ success: true,
243
+ message: `Service '${serviceId}' started successfully (PID: ${pid})`,
244
+ pid,
245
+ url: def.defaultUrl,
246
+ };
247
+ }
248
+
249
+ /**
250
+ * Starts all or selected services.
251
+ */
252
+ async startServices(serviceIds) {
253
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
254
+ const results = {};
255
+
256
+ for (const id of targets) {
257
+ results[id] = await this.startService(id);
258
+ }
259
+
260
+ return results;
261
+ }
262
+
263
+ /**
264
+ * Stops a single service by ID.
265
+ */
266
+ async stopService(serviceId) {
267
+ const state = await this.syncState();
268
+ const current = state.services[serviceId];
269
+
270
+ if (!current || current.status !== "running" || !current.pid) {
271
+ return { success: true, message: `Service '${serviceId}' is not running` };
272
+ }
273
+
274
+ const pidToKill = current.pid;
275
+ const killResult = await killProcessTree(pidToKill);
276
+
277
+ state.services[serviceId].status = "stopped";
278
+ state.services[serviceId].pid = undefined;
279
+ state.services[serviceId].startedAt = undefined;
280
+ this.saveState(state);
281
+
282
+ return {
283
+ success: killResult.success,
284
+ message: killResult.success
285
+ ? `Service '${serviceId}' stopped (PID: ${pidToKill})`
286
+ : `Failed to stop service '${serviceId}': ${killResult.message}`,
287
+ };
288
+ }
289
+
290
+ /**
291
+ * Stops all or selected services.
292
+ */
293
+ async stopServices(serviceIds) {
294
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
295
+ const results = {};
296
+
297
+ for (const id of targets) {
298
+ results[id] = await this.stopService(id);
299
+ }
300
+
301
+ return results;
302
+ }
303
+
304
+ /**
305
+ * Restarts a single service by ID.
306
+ */
307
+ async restartService(serviceId) {
308
+ await this.stopService(serviceId);
309
+ await sleep(400);
310
+ return await this.startService(serviceId);
311
+ }
312
+
313
+ /**
314
+ * Restarts all or selected services.
315
+ */
316
+ async restartServices(serviceIds) {
317
+ const targets = serviceIds && serviceIds.length > 0 ? serviceIds : SERVICE_IDS;
318
+ const results = {};
319
+
320
+ for (const id of targets) {
321
+ results[id] = await this.restartService(id);
322
+ }
323
+
324
+ return results;
325
+ }
326
+
327
+ /**
328
+ * Displays or follows logs for a service.
329
+ */
330
+ async showLogs(serviceId, lines = 50, follow = false) {
331
+ const logPath = getServiceLogPath(serviceId);
332
+ if (!existsSync(logPath)) {
333
+ console.log(yellow(`[aih] No log file exists yet for '${serviceId}' at: ${logPath}`));
334
+ return;
335
+ }
336
+
337
+ const content = readFileSync(logPath, "utf-8");
338
+ const allLines = content.split(/\r?\n/);
339
+ const tailLines = allLines.slice(-lines);
340
+
341
+ console.log(gray(`[aih] Displaying last ${tailLines.length} lines of ${logPath}:\n`));
342
+ for (const line of tailLines) {
343
+ console.log(line);
344
+ }
345
+
346
+ if (!follow) return;
347
+
348
+ console.log(gray(`\n[aih] Following log output (Press Ctrl+C to stop)...\n`));
349
+
350
+ let lastSize = statSync(logPath).size;
351
+ let running = true;
352
+
353
+ process.on("SIGINT", () => {
354
+ running = false;
355
+ console.log(gray("\n[aih] Stopped log following."));
356
+ process.exit(0);
357
+ });
358
+
359
+ while (running) {
360
+ await sleep(400);
361
+ try {
362
+ if (!existsSync(logPath)) continue;
363
+ const currentSize = statSync(logPath).size;
364
+ if (currentSize > lastSize) {
365
+ const fd = openSync(logPath, "r");
366
+ const buffer = Buffer.alloc(currentSize - lastSize);
367
+ readSync(fd, buffer, 0, buffer.length, lastSize);
368
+ closeSync(fd);
369
+ process.stdout.write(buffer.toString("utf-8"));
370
+ lastSize = currentSize;
371
+ } else if (currentSize < lastSize) {
372
+ lastSize = currentSize;
373
+ }
374
+ } catch {}
375
+ }
376
+ }
377
+ }
378
+
379
+ export const manager = new ServiceManager();
380
+