@drakonkat/ai-helper 1.2.19 → 1.2.21
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 +9 -0
- package/CHANGELOG.md +19 -0
- package/README.md +50 -4
- package/package.json +1 -1
- package/src/config.js +12 -0
- package/src/health.js +2 -1
- package/src/hindsight.js +334 -13
- package/src/index.js +2 -0
- package/src/manager.js +311 -54
- package/src/proxy-presets.js +89 -35
- package/src/pxpipe-pool.js +69 -15
- package/src/startup-services.js +2 -1
- package/src/tui-proxy-setup.js +51 -10
- package/src/tui.js +3 -1
- package/src/utils/versions.js +8 -1
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);
|
package/src/startup-services.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { SERVICE_IDS } from "./config.js";
|
|
2
2
|
|
|
3
3
|
export const STARTUP_SERVICE_IDS = Object.freeze([
|
|
4
|
-
|
|
4
|
+
// hindsight-llm is started and stopped together with hindsight.
|
|
5
|
+
"ocx", "hindsight", ...SERVICE_IDS.filter(id => !["ocx", "hindsight", "hindsight-llm"].includes(id)), "proxy",
|
|
5
6
|
]);
|
|
6
7
|
export const DEFAULT_START_SERVICES = Object.freeze(["ocx", "hindsight", "proxy"]);
|
|
7
8
|
/** Saved selections from older releases name services that were replaced. */
|
package/src/tui-proxy-setup.js
CHANGED
|
@@ -3,7 +3,9 @@ import { STARTUP_SERVICE_IDS, normalizeStartServices } from "./startup-services.
|
|
|
3
3
|
import {
|
|
4
4
|
HINDSIGHT_DEFAULTS,
|
|
5
5
|
HINDSIGHT_KEY_ENV,
|
|
6
|
+
LOCAL_LLM_OPERATIONS,
|
|
6
7
|
normalizeHindsightConfig,
|
|
8
|
+
normalizeLocalLlmConfig,
|
|
7
9
|
readHindsightApiKey,
|
|
8
10
|
validateHindsightApiKey,
|
|
9
11
|
} from "./hindsight.js";
|
|
@@ -14,7 +16,7 @@ const STARTUP_FIELD = { key: "startServices", group: "Startup", label: "Services
|
|
|
14
16
|
|
|
15
17
|
/** Shown only when Hindsight is selected for start/up. "config" maps to the saved settings. */
|
|
16
18
|
export const HINDSIGHT_FIELDS = Object.freeze([
|
|
17
|
-
{ key: "hindsightContainer", config: "containerName", group: "Hindsight", label: "Hindsight container name", help: "Docker container started/stopped by aih. An existing container with this name is reused as is; the settings below apply only to containers aih creates or adopts (u on hindsight in the dashboard imports an existing container
|
|
19
|
+
{ key: "hindsightContainer", config: "containerName", group: "Hindsight", label: "Hindsight container name", help: "Docker container started/stopped by aih. An existing container with this name is reused as is; the settings below apply only to containers aih creates or adopts (u twice on hindsight in the dashboard imports an existing container or docker compose stack, including its local LLM)." },
|
|
18
20
|
{ key: "hindsightImage", config: "image", group: "Hindsight", label: "Docker image", help: "Default ghcr.io/vectorize-io/hindsight:latest. Pin a version (e.g. :1.2.0) for repeatable installs: update (u) moves it to the latest release." },
|
|
19
21
|
{ key: "hindsightApiPort", config: "apiPort", group: "Hindsight", label: "API port", help: "Loopback port for the Hindsight API and its /health check. Default 8888." },
|
|
20
22
|
{ key: "hindsightUiPort", config: "uiPort", group: "Hindsight", label: "Web UI port", help: "Loopback port of the Hindsight control plane, opened with o in the dashboard. Default 9999." },
|
|
@@ -26,6 +28,31 @@ export const HINDSIGHT_FIELDS = Object.freeze([
|
|
|
26
28
|
{ key: "hindsightEnvFile", config: "envFile", group: "Hindsight advanced", label: "Extra environment file", help: "Optional docker --env-file with advanced HINDSIGHT_* settings (timeouts, failover models...). Empty = none." },
|
|
27
29
|
]);
|
|
28
30
|
|
|
31
|
+
/** The local LLM step; "llm" maps to config.localLlm. The other fields appear only when it is on. */
|
|
32
|
+
const LOCAL = "Hindsight local LLM";
|
|
33
|
+
export const LOCAL_LLM_TOGGLE = Object.freeze({ key: "hindsightLocalEnabled", llm: "enabled", group: LOCAL, label: "Local LLM for Hindsight", choices: ["off", "on"],
|
|
34
|
+
help: "on = aih also runs a llama.cpp server container (hindsight-llm), starts it before Hindsight and stops it after, and sends the operations you choose to it. Other operations keep the LLM above." });
|
|
35
|
+
export const LOCAL_LLM_FIELDS = Object.freeze([
|
|
36
|
+
{ key: "hindsightLocalImage", llm: "image", group: LOCAL, label: "llama.cpp server image", help: "Pin a build, e.g. ghcr.io/ggml-org/llama.cpp:server-cuda-b12282. u re-pulls this tag but never moves it: change the build here, by hand." },
|
|
37
|
+
{ key: "hindsightLocalModelsDir", llm: "modelsDir", group: LOCAL, label: "Models folder", help: "Absolute host folder with the GGUF files, mounted read-only at /models." },
|
|
38
|
+
{ key: "hindsightLocalModel", llm: "model", group: LOCAL, label: "Model file", help: "GGUF file inside the models folder, e.g. LFM3-1.7B-Q8_0.gguf." },
|
|
39
|
+
{ key: "hindsightLocalLora", llm: "lora", group: LOCAL, label: "LoRA adapter", help: "Optional GGUF adapter inside the models folder. Empty = none." },
|
|
40
|
+
{ key: "hindsightLocalAlias", llm: "alias", group: LOCAL, label: "Model alias", help: "Name the server answers to and Hindsight asks for (--alias)." },
|
|
41
|
+
{ key: "hindsightLocalPort", llm: "port", group: LOCAL, label: "Host port", help: "Loopback port of the server, for its health check and your own tests. Hindsight uses the Docker network. Default 8085." },
|
|
42
|
+
{ key: "hindsightLocalGpus", llm: "gpus", group: LOCAL, label: "GPUs", help: "docker --gpus value: all, a count, device=0,1, or none for CPU only (then use a CPU image tag)." },
|
|
43
|
+
{ key: "hindsightLocalCtxSize", llm: "ctxSize", group: LOCAL, label: "Context size", help: "Total --ctx-size, shared by the parallel slots: each slot gets context / slots tokens." },
|
|
44
|
+
{ key: "hindsightLocalParallel", llm: "parallel", group: LOCAL, label: "Parallel slots", help: "--parallel: requests served at the same time." },
|
|
45
|
+
{ key: "hindsightLocalExtraArgs", llm: "extraArgs", group: LOCAL, label: "Extra llama-server arguments", help: "Space-separated, e.g. --jinja --n-gpu-layers 999 --flash-attn on --no-kv-unified --metrics. Model, adapter, alias, host, port, context and slots come from the fields above." },
|
|
46
|
+
{ key: "hindsightLocalOperations", llm: "operations", group: LOCAL, label: "Operations sent to the local LLM", choices: LOCAL_LLM_OPERATIONS, multiple: true,
|
|
47
|
+
help: "Arrows move; Space toggles. Mental model refresh follows reflect unless chosen separately. Unchosen operations use the Hindsight LLM." },
|
|
48
|
+
{ key: "hindsightLocalMaxConcurrent", llm: "maxConcurrent", group: LOCAL, label: "Max concurrent requests", help: "Per operation; at most the parallel slots." },
|
|
49
|
+
{ key: "hindsightLocalTimeout", llm: "timeout", group: LOCAL, label: "Timeout (seconds)", help: "Per request to the local LLM." },
|
|
50
|
+
{ key: "hindsightLocalMaxContext", llm: "maxContextTokens", group: LOCAL, label: "Reflect max context tokens", help: "Reflect prompt budget. Context + completion must fit one slot." },
|
|
51
|
+
{ key: "hindsightLocalMaxCompletion", llm: "maxCompletionTokens", group: LOCAL, label: "Reflect max completion tokens", help: "Reflect answer budget." },
|
|
52
|
+
]);
|
|
53
|
+
const ALL_LOCAL_FIELDS = [LOCAL_LLM_TOGGLE, ...LOCAL_LLM_FIELDS];
|
|
54
|
+
const localValue = (field, llm) => field.llm === "enabled" ? (llm.enabled ? "on" : "off") : Array.isArray(llm[field.llm]) ? llm[field.llm].join(",") : String(llm[field.llm] ?? "");
|
|
55
|
+
|
|
29
56
|
const clean = value => String(value ?? "").replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
30
57
|
const isHindsightField = field => field.key.startsWith("hindsight");
|
|
31
58
|
|
|
@@ -43,8 +70,9 @@ export class ProxySetupWizard {
|
|
|
43
70
|
this.hindsightSaved = state.config?.hindsight ? savedHindsight(state) : null;
|
|
44
71
|
const hindsight = savedHindsight(state);
|
|
45
72
|
for (const f of HINDSIGHT_FIELDS) this.draft[f.key] = f.secret ? "" : String(hindsight[f.config] ?? "");
|
|
73
|
+
for (const f of ALL_LOCAL_FIELDS) this.draft[f.key] = localValue(f, hindsight.localLlm);
|
|
46
74
|
this.keyStatus = keyStatus;
|
|
47
|
-
this.
|
|
75
|
+
this.choiceIndex = {};
|
|
48
76
|
this.initial = { ...this.draft };
|
|
49
77
|
this.active = state.services?.proxy?.proxyOptions;
|
|
50
78
|
this.running = state.services?.proxy?.status === "running";
|
|
@@ -60,16 +88,21 @@ export class ProxySetupWizard {
|
|
|
60
88
|
}
|
|
61
89
|
|
|
62
90
|
get hindsightSelected() { return this.draft.startServices.split(",").includes("hindsight"); }
|
|
91
|
+
get localLlmSelected() { return this.hindsightSelected && this.draft.hindsightLocalEnabled === "on"; }
|
|
63
92
|
get fields() {
|
|
64
93
|
return [...PROXY_FIELDS.filter(f => !f.stage || this.draft.preset.split("-").includes(f.stage)), STARTUP_FIELD,
|
|
65
|
-
...(this.hindsightSelected ? HINDSIGHT_FIELDS : [])];
|
|
94
|
+
...(this.hindsightSelected ? [...HINDSIGHT_FIELDS, LOCAL_LLM_TOGGLE] : []), ...(this.localLlmSelected ? LOCAL_LLM_FIELDS : [])];
|
|
66
95
|
}
|
|
67
96
|
get field() { return this.fields[this.step]; }
|
|
68
97
|
get summary() { return this.step >= this.fields.length; }
|
|
69
98
|
get dirty() { return JSON.stringify(this.initial) !== JSON.stringify(this.draft); }
|
|
70
99
|
|
|
71
100
|
hindsightDraft() {
|
|
72
|
-
return Object.fromEntries(HINDSIGHT_FIELDS.filter(f => !f.secret).map(f => [f.config, this.draft[f.key]]));
|
|
101
|
+
return { ...Object.fromEntries(HINDSIGHT_FIELDS.filter(f => !f.secret).map(f => [f.config, this.draft[f.key]])), localLlm: this.localLlmDraft() };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
localLlmDraft(enabled = this.draft.hindsightLocalEnabled === "on") {
|
|
105
|
+
return { ...Object.fromEntries(LOCAL_LLM_FIELDS.map(f => [f.llm, this.draft[f.key]])), enabled };
|
|
73
106
|
}
|
|
74
107
|
|
|
75
108
|
/** null when Hindsight is not started by start/up: its settings are then left untouched. */
|
|
@@ -93,8 +126,10 @@ export class ProxySetupWizard {
|
|
|
93
126
|
validateField() {
|
|
94
127
|
const field = this.field;
|
|
95
128
|
const value = this.draft[field.key];
|
|
96
|
-
if (field
|
|
129
|
+
if (field === STARTUP_FIELD) { normalizeStartServices(value.split(",")); return; }
|
|
97
130
|
if (field.secret) { validateHindsightApiKey(value.trim()); return; }
|
|
131
|
+
// Field by field only the format is checked; the summary checks the whole local LLM setup.
|
|
132
|
+
if (field.llm) { normalizeLocalLlmConfig(this.localLlmDraft(false)); return; }
|
|
98
133
|
if (isHindsightField(field)) { normalizeHindsightConfig(this.hindsightDraft()); return; }
|
|
99
134
|
// Validate only this field, against known valid defaults, without discarding other edits.
|
|
100
135
|
const base = proxySetupDraft({ services: {} });
|
|
@@ -150,11 +185,12 @@ export class ProxySetupWizard {
|
|
|
150
185
|
}
|
|
151
186
|
if (f.choices) {
|
|
152
187
|
if (f.multiple) {
|
|
153
|
-
|
|
154
|
-
if (key === "\x1b[
|
|
188
|
+
const index = this.choiceIndex[f.key] || 0;
|
|
189
|
+
if (key === "\x1b[A") this.choiceIndex[f.key] = (index + f.choices.length - 1) % f.choices.length;
|
|
190
|
+
if (key === "\x1b[B") this.choiceIndex[f.key] = (index + 1) % f.choices.length;
|
|
155
191
|
if (key === " ") {
|
|
156
192
|
const selected = new Set(value.split(",").filter(Boolean));
|
|
157
|
-
const service = f.choices[
|
|
193
|
+
const service = f.choices[index];
|
|
158
194
|
if (selected.has(service)) selected.delete(service); else selected.add(service);
|
|
159
195
|
this.draft[f.key] = f.choices.filter(id => selected.has(id)).join(",");
|
|
160
196
|
}
|
|
@@ -210,13 +246,15 @@ export class ProxySetupWizard {
|
|
|
210
246
|
return wrap(`${before !== after ? "* " : " "}${f.label}: ${after || (f.key === "models" ? "pxpipe defaults; RTK/Headroom on all" : "(none)")}${before !== after ? ` (previous: ${before || "empty"})` : ""}`);
|
|
211
247
|
});
|
|
212
248
|
if (this.hindsightSelected) {
|
|
213
|
-
body.push(...HINDSIGHT_FIELDS.flatMap(f => {
|
|
249
|
+
body.push(...[...HINDSIGHT_FIELDS, LOCAL_LLM_TOGGLE, ...(this.localLlmSelected ? LOCAL_LLM_FIELDS : [])].flatMap(f => {
|
|
214
250
|
if (f.secret) return wrap(this.draft[f.key].trim() ? `* ${f.label}: new key (hidden)` : ` ${f.label}: unchanged (${this.keyDescription()})`);
|
|
215
251
|
const before = this.initial[f.key];
|
|
216
252
|
const after = this.draft[f.key];
|
|
217
253
|
return wrap(`${before !== after ? "* " : " "}${f.label}: ${after || "(none)"}${before !== after ? ` (previous: ${before || "empty"})` : ""}`);
|
|
218
254
|
}));
|
|
219
255
|
body.push(...wrap("Hindsight: settings are saved; apply recreates a running container created by aih (data volume kept). Other containers are left unchanged until adopted (u on the dashboard)."));
|
|
256
|
+
if (this.localLlmSelected) body.push(...wrap("Local LLM: started before Hindsight and stopped after it; a new or changed server must answer a test completion before Hindsight starts."));
|
|
257
|
+
else if (this.hindsightSaved?.localLlm?.enabled) body.push(...wrap("Local LLM: turned off; apply stops its container and Hindsight uses its own LLM for every operation."));
|
|
220
258
|
}
|
|
221
259
|
body.push(...wrap(this.running ? "WARNING: apply now restarts the proxy and interrupts active requests/streams." : "Apply now starts the proxy. Save only leaves it stopped."));
|
|
222
260
|
body.push(...this.checks.flatMap(wrap));
|
|
@@ -225,7 +263,7 @@ export class ProxySetupWizard {
|
|
|
225
263
|
const f = this.field;
|
|
226
264
|
body.push(...wrap(f.label), ...wrap(f.help), "");
|
|
227
265
|
if (f.choices) body.push(...f.choices.map((v, i) => f.multiple
|
|
228
|
-
? `${i === this.
|
|
266
|
+
? `${i === (this.choiceIndex[f.key] || 0) ? ">" : " "} [${this.draft[f.key].split(",").includes(v) ? "x" : " "}] ${v}`
|
|
229
267
|
: `${v === this.draft[f.key] ? ">" : " "} ${v.replaceAll("-", " -> ")}`));
|
|
230
268
|
else {
|
|
231
269
|
const value = this.draft[f.key];
|
|
@@ -236,6 +274,9 @@ export class ProxySetupWizard {
|
|
|
236
274
|
if (f.secret) {
|
|
237
275
|
body.push(...wrap("Initial value: (empty: keep the current key)"));
|
|
238
276
|
body.push(...wrap(`Current setting: key ${this.keyDescription()}`));
|
|
277
|
+
} else if (f.llm) {
|
|
278
|
+
body.push(...wrap(`Initial value: ${this.initial[f.key] || "(empty)"}`));
|
|
279
|
+
body.push(...wrap(`Current setting: ${this.hindsightSaved ? localValue(f, this.hindsightSaved.localLlm) || "(empty)" : "(not configured: defaults)"}`));
|
|
239
280
|
} else if (isHindsightField(f)) {
|
|
240
281
|
body.push(...wrap(`Initial value: ${this.initial[f.key] || "(empty)"}`));
|
|
241
282
|
body.push(...wrap(`Current setting: ${this.hindsightSaved ? String(this.hindsightSaved[f.config] ?? "") || "(empty)" : "(not configured: defaults)"}`));
|
package/src/tui.js
CHANGED
|
@@ -565,7 +565,9 @@ export class Dashboard {
|
|
|
565
565
|
const rows = this.statuses.map((s, idx) => {
|
|
566
566
|
const active = idx === this.selected;
|
|
567
567
|
const version = this.versions[s.id];
|
|
568
|
-
const update = version?.
|
|
568
|
+
const update = version?.pinned
|
|
569
|
+
? dim("pinned")
|
|
570
|
+
: version?.updateAvailable === true
|
|
569
571
|
? yellow(bold(`↑ ${version.latestVersion}`))
|
|
570
572
|
: version?.updateAvailable === false
|
|
571
573
|
? green("up to date")
|
package/src/utils/versions.js
CHANGED
|
@@ -3,7 +3,7 @@ import { readFile, realpath } from "node:fs/promises";
|
|
|
3
3
|
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
4
|
import { baseUrl, fetchJson } from "./metrics.js";
|
|
5
5
|
import { SERVICE_PACKAGES as PACKAGES, SERVICES } from "../config.js";
|
|
6
|
-
import { HINDSIGHT_RELEASES_URL } from "../hindsight.js";
|
|
6
|
+
import { HINDSIGHT_RELEASES_URL, LOCAL_LLM_ID } from "../hindsight.js";
|
|
7
7
|
import { refreshToolPath } from "./tool-path.js";
|
|
8
8
|
|
|
9
9
|
function parseVersion(value) {
|
|
@@ -143,6 +143,13 @@ export async function getServiceVersions(statuses, {
|
|
|
143
143
|
const readCommands = () => commands ||= Promise.resolve().then(() => processCommands(services)).catch(() => ({}));
|
|
144
144
|
// Docker images: the running API reports its version; releases come from GitHub.
|
|
145
145
|
const dockerVersions = docker.map(async status => {
|
|
146
|
+
// The llama.cpp build is pinned and changed by hand: report it, never offer an update.
|
|
147
|
+
if (status.id === LOCAL_LLM_ID) {
|
|
148
|
+
const version = status.status === "running" && baseUrl(status.apiUrl)
|
|
149
|
+
? await request(`${baseUrl(status.apiUrl)}/props`, 2000).then(data => typeof data?.build_info === "string" ? data.build_info.split("-")[0] : null).catch(() => null)
|
|
150
|
+
: null;
|
|
151
|
+
return [status.id, { version, latestVersion: null, updateAvailable: null, pinned: true }];
|
|
152
|
+
}
|
|
146
153
|
const [version, latestVersion] = await Promise.all([
|
|
147
154
|
status.status === "running" && baseUrl(status.apiUrl)
|
|
148
155
|
? request(`${baseUrl(status.apiUrl)}/health/live`, 2000).then(data => cleanVersion(data?.version)).catch(() => null)
|