forgedock 1.63.0 → 1.65.0
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/bin/config-schema.mjs +3 -0
- package/bin/engine/outcome-codes.mjs +5 -0
- package/bin/engine-cli.mjs +88 -12
- package/bin/env/cli.mjs +18 -1
- package/bin/lean/basered.mjs +56 -11
- package/bin/lean/basered.test.mjs +58 -5
- package/bin/lean/batch-health.mjs +46 -4
- package/bin/lean/batch-health.test.mjs +55 -1
- package/bin/lean/batch.mjs +8 -1
- package/bin/lean/batch.test.mjs +71 -6
- package/bin/lean/ceiling.mjs +47 -3
- package/bin/lean/ceiling.test.mjs +32 -1
- package/bin/lean/clear-breaker.mjs +15 -0
- package/bin/lean/clear-breaker.test.mjs +100 -0
- package/bin/lean/conformance.e2e.test.mjs +32 -6
- package/bin/lean/conformance.mjs +57 -13
- package/bin/lean/conformance.test.mjs +93 -1
- package/bin/lean/execution.mjs +18 -8
- package/bin/lean/execution.test.mjs +44 -3
- package/bin/lean/issuewatch-reconcile.mjs +2 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
- package/bin/lean/issuewatch.mjs +3 -0
- package/bin/lean/lanecheck.test.mjs +13 -1
- package/bin/lean/lean.mjs +157 -28
- package/bin/lean/lean.test.mjs +289 -21
- package/bin/lean/live-execution.mjs +25 -0
- package/bin/lean/live-execution.test.mjs +35 -1
- package/bin/lean/merged-park.mjs +76 -0
- package/bin/lean/merged-park.test.mjs +64 -0
- package/bin/lean/mergetrain.mjs +357 -0
- package/bin/lean/mergetrain.test.mjs +348 -0
- package/bin/lean/mirror-bundle.mjs +84 -0
- package/bin/lean/orchestrate-envhold.test.mjs +62 -0
- package/bin/lean/orchestrate-stacking.test.mjs +23 -1
- package/bin/lean/orchestrate-train.test.mjs +130 -0
- package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
- package/bin/lean/orchestrate.mjs +170 -13
- package/bin/lean/prompts.mjs +4 -3
- package/bin/lean/release-review.mjs +8 -1
- package/bin/lean/release-review.test.mjs +42 -2
- package/bin/lean/release-status.test.mjs +53 -1
- package/bin/lean/release.mjs +6 -3
- package/bin/lean/render.mjs +6 -1
- package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
- package/bin/lean/sandbox-remote.mjs +43 -3
- package/bin/lean/sched.mjs +19 -2
- package/bin/lean/sched.test.mjs +33 -1
- package/bin/lean/schedd-health.mjs +2 -1
- package/bin/lean/schedd-health.test.mjs +7 -0
- package/bin/lean/schedd.mjs +58 -7
- package/bin/lean/schedd.test.mjs +78 -1
- package/bin/lean/stacking.mjs +45 -0
- package/bin/lean/stacking.test.mjs +25 -1
- package/bin/lean/statuscomment.mjs +14 -8
- package/bin/lean/statuscomment.test.mjs +18 -1
- package/bin/lean/validate-catalog.mjs +1 -1
- package/bin/lean/validate-catalog.test.mjs +3 -0
- package/bin/lean/worktree.mjs +8 -3
- package/bin/lean/worktree.test.mjs +18 -0
- package/bin/pool/agent.mjs +309 -33
- package/bin/pool/cache-sweep.mjs +4 -2
- package/bin/pool/cli.mjs +125 -6
- package/bin/pool/disk.mjs +43 -0
- package/bin/pool/docker.mjs +11 -0
- package/bin/pool/health.mjs +95 -0
- package/bin/pool/mirror-seed.mjs +103 -0
- package/bin/pool/router.mjs +301 -27
- package/bin/runner.mjs +3 -1
- package/bin/stats/chains.mjs +101 -0
- package/bin/stats/chains.test.mjs +53 -0
- package/bin/stats/efficiency.mjs +7 -6
- package/bin/stats/efficiency.test.mjs +48 -7
- package/bin/stats/index.mjs +11 -3
- package/bin/stats/stats.test.mjs +9 -0
- package/docs/CONFIG.md +8 -1
- package/docs/OUTCOME-CODES.md +4 -0
- package/package.json +1 -1
- package/pool/README.md +10 -0
- package/pool/image/Dockerfile +2 -1
- package/pool/image/entrypoint.sh +25 -6
- package/pool/image/mirror.sh +71 -0
- package/pool/install/install-agent-linux.sh +57 -5
- package/pool/install/install-agent-macos.sh +148 -0
- package/pool/install/install-agent.ps1 +11 -0
- package/pool/install/install-agent.sh +59 -7
- package/pool/install/uninstall-agent-linux.sh +75 -0
- package/pool/install/uninstall-agent-macos.sh +60 -0
- package/pool/install/uninstall-agent.ps1 +1 -0
- package/scripts/transition-label.sh +11 -0
package/bin/pool/router.mjs
CHANGED
|
@@ -93,12 +93,44 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
93
93
|
if (consume) { c.used = true; store.save(); }
|
|
94
94
|
return true;
|
|
95
95
|
}
|
|
96
|
-
function issueCode() {
|
|
96
|
+
function issueCode(account) {
|
|
97
97
|
const code = randomBytes(9).toString("base64url");
|
|
98
|
-
codes()[code] = { expires: now() + codeTtlMs, used: false };
|
|
98
|
+
codes()[code] = { expires: now() + codeTtlMs, used: false, ...(account ? { account } : {}) };
|
|
99
99
|
store.save();
|
|
100
100
|
return { code, expires_at: new Date(now() + codeTtlMs).toISOString() };
|
|
101
101
|
}
|
|
102
|
+
// #5886: device-code login. A box asks for a device+user code, the operator approves the user code (binding an account),
|
|
103
|
+
// the box polls /device/token and receives a single-use enroll code that stamps that account on its agent record.
|
|
104
|
+
const devices = () => (store.data.devices ??= {});
|
|
105
|
+
const ACCOUNT_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$/;
|
|
106
|
+
const deviceTtlMs = (cfg.device_ttl_s ?? 600) * 1000, deviceIntervalS = cfg.device_interval_s ?? 5;
|
|
107
|
+
let deviceBurst = { at: 0, n: 0 };
|
|
108
|
+
function deviceStart() {
|
|
109
|
+
if (now() - deviceBurst.at > 60000) deviceBurst = { at: now(), n: 0 };
|
|
110
|
+
if (++deviceBurst.n > (cfg.device_codes_per_min ?? 20) || Object.keys(devices()).length >= 200) return { status: 429, body: { error: "too many device codes" }, retryAfter: 60 };
|
|
111
|
+
const device_code = randomBytes(24).toString("base64url"), user_code = randomBytes(5).toString("hex").toUpperCase().replace(/^(.{4})/, "$1-");
|
|
112
|
+
devices()[device_code] = { user_code, expires: now() + deviceTtlMs, interval: deviceIntervalS, polled: 0 };
|
|
113
|
+
store.save();
|
|
114
|
+
return { status: 200, body: { device_code, user_code, interval: deviceIntervalS, expires_in: Math.floor(deviceTtlMs / 1000) } };
|
|
115
|
+
}
|
|
116
|
+
function deviceApprove(body) {
|
|
117
|
+
const code = String(body?.user_code ?? "").toUpperCase().trim(), account = String(body?.account ?? "default");
|
|
118
|
+
if (!ACCOUNT_RE.test(account)) return { status: 400, body: { error: "account must be 1-64 chars of [A-Za-z0-9._@-]" } };
|
|
119
|
+
const d = Object.values(devices()).find((x) => x.user_code === code && !x.account && x.expires > now());
|
|
120
|
+
if (!d) return { status: 404, body: { error: "unknown, expired or already approved user code" } };
|
|
121
|
+
d.account = account; store.save();
|
|
122
|
+
return { status: 200, body: { ok: true, account } };
|
|
123
|
+
}
|
|
124
|
+
function deviceToken(body) {
|
|
125
|
+
const d = own(devices(), body?.device_code);
|
|
126
|
+
if (!d || d.expires <= now()) { if (d) { delete devices()[body.device_code]; store.save(); } return { status: 400, body: { error: "expired_token" } }; }
|
|
127
|
+
if (d.polled && now() - d.polled < d.interval * 1000) { d.interval += 5; d.polled = now(); return { status: 400, body: { error: "slow_down", interval: d.interval } }; }
|
|
128
|
+
d.polled = now();
|
|
129
|
+
if (!d.account) return { status: 400, body: { error: "authorization_pending", interval: d.interval } };
|
|
130
|
+
delete devices()[body.device_code];
|
|
131
|
+
const { code } = issueCode(d.account);
|
|
132
|
+
return { status: 200, body: { enroll_code: code, account: d.account } };
|
|
133
|
+
}
|
|
102
134
|
/** The enrolled agent whose token the request carries, or null. */
|
|
103
135
|
function agentFor(req) {
|
|
104
136
|
const m = /^Bearer\s+(\S.*)$/i.exec(req.headers.authorization ?? "");
|
|
@@ -155,15 +187,68 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
155
187
|
log.info?.(`claude login limited: account=${n} agent=${agent} until=${new Date(until).toISOString()}`);
|
|
156
188
|
return { status: 200, body: { account: n, until: new Date(until).toISOString() } };
|
|
157
189
|
}
|
|
158
|
-
|
|
190
|
+
// #5882: outbound-only agents (no url) dial the router: GET /agent/poll long-polls for the next queued request (the poll is also
|
|
191
|
+
// the heartbeat) and POST /agent/reply/:rid answers it. In memory only: a router restart drops queued requests, like relayQ.
|
|
192
|
+
const pollSt = new Map(), pollReplies = new Map(); // agent -> {q, waiter, seen}; rid -> {agent, done}
|
|
193
|
+
const POLL_MAX_WAIT_S = 55, pollOfflineMs = (cfg.poll_offline_s ?? 60) * 1000;
|
|
194
|
+
const pollState = (name) => { let st = pollSt.get(name); if (!st) pollSt.set(name, st = { q: [], waiter: null, seen: 0 }); return st; };
|
|
195
|
+
const pollOnline = (name) => { const st = pollSt.get(name); return Boolean(st && (st.waiter || now() - st.seen <= pollOfflineMs)); };
|
|
196
|
+
function pollCall(a, method, path, body, timeoutMs = 15000) {
|
|
197
|
+
if (!pollOnline(a.name)) return Promise.reject(new Error("agent offline (no recent poll)"));
|
|
198
|
+
return new Promise((resolve, reject) => {
|
|
199
|
+
const st = pollState(a.name), rid = randomBytes(12).toString("hex");
|
|
200
|
+
const timer = setTimeout(() => { pollReplies.delete(rid); st.q = st.q.filter((x) => x.rid !== rid); reject(new Error("agent did not answer in time")); }, timeoutMs);
|
|
201
|
+
pollReplies.set(rid, { agent: a.name, done: (r) => { clearTimeout(timer); resolve(r); } });
|
|
202
|
+
st.q.push({ rid, method, path, ...(body !== undefined ? { body } : {}) });
|
|
203
|
+
st.waiter?.();
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
async function agentPoll(req, url) {
|
|
207
|
+
const name = agentFor(req), st = pollState(name);
|
|
208
|
+
const w = Number(url.searchParams.get("wait") ?? 25), waitS = Number.isFinite(w) ? Math.min(Math.max(w, 0), POLL_MAX_WAIT_S) : 25;
|
|
209
|
+
st.waiter?.(); // a newer poll from the same agent supersedes the older one
|
|
210
|
+
st.seen = now();
|
|
211
|
+
if (!st.q.length && waitS > 0) await new Promise((res) => {
|
|
212
|
+
let t = null;
|
|
213
|
+
const done = () => { clearTimeout(t); if (st.waiter === done) st.waiter = null; res(); };
|
|
214
|
+
t = setTimeout(done, waitS * 1000);
|
|
215
|
+
st.waiter = done;
|
|
216
|
+
});
|
|
217
|
+
st.seen = now();
|
|
218
|
+
const item = st.q.shift();
|
|
219
|
+
return item ? { status: 200, body: item } : { status: 204 };
|
|
220
|
+
}
|
|
221
|
+
function agentReply(req, { rid }, body) {
|
|
222
|
+
const r = pollReplies.get(rid);
|
|
223
|
+
if (!r || r.agent !== agentFor(req)) return { status: 404, body: { error: "unknown request" } };
|
|
224
|
+
pollReplies.delete(rid);
|
|
225
|
+
const status = Number.isInteger(body?.status) ? body.status : 502;
|
|
226
|
+
r.done({ status, ok: status >= 200 && status < 300, data: body?.data ?? null, retryAfter: body?.retry_after ?? null });
|
|
227
|
+
return { status: 200, body: { ok: true } };
|
|
228
|
+
}
|
|
229
|
+
const agentCall = (a, method, path, body, timeoutMs) => a.transport === "poll"
|
|
230
|
+
? pollCall(a, method, path, body, timeoutMs)
|
|
231
|
+
: call(a.url, method, path, { body, token: a.token, timeoutMs, fetchFn });
|
|
159
232
|
|
|
233
|
+
/** #5891: host drive figures per agent, plus a warning when the projected time until the drive is full is under disk_warn_hours (2). */
|
|
234
|
+
const diskWarned = new Map();
|
|
235
|
+
function diskReport(c) {
|
|
236
|
+
if (!Number.isFinite(c.host_disk_free_gb)) return {};
|
|
237
|
+
const out = { host_disk_free_gb: c.host_disk_free_gb, ...(Number.isFinite(c.host_disk_growth_gb_per_h) ? { host_disk_growth_gb_per_h: c.host_disk_growth_gb_per_h } : {}) };
|
|
238
|
+
const limit = cfg.disk_warn_hours ?? 2;
|
|
239
|
+
if (Number.isFinite(c.host_disk_full_in_h) && c.host_disk_full_in_h < limit) {
|
|
240
|
+
out.disk_warning = `host drive full in ~${c.host_disk_full_in_h} h at ${c.host_disk_growth_gb_per_h} GB/h (${c.host_disk_free_gb} GB free)`;
|
|
241
|
+
if (now() - (diskWarned.get(c.name) ?? -Infinity) > 600000) { diskWarned.set(c.name, now()); log.warn?.(`${c.name}: ${out.disk_warning}`); }
|
|
242
|
+
}
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
160
245
|
async function capacities() {
|
|
161
246
|
const out = [];
|
|
162
247
|
for (const [name, a] of Object.entries(agents())) {
|
|
163
248
|
try {
|
|
164
249
|
const r = await agentCall(a, "GET", "/capacity", undefined, 5000);
|
|
165
|
-
out.push(r.ok ? { name, ok: true, ...r.data } : { name, ok: false, error: `HTTP ${r.status}` });
|
|
166
|
-
} catch (e) { out.push({ name, ok: false, error: String(e.message ?? e) }); }
|
|
250
|
+
out.push(r.ok ? { name, ok: true, ...(a.transport ? { transport: a.transport } : {}), ...r.data } : { name, ok: false, error: `HTTP ${r.status}` });
|
|
251
|
+
} catch (e) { out.push({ name, ok: false, ...(a.transport ? { transport: a.transport } : {}), error: String(e.message ?? e) }); }
|
|
167
252
|
}
|
|
168
253
|
return out;
|
|
169
254
|
}
|
|
@@ -171,7 +256,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
171
256
|
/** Agent liveness for the scheduler (#4547): an agent is online when it answers and is not paused. */
|
|
172
257
|
async function status() {
|
|
173
258
|
const caps = await capacities();
|
|
174
|
-
const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused) }));
|
|
259
|
+
const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...diskReport(c) }));
|
|
175
260
|
return { online: agentsView.filter((a) => a.ok && !a.paused).length, total: agentsView.length, agents: agentsView };
|
|
176
261
|
}
|
|
177
262
|
|
|
@@ -195,6 +280,39 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
195
280
|
catch (e) { log.warn?.(`forge.yaml for ${spec.repo.slug} unreadable: ${e.message}`); return spec; }
|
|
196
281
|
}
|
|
197
282
|
|
|
283
|
+
// #5735: per-agent lane ceiling across all batches. A lane sandbox is one whose id starts with `fdrsbx-`; other tenants'
|
|
284
|
+
// sandboxes are never counted or refused. Ceiling: the agent state entry's `max_lanes` (`pool limit`), else router.json
|
|
285
|
+
// `agents.<name>.max_lanes`; no valid value = no ceiling. In-flight launches reserve their slot synchronously before the
|
|
286
|
+
// awaited agent call, so concurrent launches cannot overshoot.
|
|
287
|
+
const isLane = (id) => typeof id === "string" && id.startsWith("fdrsbx-");
|
|
288
|
+
const validCeiling = (v) => Number.isInteger(v) && v >= 0;
|
|
289
|
+
function ceilingOf(name) {
|
|
290
|
+
const st = own(agents(), name)?.max_lanes;
|
|
291
|
+
if (validCeiling(st)) return st;
|
|
292
|
+
const c = cfg.agents && Object.hasOwn(cfg.agents, name) ? cfg.agents[name]?.max_lanes : undefined;
|
|
293
|
+
return validCeiling(c) ? c : null;
|
|
294
|
+
}
|
|
295
|
+
const pending = new Map(); // agent -> Set of lane ids reserved by an in-flight launch or claim
|
|
296
|
+
const lanesOn = (name) => {
|
|
297
|
+
const ids = new Set(pending.get(name) ?? []);
|
|
298
|
+
for (const [id, s] of Object.entries(sbx())) if (s?.agent === name && isLane(id)) ids.add(id);
|
|
299
|
+
return ids.size;
|
|
300
|
+
};
|
|
301
|
+
const atCeiling = (name) => { const c = ceilingOf(name); return c !== null && lanesOn(name) >= c; };
|
|
302
|
+
const reserve = (name, id) => { if (!pending.has(name)) pending.set(name, new Set()); pending.get(name).add(id); };
|
|
303
|
+
const release = (name, id) => { const s = pending.get(name); s?.delete(id); if (s && !s.size) pending.delete(name); };
|
|
304
|
+
const laneView = (name) => ({ used: lanesOn(name), ceiling: ceilingOf(name) });
|
|
305
|
+
function setLimit(name, body) {
|
|
306
|
+
const a = own(agents(), name);
|
|
307
|
+
if (!a) return { status: 404, body: { error: "unknown agent" } };
|
|
308
|
+
const v = body?.max_lanes;
|
|
309
|
+
if (v !== null && !validCeiling(v)) return { status: 400, body: { error: "max_lanes must be a non-negative integer or null" } };
|
|
310
|
+
if (v === null) delete a.max_lanes; else a.max_lanes = v;
|
|
311
|
+
store.save();
|
|
312
|
+
log.info?.(`agent ${name} max_lanes ${v === null ? "none" : v}`);
|
|
313
|
+
return { status: 200, body: { name, max_lanes: v, lanes: laneView(name) } };
|
|
314
|
+
}
|
|
315
|
+
|
|
198
316
|
/** #5053: an agent's 401 reaches the dispatcher through this router; tag it so it is not mistaken for a router auth failure. */
|
|
199
317
|
const agentBody = (r, name) => (r.status === 401 ? { ...(r.data && typeof r.data === "object" ? r.data : {}), error: "unauthorized", hop: "agent", agent: name, reason: typeof r.data?.reason === "string" ? r.data.reason : "agent auth: router token rejected by agent" } : r.data ?? {});
|
|
200
318
|
// #5856: placement by priority. Agents that report no reservations/borrowable fields are flat (cpus_free), as before.
|
|
@@ -211,6 +329,31 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
211
329
|
return cpusFree >= size.cpus && memFree >= size.mem_gb;
|
|
212
330
|
};
|
|
213
331
|
const headroom = (c, spec) => (spec?.priority === "borrow" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : 0);
|
|
332
|
+
// #5949: the dispatcher seeds a repo mirror before launch. The agent that will own the sandbox is picked here (the placing agent
|
|
333
|
+
// when it is known, else the best-fitting one) and remembered, so launch() prefers it and the seeded mirror is the one the lane uses.
|
|
334
|
+
const seedPick = new Map(); // sandbox id -> {agent, at}
|
|
335
|
+
const SEED_CHUNK_B64_MAX = 768 * 1024;
|
|
336
|
+
async function seedAgent(id) {
|
|
337
|
+
const known = own(sbx(), id);
|
|
338
|
+
if (known && own(agents(), known.agent)) return known.agent;
|
|
339
|
+
const hit = seedPick.get(id);
|
|
340
|
+
if (hit && own(agents(), hit.agent) && now() - hit.at < 30 * 60000) return hit.agent;
|
|
341
|
+
for (const [k, v] of seedPick) if (now() - v.at >= 30 * 60000) seedPick.delete(k);
|
|
342
|
+
const fits = (await capacities()).filter((c) => c.ok && !c.paused && c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
|
|
343
|
+
if (!fits.length) return null;
|
|
344
|
+
seedPick.set(id, { agent: fits[0].name, at: now() });
|
|
345
|
+
return fits[0].name;
|
|
346
|
+
}
|
|
347
|
+
async function seedForward(id, method, path, body) {
|
|
348
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id)) return { status: 400, body: { error: "bad sandbox id" } };
|
|
349
|
+
if (typeof body?.data_b64 === "string" && body.data_b64.length > SEED_CHUNK_B64_MAX) return { status: 413, body: { error: "chunk too large" } };
|
|
350
|
+
const name = await seedAgent(id), a = name && own(agents(), name);
|
|
351
|
+
if (!a) return { status: 503, body: { error: "no agent available to seed" }, retryAfter: cfg.retry_after_s ?? 60 };
|
|
352
|
+
try { const r = await agentCall(a, method, path, body, 120000); return { status: r.status, body: agentBody(r, name) }; }
|
|
353
|
+
catch (e) { return { status: 502, body: { error: `agent ${name} unreachable: ${e.message}` } }; }
|
|
354
|
+
}
|
|
355
|
+
/** #5886: a spec naming an account is placed only on that account's agents; without one, any enrolled agent (as before). */
|
|
356
|
+
const inAccount = (c, spec) => typeof spec?.account !== "string" || own(agents(), c.name)?.account === spec.account;
|
|
214
357
|
async function launch(spec) {
|
|
215
358
|
if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id)) return { status: 400, body: { error: "spec.id required ([A-Za-z0-9._-], max 128)" } };
|
|
216
359
|
const known = own(sbx(), spec.id);
|
|
@@ -222,18 +365,28 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
222
365
|
delete sbx()[spec.id]; store.save();
|
|
223
366
|
}
|
|
224
367
|
const size = sizeFor(spec);
|
|
225
|
-
const sized = (await capacities()).filter((c) => c.ok && !c.paused && fitsPriority(c, spec, size));
|
|
368
|
+
const sized = (await capacities()).filter((c) => c.ok && !c.paused && inAccount(c, spec) && fitsPriority(c, spec, size));
|
|
226
369
|
const diskLow = sized.filter((c) => c.host_disk_low === true).map((c) => c.name); // #5733: never POST to a host whose drive is short
|
|
227
|
-
const
|
|
370
|
+
const capped = sized.filter((c) => c.disk_capped === true && c.host_disk_low !== true).map((c) => c.name); // #5884: lane disk at its hard cap
|
|
371
|
+
const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
|
|
372
|
+
const laneId = isLane(spec.id), laneCapped = []; // #5735: agents skipped because their lane ceiling is reached
|
|
228
373
|
let busy = null; // the last agent 503 (e.g. lane_tools image building): its body and Retry-After are passed back
|
|
374
|
+
const seeded = seedPick.get(spec.id)?.agent; // #5949: the agent holding this lane's seeded mirror goes first
|
|
375
|
+
if (seeded) fits.sort((a, b) => (b.name === seeded) - (a.name === seeded));
|
|
229
376
|
for (const c of fits) {
|
|
230
|
-
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
|
|
377
|
+
if (laneId && atCeiling(c.name)) { laneCapped.push({ name: c.name, ...laneView(c.name) }); continue; }
|
|
378
|
+
if (laneId) reserve(c.name, spec.id);
|
|
379
|
+
try {
|
|
380
|
+
const r = await agentCall(own(agents(), c.name), "POST", "/sandboxes", { spec: withForgeYaml(spec), ...size }, 120000);
|
|
381
|
+
if (r.status === 503) { busy = { r, name: c.name }; continue; } // raced with another launch, or still building; try the next host
|
|
382
|
+
if (r.ok) { sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() }; store.save(); }
|
|
383
|
+
return { status: r.status, body: { ...agentBody(r, c.name), agent: c.name } };
|
|
384
|
+
} finally { if (laneId) release(c.name, spec.id); }
|
|
234
385
|
}
|
|
386
|
+
if (laneCapped.length && !busy) return { status: 503, body: { error: "pool.host_lane_ceiling", code: "pool.host_lane_ceiling", agents: laneCapped }, retryAfter: cfg.retry_after_s ?? 60 };
|
|
235
387
|
if (busy) return { status: 503, body: { ...agentBody(busy.r, busy.name), agent: busy.name }, retryAfter: busy.r.retryAfter ?? cfg.retry_after_s ?? 60 };
|
|
236
388
|
if (diskLow.length) return { status: 503, body: { error: "no host has free disk", code: "pool.disk_low", agents: diskLow }, retryAfter: cfg.disk_low_retry_after_s ?? 300 }; // a capacity deferral, not a failure
|
|
389
|
+
if (capped.length) return { status: 503, body: { error: "no host has lane disk below its cap", code: "pool.disk_cap", agents: capped }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
|
|
237
390
|
return { status: 503, body: { error: "no host has a free reservation", lane: size }, retryAfter: cfg.retry_after_s ?? 60 };
|
|
238
391
|
}
|
|
239
392
|
|
|
@@ -242,12 +395,17 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
242
395
|
if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id)) return { status: 400, body: { error: "spec.id required ([A-Za-z0-9._-], max 128)" } };
|
|
243
396
|
if (own(sbx(), spec.id)) return launch(spec); // already placed: the same idempotent path
|
|
244
397
|
const size = sizeFor(spec);
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
398
|
+
const laneId = isLane(spec.id);
|
|
399
|
+
for (const c of (await capacities()).filter((x) => x.ok && !x.paused && inAccount(x, spec))) {
|
|
400
|
+
if (laneId && atCeiling(c.name)) continue; // #5735: the 404 makes the caller cold-launch, which gets the ceiling 503
|
|
401
|
+
if (laneId) reserve(c.name, spec.id);
|
|
402
|
+
try {
|
|
403
|
+
const r = await agentCall(own(agents(), c.name), "POST", "/warm/claim", { spec: withForgeYaml(spec), ...size }, 30000);
|
|
404
|
+
if (!r.ok) continue;
|
|
405
|
+
sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() };
|
|
406
|
+
store.save();
|
|
407
|
+
return { status: 200, body: { ...(r.data ?? {}), agent: c.name } };
|
|
408
|
+
} finally { if (laneId) release(c.name, spec.id); }
|
|
251
409
|
}
|
|
252
410
|
return { status: 404, body: { error: "no warm sandbox ready" } };
|
|
253
411
|
}
|
|
@@ -267,6 +425,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
267
425
|
/** Renew leases for sandboxes ForgeDock still polls; destroy the ones it abandoned. */
|
|
268
426
|
async function tick() {
|
|
269
427
|
for (const [k, c] of Object.entries(codes())) if (c.expires <= now()) delete codes()[k];
|
|
428
|
+
for (const [k, d] of Object.entries(devices())) if (d.expires <= now()) delete devices()[k];
|
|
429
|
+
for (const [name, a] of Object.entries(agents())) if (a.policy_pending) await pushPolicy(name); // #5886: re-push a policy the box missed
|
|
270
430
|
for (const [id, s] of Object.entries(sbx())) {
|
|
271
431
|
const a = own(agents(), s.agent);
|
|
272
432
|
if (!a) { delete sbx()[id]; continue; }
|
|
@@ -286,17 +446,52 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
286
446
|
function enroll(body) {
|
|
287
447
|
if (!enrollOk(body?.token)) return { status: 401, body: { error: "bad enrollment token", hop: "router", reason: "router auth: bad enrollment token" } };
|
|
288
448
|
const name = String(body.name ?? "").toLowerCase().replace(/[^a-z0-9-]/g, "");
|
|
289
|
-
|
|
290
|
-
|
|
449
|
+
// #5882: no url means an outbound-only agent that polls this router (no inbound port on its host).
|
|
450
|
+
let url = null;
|
|
451
|
+
if (body.url) { try { url = new URL(String(body.url)); } catch { return { status: 400, body: { error: "url must be a valid URL (or omitted for an outbound agent)" } }; } }
|
|
291
452
|
if (!name) return { status: 400, body: { error: "name required" } };
|
|
453
|
+
const account = own(codes(), body.token)?.account; // #5886: a device-login code carries its account
|
|
292
454
|
enrollOk(body.token, true);
|
|
293
455
|
const token = randomBytes(32).toString("hex");
|
|
294
|
-
agents()
|
|
456
|
+
const keep = own(agents(), name)?.max_lanes; // #5735: re-enrollment keeps a `pool limit` ceiling
|
|
457
|
+
const keepCfg = validCeiling(keep) ? { max_lanes: keep } : {};
|
|
458
|
+
agents()[name] = { ...(url ? { url: url.origin, token, enrolledAt: new Date(now()).toISOString(), ...keepCfg } : { name, transport: "poll", token, enrolledAt: new Date(now()).toISOString(), ...keepCfg }), ...(account ? { account } : {}) };
|
|
295
459
|
store.save();
|
|
296
|
-
log.info?.(`enrolled agent ${name} at ${url.origin}`);
|
|
460
|
+
log.info?.(`enrolled agent ${name} ${url ? `at ${url.origin}` : "(outbound poll)"}`);
|
|
297
461
|
return { status: 200, body: { name, agent_token: token } };
|
|
298
462
|
}
|
|
299
463
|
|
|
464
|
+
/** #5886: per-box policy, allowlisted keys only; pushed to the agent's /admin/policy (the agent keeps its owner pause). */
|
|
465
|
+
function validPolicy(b) {
|
|
466
|
+
if (!b || typeof b !== "object" || Array.isArray(b)) return "policy must be an object";
|
|
467
|
+
const bad = Object.keys(b).filter((k) => !["cpus", "mem_gb", "idle_only", "paused", "floors"].includes(k));
|
|
468
|
+
if (bad.length) return `unknown policy key: ${bad[0]}`;
|
|
469
|
+
const int = (v, hi) => Number.isInteger(v) && v >= 1 && v <= hi;
|
|
470
|
+
if ("cpus" in b && !int(b.cpus, 256)) return "cpus must be an integer 1-256";
|
|
471
|
+
if ("mem_gb" in b && !int(b.mem_gb, 1024)) return "mem_gb must be an integer 1-1024";
|
|
472
|
+
if (("idle_only" in b && typeof b.idle_only !== "boolean") || ("paused" in b && typeof b.paused !== "boolean")) return "idle_only and paused must be booleans";
|
|
473
|
+
if ("floors" in b && !(b.floors && typeof b.floors === "object" && Object.keys(b.floors).every((k) => k === "host_disk_gb" && Number.isFinite(b.floors[k]) && b.floors[k] >= 0))) return "floors accepts only host_disk_gb >= 0";
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
async function pushPolicy(name) {
|
|
477
|
+
const a = own(agents(), name);
|
|
478
|
+
try {
|
|
479
|
+
const r = await agentCall(a, "POST", "/admin/policy", a.policy);
|
|
480
|
+
if (r.ok) { delete a.policy_pending; store.save(); }
|
|
481
|
+
return r.ok;
|
|
482
|
+
} catch { return false; }
|
|
483
|
+
}
|
|
484
|
+
async function setPolicy(name, body) {
|
|
485
|
+
const a = own(agents(), name);
|
|
486
|
+
if (!a) return { status: 404, body: { error: "unknown agent" } };
|
|
487
|
+
const err = validPolicy(body);
|
|
488
|
+
if (err) return { status: 400, body: { error: err } };
|
|
489
|
+
a.policy = { ...(a.policy ?? {}), ...body, ...(body.floors ? { floors: { ...(a.policy?.floors ?? {}), ...body.floors } } : {}) };
|
|
490
|
+
a.policy_pending = true; store.save();
|
|
491
|
+
const pushed = await pushPolicy(name);
|
|
492
|
+
return { status: pushed ? 200 : 202, body: { ok: true, policy: a.policy, pushed } };
|
|
493
|
+
}
|
|
494
|
+
|
|
300
495
|
function bootstrapScript(token, url) {
|
|
301
496
|
const q = (s) => `'${String(s).replace(/'/g, "''")}'`;
|
|
302
497
|
const int = (k) => { const v = Number(url?.searchParams.get(k)); return Number.isInteger(v) && v > 0 ? v : 0; };
|
|
@@ -316,6 +511,73 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
316
511
|
].join("\r\n");
|
|
317
512
|
}
|
|
318
513
|
|
|
514
|
+
/**
|
|
515
|
+
* #5883: the POSIX sh one-command installer served at GET /install (no auth: it holds no secret, only this router's URL).
|
|
516
|
+
* The one-time code arrives as `--code` and is checked only by /bootstrap/bundle.tar.gz and consumed by /enroll.
|
|
517
|
+
*/
|
|
518
|
+
function installScript() {
|
|
519
|
+
const q = (s) => `'${String(s ?? "").replace(/'/g, "'\\''")}'`;
|
|
520
|
+
return `#!/bin/sh
|
|
521
|
+
# computeshare agent one-command installer for Linux (systemd) and macOS (launchd), served by the router (#5883).
|
|
522
|
+
# Install: curl -fsSL ${q(`${cfg.public_url}/install`)} | sudo sh -s -- --code CODE [--name N] [--cpus N] [--mem GB]
|
|
523
|
+
# Uninstall: curl -fsSL ${q(`${cfg.public_url}/install`)} | sudo sh -s -- --uninstall
|
|
524
|
+
# Rerunning is safe: an enrolled host reuses its installed code and agent token (no download, no re-enrollment).
|
|
525
|
+
set -eu
|
|
526
|
+
ROUTER=${q(cfg.public_url)}
|
|
527
|
+
CODE=""; NAME=""; CPUS=""; MEM=""; UNINSTALL=0; DRY=0
|
|
528
|
+
while [ $# -gt 0 ]; do
|
|
529
|
+
case "$1" in
|
|
530
|
+
--code) CODE="\${2:?--code needs a value}"; shift 2 ;;
|
|
531
|
+
--name) NAME="\${2:?--name needs a value}"; shift 2 ;;
|
|
532
|
+
--cpus) CPUS="\${2:?--cpus needs a value}"; shift 2 ;;
|
|
533
|
+
--mem) MEM="\${2:?--mem needs a value}"; shift 2 ;;
|
|
534
|
+
--uninstall) UNINSTALL=1; shift ;;
|
|
535
|
+
--dry-run) DRY=1; shift ;;
|
|
536
|
+
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
|
537
|
+
esac
|
|
538
|
+
done
|
|
539
|
+
case "$(uname -s)" in
|
|
540
|
+
Linux) OS=linux; ROOT=/opt/computeshare; TOKEN_FILE=/etc/computeshare/agent.token ;;
|
|
541
|
+
Darwin) OS=macos; ROOT=/usr/local/computeshare; TOKEN_FILE=/usr/local/etc/computeshare/agent.token ;;
|
|
542
|
+
*) echo "unsupported OS $(uname -s): Linux or macOS only (Windows: forgedock pool enroll prints a PowerShell command)" >&2; exit 1 ;;
|
|
543
|
+
esac
|
|
544
|
+
if [ "$UNINSTALL" = 1 ]; then ACTION=uninstall; elif [ -s "$TOKEN_FILE" ] && [ -f "$ROOT/pool/install/install-agent-$OS.sh" ]; then ACTION=reinstall; else ACTION=install; fi
|
|
545
|
+
if [ "$DRY" = 1 ]; then
|
|
546
|
+
echo "os=$OS action=$ACTION router=$ROUTER root=$ROOT name=\${NAME:-<hostname>} cpus=\${CPUS:-<auto>} mem_gb=\${MEM:-<auto>} code=\${CODE:+<redacted>}"
|
|
547
|
+
exit 0
|
|
548
|
+
fi
|
|
549
|
+
[ "$(id -u)" = 0 ] || { echo "run as root: curl -fsSL '$ROUTER/install' | sudo sh -s -- ..." >&2; exit 1; }
|
|
550
|
+
command -v bash >/dev/null 2>&1 && command -v curl >/dev/null 2>&1 && command -v tar >/dev/null 2>&1 || { echo "needs bash, curl and tar" >&2; exit 1; }
|
|
551
|
+
TMP=""
|
|
552
|
+
cleanup() { [ -z "$TMP" ] || rm -rf "$TMP"; }
|
|
553
|
+
trap cleanup EXIT
|
|
554
|
+
fetch_bundle() {
|
|
555
|
+
TMP="$(mktemp -d "\${TMPDIR:-/tmp}/computeshare-install.XXXXXX")"
|
|
556
|
+
curl -fsS "$ROUTER/bootstrap/bundle.tar.gz?token=$CODE" -o "$TMP/bundle.tar.gz" || { echo "bundle download refused: the code is wrong, used or expired (forgedock pool enroll --outbound prints a new one)" >&2; exit 1; }
|
|
557
|
+
tar -xzf "$TMP/bundle.tar.gz" -C "$TMP"
|
|
558
|
+
}
|
|
559
|
+
if [ "$ACTION" = uninstall ]; then
|
|
560
|
+
if [ -f "$ROOT/pool/install/uninstall-agent-$OS.sh" ]; then bash "$ROOT/pool/install/uninstall-agent-$OS.sh"; exit $?; fi
|
|
561
|
+
if [ -z "$CODE" ]; then echo "[computeshare] $ROOT is not installed here; nothing to uninstall (pass --code to run the full cleanup from a fresh bundle)"; exit 0; fi
|
|
562
|
+
fetch_bundle
|
|
563
|
+
bash "$TMP/pool/install/uninstall-agent-$OS.sh"
|
|
564
|
+
exit $?
|
|
565
|
+
fi
|
|
566
|
+
set -- --router "$ROUTER" --outbound
|
|
567
|
+
if [ -n "$NAME" ]; then set -- "$@" --name "$NAME"; fi
|
|
568
|
+
if [ -n "$CPUS" ]; then set -- "$@" --cpus "$CPUS"; fi
|
|
569
|
+
if [ -n "$MEM" ]; then set -- "$@" --mem "$MEM"; fi
|
|
570
|
+
if [ "$ACTION" = reinstall ]; then
|
|
571
|
+
echo "[computeshare] already enrolled: reusing $ROOT and its agent token (no bundle download, no re-enrollment)"
|
|
572
|
+
bash "$ROOT/pool/install/install-agent-$OS.sh" "$@" --token "\${CODE:-enrolled}"
|
|
573
|
+
exit $?
|
|
574
|
+
fi
|
|
575
|
+
[ -n "$CODE" ] || { echo "--code CODE required (forgedock pool enroll --outbound prints the command)" >&2; exit 2; }
|
|
576
|
+
fetch_bundle
|
|
577
|
+
bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TMP/bundle.tar.gz"
|
|
578
|
+
`;
|
|
579
|
+
}
|
|
580
|
+
|
|
319
581
|
/** Stream an allow-listed image (docker save) to an agent whose daemon cannot reach the registry itself. */
|
|
320
582
|
async function sendImage(res, ref) {
|
|
321
583
|
const allowed = cfg.agent_images ?? ["docker:27.5.1-dind"];
|
|
@@ -340,6 +602,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
340
602
|
[route("GET", "/health"), { fn: async () => ({ status: 200, body: { ok: true, agents: Object.keys(agents()).length, sandboxes: Object.keys(sbx()).length } }), auth: "none" }],
|
|
341
603
|
[route("POST", "/sandboxes"), fd(async (_p, body) => launch(body))],
|
|
342
604
|
[route("POST", "/sandboxes/claim"), fd(async (_p, body) => claim(body))],
|
|
605
|
+
[route("GET", "/sandboxes/:id/mirrors"), fd(async ({ id }, _b, url) => seedForward(id, "GET", `/mirrors?${new URLSearchParams([...url.searchParams].filter(([k]) => ["slug", "cache_key", "upload"].includes(k)))}`))], // #5949
|
|
606
|
+
[route("POST", "/sandboxes/:id/seed"), fd(async ({ id }, body) => seedForward(id, "POST", "/mirrors/seed", body))],
|
|
343
607
|
[route("GET", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}`))],
|
|
344
608
|
[route("GET", "/sandboxes/:id/logs"), fd(async ({ id }, _b, url) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/logs?cursor=${encodeURIComponent(url.searchParams.get("cursor") ?? "0")}`))],
|
|
345
609
|
[route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/result`))],
|
|
@@ -352,17 +616,25 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
352
616
|
[route("POST", "/sandboxes/:id/stop"), fd(async ({ id }) => forward(id, "POST", `/sandboxes/${encodeURIComponent(id)}/stop`))], // #5274
|
|
353
617
|
[route("DELETE", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "DELETE", `/sandboxes/${encodeURIComponent(id)}`, DESTROY_TIMEOUT_MS))],
|
|
354
618
|
[route("GET", "/status"), fd(async () => ({ status: 200, body: await status() }))],
|
|
355
|
-
[route("GET", "/agents"), fd(async () => { // #5535: each sandbox carries disk_used_mb from its agent's sandbox_disk_mb when the agent reports it
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
|
|
619
|
+
[route("GET", "/agents"), fd(async (_p, _b, url) => { // #5535: each sandbox carries disk_used_mb from its agent's sandbox_disk_mb when the agent reports it
|
|
620
|
+
const acct = url.searchParams.get("account"); // #5886: ?account= is the per-account view; `account` and `policy` ride on enrolled records that have them
|
|
621
|
+
const caps = (await capacities()).filter((c) => acct === null || own(agents(), c.name)?.account === acct).map((c) => { const a = own(agents(), c.name); return { ...c, ...(a?.account ? { account: a.account } : {}), ...(a?.policy ? { policy: a.policy } : {}) }; }), byName = new Map(caps.map((c) => [c.name, c])), out = {};
|
|
622
|
+
for (const [id, s] of Object.entries(sbx())) { if (acct !== null && !byName.has(s?.agent)) continue; const mb = byName.get(s?.agent)?.sandbox_disk_mb?.[id]; out[id] = Number.isFinite(mb) ? { ...s, disk_used_mb: mb } : s; }
|
|
623
|
+
const remote_lanes = Object.keys(sbx()).filter(isLane).length; // #5735: lane sandboxes across all batches and agents
|
|
624
|
+
return { status: 200, body: { agents: caps.map((c) => ({ ...c, lanes: laneView(c.name), ...diskReport(c) })), sandboxes: out, remote_lanes } };
|
|
359
625
|
})],
|
|
626
|
+
[route("POST", "/device/code"), { fn: async () => deviceStart(), auth: "none" }], // #5886
|
|
627
|
+
[route("POST", "/device/token"), { fn: async (_p, body) => deviceToken(body), auth: "none" }],
|
|
628
|
+
[route("POST", "/device/approve"), fd(async (_p, body) => deviceApprove(body))],
|
|
629
|
+
[route("PUT", "/agents/:name/policy"), fd(async ({ name }, body) => setPolicy(name, body))],
|
|
360
630
|
[route("POST", "/codes"), fd(async () => ({ status: 200, body: issueCode() }))],
|
|
361
631
|
[route("GET", "/agent/creds/github"), { fn: async () => ({ status: 200, body: { token: await githubToken() } }), auth: "agent" }],
|
|
362
632
|
[route("GET", "/agent/creds/claude"), { fn: async (_p, _b, _u, req) => claudeToken(req), auth: "agent" }],
|
|
363
633
|
[route("POST", "/agent/creds/claude/limited"), { fn: async (_p, body, _u, req) => claudeLimited(req, body), auth: "agent" }], // #5205
|
|
364
634
|
[route("POST", "/agent/relay/:id"), { fn: async (p, body, _u, req) => relayPost(req, p, body), auth: "agent" }], // #4778
|
|
365
635
|
[route("GET", "/agent/relay/:id/:rid"), { fn: async (p, _b, _u, req) => relayPoll(req, p), auth: "agent" }],
|
|
636
|
+
[route("GET", "/agent/poll"), { fn: async (_p, _b, url, req) => agentPoll(req, url), auth: "agent" }], // #5882
|
|
637
|
+
[route("POST", "/agent/reply/:rid"), { fn: async (p, body, _u, req) => agentReply(req, p, body), auth: "agent" }],
|
|
366
638
|
[route("GET", "/agent/bundle"), { fn: async () => ({ bundle: true }), auth: "agent" }],
|
|
367
639
|
[route("GET", "/agent/images/:ref"), { fn: async ({ ref }) => ({ image: ref }), auth: "agent" }],
|
|
368
640
|
[route("POST", "/agents/:name/upgrade"), fd(async ({ name }) => {
|
|
@@ -383,6 +655,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
383
655
|
const r = await agentCall(a, "POST", "/admin/resize", body ?? {});
|
|
384
656
|
return { status: r.status, body: r.data };
|
|
385
657
|
})],
|
|
658
|
+
[route("POST", "/agents/:name/limit"), fd(async ({ name }, body) => setLimit(name, body))], // #5735
|
|
386
659
|
[route("GET", "/agents/:name/usage"), fd(async ({ name }) => {
|
|
387
660
|
const a = own(agents(), name);
|
|
388
661
|
if (!a) return { status: 404, body: { error: "unknown agent" } };
|
|
@@ -396,6 +669,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
396
669
|
return c.q ? { status: 200, body: await ciEvents.wait(c.q, c.since, c.waitS) } : c;
|
|
397
670
|
})],
|
|
398
671
|
[route("POST", "/enroll"), { fn: async (_p, body) => enroll(body), auth: "none" }],
|
|
672
|
+
[route("GET", "/install"), { fn: async () => ({ status: 200, body: installScript() }), auth: "none" }], // #5883: script text only, the code comes as --code
|
|
399
673
|
[route("GET", "/bootstrap/install.ps1"), { fn: async (_p, _b, url) => ({ status: 200, body: bootstrapScript(url.searchParams.get("token"), url) }), auth: "enroll" }],
|
|
400
674
|
[route("GET", "/bootstrap/bundle.tar.gz"), { fn: async () => ({ bundle: true }), auth: "enroll" }],
|
|
401
675
|
];
|
|
@@ -418,7 +692,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
418
692
|
if (r.auth === "ci" && !ciOk(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
|
|
419
693
|
if (r.auth === "agent" && !agentFor(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
|
|
420
694
|
if (r.auth === "enroll" && !enrollOk(url.searchParams.get("token"))) return send(res, 401, "unauthorized\n");
|
|
421
|
-
const body = req.method === "POST" ? await readJson(req) : null;
|
|
695
|
+
const body = req.method === "POST" || req.method === "PUT" ? await readJson(req) : null;
|
|
422
696
|
if (typeof body?.repo?.slug === "string") meta.repo = body.repo.slug.slice(0, 200);
|
|
423
697
|
if (typeof body?.id === "string") meta.id = body.id;
|
|
424
698
|
const out = await r.fn(p, body, url, req);
|
package/bin/runner.mjs
CHANGED
|
@@ -2150,6 +2150,7 @@ export async function runCliBackendAsync(opts) {
|
|
|
2150
2150
|
let limitInfo = null;
|
|
2151
2151
|
const ceiling = maxMs > 0 ? maxMs : o.timeout;
|
|
2152
2152
|
let collected, idleInfo = null, ctxInfo = null, turnInfo = null;
|
|
2153
|
+
let streamSessionId = null;
|
|
2153
2154
|
const msgUsage = new Map(); // #4390: assistant message id -> its usage (a message spans several stream lines)
|
|
2154
2155
|
const toolUses = new Map(); // #4410: tool_use id -> {msg, name, path, cmd}
|
|
2155
2156
|
const sum = (k) => [...msgUsage.values()].reduce((a, u) => a + toFiniteUsageNumber(u[k]), 0);
|
|
@@ -2214,6 +2215,7 @@ export async function runCliBackendAsync(opts) {
|
|
|
2214
2215
|
const noteLine = (line) => {
|
|
2215
2216
|
if (!line.startsWith("{") || line.length > 4_000_000) return;
|
|
2216
2217
|
let j; try { j = JSON.parse(line); } catch { return; }
|
|
2218
|
+
if (typeof j?.session_id === "string" && j.session_id) streamSessionId = j.session_id; // #5829: a context stop names the session so it can be compacted
|
|
2217
2219
|
if (j?.type === "result") resultLine = line;
|
|
2218
2220
|
else if (j?.type === "user" && Array.isArray(j.message?.content)) {
|
|
2219
2221
|
// #5346: a tool_result closes its edit; a ceiling crossed mid-edit stops the session at this safe point
|
|
@@ -2271,7 +2273,7 @@ export async function runCliBackendAsync(opts) {
|
|
|
2271
2273
|
}
|
|
2272
2274
|
if (ctxInfo) {
|
|
2273
2275
|
const err = new Error(`claude CLI session reached ${ctxInfo.context} context tokens (ceiling ${contextMax}) after ${msgUsage.size} turn(s) and was stopped`);
|
|
2274
|
-
err.code = "CLI_CONTEXT"; err.context = ctxInfo.context; err.contextMax = contextMax; err.turns = msgUsage.size; err.lastTool = ctxInfo.lastTool;
|
|
2276
|
+
err.code = "CLI_CONTEXT"; err.sessionId = streamSessionId; err.context = ctxInfo.context; err.contextMax = contextMax; err.turns = msgUsage.size; err.lastTool = ctxInfo.lastTool;
|
|
2275
2277
|
err.usage = streamUsage(); err.toolUses = [...toolUses.values()];
|
|
2276
2278
|
throw err;
|
|
2277
2279
|
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5834: stacked-lane chain metrics for `forgedock stats --chains`, from the repo's local batch report.json rows (`deps`,
|
|
5
|
+
* `admitted_at`, `ended_at`, `plan_minutes`, `stacked`, `cascade*`). No network, no model. A chain is a connected set of
|
|
6
|
+
* in-batch dependency edges; depth is its longest path in issues; wall time runs from the first admission to the last end.
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { listBatches } from "../lean/batch.mjs";
|
|
11
|
+
import { sameRepo, windowLabel } from "./efficiency.mjs";
|
|
12
|
+
|
|
13
|
+
const readJson = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
|
|
14
|
+
const round1 = (x) => Math.round(x * 10) / 10;
|
|
15
|
+
const MIN = 60000;
|
|
16
|
+
const p50 = (xs) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b), m = s.length >> 1; return round1(s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2); };
|
|
17
|
+
|
|
18
|
+
const byDepth = (chains) => {
|
|
19
|
+
const depths = {};
|
|
20
|
+
for (const c of chains) (depths[c.depth] ??= []).push(c.wall_min);
|
|
21
|
+
return Object.fromEntries(Object.entries(depths).map(([d, w]) => [d, { chains: w.length, wall_p50_min: p50(w) }]));
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Cascade rework over the stacked dependents among `rows`: share that cascaded, cascades each, and rework minutes and cost. */
|
|
25
|
+
export function cascadeMetrics(rows) {
|
|
26
|
+
const stacked = (rows ?? []).filter((r) => r?.stacked);
|
|
27
|
+
const cascaded = stacked.filter((r) => r.cascade);
|
|
28
|
+
const count = cascaded.reduce((s, r) => s + (Array.isArray(r.cascades) ? r.cascades.length : 1), 0);
|
|
29
|
+
return {
|
|
30
|
+
stacked: stacked.length, cascaded: cascaded.length, cascades: count,
|
|
31
|
+
rework_rate: stacked.length ? Math.round((cascaded.length / stacked.length) * 1000) / 1000 : null,
|
|
32
|
+
per_stacked: stacked.length ? Math.round((count / stacked.length) * 100) / 100 : null,
|
|
33
|
+
cost_usd: Math.round(cascaded.reduce((s, r) => s + (Number(r.cascade_cost_usd) || 0), 0) * 1e6) / 1e6,
|
|
34
|
+
minutes: round1(cascaded.reduce((s, r) => s + (Number(r.cascade_minutes) || 0), 0)),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Chains, per-depth wall p50 and cascade rework from final rows (latest row per issue). Rows without timestamps are skipped. */
|
|
39
|
+
export function chainMetrics(rows) {
|
|
40
|
+
const by = new Map();
|
|
41
|
+
for (const r of rows ?? []) if (Number.isSafeInteger(r?.issue) && Number.isFinite(r.admitted_at) && Number.isFinite(r.ended_at)) by.set(r.issue, r);
|
|
42
|
+
const edges = (n) => (by.get(n)?.deps ?? []).filter((d) => by.has(d) && d !== n);
|
|
43
|
+
const parent = new Map([...by.keys()].map((n) => [n, n]));
|
|
44
|
+
const find = (n) => { while (parent.get(n) !== n) { parent.set(n, parent.get(parent.get(n))); n = parent.get(n); } return n; };
|
|
45
|
+
for (const n of by.keys()) for (const d of edges(n)) parent.set(find(n), find(d));
|
|
46
|
+
const groups = new Map();
|
|
47
|
+
for (const n of by.keys()) { const g = find(n); (groups.get(g) ?? groups.set(g, []).get(g)).push(n); }
|
|
48
|
+
const depthMemo = new Map();
|
|
49
|
+
const depthOf = (n, seen = new Set()) => {
|
|
50
|
+
if (depthMemo.has(n)) return depthMemo.get(n);
|
|
51
|
+
if (seen.has(n)) return 1; // a cycle cannot extend a chain
|
|
52
|
+
seen.add(n);
|
|
53
|
+
const d = 1 + Math.max(0, ...edges(n).map((e) => depthOf(e, seen)));
|
|
54
|
+
seen.delete(n); depthMemo.set(n, d); return d;
|
|
55
|
+
};
|
|
56
|
+
const chains = [];
|
|
57
|
+
for (const members of groups.values()) {
|
|
58
|
+
if (members.length < 2) continue;
|
|
59
|
+
members.sort((a, b) => a - b);
|
|
60
|
+
const start = Math.min(...members.map((n) => by.get(n).admitted_at)), end = Math.max(...members.map((n) => by.get(n).ended_at));
|
|
61
|
+
const links = [];
|
|
62
|
+
for (const n of members) for (const d of edges(n)) {
|
|
63
|
+
const a = by.get(n), p = by.get(d);
|
|
64
|
+
links.push({ issue: n, dependency: d, overlap_min: round1(Math.max(0, Math.min(a.ended_at, p.ended_at) - a.admitted_at) / MIN) });
|
|
65
|
+
}
|
|
66
|
+
chains.push({ issues: members, depth: Math.max(...members.map((n) => depthOf(n))), wall_min: round1((end - start) / MIN), links });
|
|
67
|
+
}
|
|
68
|
+
return { chains, by_depth: byDepth(chains), cascade: cascadeMetrics(rows) };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Per window: the repo's batches created in it; an issue in several batches counts once (latest row). */
|
|
72
|
+
export function chainsReport({ batchRoot, repo = null, windows, now = Date.now() }) {
|
|
73
|
+
const batches = (existsSync(batchRoot) ? listBatches(batchRoot) : []).map((id) => {
|
|
74
|
+
const dir = join(batchRoot, id), plan = readJson(join(dir, "plan.json")) ?? {};
|
|
75
|
+
return { dir, plan, created: Date.parse(plan.created ?? "") };
|
|
76
|
+
}).filter((b) => Number.isFinite(b.created) && (!repo || sameRepo(b.plan.repo, repo))).sort((a, b) => a.created - b.created);
|
|
77
|
+
const out = {};
|
|
78
|
+
for (const w of windows) {
|
|
79
|
+
const inWin = batches.filter((b) => b.created <= now && now - b.created <= w);
|
|
80
|
+
const chains = [], rows = [];
|
|
81
|
+
for (const b of inWin) { // chains stay within one batch: edges are in-batch; cascade rates pool every batch's rows
|
|
82
|
+
const r = readJson(join(b.dir, "report.json"))?.rows ?? [];
|
|
83
|
+
chains.push(...chainMetrics(r).chains); rows.push(...r);
|
|
84
|
+
}
|
|
85
|
+
out[windowLabel(w)] = { batches: inWin.length, chains: chains.length, by_depth: byDepth(chains), cascade: cascadeMetrics(rows), detail: chains };
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function formatChainLines(windows) {
|
|
91
|
+
return Object.entries(windows).flatMap(([w, m]) => {
|
|
92
|
+
const head = `chains ${w}: ${m.batches} batch${m.batches === 1 ? "" : "es"}, ${m.chains} chain${m.chains === 1 ? "" : "s"}`;
|
|
93
|
+
const depth = Object.entries(m.by_depth).sort((a, b) => Number(a[0]) - Number(b[0]))
|
|
94
|
+
.map(([d, e]) => ` depth ${d}: ${e.chains} chain${e.chains === 1 ? "" : "s"}, wall p50 ${e.wall_p50_min.toFixed(1)} min`);
|
|
95
|
+
const overlap = m.detail.flatMap((c) => c.links).map((l) => l.overlap_min);
|
|
96
|
+
const c = m.cascade;
|
|
97
|
+
return [head, ...(depth.length ? depth : [" chain wall p50: n/a"]),
|
|
98
|
+
` link overlap p50: ${overlap.length ? `${p50(overlap).toFixed(1)} min` : "n/a"}`,
|
|
99
|
+
` cascade rework: ${c.rework_rate == null ? "n/a" : `${Math.round(c.rework_rate * 100)}% of ${c.stacked} stacked dependent${c.stacked === 1 ? "" : "s"}, ${c.per_stacked} cascades each, ${c.minutes.toFixed(1)} min, $${c.cost_usd}`}`];
|
|
100
|
+
});
|
|
101
|
+
}
|