@drakonkat/ai-helper 1.1.1 → 1.2.3
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 +14 -3
- package/CHANGELOG.md +9 -0
- package/README.md +483 -26
- package/docs/benchmark.md +373 -0
- package/package.json +17 -5
- package/scripts/bench-proxy.js +111 -0
- package/scripts/build.js +16 -0
- package/src/benchmark/fixtures.js +162 -0
- package/src/benchmark/live.js +207 -0
- package/src/benchmark/measurement.js +180 -0
- package/src/benchmark/quality-fixtures.js +95 -0
- package/src/benchmark/quality.js +206 -0
- package/src/benchmark/report.js +162 -0
- package/src/benchmark/runner.js +287 -0
- package/src/codex-config.js +247 -0
- package/src/codex-routing.js +132 -0
- package/src/config.js +19 -1
- package/src/index.js +158 -26
- package/src/manager.js +233 -15
- package/src/proxy-interceptor.example.mjs +33 -0
- package/src/proxy-presets.js +235 -0
- package/src/proxy-stats.js +64 -0
- package/src/proxy-worker.js +17 -0
- package/src/proxy.js +313 -0
- package/src/request-images.js +69 -0
- package/src/service-updates.js +68 -0
- package/src/tui.js +370 -162
- package/src/update.js +41 -0
- package/src/utils/metrics.js +39 -12
- package/src/utils/process.js +92 -146
- package/src/utils/versions.js +165 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { once } from "node:events";
|
|
3
|
+
import { performance } from "node:perf_hooks";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import WebSocket, { WebSocketServer } from "ws";
|
|
9
|
+
import { startProxy } from "../proxy.js";
|
|
10
|
+
import { normalizePresetOptions } from "../proxy-presets.js";
|
|
11
|
+
import { builtInFixtures, validateFixtures } from "./fixtures.js";
|
|
12
|
+
import { evaluatePreservation, evaluateAnswer, evaluateEvidence } from "./quality.js";
|
|
13
|
+
import { compareRequestImages } from "../request-images.js";
|
|
14
|
+
import { measureRequest } from "./measurement.js";
|
|
15
|
+
import { callProvider, validateUpstream, readLimited } from "./live.js";
|
|
16
|
+
|
|
17
|
+
export const BENCHMARK_PRESETS = ["none", "headroom", "rtk", "pxpipe", "headroom-pxpipe", "rtk-pxpipe", "rtk-headroom-pxpipe"];
|
|
18
|
+
export const SUPPORTED_BENCHMARK_PRESETS = [...BENCHMARK_PRESETS, ...BENCHMARK_PRESETS.filter(p => p.includes("pxpipe")).map(p => `${p}-native-bypass`)];
|
|
19
|
+
function flowOptions(flow) {
|
|
20
|
+
const bypass = flow.endsWith("-native-bypass");
|
|
21
|
+
return { preset: bypass ? flow.slice(0, -"-native-bypass".length) : flow, pxpipeNativeImages: bypass ? "bypass" : "allow" };
|
|
22
|
+
}
|
|
23
|
+
const exec = promisify(execFile);
|
|
24
|
+
const digest = value => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
25
|
+
|
|
26
|
+
export function normalizeBenchmarkOptions(options = {}) {
|
|
27
|
+
const presets = options.presets || BENCHMARK_PRESETS;
|
|
28
|
+
if (!Array.isArray(presets) || !presets.length || new Set(presets).size !== presets.length || presets.some(p => !SUPPORTED_BENCHMARK_PRESETS.includes(p))) throw new Error("presets must be a unique nonempty list of supported presets");
|
|
29
|
+
if (options.suite !== undefined && !["core", "quality", "all"].includes(options.suite)) throw new Error("suite must be core, quality or all");
|
|
30
|
+
if (options.fixtures && options.suite !== undefined) throw new Error("Use fixtures OR suite, not both");
|
|
31
|
+
// Every comparison includes a concurrently replayed baseline, not old global stats.
|
|
32
|
+
const normalized = { ...options, presets: [...new Set(["none", ...presets])],
|
|
33
|
+
repetitions: options.repetitions ?? 3, warmup: options.warmup ?? 1,
|
|
34
|
+
seed: options.seed ?? 42, transports: options.transports || ["http"],
|
|
35
|
+
timeoutMs: options.timeoutMs ?? 120000, maxBodyBytes: options.maxBodyBytes ?? 64 * 1024 * 1024,
|
|
36
|
+
live: Boolean(options.live), maxOutputTokens: options.maxOutputTokens ?? 256, maxLiveCalls: options.maxLiveCalls ?? 200 };
|
|
37
|
+
for (const key of ["repetitions", "timeoutMs", "maxBodyBytes", "maxOutputTokens", "maxLiveCalls"]) {
|
|
38
|
+
if (!Number.isSafeInteger(normalized[key]) || normalized[key] < 1) throw new Error(`${key} must be a positive integer`);
|
|
39
|
+
}
|
|
40
|
+
if (!Number.isSafeInteger(normalized.warmup) || normalized.warmup < 0 || !Number.isSafeInteger(normalized.seed)) throw new Error("warmup must be nonnegative and seed must be an integer");
|
|
41
|
+
if (!Array.isArray(normalized.transports) || !normalized.transports.length || new Set(normalized.transports).size !== normalized.transports.length || normalized.transports.some(t => !["http", "ws"].includes(t))) throw new Error("transports must contain http and/or ws");
|
|
42
|
+
if (options.formats && (!Array.isArray(options.formats) || !options.formats.length || new Set(options.formats).size !== options.formats.length || options.formats.some(f => !["responses", "chat", "anthropic"].includes(f)))) throw new Error("formats must contain responses, chat and/or anthropic");
|
|
43
|
+
if (options.compareModels !== undefined) {
|
|
44
|
+
if (options.model !== undefined) throw new Error("Use model OR compareModels, not both");
|
|
45
|
+
if (!Array.isArray(options.compareModels) || !options.compareModels.length || new Set(options.compareModels).size !== options.compareModels.length || options.compareModels.some(m => typeof m !== "string" || !/^[\w./:-]+$/.test(m))) throw new Error("compareModels must be a unique nonempty list of model IDs");
|
|
46
|
+
}
|
|
47
|
+
if (options.responsesStream !== undefined && typeof options.responsesStream !== "boolean") throw new Error("responsesStream must be boolean");
|
|
48
|
+
if (normalized.live) {
|
|
49
|
+
if (!options.upstream) throw new Error("--live requires --upstream (provider root, before /v1)");
|
|
50
|
+
normalized.upstream = validateUpstream(options.upstream);
|
|
51
|
+
if (normalized.transports.includes("ws")) throw new Error("Live evaluation supports HTTP only; WS is available in offline replay");
|
|
52
|
+
} else if (options.upstream || options.apiKey) throw new Error("An upstream/API key requires explicit --live");
|
|
53
|
+
normalizePresetOptions({ ...options, preset: "none" });
|
|
54
|
+
return normalized;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function randomizer(seed) {
|
|
58
|
+
let state = seed >>> 0;
|
|
59
|
+
return () => { state = (Math.imul(state, 1664525) + 1013904223) >>> 0; return state / 4294967296; };
|
|
60
|
+
}
|
|
61
|
+
function shuffle(items, random) {
|
|
62
|
+
const result = [...items];
|
|
63
|
+
for (let i = result.length - 1; i > 0; i--) { const j = Math.floor(random() * (i + 1)); [result[i], result[j]] = [result[j], result[i]]; }
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function version(command) {
|
|
68
|
+
try { return (await exec(command, ["--version"], { timeout: 15000, windowsHide: true, maxBuffer: 8192 })).stdout.trim().slice(0, 128); }
|
|
69
|
+
catch { return null; }
|
|
70
|
+
}
|
|
71
|
+
async function packageVersion(name) {
|
|
72
|
+
try { return JSON.parse(await readFile(new URL(`../../node_modules/${name}/package.json`, import.meta.url), "utf8")).version; } catch { return null; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function collector(options) {
|
|
76
|
+
const records = new Map(), sockets = new Set();
|
|
77
|
+
const server = http.createServer(async (req, res) => {
|
|
78
|
+
const id = req.headers["x-request-id"];
|
|
79
|
+
const entry = records.get(id);
|
|
80
|
+
if (!entry) { res.writeHead(400); res.end(); return; }
|
|
81
|
+
res.on("close", () => { if (!res.writableFinished) entry.controller.abort(); });
|
|
82
|
+
try {
|
|
83
|
+
const chunks = []; let size = 0;
|
|
84
|
+
for await (const chunk of req) { size += chunk.length; if (size > options.maxBodyBytes) throw new Error("Collector body limit"); chunks.push(chunk); }
|
|
85
|
+
entry.body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
86
|
+
if (options.live) entry.live = await callProvider(entry.body, entry.fixture, { ...options, signal: entry.signal });
|
|
87
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
88
|
+
res.end("{}");
|
|
89
|
+
} catch (error) {
|
|
90
|
+
entry.error = entry.signal.aborted ? "Benchmark interrupted or timed out" : `Collector/provider request failed (${error.name})`;
|
|
91
|
+
res.writeHead(502); res.end("{}");
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
server.on("connection", socket => { sockets.add(socket); socket.on("close", () => sockets.delete(socket)); });
|
|
95
|
+
const ws = new WebSocketServer({ server, maxPayload: options.maxBodyBytes });
|
|
96
|
+
ws.on("connection", (socket, req) => {
|
|
97
|
+
socket.on("error", () => {});
|
|
98
|
+
socket.on("message", data => {
|
|
99
|
+
const entry = records.get(req.headers["x-request-id"]);
|
|
100
|
+
try {
|
|
101
|
+
const envelope = JSON.parse(data.toString());
|
|
102
|
+
if (entry) entry.body = envelope.response || envelope;
|
|
103
|
+
socket.send("{}");
|
|
104
|
+
} catch { socket.close(1007); }
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
server.listen(0, "127.0.0.1"); await once(server, "listening");
|
|
108
|
+
return { records, url: `http://127.0.0.1:${server.address().port}`,
|
|
109
|
+
async close() { for (const c of ws.clients) c.terminate(); for (const s of sockets) s.destroy(); await new Promise(done => ws.close(done)); await new Promise(done => server.close(done)); } };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function replay(proxy, fixture, transport, id, options) {
|
|
113
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]) : AbortSignal.timeout(options.timeoutMs);
|
|
114
|
+
if (transport === "http") {
|
|
115
|
+
const started = performance.now();
|
|
116
|
+
const response = await fetch(proxy.url + fixture.path, {
|
|
117
|
+
method: "POST", headers: { "content-type": "application/json", "x-request-id": id },
|
|
118
|
+
body: JSON.stringify(fixture.body), signal, redirect: "error",
|
|
119
|
+
});
|
|
120
|
+
await readLimited(response, options.maxBodyBytes);
|
|
121
|
+
if (!response.ok) throw new Error(`Proxy HTTP ${response.status}`);
|
|
122
|
+
return { durationMs: performance.now() - started, connectionMs: null };
|
|
123
|
+
}
|
|
124
|
+
const started = performance.now();
|
|
125
|
+
const socket = new WebSocket(proxy.url.replace("http:", "ws:") + fixture.path, { headers: { "x-request-id": id }, maxPayload: options.maxBodyBytes });
|
|
126
|
+
socket.on("error", () => {});
|
|
127
|
+
const abort = () => socket.terminate();
|
|
128
|
+
let abortReply;
|
|
129
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
130
|
+
try {
|
|
131
|
+
await once(socket, "open", { signal });
|
|
132
|
+
const connectionMs = performance.now() - started;
|
|
133
|
+
const sent = performance.now();
|
|
134
|
+
const reply = new Promise((resolve, reject) => {
|
|
135
|
+
socket.once("message", resolve);
|
|
136
|
+
socket.once("close", () => reject(new Error("WebSocket closed before reply")));
|
|
137
|
+
socket.once("error", reject);
|
|
138
|
+
abortReply = () => reject(new Error("WebSocket request timed out or interrupted"));
|
|
139
|
+
signal.addEventListener("abort", abortReply, { once: true });
|
|
140
|
+
});
|
|
141
|
+
socket.send(JSON.stringify({ type: "response.create", response: fixture.body }));
|
|
142
|
+
await reply;
|
|
143
|
+
return { durationMs: performance.now() - sent, connectionMs };
|
|
144
|
+
} finally { signal.removeEventListener("abort", abort); if (abortReply) signal.removeEventListener("abort", abortReply); socket.terminate(); }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function prepareBenchmark(inputOptions = {}) {
|
|
148
|
+
const options = normalizeBenchmarkOptions(inputOptions);
|
|
149
|
+
let fixtures = structuredClone(options.fixtures || builtInFixtures({ model: options.model, formats: options.formats, suite: options.suite }));
|
|
150
|
+
if (!fixtures.length) throw new Error("No fixtures for requested suite/formats; quality suite currently supports Responses only");
|
|
151
|
+
if (options.formats) fixtures = fixtures.filter(f => options.formats.includes(f.format));
|
|
152
|
+
if (options.model) for (const fixture of fixtures) fixture.body.model = options.model;
|
|
153
|
+
if (options.compareModels) fixtures = options.compareModels.flatMap(model => fixtures.map(fixture => ({
|
|
154
|
+
...structuredClone(fixture), id: `${fixture.id}@${model}`, body: { ...structuredClone(fixture.body), model },
|
|
155
|
+
})));
|
|
156
|
+
if (options.live) for (const { body, format } of fixtures) {
|
|
157
|
+
body.stream = format === "responses" && Boolean(options.responsesStream); delete body.stream_options;
|
|
158
|
+
if (format === "responses") { body.store = false; delete body.background; }
|
|
159
|
+
if (Array.isArray(body.tools) && body.tools.some(tool => format === "anthropic" ? tool.type && tool.type !== "custom" : tool.type !== "function")) {
|
|
160
|
+
throw new Error("Live fixtures support client function tools only, not provider-hosted tools");
|
|
161
|
+
}
|
|
162
|
+
if (format === "anthropic") body.max_tokens = options.maxOutputTokens;
|
|
163
|
+
else if (format === "chat") { delete body.max_tokens; body.max_completion_tokens = options.maxOutputTokens; body.n = 1; }
|
|
164
|
+
else body.max_output_tokens = options.maxOutputTokens;
|
|
165
|
+
}
|
|
166
|
+
validateFixtures(fixtures);
|
|
167
|
+
// A benchmark must exercise pxpipe instead of accidentally measuring its
|
|
168
|
+
// default model gate. This opt-in is isolated from production configuration.
|
|
169
|
+
options.models ||= [...new Set(fixtures.map(f => f.body.model))].join(",");
|
|
170
|
+
normalizePresetOptions({ ...options, preset: "none" });
|
|
171
|
+
for (const fixture of fixtures) if (Buffer.byteLength(JSON.stringify(fixture.body)) > options.maxBodyBytes) throw new Error(`Fixture ${fixture.id} exceeds maxBodyBytes`);
|
|
172
|
+
const cases = fixtures.flatMap(fixture => options.transports.filter(t => t === "http" || fixture.format === "responses").map(transport => ({ fixture, transport })));
|
|
173
|
+
if (!cases.length) throw new Error("No applicable cases (WS requires Responses fixtures)");
|
|
174
|
+
const planned = cases.length * options.presets.length * (options.repetitions + options.warmup);
|
|
175
|
+
if (options.live && planned > options.maxLiveCalls) throw new Error(`Live plan needs ${planned} calls, exceeding maxLiveCalls=${options.maxLiveCalls}; reduce the corpus/rounds or explicitly raise --max-live-calls`);
|
|
176
|
+
return { options, fixtures, cases };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function privateQuality(result) {
|
|
180
|
+
// Assertions can contain sensitive fixture excerpts: persist identifiers and
|
|
181
|
+
// hashes, not the expected literal text. Payloads require a separate opt-in.
|
|
182
|
+
return { ...result, checks: result.checks.map(({ expected, ...check }) => ({ ...check, ...(expected === undefined ? {} : { expectedHash: digest(expected) }) })) };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** All traffic traverses the real proxy, then a private loopback collector. No managed service/state is touched. */
|
|
186
|
+
export async function runBenchmark(inputOptions = {}) {
|
|
187
|
+
const { options, fixtures, cases } = prepareBenchmark(inputOptions);
|
|
188
|
+
const meta = {
|
|
189
|
+
schemaVersion: 1, startedAt: new Date().toISOString(), mode: options.live ? "live" : "offline",
|
|
190
|
+
presets: options.presets, repetitions: options.repetitions, warmup: options.warmup, seed: options.seed,
|
|
191
|
+
transports: options.transports, corpusHash: digest(fixtures), fixtureCount: fixtures.length,
|
|
192
|
+
fixtures: fixtures.map(f => ({ id: f.id, category: f.category, format: f.format, model: f.body.model, hash: digest(f),
|
|
193
|
+
reasoningEffort: f.body.reasoning?.effort || null, evaluationKind: f.evaluation?.kind || null })),
|
|
194
|
+
flowConfigs: Object.fromEntries(options.presets.map(p => [p, flowOptions(p)])),
|
|
195
|
+
plannedRecords: cases.length * options.presets.length * (options.repetitions + options.warmup),
|
|
196
|
+
versions: { node: process.version, platform: process.platform, arch: process.arch,
|
|
197
|
+
pxpipe: await packageVersion("pxpipe-proxy"), tokenizer: await packageVersion("gpt-tokenizer"),
|
|
198
|
+
rtk: options.presets.some(p => p.includes("rtk")) ? await version("rtk") : null,
|
|
199
|
+
headroomLocalCli: options.presets.some(p => p.includes("headroom")) ? await version("headroom") : null },
|
|
200
|
+
config: { suite: options.fixtures ? "custom" : options.suite || "core", rtkFilter: options.rtkFilter || "auto", models: options.models, compareModels: options.compareModels || null, headroomUrl: options.headroomUrl || "http://127.0.0.1:8787",
|
|
201
|
+
headroomMode: "lossy_inline", upstream: options.live ? options.upstream : null, responsesStream: Boolean(options.responsesStream), timeoutMs: options.timeoutMs, maxOutputTokens: options.live ? options.maxOutputTokens : null, maxLiveCalls: options.live ? options.maxLiveCalls : null },
|
|
202
|
+
notes: ["Local token estimates are not provider billing. Native stage counts are diagnostic only.",
|
|
203
|
+
"Offline preservation checks are not semantic answer-quality evidence. Image content is not OCR-validated.",
|
|
204
|
+
"Benchmark-only pxpipe allowlist defaults to all fixture models. This exercises imaging, but is not a model-support or quality guarantee.",
|
|
205
|
+
"Native-bypass flow aliases skip only pxpipe when images exist before compression; other stages remain active. Production defaults are unchanged.",
|
|
206
|
+
"Image integrity checks compare native attachment content/metadata, order, grouping and adjacent text; they do not evaluate visual understanding.",
|
|
207
|
+
"Image-required evidence means expected literals are absent from native text, not proof that an image contains legible evidence. Live evaluation is still required.",
|
|
208
|
+
"First request means first request through this benchmark instance, NOT a cold external service/cache.",
|
|
209
|
+
"HTTP durations include a local collector hop; WS message durations exclude connection setup (reported separately).",
|
|
210
|
+
"Live mode is a fixed single-answer evaluation, not a full agent task; no tool calls or retries are executed.",
|
|
211
|
+
"Provider cache state is uncontrolled; cache reads/writes are reported separately. Warmup live calls also consume tokens.",
|
|
212
|
+
"Aborted/failed provider calls can still incur usage that the provider does not return; measured usage is not a complete invoice.",
|
|
213
|
+
"Call limits count runner HTTP attempts. A gateway may internally retry, fall back, or ignore output caps; inspect its logs for billed attempts and effective settings.",
|
|
214
|
+
"headroomLocalCli is the installed CLI version, not proof of the remote compression service version/configuration."],
|
|
215
|
+
};
|
|
216
|
+
const records = [], states = new Map();
|
|
217
|
+
const sink = await collector(options);
|
|
218
|
+
try {
|
|
219
|
+
for (const preset of options.presets) {
|
|
220
|
+
const state = { attempts: 0 };
|
|
221
|
+
states.set(preset, state);
|
|
222
|
+
const start = performance.now();
|
|
223
|
+
try {
|
|
224
|
+
state.proxy = await startProxy({ upstream: sink.url, listen: "http://127.0.0.1:0", ...flowOptions(preset),
|
|
225
|
+
headroomUrl: options.headroomUrl, rtkFilter: options.rtkFilter, models: options.models,
|
|
226
|
+
maxBodyBytes: options.maxBodyBytes, onStats: event => sink.records.get(event.requestId)?.events.push(event) });
|
|
227
|
+
} catch (error) { state.error = `Preset setup failed (${error.name})`; }
|
|
228
|
+
state.startupMs = performance.now() - start;
|
|
229
|
+
}
|
|
230
|
+
const baselines = new Map();
|
|
231
|
+
for (const fixture of fixtures) baselines.set(fixture.id, await measureRequest(fixture.body));
|
|
232
|
+
const random = randomizer(options.seed);
|
|
233
|
+
let sequence = 0;
|
|
234
|
+
outer: for (let round = -options.warmup; round < options.repetitions; round++) {
|
|
235
|
+
for (const { fixture, transport } of shuffle(cases, random)) {
|
|
236
|
+
for (const preset of shuffle(options.presets, random)) {
|
|
237
|
+
if (options.signal?.aborted) break outer;
|
|
238
|
+
const state = states.get(preset), id = String(++sequence);
|
|
239
|
+
const controller = new AbortController();
|
|
240
|
+
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(options.timeoutMs), ...(options.signal ? [options.signal] : [])]);
|
|
241
|
+
const entry = { fixture, controller, signal, events: [] };
|
|
242
|
+
sink.records.set(id, entry);
|
|
243
|
+
const row = { sequence, caseId: fixture.id, category: fixture.category, format: fixture.format, model: fixture.body.model,
|
|
244
|
+
transport, preset, basePreset: flowOptions(preset).preset, nativeImagePolicy: flowOptions(preset).pxpipeNativeImages, round, phase: round < 0 ? "warmup" : "measured", firstRequest: state.attempts++ === 0,
|
|
245
|
+
status: "ok", before: baselines.get(fixture.id), after: null, stages: [], durationMs: null,
|
|
246
|
+
preservation: null, answerQuality: null, live: null };
|
|
247
|
+
const start = performance.now();
|
|
248
|
+
try {
|
|
249
|
+
if (state.error) throw new Error(state.error);
|
|
250
|
+
Object.assign(row, await replay(state.proxy, fixture, transport, id, { ...options, signal }));
|
|
251
|
+
if (entry.error) throw new Error(entry.error);
|
|
252
|
+
if (!entry.body) throw new Error("No request reached the benchmark collector");
|
|
253
|
+
row.after = await measureRequest(entry.body);
|
|
254
|
+
row.imageIntegrity = compareRequestImages(fixture.body, entry.body);
|
|
255
|
+
row.evidence = evaluateEvidence(entry.body, fixture.evaluation, row.imageIntegrity);
|
|
256
|
+
row.preservation = privateQuality(evaluatePreservation(fixture.body, entry.body, fixture.checks));
|
|
257
|
+
row.changed = digest(fixture.body) !== digest(entry.body);
|
|
258
|
+
row.outputHash = digest(entry.body);
|
|
259
|
+
if (options.live) {
|
|
260
|
+
const { text, ...live } = entry.live || {};
|
|
261
|
+
row.live = live;
|
|
262
|
+
if (live.error) throw new Error(live.error);
|
|
263
|
+
row.answerQuality = privateQuality(evaluateAnswer(text || "", fixture.answerChecks));
|
|
264
|
+
}
|
|
265
|
+
if (options.onPayload) await options.onPayload({ sequence, fixture, preset, transport, phase: row.phase, transformed: entry.body, answer: entry.live?.text });
|
|
266
|
+
} catch (error) {
|
|
267
|
+
row.status = "error";
|
|
268
|
+
// Only our bounded messages, never provider response bodies or full stacks.
|
|
269
|
+
row.error = error.message.startsWith("Proxy HTTP") || error.message.startsWith("Provider HTTP") ? error.message : `Benchmark request failed (${error.name})`;
|
|
270
|
+
row.durationMs ??= performance.now() - start;
|
|
271
|
+
} finally { controller.abort(); sink.records.delete(id); }
|
|
272
|
+
row.stages = entry.events.flatMap(event => event.stages || []);
|
|
273
|
+
records.push(row);
|
|
274
|
+
await options.onRecord?.(row);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
meta.interrupted = Boolean(options.signal?.aborted);
|
|
279
|
+
meta.completed = !meta.interrupted && records.length === meta.plannedRecords;
|
|
280
|
+
meta.startup = Object.fromEntries([...states].map(([preset, state]) => [preset, { durationMs: state.startupMs, error: state.error || null }]));
|
|
281
|
+
meta.finishedAt = new Date().toISOString();
|
|
282
|
+
return { meta, records };
|
|
283
|
+
} finally {
|
|
284
|
+
await Promise.allSettled([...states.values()].map(state => state.proxy?.close()));
|
|
285
|
+
await sink.close();
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { parseTOML, getStaticTOMLValue } from 'toml-eslint-parser';
|
|
6
|
+
|
|
7
|
+
const URL_KEYS = ['openai_base_url', 'experimental_realtime_ws_base_url'];
|
|
8
|
+
|
|
9
|
+
class ConfigWarning extends Error {}
|
|
10
|
+
|
|
11
|
+
function warning(message) {
|
|
12
|
+
throw new ConfigWarning(message);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function listenerUrl(value) {
|
|
16
|
+
let url;
|
|
17
|
+
try {
|
|
18
|
+
url = new URL(value);
|
|
19
|
+
} catch {
|
|
20
|
+
warning('Codex configuration skipped: the proxy listener URL is invalid.');
|
|
21
|
+
}
|
|
22
|
+
if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
|
|
23
|
+
|| url.username || url.password || url.port === '0' || url.pathname !== '/' || url.search || url.hash) {
|
|
24
|
+
warning('Codex configuration requires an HTTP loopback proxy listener origin with a nonzero port.');
|
|
25
|
+
}
|
|
26
|
+
return `${url.origin}/v1`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function parseConfig(source) {
|
|
30
|
+
try {
|
|
31
|
+
const ast = parseTOML(source, { tomlVersion: '1.0.0' });
|
|
32
|
+
return { ast, values: getStaticTOMLValue(ast) };
|
|
33
|
+
} catch {
|
|
34
|
+
// Parser errors can quote tokens containing credentials: never expose them.
|
|
35
|
+
warning('Codex config.toml is not valid supported TOML; it was left unchanged.');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function rewriteConfig(original, url) {
|
|
40
|
+
const bom = original.startsWith('\uFEFF') ? '\uFEFF' : '';
|
|
41
|
+
const source = original.slice(bom.length);
|
|
42
|
+
const { ast, values } = parseConfig(source);
|
|
43
|
+
const body = ast.body[0].body;
|
|
44
|
+
const edits = [];
|
|
45
|
+
const missing = [];
|
|
46
|
+
|
|
47
|
+
const profile = typeof values.profile === 'string' && values.profiles
|
|
48
|
+
&& Object.hasOwn(values.profiles, values.profile) ? values.profiles[values.profile] : null;
|
|
49
|
+
if (profile && URL_KEYS.some(key => Object.hasOwn(profile, key) && profile[key] !== url)) {
|
|
50
|
+
warning('The active Codex profile overrides proxy URL settings; config.toml was left unchanged. Update that profile explicitly.');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for (const key of URL_KEYS) {
|
|
54
|
+
if (!Object.hasOwn(values, key)) {
|
|
55
|
+
missing.push(key);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const node = body.find(entry => entry.type === 'TOMLKeyValue' && entry.key.keys.length === 1
|
|
59
|
+
&& (entry.key.keys[0].name ?? entry.key.keys[0].value) === key);
|
|
60
|
+
if (typeof values[key] !== 'string' || !node || node.value.kind !== 'string') {
|
|
61
|
+
warning(`Codex ${key} must be a root-level string; config.toml was left unchanged.`);
|
|
62
|
+
}
|
|
63
|
+
if (values[key] !== url) {
|
|
64
|
+
edits.push({ start: node.value.range[0], end: node.value.range[1], text: JSON.stringify(url) });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (missing.length) {
|
|
69
|
+
const firstNewline = source.indexOf('\n');
|
|
70
|
+
const newline = firstNewline > 0 && source[firstNewline - 1] === '\r' ? '\r\n' : '\n';
|
|
71
|
+
const table = body.find(entry => entry.type === 'TOMLTable');
|
|
72
|
+
// Insert at the table's line start, not inside its indentation or a string.
|
|
73
|
+
const at = table ? source.lastIndexOf('\n', table.range[0] - 1) + 1 : source.length;
|
|
74
|
+
const prefix = at > 0 && source[at - 1] !== '\n' ? newline : '';
|
|
75
|
+
const lines = missing.map(key => `${key} = ${JSON.stringify(url)}`).join(newline);
|
|
76
|
+
edits.push({ start: at, end: at, text: `${prefix}${lines}${newline}` });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let result = source;
|
|
80
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
|
81
|
+
result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
|
|
82
|
+
}
|
|
83
|
+
const verified = parseConfig(result).values;
|
|
84
|
+
if (URL_KEYS.some(key => verified[key] !== url)) {
|
|
85
|
+
warning('Could not safely set the root Codex proxy URLs; config.toml was left unchanged.');
|
|
86
|
+
}
|
|
87
|
+
return bom + result;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function statOrNull(file) {
|
|
91
|
+
try {
|
|
92
|
+
return fs.lstatSync(file);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error.code === 'ENOENT') return null;
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function sameStat(a, b) {
|
|
100
|
+
return a.dev === b.dev && a.ino === b.ino && a.size === b.size
|
|
101
|
+
&& a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function snapshot(file) {
|
|
105
|
+
const stat = statOrNull(file);
|
|
106
|
+
if (!stat) return null;
|
|
107
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink > 1) {
|
|
108
|
+
warning('Codex config.toml is a link or not a regular file; automatic configuration was skipped.');
|
|
109
|
+
}
|
|
110
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
111
|
+
try {
|
|
112
|
+
const before = fs.fstatSync(fd);
|
|
113
|
+
const bytes = fs.readFileSync(fd);
|
|
114
|
+
if (!sameStat(stat, before) || !sameStat(before, fs.fstatSync(fd))) {
|
|
115
|
+
warning('Codex config.toml changed concurrently; automatic configuration was skipped. Retry when the other writer is finished.');
|
|
116
|
+
}
|
|
117
|
+
const source = bytes.toString('utf8');
|
|
118
|
+
if (!Buffer.from(source, 'utf8').equals(bytes)) {
|
|
119
|
+
warning('Codex config.toml is not valid UTF-8; it was left unchanged.');
|
|
120
|
+
}
|
|
121
|
+
return { stat, bytes, source };
|
|
122
|
+
} finally {
|
|
123
|
+
fs.closeSync(fd);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function assertUnchanged(file, original) {
|
|
128
|
+
const current = snapshot(file);
|
|
129
|
+
if (Boolean(current) !== Boolean(original)
|
|
130
|
+
|| (current && (!sameStat(original.stat, current.stat) || !original.bytes.equals(current.bytes)))) {
|
|
131
|
+
warning('Codex config.toml changed concurrently; automatic configuration was skipped. Retry when the other writer is finished.');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function backupOriginal(file, bytes) {
|
|
136
|
+
let fd;
|
|
137
|
+
let complete = false;
|
|
138
|
+
try {
|
|
139
|
+
fd = fs.openSync(file, 'wx', 0o600);
|
|
140
|
+
fs.writeFileSync(fd, bytes);
|
|
141
|
+
fs.fsyncSync(fd);
|
|
142
|
+
complete = true;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (fd === undefined && error.code === 'EEXIST') {
|
|
145
|
+
const existing = statOrNull(file);
|
|
146
|
+
if (existing?.isFile() && !existing.isSymbolicLink()) return;
|
|
147
|
+
warning('The Codex backup path is not a regular file; automatic configuration was skipped.');
|
|
148
|
+
}
|
|
149
|
+
throw error;
|
|
150
|
+
} finally {
|
|
151
|
+
if (fd !== undefined) {
|
|
152
|
+
fs.closeSync(fd);
|
|
153
|
+
if (!complete) {
|
|
154
|
+
try { fs.unlinkSync(file); } catch { /* Keep the original config intact. */ }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Point only Codex's two root URL keys at a ready, local AIH proxy listener.
|
|
162
|
+
* Synchronous and nonthrowing. env/home injection keeps tests away from real configs.
|
|
163
|
+
* The caller owns proxy readiness; this function never changes provider/profile URLs.
|
|
164
|
+
*/
|
|
165
|
+
export function syncCodexProxyConfig(proxyUrl, options = {}) {
|
|
166
|
+
const env = options.env ?? process.env;
|
|
167
|
+
if (env.AIH_CODEX_AUTOCONFIG === '0') {
|
|
168
|
+
return { status: 'skipped', message: 'Automatic Codex proxy configuration is disabled (AIH_CODEX_AUTOCONFIG=0).' };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
let configPath;
|
|
172
|
+
let url;
|
|
173
|
+
let lockPath;
|
|
174
|
+
let lockFd;
|
|
175
|
+
let lockStat;
|
|
176
|
+
let tempPath;
|
|
177
|
+
try {
|
|
178
|
+
url = listenerUrl(proxyUrl);
|
|
179
|
+
const home = options.home ?? os.homedir();
|
|
180
|
+
const configDir = path.resolve(typeof env.CODEX_HOME === 'string' && env.CODEX_HOME.trim()
|
|
181
|
+
? env.CODEX_HOME : path.join(home, '.codex'));
|
|
182
|
+
configPath = path.join(configDir, 'config.toml');
|
|
183
|
+
const directory = statOrNull(configDir);
|
|
184
|
+
if (directory && (directory.isSymbolicLink() || !directory.isDirectory())) {
|
|
185
|
+
warning('The Codex configuration directory is a link or not a directory; automatic configuration was skipped.');
|
|
186
|
+
}
|
|
187
|
+
const original = snapshot(configPath);
|
|
188
|
+
const next = rewriteConfig(original?.source ?? '', url);
|
|
189
|
+
if (original?.source === next) return { status: 'unchanged', path: configPath, url };
|
|
190
|
+
|
|
191
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
192
|
+
lockPath = `${configPath}.aih.lock`;
|
|
193
|
+
try {
|
|
194
|
+
lockFd = fs.openSync(lockPath, 'wx', 0o600);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
if (error.code === 'EEXIST') {
|
|
197
|
+
warning('Codex configuration is locked by another AIH operation; it was left unchanged. Retry later.');
|
|
198
|
+
}
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
lockStat = fs.fstatSync(lockFd);
|
|
202
|
+
assertUnchanged(configPath, original);
|
|
203
|
+
|
|
204
|
+
tempPath = `${configPath}.aih-${process.pid}-${randomUUID()}.tmp`;
|
|
205
|
+
const tempFd = fs.openSync(tempPath, 'wx', 0o600);
|
|
206
|
+
try {
|
|
207
|
+
fs.writeFileSync(tempFd, next, 'utf8');
|
|
208
|
+
fs.fsyncSync(tempFd);
|
|
209
|
+
} finally {
|
|
210
|
+
fs.closeSync(tempFd);
|
|
211
|
+
}
|
|
212
|
+
const backupPath = original ? `${configPath}.aih.bak` : undefined;
|
|
213
|
+
if (original) backupOriginal(backupPath, original.bytes);
|
|
214
|
+
assertUnchanged(configPath, original);
|
|
215
|
+
if (original) {
|
|
216
|
+
fs.renameSync(tempPath, configPath);
|
|
217
|
+
tempPath = undefined;
|
|
218
|
+
} else {
|
|
219
|
+
// Unlike rename, an atomic link cannot overwrite a concurrently created file.
|
|
220
|
+
fs.linkSync(tempPath, configPath);
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
status: 'updated', path: configPath, url,
|
|
224
|
+
message: `Codex proxy URLs set to ${url} (config: ${configPath}${backupPath ? `; backup: ${backupPath}` : ''}).`,
|
|
225
|
+
...(backupPath ? { backupPath } : {}),
|
|
226
|
+
};
|
|
227
|
+
} catch (error) {
|
|
228
|
+
const code = typeof error.code === 'string' && /^[A-Z0-9_]+$/.test(error.code) ? ` (${error.code})` : '';
|
|
229
|
+
return {
|
|
230
|
+
status: 'warning',
|
|
231
|
+
message: error instanceof ConfigWarning ? error.message : `Could not safely update Codex config.toml${code}; automatic configuration was skipped.`,
|
|
232
|
+
...(configPath ? { path: configPath } : {}),
|
|
233
|
+
...(url ? { url } : {}),
|
|
234
|
+
};
|
|
235
|
+
} finally {
|
|
236
|
+
if (tempPath) {
|
|
237
|
+
try { fs.unlinkSync(tempPath); } catch { /* Best-effort cleanup; never remove config.toml. */ }
|
|
238
|
+
}
|
|
239
|
+
if (lockFd !== undefined) {
|
|
240
|
+
try { fs.closeSync(lockFd); } catch { /* Best-effort lock cleanup. */ }
|
|
241
|
+
try {
|
|
242
|
+
const current = statOrNull(lockPath);
|
|
243
|
+
if (current && lockStat && current.ino === lockStat.ino && current.dev === lockStat.dev) fs.unlinkSync(lockPath);
|
|
244
|
+
} catch { /* Never hide the update result with a cleanup error. */ }
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import { syncCodexProxyConfig } from "./codex-config.js";
|
|
4
|
+
import { isPidRunning, sleep } from "./utils/process.js";
|
|
5
|
+
|
|
6
|
+
function localListener(value) {
|
|
7
|
+
const url = new URL(value);
|
|
8
|
+
if (url.protocol !== "http:" || !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
|
|
9
|
+
|| url.port === "0" || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
10
|
+
throw new Error("Expected a bound HTTP loopback listener");
|
|
11
|
+
}
|
|
12
|
+
return url;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** TCP only: checking a reverse proxy must not generate an upstream AI request. */
|
|
16
|
+
export function probeProxyListener(value, timeoutMs = 1000) {
|
|
17
|
+
let url;
|
|
18
|
+
try { url = localListener(value); } catch { return Promise.resolve(false); }
|
|
19
|
+
return new Promise(resolve => {
|
|
20
|
+
const socket = net.createConnection({ host: url.hostname.replace(/^\[|\]$/g, ""), port: Number(url.port || 80) });
|
|
21
|
+
const finish = result => { socket.destroy(); resolve(result); };
|
|
22
|
+
socket.setTimeout(timeoutMs);
|
|
23
|
+
socket.once("connect", () => finish(true));
|
|
24
|
+
socket.once("error", () => finish(false));
|
|
25
|
+
socket.once("timeout", () => finish(false));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Bounded unauthenticated readiness probe, with no redirects or payload logging. */
|
|
30
|
+
function readOcxReadiness(url, timeoutMs) {
|
|
31
|
+
return new Promise(resolve => {
|
|
32
|
+
let settled = false;
|
|
33
|
+
const request = http.get(new URL("/readyz", url), response => {
|
|
34
|
+
const chunks = [];
|
|
35
|
+
let size = 0;
|
|
36
|
+
response.on("data", chunk => {
|
|
37
|
+
size += chunk.length;
|
|
38
|
+
if (size > 8192) finish(null);
|
|
39
|
+
else chunks.push(chunk);
|
|
40
|
+
});
|
|
41
|
+
response.once("error", () => finish(null));
|
|
42
|
+
response.once("end", () => {
|
|
43
|
+
try { finish({ ...JSON.parse(Buffer.concat(chunks).toString("utf8")), code: response.statusCode }); }
|
|
44
|
+
catch { finish({ code: response.statusCode }); }
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
const timer = setTimeout(() => finish(null), timeoutMs);
|
|
48
|
+
function finish(result) {
|
|
49
|
+
if (settled) return;
|
|
50
|
+
settled = true;
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
request.destroy();
|
|
53
|
+
resolve(result);
|
|
54
|
+
}
|
|
55
|
+
request.once("error", () => finish(null));
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** /healthz and a live PID are insufficient: ocx writes Codex config late in startup. */
|
|
60
|
+
export async function waitForOcxReady(value, { timeoutMs = 30000, intervalMs = 250 } = {}) {
|
|
61
|
+
let url;
|
|
62
|
+
try { url = localListener(value); } catch { return { ready: false, reason: "ocx has no valid loopback address" }; }
|
|
63
|
+
const deadline = Date.now() + timeoutMs;
|
|
64
|
+
do {
|
|
65
|
+
const result = await readOcxReadiness(url, Math.max(1, Math.min(1000, deadline - Date.now())));
|
|
66
|
+
if (result?.service === "opencodex" && result.status === "ready" && result.code === 200) return { ready: true };
|
|
67
|
+
if (result?.service === "opencodex" && result.status === "failed") return { ready: false, reason: "ocx startup configuration failed" };
|
|
68
|
+
if (result && (result.service !== "opencodex" || !["pending", "ready"].includes(result.status))) {
|
|
69
|
+
return { ready: false, reason: "ocx does not expose a recognized /readyz endpoint; update ocx before automatic configuration" };
|
|
70
|
+
}
|
|
71
|
+
if (Date.now() < deadline) await sleep(Math.min(intervalMs, deadline - Date.now()));
|
|
72
|
+
} while (Date.now() < deadline);
|
|
73
|
+
return { ready: false, reason: "timed out waiting for ocx to finish configuring Codex" };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function sameListener(left, right) {
|
|
77
|
+
try {
|
|
78
|
+
const a = localListener(left);
|
|
79
|
+
const b = localListener(right);
|
|
80
|
+
// All supported listen hosts are loopback aliases.
|
|
81
|
+
return (a.port || "80") === (b.port || "80");
|
|
82
|
+
} catch { return false; }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Only explicit start/restart actions call this; status/discovery never edits Codex. */
|
|
86
|
+
export async function configureCodexForProxy(state, {
|
|
87
|
+
waitForOcx = false,
|
|
88
|
+
env = process.env,
|
|
89
|
+
isRunning = isPidRunning,
|
|
90
|
+
probe = probeProxyListener,
|
|
91
|
+
waitReady = waitForOcxReady,
|
|
92
|
+
apply = syncCodexProxyConfig,
|
|
93
|
+
readState = () => state,
|
|
94
|
+
} = {}) {
|
|
95
|
+
if (env.AIH_CODEX_AUTOCONFIG === "0") return { status: "skipped" };
|
|
96
|
+
const proxy = state.services?.proxy;
|
|
97
|
+
if (!proxy?.proxyOptions || proxy.status !== "running" || !isRunning(proxy.pid)) return { status: "skipped" };
|
|
98
|
+
const warning = reason => ({ status: "warning", message: `Codex configuration unchanged: ${reason}. Retry 'aih start proxy' when ready.` });
|
|
99
|
+
try {
|
|
100
|
+
// This integration targets the standard /v1 API on a root upstream. Prefixes
|
|
101
|
+
// such as /v1 or /backend-api/codex need a different client base path.
|
|
102
|
+
if (new URL(proxy.proxyOptions.upstream).pathname !== "/") {
|
|
103
|
+
return { status: "warning", message: "Codex configuration unchanged: this proxy has an upstream path prefix. Configure Codex's base URLs manually to avoid duplicating the API path." };
|
|
104
|
+
}
|
|
105
|
+
if (!await probe(proxy.url)) return warning("the aih proxy listener is unavailable");
|
|
106
|
+
const ocx = state.services.ocx;
|
|
107
|
+
// When the proxy starts second, also wait for the known ocx upstream to finish its writes.
|
|
108
|
+
const ocxIsUpstream = ocx?.status === "running" && isRunning(ocx.pid)
|
|
109
|
+
&& sameListener(proxy.proxyOptions.upstream, ocx.url);
|
|
110
|
+
if (waitForOcx || ocxIsUpstream) {
|
|
111
|
+
if (ocx?.status !== "running" || !isRunning(ocx.pid)) return warning("ocx is no longer running");
|
|
112
|
+
const readiness = await waitReady(ocx.url);
|
|
113
|
+
if (!readiness.ready) return warning(readiness.reason);
|
|
114
|
+
}
|
|
115
|
+
// Do not write an obsolete port if another action stopped/restarted the proxy while waiting.
|
|
116
|
+
if (!await probe(proxy.url)) return warning("the aih proxy changed or stopped during configuration");
|
|
117
|
+
const latestState = readState();
|
|
118
|
+
const latest = latestState.services?.proxy;
|
|
119
|
+
if (latest?.status !== "running" || latest.pid !== proxy.pid || latest.url !== proxy.url || !isRunning(latest.pid)) {
|
|
120
|
+
return warning("the aih proxy changed or stopped during configuration");
|
|
121
|
+
}
|
|
122
|
+
if (waitForOcx || ocxIsUpstream) {
|
|
123
|
+
const latestOcx = latestState.services?.ocx;
|
|
124
|
+
if (latestOcx?.status !== "running" || latestOcx.pid !== ocx.pid || latestOcx.url !== ocx.url || !isRunning(latestOcx.pid)) {
|
|
125
|
+
return warning("ocx changed or stopped during configuration");
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return apply(latest.url, { env });
|
|
129
|
+
} catch {
|
|
130
|
+
return warning("automatic configuration could not be completed safely");
|
|
131
|
+
}
|
|
132
|
+
}
|