@drakonkat/ai-helper 1.0.0 → 1.0.2

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/CHANGELOG.md CHANGED
@@ -4,19 +4,31 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.0.2] - 2026-08-19
8
+
9
+ ### 🐛 Bug Fixes
10
+ - **Auto-Discovery Fix**: Strictly exclude `agentmemory-mcp` / `@agentmemory/mcp` client shims from matching the `agentmemory` daemon server, ensuring the background web server (`http://localhost:3113`) is launched properly on `aih start`.
11
+
12
+ ---
13
+
14
+ ## [1.0.1] - 2026-08-19
15
+
16
+ ### 🔧 Improvements & Fixes
17
+ - **Scoped Package Deployment**: Published under the `@drakonkat/ai-helper` npm scope for instant `npx` execution.
18
+ - **Enhanced Process Auto-Discovery**: Optimized WMI/CIM process query performance on Windows.
19
+ - **Documentation & CI**: Added complete GitHub community templates, architecture guides, and CI workflows.
20
+
21
+ ---
22
+
7
23
  ## [1.0.0] - 2026-08-19
8
24
 
9
25
  ### 🚀 Initial Release
10
- - **Managed Services**: Support for background lifecycle management of:
11
- - `pxpipe` (`npx pxpipe-proxy`)
12
- - `ocx` (`ocx start`)
13
- - `agentmemory` (`npx @agentmemory/agentmemory`)
14
- - **Auto-Discovery Engine**: Detects running service instances started from external terminal windows via OS process table queries (`Win32_Process` and `ps`).
26
+ - **Managed Services**: Support for background lifecycle management of `pxpipe`, `ocx`, and `agentmemory`.
27
+ - **Auto-Discovery Engine**: Detects running service instances started from external terminal windows via OS process table queries.
15
28
  - **TCP Port & Dashboard Mapping**: Dynamically detects listening web ports and exposes clickable dashboard URLs.
16
29
  - **One-Click Browser Dashboard Launcher**: Added `aih open [service]` to launch active dashboards directly in the user's default browser.
17
30
  - **Safe Process Tree Termination**: Tree-killing on Windows via `taskkill /pid <PID> /T /F` and process group termination on Unix.
18
31
  - **Unified Live Log Streaming**: Real-time log capture and streaming with `aih logs <service> -f`.
19
32
  - **Programmatic JSON API**: Added `--json` flag for IDE, agent, and pipeline integration.
20
- - **Cross-Runtime & NPX Ready**: Universal Node.js (>=18) and Bun support, publishable directly to npm for instant `npx ai-helper` execution.
21
- - **Standalone Binary Compilation**: Optional compilation to standalone `aih.exe` via `bun run install-bin`.
33
+ - **Cross-Runtime & NPX Ready**: Universal Node.js (>=18) and Bun support.
22
34
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakonkat/ai-helper",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, agentmemory)",
5
5
  "main": "src/index.js",
6
6
  "module": "src/index.js",
package/src/config.js CHANGED
@@ -12,22 +12,27 @@ export const SERVICES = {
12
12
  description: "AI LLM / MCP reverse proxy bridge (pxpipe-proxy)",
13
13
  defaultPort: 47821,
14
14
  defaultUrl: "http://localhost:47821",
15
+ ports: [47821],
15
16
  },
16
17
  ocx: {
17
18
  id: "ocx",
18
19
  name: "ocx",
19
20
  command: "ocx start",
21
+ stopCommand: "ocx stop",
20
22
  description: "OpenCode Interpreter daemon service (ocx start)",
21
23
  defaultPort: 10100,
22
24
  defaultUrl: "http://localhost:10100",
25
+ ports: [10100],
23
26
  },
24
27
  agentmemory: {
25
28
  id: "agentmemory",
26
29
  name: "agentmemory",
27
30
  command: "npx @agentmemory/agentmemory",
31
+ stopCommand: "npx @agentmemory/agentmemory stop --force",
28
32
  description: "Long-term persistent agent memory service (@agentmemory/agentmemory)",
29
33
  defaultPort: 3113,
30
34
  defaultUrl: "http://localhost:3113",
35
+ ports: [3111, 3112, 3113, 49134],
31
36
  },
32
37
  };
33
38
 
@@ -35,5 +40,5 @@ export const SERVICE_IDS = Object.keys(SERVICES);
35
40
 
36
41
  export const APP_NAME = "ai-helper";
37
42
  export const CLI_NAME = "aih";
38
- export const VERSION = "1.0.0";
43
+ export const VERSION = "1.0.3";
39
44
 
package/src/manager.js CHANGED
@@ -1,7 +1,16 @@
1
1
  import { existsSync, readFileSync, writeFileSync, statSync, openSync, readSync, closeSync } from "node:fs";
2
2
  import { SERVICES, SERVICE_IDS } from "./config.js";
3
3
  import { ensureDir, getAihDir, getLogsDir, getServiceLogPath, getStateFilePath } from "./utils/path.js";
4
- import { isPidRunning, killProcessTree, spawnDetachedProcess, discoverRunningProcesses, openBrowser, sleep } from "./utils/process.js";
4
+ import {
5
+ isPidRunning,
6
+ killProcessTree,
7
+ spawnDetachedProcess,
8
+ discoverRunningProcesses,
9
+ openBrowser,
10
+ sleep,
11
+ execCommand,
12
+ findPidsListeningOnPorts,
13
+ } from "./utils/process.js";
5
14
  import { formatBytes, formatUptime, gray, red, yellow, green, cyan } from "./utils/format.js";
6
15
 
7
16
  export class ServiceManager {
@@ -48,35 +57,39 @@ export class ServiceManager {
48
57
  const state = this.readState();
49
58
  let needsSave = false;
50
59
 
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
60
+ // Discover active verified daemon processes from OS
65
61
  const discovered = await discoverRunningProcesses();
66
- for (const id of Object.keys(discovered)) {
67
- const info = discovered[id];
62
+
63
+ for (const id of SERVICE_IDS) {
68
64
  const svc = state.services[id];
69
- if (svc) {
70
- if (svc.status !== "running" || !svc.pid || !isPidRunning(svc.pid)) {
65
+ const info = discovered[id];
66
+
67
+ if (info && info.pid && isPidRunning(info.pid)) {
68
+ // Confirmed active service daemon discovered in OS
69
+ if (svc.status !== "running" || svc.pid !== info.pid) {
71
70
  svc.status = "running";
72
71
  svc.pid = info.pid;
73
- svc.startedAt = info.startedAt || new Date().toISOString();
72
+ svc.startedAt = info.startedAt || svc.startedAt || new Date().toISOString();
74
73
  svc.url = info.url || SERVICES[id]?.defaultUrl;
75
74
  needsSave = true;
76
75
  } else if (info.url && svc.url !== info.url) {
77
76
  svc.url = info.url;
78
77
  needsSave = true;
79
78
  }
79
+ } else if (svc.status === "running" && svc.pid && isPidRunning(svc.pid)) {
80
+ // Process spawned by aih is still actively running in background
81
+ if (!svc.url) {
82
+ svc.url = SERVICES[id]?.defaultUrl;
83
+ needsSave = true;
84
+ }
85
+ } else {
86
+ // Not running and not discovered
87
+ if (svc.status === "running" || svc.pid !== undefined) {
88
+ svc.status = "stopped";
89
+ svc.pid = undefined;
90
+ svc.startedAt = undefined;
91
+ needsSave = true;
92
+ }
80
93
  }
81
94
  }
82
95
 
@@ -223,20 +236,11 @@ export class ServiceManager {
223
236
  };
224
237
  this.saveState(state);
225
238
 
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);
239
+ // Wait a moment for background boot
240
+ await sleep(2000);
233
241
 
234
- return {
235
- success: false,
236
- message: `Service '${serviceId}' exited immediately. Check logs with 'aih logs ${serviceId}'`,
237
- pid,
238
- };
239
- }
242
+ // Re-sync with OS
243
+ await this.syncState();
240
244
 
241
245
  return {
242
246
  success: true,
@@ -261,29 +265,48 @@ export class ServiceManager {
261
265
  }
262
266
 
263
267
  /**
264
- * Stops a single service by ID.
268
+ * Stops a single service cleanly, executing stop commands and clearing ports/workers.
265
269
  */
266
270
  async stopService(serviceId) {
271
+ const def = SERVICES[serviceId];
267
272
  const state = await this.syncState();
268
273
  const current = state.services[serviceId];
269
274
 
270
- if (!current || current.status !== "running" || !current.pid) {
271
- return { success: true, message: `Service '${serviceId}' is not running` };
275
+ // 1. If service has a dedicated graceful stopCommand, run it
276
+ if (def?.stopCommand) {
277
+ const isWin = process.platform === "win32";
278
+ if (isWin) {
279
+ await execCommand("cmd.exe", ["/c", def.stopCommand]);
280
+ } else {
281
+ await execCommand("sh", ["-c", def.stopCommand]);
282
+ }
283
+ await sleep(400);
284
+ }
285
+
286
+ // 2. Kill recorded process tree if still active
287
+ if (current && current.pid && isPidRunning(current.pid)) {
288
+ await killProcessTree(current.pid);
272
289
  }
273
290
 
274
- const pidToKill = current.pid;
275
- const killResult = await killProcessTree(pidToKill);
291
+ // 3. Clean up any remaining processes holding the service's ports
292
+ if (def?.ports && def.ports.length > 0) {
293
+ const portPids = await findPidsListeningOnPorts(def.ports);
294
+ for (const p of portPids) {
295
+ if (isPidRunning(p)) {
296
+ await killProcessTree(p);
297
+ }
298
+ }
299
+ }
276
300
 
301
+ // 4. Update state to stopped
277
302
  state.services[serviceId].status = "stopped";
278
303
  state.services[serviceId].pid = undefined;
279
304
  state.services[serviceId].startedAt = undefined;
280
305
  this.saveState(state);
281
306
 
282
307
  return {
283
- success: killResult.success,
284
- message: killResult.success
285
- ? `Service '${serviceId}' stopped (PID: ${pidToKill})`
286
- : `Failed to stop service '${serviceId}': ${killResult.message}`,
308
+ success: true,
309
+ message: `Service '${serviceId}' stopped cleanly`,
287
310
  };
288
311
  }
289
312
 
@@ -306,7 +329,7 @@ export class ServiceManager {
306
329
  */
307
330
  async restartService(serviceId) {
308
331
  await this.stopService(serviceId);
309
- await sleep(400);
332
+ await sleep(600);
310
333
  return await this.startService(serviceId);
311
334
  }
312
335
 
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { openSync, closeSync, appendFileSync } from "node:fs";
2
+ import { openSync, appendFileSync } from "node:fs";
3
3
  import { ensureDir, getLogsDir } from "./path.js";
4
4
 
5
5
  /**
@@ -94,6 +94,46 @@ export function openBrowser(url) {
94
94
  } catch {}
95
95
  }
96
96
 
97
+ /**
98
+ * Finds PIDs of processes currently listening on the specified TCP ports.
99
+ * @param {number[]} ports
100
+ * @returns {Promise<number[]>}
101
+ */
102
+ export async function findPidsListeningOnPorts(ports) {
103
+ if (!ports || ports.length === 0) return [];
104
+ const matchedPids = new Set();
105
+
106
+ if (process.platform === "win32") {
107
+ try {
108
+ const portList = ports.join(", ");
109
+ const script = `Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $_.LocalPort -in ${portList} } | Select-Object -ExpandProperty OwningProcess`;
110
+ const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
111
+ const lines = res.stdout.trim().split(/\r?\n/);
112
+ for (const line of lines) {
113
+ const pid = parseInt(line.trim(), 10);
114
+ if (pid && !isNaN(pid) && pid > 0) {
115
+ matchedPids.add(pid);
116
+ }
117
+ }
118
+ } catch {}
119
+ } else {
120
+ try {
121
+ for (const port of ports) {
122
+ const res = await execCommand("lsof", ["-t", `-i:${port}`, "-sTCP:LISTEN"]);
123
+ const lines = res.stdout.trim().split(/\r?\n/);
124
+ for (const line of lines) {
125
+ const pid = parseInt(line.trim(), 10);
126
+ if (pid && !isNaN(pid) && pid > 0) {
127
+ matchedPids.add(pid);
128
+ }
129
+ }
130
+ }
131
+ } catch {}
132
+ }
133
+
134
+ return Array.from(matchedPids);
135
+ }
136
+
97
137
  /**
98
138
  * Kills a process and its entire child process tree.
99
139
  * @param {number} pid
@@ -181,28 +221,16 @@ export function spawnDetachedProcess(command, logFilePath, options) {
181
221
 
182
222
  const fd = openSync(logFilePath, "a");
183
223
 
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
- }
224
+ const proc = spawn(command, [], {
225
+ shell: true,
226
+ detached: true,
227
+ stdio: ["ignore", fd, fd],
228
+ env: { ...process.env, ...options?.env },
229
+ cwd: options?.cwd,
230
+ windowsHide: true,
231
+ });
201
232
 
202
233
  proc.unref();
203
- try {
204
- closeSync(fd);
205
- } catch {}
206
234
 
207
235
  return { pid: proc.pid };
208
236
  }
@@ -270,7 +298,7 @@ export async function discoverRunningProcesses() {
270
298
  const ports = pidToPorts[pid] || [];
271
299
 
272
300
  // 1. pxpipe
273
- if (cmd.includes("pxpipe-proxy") || (cmd.toLowerCase().includes("pxpipe") && !cmd.includes("@agentmemory"))) {
301
+ if (cmd.includes("pxpipe-proxy") || (cmd.toLowerCase().includes("pxpipe") && !cmd.includes("agentmemory"))) {
274
302
  if (!discovered.pxpipe || (item.Name && item.Name.toLowerCase() === "node.exe" && cmd.includes("cli.js"))) {
275
303
  const webPort = ports.find(p => p > 1000 && p < 65000) || (discovered.pxpipe?.port);
276
304
  discovered.pxpipe = {
@@ -297,16 +325,20 @@ export async function discoverRunningProcesses() {
297
325
  }
298
326
  }
299
327
 
300
- // 3. agentmemory
328
+ // 3. agentmemory (daemon / iii-engine only, strictly exclude MCP stdio shims)
329
+ const isMcpShim = cmd.includes("agentmemory-mcp") || cmd.includes("@agentmemory/mcp") || cmd.includes("agentmemory mcp");
330
+
301
331
  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"))
332
+ !isMcpShim &&
333
+ (cmd.includes("@agentmemory/agentmemory") ||
334
+ cmd.includes("agentmemory\\dist\\cli.mjs") ||
335
+ cmd.includes("agentmemory/dist/cli.mjs") ||
336
+ cmd.includes("iii-config.yaml") ||
337
+ cmd.includes("iii.exe") ||
338
+ (cmd.includes("agentmemory") && !cmd.includes("mcp")))
307
339
  ) {
308
340
  const webPort = ports.find(p => p === 3113 || p === 43210 || (p > 1000 && p < 65000));
309
- if (!discovered.agentmemory || cmd.includes("agentmemory/agentmemory")) {
341
+ if (!discovered.agentmemory || cmd.includes("agentmemory/agentmemory") || cmd.includes("dist\\cli.mjs")) {
310
342
  discovered.agentmemory = {
311
343
  pid,
312
344
  command: cmd,
@@ -353,10 +385,14 @@ export async function discoverRunningProcesses() {
353
385
  if (cmd.includes("ocx start") || cmd.includes("ocx.mjs") || cmd.includes("opencodex")) {
354
386
  if (!discovered.ocx) discovered.ocx = { pid, command: cmd, url: "http://localhost:10100" };
355
387
  }
388
+
389
+ const isMcpShim = cmd.includes("agentmemory-mcp") || cmd.includes("@agentmemory/mcp") || cmd.includes("agentmemory mcp");
356
390
  if (
357
- cmd.includes("@agentmemory/agentmemory") ||
358
- cmd.includes("iii-config.yaml") ||
359
- (cmd.includes("agentmemory") && !cmd.includes("@agentmemory/mcp"))
391
+ !isMcpShim &&
392
+ (cmd.includes("@agentmemory/agentmemory") ||
393
+ cmd.includes("iii-config.yaml") ||
394
+ cmd.includes("iii") ||
395
+ (cmd.includes("agentmemory") && !cmd.includes("mcp")))
360
396
  ) {
361
397
  if (!discovered.agentmemory) discovered.agentmemory = { pid, command: cmd, url: "http://localhost:3113" };
362
398
  }