@drakonkat/ai-helper 1.2.19 → 1.2.20
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 +9 -0
- package/README.md +11 -4
- package/package.json +1 -1
- package/src/proxy-presets.js +89 -35
- package/src/pxpipe-pool.js +69 -15
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,15 @@ All notable changes to **`ai-helper` (`aih`)** are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [1.2.20] - 2026-11-13
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
- **pxpipe overload no longer fails requests**: when the worker queue is full, a request waits more than 10 s, or the body exceeds 64 MiB, the proxy forwards it without pxpipe (stage reason `queue_full`, `queue_timeout`, `body_too_large`) instead of answering HTTP 503. pxpipe-only requests are checked before the JSON body is parsed.
|
|
11
|
+
- The worker queue is limited per worker (4 waiting requests) and by waiting time; the byte cap is now a memory guard of 4 × `--max-body-bytes` instead of a single request's size.
|
|
12
|
+
- Worker affinity follows the Codex thread instead of the session, so forked subagents no longer queue behind their parent and each other.
|
|
13
|
+
- A client disconnect no longer terminates the active pxpipe worker: its result is discarded and the warm worker is kept (replaced only if still busy after 120 s).
|
|
14
|
+
- Compressed requests that decompress beyond `--max-body-bytes` are forwarded unchanged instead of failing; unchanged bodies are no longer re-serialized before pxpipe.
|
|
15
|
+
|
|
7
16
|
## [1.2.19] - 2026-11-10
|
|
8
17
|
|
|
9
18
|
### Added
|
package/README.md
CHANGED
|
@@ -466,10 +466,17 @@ tokenization costs and worker-thread experiments.
|
|
|
466
466
|
|
|
467
467
|
Pxpipe transformations and their token estimates run in up to **two persistent
|
|
468
468
|
CPU workers**. Excluded models bypass the worker queue; HTTP and SSE streaming
|
|
469
|
-
remain on the main thread.
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
469
|
+
remain on the main thread. Each Codex thread keeps a stable worker to reuse caches;
|
|
470
|
+
a new thread (for example a forked subagent) starts on its parent's worker only when
|
|
471
|
+
that worker is idle, otherwise on the least busy one. Each worker accepts up to 4
|
|
472
|
+
waiting requests, each waiting at most 10 s, and all waiting input is capped at
|
|
473
|
+
4 × `--max-body-bytes`. Requests over these limits, or with bodies over 64 MiB, are
|
|
474
|
+
**forwarded without pxpipe** (stage reason `queue_full`, `queue_timeout` or
|
|
475
|
+
`body_too_large`) instead of failing; pxpipe-only requests are checked before
|
|
476
|
+
parsing. Compressed bodies that decompress beyond `--max-body-bytes` are forwarded
|
|
477
|
+
unchanged. Disconnecting cancels queued work; an active transformation finishes on
|
|
478
|
+
its warm worker and its result is discarded (a worker still busy after 120 s is
|
|
479
|
+
replaced). Shutdown closes both workers.
|
|
473
480
|
|
|
474
481
|
Installation applies a version-checked correction to pxpipe 0.14.0: diagnostic
|
|
475
482
|
composition counts exclude encrypted reasoning, opaque compaction and media data,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drakonkat/ai-helper",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.20",
|
|
4
4
|
"description": "Zero-config background service manager, auto-discovery daemon & dashboard launcher for AI agent ecosystems (pxpipe, ocx, hindsight, headroom)",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"module": "src/index.js",
|
package/src/proxy-presets.js
CHANGED
|
@@ -10,6 +10,28 @@ import { createPxpipePool } from "./pxpipe-pool.js";
|
|
|
10
10
|
export const PRESETS = Object.freeze(["none", "pxpipe", "headroom", "rtk", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"]);
|
|
11
11
|
const DECODERS = { gzip: promisify(zlib.gunzip), deflate: promisify(zlib.inflate), br: promisify(zlib.brotliDecompress),
|
|
12
12
|
...(typeof zlib.zstdDecompress === "function" ? { zstd: promisify(zlib.zstdDecompress) } : {}) };
|
|
13
|
+
// Safety net, not load control: bodies this large would occupy a worker for minutes.
|
|
14
|
+
export const PXPIPE_MAX_INPUT_BYTES = 64 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
const requestFormat = path => {
|
|
17
|
+
const pathname = new URL(path, "http://localhost").pathname;
|
|
18
|
+
return /\/(?:v1\/|anthropic\/)?messages$/.test(pathname) ? "anthropic"
|
|
19
|
+
: /\/chat\/completions$/.test(pathname) ? "chat" : /\/responses$/.test(pathname) ? "responses" : null;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function turnMetadata(headers) {
|
|
23
|
+
try {
|
|
24
|
+
const metadata = JSON.parse(headers?.["x-codex-turn-metadata"] || "{}");
|
|
25
|
+
return metadata && typeof metadata === "object" ? metadata : {};
|
|
26
|
+
} catch { return {}; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const text = value => typeof value === "string" && value.length ? value.slice(0, 128) : undefined;
|
|
30
|
+
const affinityOf = context => {
|
|
31
|
+
const metadata = turnMetadata(context.headers);
|
|
32
|
+
return { threadId: text(metadata.thread_id), sessionId: text(metadata.session_id) };
|
|
33
|
+
};
|
|
34
|
+
const skippedPxpipe = reason => tokenStage("pxpipe", 0, 0, false, reason, "not_measured");
|
|
13
35
|
|
|
14
36
|
export function normalizePresetOptions(options) {
|
|
15
37
|
const preset = options.preset || "none";
|
|
@@ -88,9 +110,44 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
88
110
|
const px = config.preset.includes("pxpipe") ? await import("pxpipe-proxy/applicability") : null;
|
|
89
111
|
const pool = px ? createPxpipePool(config.maxBodyBytes) : null;
|
|
90
112
|
const models = config.models?.split(",");
|
|
113
|
+
const listed = model => models.some(m => m.endsWith("*") ? model.startsWith(m.slice(0, -1)) : model === m);
|
|
114
|
+
const pxpipeModel = model => models ? listed(model) : px.isPxpipeSupportedModel(model) || px.isPxpipeSupportedGptModel(model);
|
|
91
115
|
const wsModels = new WeakMap();
|
|
92
116
|
const warnedEncodings = new Set();
|
|
93
117
|
|
|
118
|
+
function record(context, websocket, started, { model, changed, stages, error, timings = {} }) {
|
|
119
|
+
// Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
|
|
120
|
+
// Optional correlation only; never pass headers or bodies to the recorder.
|
|
121
|
+
const requestId = typeof context.headers?.["x-request-id"] === "string" ? context.headers["x-request-id"].slice(0, 128) : undefined;
|
|
122
|
+
let source = {};
|
|
123
|
+
try {
|
|
124
|
+
const metadata = turnMetadata(context.headers);
|
|
125
|
+
const remotes = Object.values(metadata.workspaces || {}).flatMap(workspace => Object.values(workspace?.associated_remote_urls || {}));
|
|
126
|
+
const project = remotes.filter(value => typeof value === "string").map(value => value.replace(/^[^@/]+@[^:/]+:/, "")
|
|
127
|
+
.replace(/^[a-z]+:\/\/[^/]+/i, "").split(/[?#]/)[0].replace(/\.git$/i, "").split("/").filter(Boolean).slice(-2).join("/")).find(Boolean);
|
|
128
|
+
source = Object.fromEntries(Object.entries({ sessionId: text(metadata.session_id), threadId: text(metadata.thread_id), project: text(project) })
|
|
129
|
+
.filter(([, value]) => value !== undefined));
|
|
130
|
+
} catch {}
|
|
131
|
+
try {
|
|
132
|
+
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
133
|
+
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10, ...timings },
|
|
134
|
+
...source, ...(requestId ? { requestId } : {}) });
|
|
135
|
+
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
136
|
+
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
137
|
+
} catch {}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// pxpipe-only HTTP: decide a capacity/size skip before parsing a multi-MB JSON body.
|
|
141
|
+
function skipBeforeParse(raw, context, started) {
|
|
142
|
+
if (!requestFormat(context.path)) return false;
|
|
143
|
+
// Only a leading top-level model is trusted; anything else takes the normal path.
|
|
144
|
+
const model = /^\s*\{\s*"model"\s*:\s*"([^"\\]{1,128})"/.exec(raw.subarray(0, 512).toString("latin1"))?.[1];
|
|
145
|
+
if (!model || !pxpipeModel(model)) return false;
|
|
146
|
+
const reason = raw.length > PXPIPE_MAX_INPUT_BYTES ? "body_too_large" : pool.full(affinityOf(context), raw.length) ? "queue_full" : null;
|
|
147
|
+
if (reason) record(context, false, started, { model, changed: false, stages: [skippedPxpipe(reason)], error: false });
|
|
148
|
+
return Boolean(reason);
|
|
149
|
+
}
|
|
150
|
+
|
|
94
151
|
async function headroom(body, model) {
|
|
95
152
|
// Responses items (reasoning, calls, IDs, images) stay native. Compress only their tool text.
|
|
96
153
|
const slots = Array.isArray(body.input) ? toolTexts(body) : null;
|
|
@@ -123,9 +180,7 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
123
180
|
}
|
|
124
181
|
|
|
125
182
|
async function transform(raw, context, websocket = false, started = performance.now()) {
|
|
126
|
-
const
|
|
127
|
-
const format = /\/(?:v1\/|anthropic\/)?messages$/.test(path) ? "anthropic"
|
|
128
|
-
: /\/chat\/completions$/.test(path) ? "chat" : /\/responses$/.test(path) ? "responses" : null;
|
|
183
|
+
const format = requestFormat(context.path);
|
|
129
184
|
if (!format) return raw;
|
|
130
185
|
let envelope;
|
|
131
186
|
try { envelope = JSON.parse(raw.toString("utf8")); } catch { return raw; }
|
|
@@ -142,29 +197,9 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
142
197
|
let changed = false;
|
|
143
198
|
const stages = [];
|
|
144
199
|
let pxpipeTimings = {};
|
|
145
|
-
const report = error => {
|
|
146
|
-
// Observability must never interrupt proxy traffic; no request bodies are passed to the recorder.
|
|
147
|
-
// Optional correlation only; never pass headers or bodies to the recorder.
|
|
148
|
-
const requestId = typeof context.headers?.["x-request-id"] === "string" ? context.headers["x-request-id"].slice(0, 128) : undefined;
|
|
149
|
-
let source = {};
|
|
150
|
-
try {
|
|
151
|
-
const metadata = JSON.parse(context.headers?.["x-codex-turn-metadata"] || "{}");
|
|
152
|
-
const remotes = Object.values(metadata.workspaces || {}).flatMap(workspace => Object.values(workspace?.associated_remote_urls || {}));
|
|
153
|
-
const project = remotes.filter(value => typeof value === "string").map(value => value.replace(/^[^@/]+@[^:/]+:/, "")
|
|
154
|
-
.replace(/^[a-z]+:\/\/[^/]+/i, "").split(/[?#]/)[0].replace(/\.git$/i, "").split("/").filter(Boolean).slice(-2).join("/")).find(Boolean);
|
|
155
|
-
source = Object.fromEntries(Object.entries({ sessionId: metadata.session_id, threadId: metadata.thread_id, project })
|
|
156
|
-
.filter(([, value]) => typeof value === "string" && value.length).map(([key, value]) => [key, value.slice(0, 128)]));
|
|
157
|
-
} catch {}
|
|
158
|
-
try {
|
|
159
|
-
const update = onStats({ model, preset: config.preset, transport: websocket ? "WS" : "HTTP", changed, stages, error,
|
|
160
|
-
timings: { presetMs: Math.round((performance.now() - started) * 10) / 10, ...pxpipeTimings },
|
|
161
|
-
...source, ...(requestId ? { requestId } : {}) });
|
|
162
|
-
// ponytail: WS measures presets only; response timings need per-response-ID correlation.
|
|
163
|
-
if (!websocket && typeof update === "function") context.updateTiming = update;
|
|
164
|
-
} catch {}
|
|
165
|
-
};
|
|
200
|
+
const report = error => record(context, websocket, started, { model, changed, stages, error, timings: pxpipeTimings });
|
|
166
201
|
// Preserve observability and byte-for-byte forwarding for excluded models.
|
|
167
|
-
if (models && !
|
|
202
|
+
if (models && !listed(model)) {
|
|
168
203
|
for (const stage of config.preset.split("-")) stages.push(tokenStage(stage, 0, 0, false, "model_excluded", "not_measured"));
|
|
169
204
|
report(false);
|
|
170
205
|
return raw;
|
|
@@ -192,15 +227,26 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
192
227
|
// A Headroom no-op must not discard changes already made by RTK.
|
|
193
228
|
changed = JSON.stringify(body) !== before || changed;
|
|
194
229
|
}
|
|
230
|
+
let result;
|
|
195
231
|
if (bypassPxpipe) {
|
|
196
232
|
stages.push(tokenStage("pxpipe", 0, 0, false, "native_images_present", "pxpipe_estimate"));
|
|
197
|
-
} else if (px && (
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
233
|
+
} else if (px && pxpipeModel(model) && raw.length > PXPIPE_MAX_INPUT_BYTES) {
|
|
234
|
+
stages.push(skippedPxpipe("body_too_large"));
|
|
235
|
+
} else if (px && pxpipeModel(model)) {
|
|
236
|
+
// An unchanged HTTP body already carries the model: skip a second multi-MB serialization.
|
|
237
|
+
const reuse = !changed && body === envelope && body.model === model;
|
|
238
|
+
const bytes = reuse ? raw : Buffer.from(JSON.stringify({ ...body, model }));
|
|
239
|
+
try {
|
|
240
|
+
result = await pool.run({ body: bytes, format, model }, { ...affinityOf(context), signal: context.signal, transfer: !reuse });
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (error.code !== "PXPIPE_BUSY") throw error;
|
|
243
|
+
// Availability over savings: forward without pxpipe instead of a 503 the client retries at once.
|
|
244
|
+
stages.push(skippedPxpipe(error.reason));
|
|
245
|
+
}
|
|
246
|
+
} else if (px) {
|
|
247
|
+
stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
|
|
248
|
+
}
|
|
249
|
+
if (result) {
|
|
204
250
|
pxpipeTimings = Object.fromEntries(Object.entries(result.timings).map(([key, value]) => [key, Math.round(value * 10) / 10]));
|
|
205
251
|
stages.push(result.stage);
|
|
206
252
|
if (result.stage.applied) {
|
|
@@ -211,8 +257,6 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
211
257
|
else { for (const key of Object.keys(body)) delete body[key]; Object.assign(body, transformed); }
|
|
212
258
|
changed = true;
|
|
213
259
|
}
|
|
214
|
-
} else if (px) {
|
|
215
|
-
stages.push(tokenStage("pxpipe", 0, 0, false, "model_excluded", "pxpipe_estimate"));
|
|
216
260
|
}
|
|
217
261
|
const output = changed ? Buffer.from(JSON.stringify(envelope)) : raw;
|
|
218
262
|
report(false);
|
|
@@ -233,7 +277,17 @@ export async function createPresetHooks(config, onStats = () => {}) {
|
|
|
233
277
|
}
|
|
234
278
|
return;
|
|
235
279
|
}
|
|
236
|
-
|
|
280
|
+
let raw = context.body;
|
|
281
|
+
if (encoding !== "identity") {
|
|
282
|
+
try { raw = await DECODERS[encoding](context.body, { maxOutputLength: config.maxBodyBytes }); }
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (error.code !== "ERR_BUFFER_TOO_LARGE") throw error;
|
|
285
|
+
// Too large to inspect: forward the compressed bytes unchanged instead of failing the request.
|
|
286
|
+
console.warn(`[aih preset] Skipped presets: decompressed ${encoding} body exceeds maxBodyBytes`);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (config.preset === "pxpipe" && skipBeforeParse(raw, context, started)) return;
|
|
237
291
|
const body = await transform(raw, context, false, started);
|
|
238
292
|
if (body !== raw) {
|
|
239
293
|
context.body = body;
|
package/src/pxpipe-pool.js
CHANGED
|
@@ -1,12 +1,40 @@
|
|
|
1
1
|
import { Worker } from "node:worker_threads";
|
|
2
2
|
import { performance } from "node:perf_hooks";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// Sized from field data: ~50 MB screenshot-heavy bodies take 20-40 s of worker CPU each.
|
|
5
|
+
export const PXPIPE_POOL_DEFAULTS = Object.freeze({
|
|
6
|
+
lanes: 2, maxQueuedPerLane: 4, maxQueueWaitMs: 10000, abandonedJobMs: 120000, affinityEntries: 512,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
/** Capacity rejection: callers forward the request without pxpipe instead of failing it. */
|
|
10
|
+
const busy = reason => Object.assign(new Error(reason === "queue_timeout" ? "pxpipe queue wait exceeded" : "pxpipe queue is full"),
|
|
11
|
+
{ code: "PXPIPE_BUSY", reason, statusCode: 503 });
|
|
12
|
+
|
|
13
|
+
export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = new URL("./pxpipe-thread.js", import.meta.url), options = {}) {
|
|
14
|
+
const { lanes, maxQueuedPerLane, maxQueueWaitMs, abandonedJobMs, affinityEntries } = { ...PXPIPE_POOL_DEFAULTS, ...options };
|
|
15
|
+
// Memory guard only: waiting time is bounded by maxQueueWaitMs, not by the size of one request.
|
|
16
|
+
const maxQueuedBytes = options.maxQueuedBytes ?? 4 * maxBodyBytes;
|
|
5
17
|
// The standalone CLI embeds a separate bundle: runtime relative files do not exist there.
|
|
6
18
|
if (typeof AIH_PXPIPE_THREAD_SOURCE !== "undefined") workerUrl = new URL(`data:text/javascript,${encodeURIComponent(AIH_PXPIPE_THREAD_SOURCE)}`);
|
|
7
|
-
const slots = Array.from({ length:
|
|
19
|
+
const slots = Array.from({ length: lanes }, () => ({ worker: null, ready: false, job: null, queue: [] }));
|
|
20
|
+
const affinity = new Map();
|
|
8
21
|
let closed = false, sequence = 0, queuedBytes = 0;
|
|
9
22
|
const pendingTerminations = new Set();
|
|
23
|
+
const load = slot => slot.queue.length + Boolean(slot.job);
|
|
24
|
+
// Known threads keep their lane (warm caches). A new thread prefers its idle parent lane, else the least loaded.
|
|
25
|
+
const pick = (key, parent) => {
|
|
26
|
+
const known = key === undefined ? undefined : affinity.get(key);
|
|
27
|
+
if (known) return known;
|
|
28
|
+
const parentSlot = parent === undefined ? undefined : affinity.get(parent);
|
|
29
|
+
return parentSlot && !load(parentSlot) ? parentSlot : slots.reduce((best, slot) => load(slot) < load(best) ? slot : best);
|
|
30
|
+
};
|
|
31
|
+
const remember = (key, slot) => {
|
|
32
|
+
if (key === undefined) return;
|
|
33
|
+
affinity.delete(key);
|
|
34
|
+
affinity.set(key, slot);
|
|
35
|
+
if (affinity.size > affinityEntries) affinity.delete(affinity.keys().next().value);
|
|
36
|
+
};
|
|
37
|
+
const full = (slot, bytes) => slot.queue.length >= maxQueuedPerLane || queuedBytes + bytes > maxQueuedBytes;
|
|
10
38
|
const terminate = slot => {
|
|
11
39
|
const worker = slot.worker;
|
|
12
40
|
slot.worker = null;
|
|
@@ -17,6 +45,9 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
17
45
|
termination.then(() => pendingTerminations.delete(termination), () => pendingTerminations.delete(termination));
|
|
18
46
|
};
|
|
19
47
|
const settle = (job, error, result) => {
|
|
48
|
+
clearTimeout(job.timer);
|
|
49
|
+
if (job.settled) return; // abandoned jobs were already rejected
|
|
50
|
+
job.settled = true;
|
|
20
51
|
job.signal?.removeEventListener("abort", job.abort);
|
|
21
52
|
if (error) job.reject(error); else job.resolve(result);
|
|
22
53
|
};
|
|
@@ -27,11 +58,15 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
27
58
|
}
|
|
28
59
|
if (!slot.ready) return;
|
|
29
60
|
const job = slot.queue.shift();
|
|
61
|
+
clearTimeout(job.timer);
|
|
30
62
|
queuedBytes -= job.bytes;
|
|
31
63
|
slot.job = job;
|
|
32
64
|
job.queueMs = performance.now() - job.queuedAt;
|
|
33
65
|
slot.worker.ref();
|
|
34
|
-
|
|
66
|
+
const body = job.input.body;
|
|
67
|
+
// Move a private copy instead of cloning it; a caller-owned buffer must stay readable.
|
|
68
|
+
const transfer = job.transfer && body.byteOffset === 0 && body.byteLength === body.buffer.byteLength ? [body.buffer] : [];
|
|
69
|
+
try { slot.worker.postMessage({ ...job.input, id: job.id }, transfer); }
|
|
35
70
|
catch (error) { fail(slot, error); }
|
|
36
71
|
}
|
|
37
72
|
function fail(slot, error) {
|
|
@@ -49,6 +84,7 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
49
84
|
const job = slot.job;
|
|
50
85
|
if (!job || result.id !== job.id) return fail(slot, new Error("Unexpected pxpipe worker response"));
|
|
51
86
|
slot.job = null;
|
|
87
|
+
clearTimeout(job.watchdog);
|
|
52
88
|
worker.unref();
|
|
53
89
|
if (result.error) settle(job, new Error(result.error));
|
|
54
90
|
else settle(job, null, { ...result, timings: { ...result.timings, pxpipeQueueMs: job.queueMs } });
|
|
@@ -58,23 +94,41 @@ export function createPxpipePool(maxBodyBytes = 64 * 1024 * 1024, workerUrl = ne
|
|
|
58
94
|
worker.on("exit", code => { if (slot.worker === worker) fail(slot, new Error(`pxpipe worker exited (${code})`)); });
|
|
59
95
|
}
|
|
60
96
|
return {
|
|
61
|
-
run(
|
|
97
|
+
/** True when run() would reject for capacity; lets callers skip parsing a body pxpipe cannot take. */
|
|
98
|
+
full({ threadId, sessionId } = {}, bytes = 0) {
|
|
99
|
+
return full(pick(threadId || sessionId, sessionId), bytes);
|
|
100
|
+
},
|
|
101
|
+
run(input, { threadId, sessionId, signal, transfer = false } = {}) {
|
|
62
102
|
if (closed) return Promise.reject(new Error("pxpipe pool is closed"));
|
|
63
103
|
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const slot = sessionId ? slots[hash % slots.length]
|
|
70
|
-
: slots.reduce((best, current) => current.queue.length + Boolean(current.job) < best.queue.length + Boolean(best.job) ? current : best);
|
|
104
|
+
// Forked subagents share the parent's session_id: the thread is the affinity unit.
|
|
105
|
+
const key = threadId || sessionId;
|
|
106
|
+
const slot = pick(key, sessionId);
|
|
107
|
+
if (full(slot, input.body.byteLength)) return Promise.reject(busy("queue_full"));
|
|
108
|
+
remember(key, slot);
|
|
71
109
|
return new Promise((resolve, reject) => {
|
|
72
|
-
const job = { id: ++sequence, input, resolve, reject, signal, bytes: input.body.byteLength, queuedAt: performance.now() };
|
|
110
|
+
const job = { id: ++sequence, input, resolve, reject, signal, transfer, bytes: input.body.byteLength, queuedAt: performance.now() };
|
|
111
|
+
job.timer = setTimeout(() => {
|
|
112
|
+
const index = slot.queue.indexOf(job);
|
|
113
|
+
if (index < 0) return;
|
|
114
|
+
slot.queue.splice(index, 1);
|
|
115
|
+
queuedBytes -= job.bytes;
|
|
116
|
+
settle(job, busy("queue_timeout"));
|
|
117
|
+
}, maxQueueWaitMs);
|
|
118
|
+
job.timer.unref?.();
|
|
73
119
|
job.abort = () => {
|
|
74
|
-
if (slot.job === job) {
|
|
75
|
-
|
|
120
|
+
if (slot.job === job) {
|
|
121
|
+
// ponytail: the CPU transform cannot be interrupted; keep the warm worker and drop its result.
|
|
122
|
+
// The watchdog still replaces a worker stuck on an abandoned job.
|
|
123
|
+
job.watchdog = setTimeout(() => { if (slot.job === job) { slot.job = null; terminate(slot); dispatch(slot); } }, abandonedJobMs);
|
|
124
|
+
job.watchdog.unref?.();
|
|
125
|
+
} else {
|
|
126
|
+
const index = slot.queue.indexOf(job);
|
|
127
|
+
if (index < 0) return;
|
|
128
|
+
slot.queue.splice(index, 1);
|
|
129
|
+
queuedBytes -= job.bytes;
|
|
130
|
+
}
|
|
76
131
|
settle(job, signal.reason);
|
|
77
|
-
dispatch(slot);
|
|
78
132
|
};
|
|
79
133
|
signal?.addEventListener("abort", job.abort, { once: true });
|
|
80
134
|
slot.queue.push(job);
|