@drakonkat/ai-helper 1.2.9 → 1.2.10

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,6 +4,17 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.2.10] - 2026-09-29
8
+
9
+ ### Added
10
+ - Show preset processing time, upstream response-header latency, total HTTP/SSE duration, upstream status and interrupted/failed responses in the live request stream. WebSocket events report preset time only.
11
+ - Regression coverage for streaming, concurrent requests, transport failures, cancellation and timing persistence without duplicate counters.
12
+
13
+ ### Fixed
14
+ - Close parent log descriptors after spawning detached services and allow cold Windows process discovery to finish in CI.
15
+
16
+ ---
17
+
7
18
  ## [1.2.9] - 2026-09-29
8
19
 
9
20
  ### Added
package/README.md CHANGED
@@ -197,11 +197,33 @@ upgrade, restart the proxy and reopen the updated dashboard; a source checkout
197
197
  can be run directly with `node bin/cli.js status --ui` to avoid an older global
198
198
  installation taking precedence on PATH.
199
199
 
200
+ Request timings use a monotonic clock and appear on new events:
201
+
202
+ - `proxy`: preset processing, including request decompression and serialization,
203
+ but excluding client upload, custom interceptors and forwarding.
204
+ - `header`: time from dispatching the upstream HTTP request to receiving its
205
+ response headers, including connection setup and upstream request upload.
206
+ This is **not** time to first model token; SSE headers can arrive before output.
207
+ - `tot`: time from receiving the client's HTTP request headers until the proxy
208
+ finishes sending the response (or the connection fails/closes). Includes client
209
+ upload, preset/interceptor work, upstream waiting and streaming/downstream
210
+ backpressure; it does not confirm delivery to the client application.
211
+
212
+ HTTP/SSE entries also show the upstream HTTP status and incomplete/error states.
213
+ The existing event is updated without counting another request. A pending state
214
+ only means no completion was recorded (for example after a proxy crash), not a
215
+ global count of active calls. Updates do not bring evicted events back into the
216
+ bounded recent list. WebSocket events report **only preset time**: connection
217
+ duration and arbitrary response frames cannot safely be attributed to individual
218
+ calls. Missing/older timings remain `n/d`. Error responses that arrive normally
219
+ (such as HTTP 500) retain their status; a transport failure is marked separately
220
+ from a preset error. Preset `none` remains unrecorded.
221
+
200
222
  Press **`d`** for source/configuration details and per-stage
201
223
  before/after token counts, percentages and measurement methods. Unknown savings
202
224
  remain unknown; partial estimates and token increases are explicitly marked.
203
- The panels do not infer provider cache savings, costs, upstream latency or
204
- active requests. Preset `none` and interceptor-only traffic are not recorded.
225
+ The panels do not infer provider cache savings, costs, model-only latency or
226
+ active request counts. Preset `none` and interceptor-only traffic are not recorded.
205
227
 
206
228
  A running process is not a health check, and the final upstream is not monitored.
207
229
  Snapshot read time is separate from last-event time: an idle proxy is not stale
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drakonkat/ai-helper",
3
- "version": "1.2.9",
3
+ "version": "1.2.10",
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",
@@ -1,6 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import zlib from "node:zlib";
4
+ import { performance } from "node:perf_hooks";
4
5
  import { tokenStage } from "./proxy-stats.js";
5
6
  import { requestImages } from "./request-images.js";
6
7
 
@@ -119,7 +120,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
119
120
  JSON.stringify(result.messages) !== JSON.stringify(messages), result.compression_skipped ? "compression_skipped" : "processed", "headroom");
120
121
  }
121
122
 
122
- async function transform(raw, context, websocket = false) {
123
+ async function transform(raw, context, websocket = false, started = performance.now()) {
123
124
  const path = new URL(context.path, "http://localhost").pathname;
124
125
  const format = /\/(?:v1\/|anthropic\/)?messages$/.test(path) ? "anthropic"
125
126
  : /\/chat\/completions$/.test(path) ? "chat" : /\/responses$/.test(path) ? "responses" : null;
@@ -151,7 +152,13 @@ export async function createPresetHooks(config, onStats = () => {}) {
151
152
  source = Object.fromEntries(Object.entries({ sessionId: metadata.session_id, threadId: metadata.thread_id, project })
152
153
  .filter(([, value]) => typeof value === "string" && value.length).map(([key, value]) => [key, value.slice(0, 128)]));
153
154
  } catch {}
154
- try { onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error, ...source, ...(requestId ? { requestId } : {}) }); } catch {}
155
+ try {
156
+ const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
157
+ timings: { presetMs: Math.round((performance.now() - started) * 10) / 10 },
158
+ ...source, ...(requestId ? { requestId } : {}) });
159
+ // ponytail: WS measures presets only; response timings need per-response-ID correlation.
160
+ if (!websocket && typeof update === "function") context.updateTiming = update;
161
+ } catch {}
155
162
  };
156
163
  try {
157
164
  // Fixed stage order, including the triple recipe: RTK -> Headroom -> pxpipe.
@@ -212,13 +219,15 @@ export async function createPresetHooks(config, onStats = () => {}) {
212
219
  } else if (px) {
213
220
  stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
214
221
  }
222
+ const output = changed ? Buffer.from(JSON.stringify(envelope)) : raw;
215
223
  report(false);
216
- return changed ? Buffer.from(JSON.stringify(envelope)) : raw;
224
+ return output;
217
225
  } catch (error) { report(true); throw error; }
218
226
  }
219
227
 
220
228
  return {
221
229
  async onRequest(context) {
230
+ const started = performance.now();
222
231
  if (context.method !== "POST" || !/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(String(context.headers["content-type"] || ""))) return;
223
232
  const encoding = String(context.headers["content-encoding"] || "identity").toLowerCase();
224
233
  if (encoding !== "identity" && !DECODERS[encoding]) {
@@ -229,7 +238,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
229
238
  return;
230
239
  }
231
240
  const raw = encoding === "identity" ? context.body : await DECODERS[encoding](context.body, { maxOutputLength: config.maxBodyBytes });
232
- const body = await transform(raw, context);
241
+ const body = await transform(raw, context, false, started);
233
242
  if (body !== raw) {
234
243
  context.body = body;
235
244
  delete context.headers["content-encoding"];
@@ -22,6 +22,18 @@ export function createProxyStatsRecorder(file = getProxyStatsPath()) {
22
22
  const stats = readProxyStats(file) || { version: 1, since: new Date().toISOString(), requests: 0,
23
23
  changed: 0, errors: 0, estimatedSavedTokens: 0, unmeasuredStages: 0, stages: {}, recent: [] };
24
24
  let warned = false;
25
+ const warn = error => {
26
+ if (!warned) console.error(`[aih stats] Cannot save statistics: ${error.message}`);
27
+ warned = true;
28
+ };
29
+ const save = () => {
30
+ try {
31
+ mkdirSync(dirname(file), { recursive: true });
32
+ const temporary = `${file}.${process.pid}.tmp`;
33
+ writeFileSync(temporary, JSON.stringify(stats) + "\n");
34
+ renameSync(temporary, file);
35
+ } catch (error) { warn(error); }
36
+ };
25
37
  return event => {
26
38
  try {
27
39
  stats.updatedAt = new Date().toISOString();
@@ -39,19 +51,21 @@ export function createProxyStatsRecorder(file = getProxyStatsPath()) {
39
51
  }
40
52
  stats.estimatedSavedTokens += saved;
41
53
  const model = String(event.model).replace(/[\r\n]/g, " ").slice(0, 128);
42
- stats.recent.push({ at: stats.updatedAt, model, preset: event.preset, transport: event.transport,
54
+ const recent = { at: stats.updatedAt, model, preset: event.preset, transport: event.transport,
43
55
  changed: event.changed, error: Boolean(event.error), saved: event.error ? null : saved,
44
- sessionId: event.sessionId, threadId: event.threadId, project: event.project, stages });
56
+ sessionId: event.sessionId, threadId: event.threadId, project: event.project,
57
+ ...(event.timings ? { timings: { ...event.timings } } : {}), stages };
58
+ stats.recent.push(recent);
45
59
  stats.recent = stats.recent.slice(-20);
46
- mkdirSync(dirname(file), { recursive: true });
47
- const temporary = `${file}.${process.pid}.tmp`;
48
- writeFileSync(temporary, JSON.stringify(stats) + "\n");
49
- renameSync(temporary, file);
60
+ save();
50
61
  console.log(`[aih stats] ${event.transport} ${model} ${event.preset}: ${event.error ? "processing failed" : stages.map(s => `${s.name}=${s.saved ?? "?"} (${s.reason})`).join(", ") + `; estimated saved=${saved} tokens`}`);
51
- } catch (error) {
52
- if (!warned) console.error(`[aih stats] Cannot save statistics: ${error.message}`);
53
- warned = true;
54
- }
62
+ // Update this entry, never recount a request or resurrect an evicted entry.
63
+ return timings => {
64
+ if (!stats.recent.includes(recent)) return;
65
+ recent.timings = { ...recent.timings, ...timings };
66
+ save();
67
+ };
68
+ } catch (error) { warn(error); }
55
69
  };
56
70
  }
57
71
 
package/src/proxy.js CHANGED
@@ -4,6 +4,7 @@ import { resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { Transform } from "node:stream";
6
6
  import { pipeline } from "node:stream/promises";
7
+ import { performance } from "node:perf_hooks";
7
8
  import WebSocket, { WebSocketServer } from "ws";
8
9
  import { normalizePresetOptions, createPresetHooks } from "./proxy-presets.js";
9
10
 
@@ -121,7 +122,7 @@ export async function startProxy(options) {
121
122
  response.end(error.statusCode === 413 ? "Request body too large\n" : "Proxy request failed\n");
122
123
  }
123
124
 
124
- async function relayResponse(incoming, response, request) {
125
+ async function relayResponse(incoming, response, request, onFailure = error => fail(response, error)) {
125
126
  const context = { request, statusCode: incoming.statusCode, headers: { ...incoming.headers } };
126
127
  try {
127
128
  await hooks.onResponse?.(context);
@@ -161,32 +162,69 @@ export async function startProxy(options) {
161
162
  await pipeline(incoming, response);
162
163
  }
163
164
  } catch (error) {
164
- fail(response, error);
165
+ onFailure(error);
165
166
  incoming.destroy();
166
167
  }
167
168
  }
168
169
 
169
170
  const server = http.createServer(async (request, response) => {
171
+ const started = performance.now();
170
172
  let upstream;
171
- response.on("close", () => upstream?.destroy());
172
- request.on("error", error => { upstream?.destroy(); fail(response, error); });
173
+ let context;
174
+ let finished = false;
175
+ let failed = false;
176
+ const timings = { state: "waiting" };
177
+ const elapsed = since => Math.round((performance.now() - since) * 10) / 10;
178
+ const publishTiming = () => {
179
+ // Optional recorder updater: never emit a second preset event or disrupt traffic.
180
+ try { context?.updateTiming?.(timings); } catch {}
181
+ };
182
+ const finishTiming = state => {
183
+ if (finished) return;
184
+ finished = true;
185
+ timings.state = state;
186
+ timings.totalMs = elapsed(started);
187
+ publishTiming();
188
+ };
189
+ const failRequest = error => { failed = true; fail(response, error); };
190
+ response.once("finish", () => finishTiming(failed ? "error" : "completed"));
191
+ response.once("close", () => {
192
+ finishTiming(failed ? "error" : "aborted");
193
+ upstream?.destroy();
194
+ });
195
+ request.on("error", error => { upstream?.destroy(); failRequest(error); });
173
196
  try {
174
- const context = requestContext(request);
197
+ context = requestContext(request);
175
198
  if (hooks.onRequest) {
176
199
  context.body = await readBody(request, config.maxBodyBytes);
177
200
  await hooks.onRequest(context);
178
201
  context.body = bytes(context.body);
179
202
  if (context.body.length > config.maxBodyBytes) throw Object.assign(new Error("Modified request body exceeds maxBodyBytes"), { statusCode: 413 });
180
203
  }
204
+ // A disconnect may have happened while the preset was still processing.
205
+ publishTiming();
181
206
  if (response.destroyed) return;
182
207
  const headers = headersForHop(context.headers);
183
208
  headers.host = target.host;
184
209
  if (context.body !== undefined) headers["content-length"] = String(context.body.length);
185
210
  else if (context.headers.trailer) headers.trailer = context.headers.trailer;
211
+ const sentAt = performance.now();
186
212
  upstream = (target.protocol === "https:" ? https : http).request(target, {
187
213
  method: context.method, path: upstreamPath(context.path), headers,
188
- }, incoming => { void relayResponse(incoming, response, context); });
189
- upstream.on("error", error => fail(response, error));
214
+ }, incoming => {
215
+ // Mark upstream truncation before pipeline destroys the downstream response.
216
+ incoming.once("aborted", () => { failed = true; });
217
+ incoming.once("error", () => { failed = true; });
218
+ if (!finished) {
219
+ // Header arrival is observable without consuming/buffering SSE body chunks.
220
+ timings.upstreamHeadersMs = elapsed(sentAt);
221
+ timings.statusCode = incoming.statusCode;
222
+ timings.state = "responding";
223
+ publishTiming();
224
+ }
225
+ void relayResponse(incoming, response, context, failRequest);
226
+ });
227
+ upstream.on("error", failRequest);
190
228
  request.on("aborted", () => upstream.destroy());
191
229
  if (context.body !== undefined) upstream.end(context.body);
192
230
  else {
@@ -195,7 +233,8 @@ export async function startProxy(options) {
195
233
  }
196
234
  } catch (error) {
197
235
  upstream?.destroy();
198
- fail(response, error);
236
+ failRequest(error);
237
+ publishTiming();
199
238
  }
200
239
  });
201
240
  // Long-lived SSE streams must not expire between model events.
package/src/tui.js CHANGED
@@ -98,6 +98,11 @@ function age(timestamp, now) {
98
98
  return `${Math.floor(seconds / 3600)}h`;
99
99
  }
100
100
 
101
+ function duration(ms) {
102
+ if (!Number.isFinite(ms) || ms < 0) return "n/d";
103
+ return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
104
+ }
105
+
101
106
  // Snapshot strings are data, never terminal escape sequences or extra rows.
102
107
  function plain(value, fallback = "-") {
103
108
  return stripAnsi(String(value ?? fallback)).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
@@ -350,7 +355,10 @@ export class Dashboard {
350
355
  }
351
356
  add([dim("elab/s: richieste elaborate dai preset, non tutto il traffico proxy")]);
352
357
  add([dim("Risparmio: somma dei delta misurati per stadio; basi non sommabili")]);
353
- add([dim("Errori preset != errori upstream; latenza e richieste in corso non misurate")]);
358
+ add([dim("Errori preset != errori upstream; nessun conteggio globale delle richieste in corso")]);
359
+ add([dim("Tempi: proxy = preset; header = invio upstream -> header (non primo token)")]);
360
+ add([dim("Totale HTTP include upload, interceptor e streaming fino a fine invio/chiusura")]);
361
+ add([dim("WS: solo tempo preset; attesa esito non implica che la richiesta sia ancora attiva")]);
354
362
  }
355
363
  return lines.map(line => clip(line, width));
356
364
  }
@@ -375,9 +383,23 @@ export class Dashboard {
375
383
  const unmeasured = partial && stages.every(stage => !Number.isFinite(stage.saved));
376
384
  const status = event.error ? red(bold("errore preset")) : event.changed === true ? green("modificata")
377
385
  : event.changed === false ? dim("invariata") : dim("esito non disponibile");
386
+ const timing = event.timings;
387
+ const responseState = {
388
+ waiting: dim("attesa esito"), responding: cyan("risposta iniziata"),
389
+ error: red(event.error ? "non inoltrata" : "errore proxy/trasporto"), aborted: yellow("interrotta"),
390
+ }[timing?.state];
378
391
  const lines = wrapCells([gray(time), cyan(plain(event.transport)), magenta(plain(event.model, "?")),
379
392
  plain(event.preset), status,
380
393
  ...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
394
+ ...(timing ? [
395
+ `proxy: ${duration(timing.presetMs)}`,
396
+ ...(event.transport === "HTTP" ? [
397
+ `header: ${duration(timing.upstreamHeadersMs)}`, `tot: ${duration(timing.totalMs)}`,
398
+ ...(Number.isInteger(timing.statusCode) && timing.statusCode >= 100 && timing.statusCode <= 599
399
+ ? [timing.statusCode >= 400 ? red(`HTTP ${timing.statusCode}`) : `HTTP ${timing.statusCode}`] : []),
400
+ ...(responseState ? [responseState] : []),
401
+ ] : [dim("risposta WS: n/d")]),
402
+ ] : [dim("tempi: n/d")]),
381
403
  ...(event.project ? [`progetto: ${plain(event.project)}`] : []),
382
404
  ...(event.sessionId || event.threadId ? [`sessione: ${plain(event.sessionId || event.threadId)}`] : []),
383
405
  ...(!this.showPipelineDetails ? stages.map(s => dim(`${plain(s.name)}: ${plain(s.reason)}`)) : []),
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { openSync, appendFileSync } from "node:fs";
2
+ import { openSync, appendFileSync, closeSync } from "node:fs";
3
3
  import { ensureDir, getLogsDir } from "./path.js";
4
4
 
5
5
  /**
@@ -221,14 +221,20 @@ export function spawnDetachedProcess(command, logFilePath, options) {
221
221
 
222
222
  const fd = openSync(logFilePath, "a");
223
223
 
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
- });
224
+ let proc;
225
+ try {
226
+ proc = spawn(command, [], {
227
+ shell: true,
228
+ detached: true,
229
+ stdio: ["ignore", fd, fd],
230
+ env: { ...process.env, ...options?.env },
231
+ cwd: options?.cwd,
232
+ windowsHide: true,
233
+ });
234
+ } finally {
235
+ // The child owns its inherited handles; the parent must not keep the log open.
236
+ closeSync(fd);
237
+ }
232
238
 
233
239
  proc.unref();
234
240