@drakonkat/ai-helper 1.2.12 → 1.2.14

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/ARCHITECTURE.md CHANGED
@@ -74,6 +74,11 @@ $ports = Get-NetTCPConnection -State Listen | Select-Object LocalPort, OwningPro
74
74
  3. Automatically computes uptimes from `CreationDate`.
75
75
  4. Maps dynamic ports to Web Dashboard URLs.
76
76
 
77
+ PowerShell discovery queries have a 10-second deadline so a cold or stalled CIM
78
+ provider cannot block status indefinitely. A failed scan is discarded; persisted
79
+ service PIDs are still checked for liveness and the next status refresh retries
80
+ external-process discovery.
81
+
77
82
  ### Unix Implementation
78
83
  Uses `ps -eo pid,command` to match command line strings and extract active PIDs.
79
84
 
package/CHANGELOG.md CHANGED
@@ -4,6 +4,25 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.2.14] - 2026-09-30
8
+
9
+ ### Fixed
10
+ - Bound Windows PowerShell/CIM discovery to 10 seconds so a cold or stalled provider cannot hang CLI status or port discovery. Discard failed scans while preserving live service PIDs already recorded in state.
11
+ - Treat subprocess termination without an exit code as failure and add a regression check for command deadlines. This fixes the Windows/Node 20 CI status test failure.
12
+
13
+ ---
14
+
15
+ ## [1.2.13] - 2026-09-30
16
+
17
+ ### Fixed
18
+ - Keep media-bearing Responses tool rounds native during history planning instead of tokenizing or rendering their base64 payloads. Preserve atomic parallel rounds, call IDs, recency and barriers between text history segments.
19
+ - Filter JSON-serialized media at the root of diagnostic tool outputs and upgrade the existing 1.2.12 diagnostic patch during installation.
20
+
21
+ ### Added
22
+ - Regression checks for old and recent media outputs, serialized images, audio, parallel rounds, text-history barriers and payload preservation in CPU workers.
23
+
24
+ ---
25
+
7
26
  ## [1.2.12] - 2026-09-30
8
27
 
9
28
  ### Fixed
@@ -248,3 +248,55 @@ I nuovi test controllano anche output identici prima/dopo la correzione, media
248
248
  nativi, compaction, Sol escluso durante due lavori CPU, coda limitata, cancellazione,
249
249
  crash e chiusura. La suite completa e il test CLI standalone sono passati.
250
250
  Il probe e `optimized-production.json` rimangono negli artefatti locali ignorati.
251
+
252
+ ## Picchi residui: immagini nei risultati dei tool
253
+
254
+ La profilazione successiva ha trovato un secondo percorso non coperto dalla
255
+ correzione della composizione: `classifyResponsesPairs` in `openai-history.js`
256
+ conta i token di ogni coppia call/output, anche se recente e mantenuta nativa.
257
+ Un output contenente `input_image` viene serializzato integralmente e il base64
258
+ passa a `gptCountTokens`. Lo stesso output può quindi essere conteggiato a ogni
259
+ nuovo turno, pur essendo già escluso dalla diagnostica iniziale.
260
+
261
+ Le metriche live prima dell'esclusione di Sol mostravano lavori CPU da
262
+ 42–148 secondi e lavori da 0,13–0,30 secondi che aspettavano 130–174 secondi
263
+ nella stessa coda. Gli header upstream arrivavano in circa 1–3 secondi. Questi
264
+ valori individuano un costo locale e il suo effetto sulle richieste concorrenti;
265
+ non sono una distribuzione di latenza del provider.
266
+
267
+ La correzione di aih 1.2.13 riconosce media nativi o serializzati, non ne tokenizza il payload
268
+ nel planner e mantiene nativo l'intero round parallelo di tool. Il round continua
269
+ a contare per la recenza e costituisce una barriera fra segmenti comprimibili.
270
+ I round di solo testo continuano a essere compressi. È corretto anche il filtro
271
+ diagnostico per un output JSON il cui oggetto radice è un'immagine.
272
+
273
+ | Riproduzione offline, primo uso | Prima | Dopo |
274
+ |---|---:|---:|
275
+ | Output di tool con screenshot reale da 3,25 MB | 12.505 ms | 158 ms |
276
+ | Output di tool con base64 ripetitivo da 128 KiB | 11.451 ms | 127 ms |
277
+
278
+ Ogni riga è una singola osservazione con Inspector attivo, non un benchmark
279
+ statistico. Nel caso reale il profilo prima della patch è dominato dallo stack
280
+ `countNative → gptCountTokens → classifyResponsesPairs`. Gli SHA-256 dei payload
281
+ in uscita coincidono prima e dopo in entrambi i casi recenti; gli output dei tool
282
+ e le immagini sono conservati. Per i round media vecchi cambia intenzionalmente
283
+ la selezione: restano nativi invece di essere convertiti in testo base64 renderizzato.
284
+ L'esclusione di Sol configurata dall'utente resta attiva.
285
+
286
+ I risultati e i profili senza payload sono in
287
+ `benchmark-results/pxpipe-residual-2026-09-30/`. Il probe usa uno screenshot già
288
+ presente nel rollout locale e non chiama provider. I test permanenti in
289
+ `test/pxpipe-performance.test.js` coprono round vecchi/recenti, media serializzati,
290
+ audio, round paralleli atomici e conservazione dell'output nel worker.
291
+
292
+ La suite completa `npm test`, la build e il test CLI del binario standalone
293
+ sono passati. La copia globale npm è stata patchata e verificata in un processo
294
+ nuovo: il controllo sintetico Astra con 256 KiB di immagine ha completato in
295
+ 115 ms conservando l'output. Esiste un backup dei due file della dipendenza e
296
+ dello script in `~/.aih/backups/pxpipe-media-20260930-141041/`.
297
+ La correzione viene applicata da `postinstall` e dalla build standalone di aih
298
+ 1.2.13. Un proxy già avviato deve essere riavviato per ricaricare la libreria.
299
+ Nel controllo locale Windows ha negato la terminazione del processo elevato
300
+ con `Access is denied`: in questo caso `aih restart proxy --json` deve essere
301
+ eseguito da una PowerShell con privilegi di amministratore.
302
+ La configurazione è stata verificata dopo il tentativo: Sol rimane escluso.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakonkat/ai-helper",
3
- "version": "1.2.12",
3
+ "version": "1.2.14",
4
4
  "description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, agentmemory, headroom)",
5
5
  "main": "src/index.js",
6
6
  "module": "src/index.js",
@@ -7,15 +7,15 @@ const original = "info.responsesComposition = measureResponsesComposition(req, i
7
7
  const replacement = `// aih: partial diagnostics exclude opaque payloads (pxpipe 0.14.0).
8
8
  const diagnosticOriginal = JSON.stringify(req);
9
9
  const diagnosticJson = JSON.stringify(req, (key, value) => {
10
+ // Parse before filtering so a serialized media object is filtered at its root too.
11
+ if (key === 'output' && typeof value === 'string' && /"(?:encrypted_content|inline_data|inlineData)"|"type"\\s*:\\s*"(?:image|input_image|output_image|image_url|input_audio|audio|audio_url|input_video|video|video_url)"/.test(value)) {
12
+ try { const parsed = JSON.parse(value); if (parsed && typeof parsed === 'object') value = parsed; } catch {}
13
+ }
10
14
  if (key === 'encrypted_content') return undefined;
11
15
  if (['image', 'input_image', 'output_image', 'image_url', 'input_audio', 'audio', 'audio_url', 'input_video', 'video', 'video_url'].includes(value?.type) || value?.inline_data || value?.inlineData)
12
16
  return { type: value.type || 'opaque_media' };
13
17
  if (['compaction', 'compaction_trigger', 'context_compaction'].includes(value?.type))
14
18
  return { type: value.type, id: value.id };
15
- // Tool outputs may contain JSON-serialized media instead of a content array.
16
- if (key === 'output' && typeof value === 'string' && /"(?:encrypted_content|inline_data|inlineData)"|"type"\\s*:\\s*"(?:image|input_image|output_image|image_url|input_audio|audio|audio_url|input_video|video|video_url)"/.test(value)) {
17
- try { const parsed = JSON.parse(value); if (parsed && typeof parsed === 'object') return parsed; } catch {}
18
- }
19
19
  return value;
20
20
  });
21
21
  const diagnosticRequest = JSON.parse(diagnosticJson);
@@ -26,20 +26,65 @@ const replacement = `// aih: partial diagnostics exclude opaque payloads (pxpipe
26
26
  export function patchPxpipeSource(source, version) {
27
27
  if (version !== "0.14.0") throw new Error(`Review the pxpipe diagnostic patch before using version ${version}`);
28
28
  if (source.includes(replacement)) return source;
29
+ // Upgrade the diagnostic block installed by aih 1.2.12 in place.
30
+ const previous = /\/\/ aih: partial diagnostics exclude opaque payloads \(pxpipe 0\.14\.0\)\.[\s\S]*?info\.responsesComposition\.partial = diagnosticJson !== diagnosticOriginal;/g;
31
+ if (source.match(previous)?.length === 1) source = source.replace(previous, original);
29
32
  if (source.split(original).length !== 2) throw new Error("pxpipe diagnostic patch target changed");
30
33
  return source.replace(original, replacement);
31
34
  }
32
35
 
36
+ // History planning must keep media-bearing tool rounds native, including their call IDs.
37
+ const historyMarker = "// aih: native tool media is a history barrier (pxpipe 0.14.0).";
38
+ const historyChanges = [
39
+ ["function responseOutputText(item) {", `${historyMarker}
40
+ function responseOutputHasMedia(output) {
41
+ if (typeof output === 'string') {
42
+ if (!/"(?:encrypted_content|inline_data|inlineData)"|"type"\\s*:\\s*"(?:image|input_image|output_image|image_url|input_audio|audio|audio_url|input_video|video|video_url|compaction|compaction_trigger|context_compaction)"/.test(output)) return false;
43
+ try { output = JSON.parse(output); } catch { return false; }
44
+ }
45
+ const pending = [output];
46
+ while (pending.length) {
47
+ const value = pending.pop();
48
+ if (!value || typeof value !== 'object') continue;
49
+ if (['image', 'input_image', 'output_image', 'image_url', 'input_audio', 'audio', 'audio_url', 'input_video', 'video', 'video_url', 'compaction', 'compaction_trigger', 'context_compaction'].includes(value.type)
50
+ || value.inline_data || value.inlineData || typeof value.encrypted_content === 'string') return true;
51
+ for (const child of Object.values(value)) pending.push(child);
52
+ }
53
+ return false;
54
+ }
55
+ function responseOutputText(item) {`],
56
+ ["const output = items[outputIndex];", "const output = items[outputIndex];\n const opaque = responseOutputHasMedia(output.output);"],
57
+ ["text: `${responseCallText(call)}\\n${responseOutputText(output)}`,", "opaque,\n text: opaque ? '' : `${responseCallText(call)}\\n${responseOutputText(output)}`,"],
58
+ ["outputTokens: gptCountTokens(typeof output.output === 'string' ? output.output : safeJson(output.output)),", "outputTokens: opaque ? 0 : gptCountTokens(typeof output.output === 'string' ? output.output : safeJson(output.output)),"],
59
+ ["pairs: calls,", "opaque: calls.some((pair) => pair.opaque),\n pairs: calls,"],
60
+ ["const old = completed.slice(0, recentStart);", "const oldRounds = completed.slice(0, recentStart);\n const old = oldRounds.filter((round) => !round.opaque);"],
61
+ ["const oldPairs = old.reduce", "const oldPairs = oldRounds.reduce"],
62
+ ];
63
+
64
+ export function patchPxpipeHistorySource(source, version) {
65
+ if (version !== "0.14.0") throw new Error(`Review the pxpipe history patch before using version ${version}`);
66
+ if (source.includes(historyMarker) && historyChanges.every(([, patched]) => source.includes(patched))) return source;
67
+ for (const [target, patched] of historyChanges) {
68
+ if (source.split(target).length !== 2) throw new Error("pxpipe history patch target changed");
69
+ source = source.replace(target, patched);
70
+ }
71
+ return source;
72
+ }
73
+
33
74
  export function patchPxpipe() {
34
75
  const entry = fileURLToPath(import.meta.resolve("pxpipe-proxy"));
35
76
  const manifest = JSON.parse(readFileSync(resolve(dirname(entry), "../../package.json"), "utf8"));
36
- const file = resolve(dirname(entry), "openai.js");
37
- const source = readFileSync(file, "utf8");
38
- const patched = patchPxpipeSource(source, manifest.version);
39
- if (patched !== source) {
40
- const temporary = `${file}.${process.pid}.tmp`;
41
- try { writeFileSync(temporary, patched); renameSync(temporary, file); }
42
- finally { rmSync(temporary, { force: true }); }
77
+ // Validate both targets before modifying either dependency file.
78
+ const changes = [["openai.js", patchPxpipeSource], ["openai-history.js", patchPxpipeHistorySource]].map(([name, patch]) => {
79
+ const file = resolve(dirname(entry), name), source = readFileSync(file, "utf8");
80
+ return { file, source, patched: patch(source, manifest.version) };
81
+ });
82
+ for (const { file, source, patched } of changes) {
83
+ if (patched !== source) {
84
+ const temporary = `${file}.${process.pid}.tmp`;
85
+ try { writeFileSync(temporary, patched); renameSync(temporary, file); }
86
+ finally { rmSync(temporary, { force: true }); }
87
+ }
43
88
  }
44
89
  }
45
90
 
@@ -15,14 +15,16 @@ export function sleep(ms) {
15
15
  * Helper to run a command and return stdout/stderr asynchronously.
16
16
  * @param {string} cmd
17
17
  * @param {string[]} args
18
+ * @param {number} [timeout=0] Maximum runtime in milliseconds; zero disables the deadline.
18
19
  * @returns {Promise<{ exitCode: number; stdout: string; stderr: string }>}
19
20
  */
20
- export function execCommand(cmd, args) {
21
+ export function execCommand(cmd, args, timeout = 0) {
21
22
  return new Promise(resolve => {
22
23
  try {
23
24
  const proc = spawn(cmd, args, {
24
25
  stdio: ["ignore", "pipe", "pipe"],
25
26
  windowsHide: true,
27
+ timeout,
26
28
  });
27
29
 
28
30
  let stdout = "";
@@ -32,7 +34,7 @@ export function execCommand(cmd, args) {
32
34
  proc.stderr?.on("data", d => (stderr += d.toString()));
33
35
 
34
36
  proc.on("close", exitCode => {
35
- resolve({ exitCode: exitCode ?? 0, stdout, stderr });
37
+ resolve({ exitCode: exitCode ?? 1, stdout, stderr });
36
38
  });
37
39
 
38
40
  proc.on("error", err => {
@@ -107,7 +109,8 @@ export async function findPidsListeningOnPorts(ports) {
107
109
  try {
108
110
  const portList = ports.join(", ");
109
111
  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]);
112
+ const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], 10000);
113
+ if (res.exitCode !== 0) return [];
111
114
  const lines = res.stdout.trim().split(/\r?\n/);
112
115
  for (const line of lines) {
113
116
  const pid = parseInt(line.trim(), 10);
@@ -372,8 +375,9 @@ export async function discoverRunningProcesses({ knownServices = {} } = {}) {
372
375
  Select-Object LocalPort, OwningProcess
373
376
  @{ Procs = $procs; Ports = $ports } | ConvertTo-Json -Depth 3
374
377
  `;
375
- const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
376
- if (res.stdout.trim()) return discoverWindowsProcesses(JSON.parse(res.stdout), { knownServices });
378
+ // A cold or stalled CIM provider must not hold status and the dashboard indefinitely.
379
+ const res = await execCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], 10000);
380
+ if (res.exitCode === 0 && res.stdout.trim()) return discoverWindowsProcesses(JSON.parse(res.stdout), { knownServices });
377
381
  } catch {}
378
382
  } else {
379
383
  try {