@pasko70/pibo 1.8.2 → 1.9.2
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/dist/apps/chat/data/chat-data-mappers.js +8 -0
- package/dist/apps/chat/data/project-service.js +23 -0
- package/dist/apps/chat/static-assets.js +6 -5
- package/dist/apps/chat-ui/assets/{dist--lraqdDn.js → dist-2KdPXbMT.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-Dgz3iWay.js → dist-5GM30SQK.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-CMFjl7MX.js → dist-9lsp1UpA.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-6pcjNbPQ.js → dist-BWbWIOcD.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-COlFTw2x.js → dist-BYKMZlI0.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-IlQbTNzw.js → dist-C-5u2QIS.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-bLd-NaVv.js → dist-Cge8JklW.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-CoCvyd4f.js → dist-CjYtD7ZT.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-CZSEM5So.js → dist-DFhhiR8M.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-YdEosvsr.js → dist-Etxmpyxg.js} +1 -1
- package/dist/apps/chat-ui/assets/{dist-CajLLpaw.js → dist-Idz5kzy8.js} +1 -1
- package/dist/apps/chat-ui/assets/index-BqD_bm7z.js +173 -0
- package/dist/apps/chat-ui/assets/index-C0x9nEcf.css +1 -0
- package/dist/apps/chat-ui/index.html +2 -2
- package/dist/apps/chat-vscode-web/assets/index-Cst9OUkC.js +41 -0
- package/dist/apps/chat-vscode-web/index.html +1 -1
- package/dist/cli.js +17 -0
- package/dist/compute/resource-health.js +12 -11
- package/dist/gateway/server.js +14 -1
- package/dist/gateway/web.js +2 -1
- package/dist/plugins/context-files.js +4 -2
- package/dist/ralph/store.js +1 -1
- package/dist/resources/cli.js +135 -0
- package/dist/resources/lifecycle.js +353 -0
- package/dist/resources/reaper-state.js +94 -0
- package/dist/resources/reaper.js +145 -0
- package/dist/session-ui/activeTurn.js +126 -0
- package/dist/session-ui/delegation.js +89 -0
- package/dist/session-ui/index.js +1 -0
- package/dist/session-ui/terminalRows.js +61 -0
- package/dist/shared/trace-engine.js +3 -2
- package/dist/shared/trace-event-projection.js +124 -14
- package/dist/shared/trace-transcript.js +73 -5
- package/package.json +1 -1
- package/dist/apps/chat-ui/assets/index-DbRZGRDd.css +0 -1
- package/dist/apps/chat-ui/assets/index-HPWlrJwv.js +0 -173
- package/dist/apps/chat-vscode-web/assets/index-Dge6XEYB.js +0 -41
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { readdir, readFile, rm } from "node:fs/promises";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { applyComputeWorkerReapPlan, buildComputeWorkerReapPlan, planReapWorkers, } from "../compute/docker.js";
|
|
7
|
+
import { defaultBrowserPoolRoot, defaultBrowserUseHome, getComputeResourceHealth, parseProcessList, } from "../compute/resource-health.js";
|
|
8
|
+
import { loadBrowserPoolState, reapIdleBrowserPool, } from "../tools/browser-pool.js";
|
|
9
|
+
const execFileAsync = promisify(execFile);
|
|
10
|
+
export async function collectManagedBrowserPools(rootDir) {
|
|
11
|
+
const records = [];
|
|
12
|
+
for (const statePath of await findStateFiles(rootDir)) {
|
|
13
|
+
const raw = await readFile(statePath, "utf8").catch(() => undefined);
|
|
14
|
+
if (!raw)
|
|
15
|
+
continue;
|
|
16
|
+
let parsed;
|
|
17
|
+
try {
|
|
18
|
+
parsed = JSON.parse(raw);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
24
|
+
continue;
|
|
25
|
+
const candidate = parsed;
|
|
26
|
+
if (typeof candidate.workerId !== "string" || typeof candidate.poolId !== "string")
|
|
27
|
+
continue;
|
|
28
|
+
const identity = {
|
|
29
|
+
workerId: candidate.workerId,
|
|
30
|
+
poolId: candidate.poolId,
|
|
31
|
+
maxBrowserProcesses: typeof candidate.maxBrowserProcesses === "number" ? candidate.maxBrowserProcesses : 1,
|
|
32
|
+
};
|
|
33
|
+
const state = await loadBrowserPoolState(statePath, { ...identity, onMalformed: "throw" }).catch(() => undefined);
|
|
34
|
+
if (!state)
|
|
35
|
+
continue;
|
|
36
|
+
records.push({ statePath, lockPath: join(dirname(statePath), "state.lock"), state });
|
|
37
|
+
}
|
|
38
|
+
return records;
|
|
39
|
+
}
|
|
40
|
+
export function listActiveResourceLeases(records) {
|
|
41
|
+
return records
|
|
42
|
+
.filter(({ state }) => Boolean(state.activeLeaseId))
|
|
43
|
+
.map(({ state }) => ({
|
|
44
|
+
leaseId: state.activeLeaseId,
|
|
45
|
+
holder: state.holder,
|
|
46
|
+
workerId: state.workerId,
|
|
47
|
+
poolId: state.poolId,
|
|
48
|
+
expiresAt: state.idleExpiresAt,
|
|
49
|
+
state: state.state,
|
|
50
|
+
}))
|
|
51
|
+
.sort((a, b) => a.leaseId.localeCompare(b.leaseId));
|
|
52
|
+
}
|
|
53
|
+
export async function getActiveResourceLeases(browserPoolRoot = defaultBrowserPoolRoot()) {
|
|
54
|
+
return listActiveResourceLeases(await collectManagedBrowserPools(browserPoolRoot));
|
|
55
|
+
}
|
|
56
|
+
export async function planResourceReap(options = {}) {
|
|
57
|
+
const now = options.now ?? new Date();
|
|
58
|
+
const resolved = resolveReapOptions(options);
|
|
59
|
+
const [records, staleFiles, compute, health] = await Promise.all([
|
|
60
|
+
collectManagedBrowserPools(resolved.browserPoolRoot),
|
|
61
|
+
planStaleCdpFiles(resolved.browserUseHome),
|
|
62
|
+
planComputeReapSafely({ includeDev: resolved.includeDev, maxAgeMinutes: resolved.maxAgeMinutes, now }),
|
|
63
|
+
getComputeResourceHealth({ now, browserPoolRoot: resolved.browserPoolRoot, browserUseHome: resolved.browserUseHome }),
|
|
64
|
+
]);
|
|
65
|
+
const unmanagedBrowsers = buildUnmanagedBrowserPlanItems(health.browserProcesses.unassignedMainProcessDetails, resolved.unmanagedBrowserGraceMinutes, new Set(resolved.exemptBrowserPids));
|
|
66
|
+
return buildResourceReapPlan({ now, options: resolved, records, staleFiles, unmanagedBrowsers, compute });
|
|
67
|
+
}
|
|
68
|
+
export function buildResourceReapPlan(input) {
|
|
69
|
+
const browserItems = input.records.map((record) => buildBrowserReapPlanItem(record, input.now, input.options.idleTimeoutMinutes));
|
|
70
|
+
const unmanagedBrowsers = input.unmanagedBrowsers ?? [];
|
|
71
|
+
return {
|
|
72
|
+
createdAt: input.now.toISOString(),
|
|
73
|
+
dryRun: true,
|
|
74
|
+
options: input.options,
|
|
75
|
+
browserPools: {
|
|
76
|
+
items: browserItems,
|
|
77
|
+
selected: browserItems.filter((item) => item.action === "reap").length,
|
|
78
|
+
skipped: browserItems.filter((item) => item.action === "skip").length,
|
|
79
|
+
},
|
|
80
|
+
staleFiles: { items: input.staleFiles, selected: input.staleFiles.length },
|
|
81
|
+
unmanagedBrowsers: {
|
|
82
|
+
items: unmanagedBrowsers,
|
|
83
|
+
selected: unmanagedBrowsers.filter((item) => item.action === "terminate").length,
|
|
84
|
+
skipped: unmanagedBrowsers.filter((item) => item.action === "skip").length,
|
|
85
|
+
},
|
|
86
|
+
compute: input.compute,
|
|
87
|
+
worktreesPreserved: true,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
export async function applyResourceReapPlan(plan, dependencies = {}) {
|
|
91
|
+
const replan = dependencies.plan ?? planResourceReap;
|
|
92
|
+
const confirmed = await replan({ ...plan.options, now: new Date() });
|
|
93
|
+
const reapBrowserPool = dependencies.reapBrowserPool ?? reapIdleBrowserPool;
|
|
94
|
+
const browserResults = [];
|
|
95
|
+
for (const item of confirmed.browserPools.items) {
|
|
96
|
+
if (item.action !== "reap")
|
|
97
|
+
continue;
|
|
98
|
+
browserResults.push(await reapBrowserPool({ statePath: item.statePath, lockPath: item.lockPath }, { workerId: item.workerId, poolId: item.poolId }, { idleTimeoutMs: confirmed.options.idleTimeoutMinutes * 60_000 }));
|
|
99
|
+
}
|
|
100
|
+
const terminateUnmanagedBrowser = dependencies.terminateUnmanagedBrowser ?? terminateUnmanagedBrowserProcessGroup;
|
|
101
|
+
const terminatedUnmanagedBrowsers = [];
|
|
102
|
+
for (const item of confirmed.unmanagedBrowsers.items) {
|
|
103
|
+
if (item.action !== "terminate")
|
|
104
|
+
continue;
|
|
105
|
+
if (await terminateUnmanagedBrowser(item))
|
|
106
|
+
terminatedUnmanagedBrowsers.push(item.pid);
|
|
107
|
+
}
|
|
108
|
+
const removedStaleFiles = await applyStaleCdpFilePlan(confirmed.staleFiles.items, dependencies.isPidAlive);
|
|
109
|
+
const removedComputeWorkers = await (dependencies.applyCompute ?? applyComputeWorkerReapPlan)(confirmed.compute);
|
|
110
|
+
return {
|
|
111
|
+
applied: true,
|
|
112
|
+
plan: confirmed,
|
|
113
|
+
browserResults,
|
|
114
|
+
terminatedUnmanagedBrowsers,
|
|
115
|
+
removedStaleFiles,
|
|
116
|
+
removedComputeWorkers,
|
|
117
|
+
worktreesPreserved: true,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function resolveReapOptions(options) {
|
|
121
|
+
return {
|
|
122
|
+
includeDev: options.includeDev === true,
|
|
123
|
+
maxAgeMinutes: options.maxAgeMinutes ?? 60,
|
|
124
|
+
idleTimeoutMinutes: options.idleTimeoutMinutes ?? 10,
|
|
125
|
+
unmanagedBrowserGraceMinutes: options.unmanagedBrowserGraceMinutes ?? 10,
|
|
126
|
+
browserPoolRoot: options.browserPoolRoot ?? defaultBrowserPoolRoot(),
|
|
127
|
+
browserUseHome: options.browserUseHome ?? defaultBrowserUseHome(),
|
|
128
|
+
exemptBrowserPids: options.exemptBrowserPids ?? readExemptBrowserPids(),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
export function buildUnmanagedBrowserPlanItems(processes, graceMinutes, exemptPids = new Set()) {
|
|
132
|
+
const graceSeconds = graceMinutes * 60;
|
|
133
|
+
return processes.map((process) => {
|
|
134
|
+
let action = "terminate";
|
|
135
|
+
let reason = "unmanaged Chromium main process has no managed browser-pool lease";
|
|
136
|
+
if (process.pid <= 1 || process.pgid <= 1) {
|
|
137
|
+
action = "skip";
|
|
138
|
+
reason = "unsafe pid or process group";
|
|
139
|
+
}
|
|
140
|
+
else if (exemptPids.has(process.pid) || exemptPids.has(process.pgid)) {
|
|
141
|
+
action = "skip";
|
|
142
|
+
reason = "explicitly exempted pid or process group";
|
|
143
|
+
}
|
|
144
|
+
else if (process.elapsedSeconds !== undefined && process.elapsedSeconds < graceSeconds) {
|
|
145
|
+
action = "skip";
|
|
146
|
+
reason = `process age ${process.elapsedSeconds}s is within ${graceSeconds}s grace period`;
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
pid: process.pid,
|
|
150
|
+
ppid: process.ppid,
|
|
151
|
+
processGroupId: process.pgid,
|
|
152
|
+
commandName: process.commandName,
|
|
153
|
+
userDataDir: process.userDataDir,
|
|
154
|
+
elapsedSeconds: process.elapsedSeconds,
|
|
155
|
+
action,
|
|
156
|
+
reason,
|
|
157
|
+
processGroup: true,
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async function terminateUnmanagedBrowserProcessGroup(item) {
|
|
162
|
+
if (!defaultIsPidAlive(item.pid))
|
|
163
|
+
return false;
|
|
164
|
+
const [processInfo, ownProcessGroupId] = await Promise.all([inspectProcess(item.pid), readProcessGroupId(process.pid)]);
|
|
165
|
+
if (!processInfo || !processInfo.isChromium || !processInfo.isMainProcess || processInfo.pgid !== item.processGroupId)
|
|
166
|
+
return false;
|
|
167
|
+
if (ownProcessGroupId !== undefined && ownProcessGroupId === item.processGroupId)
|
|
168
|
+
return false;
|
|
169
|
+
try {
|
|
170
|
+
process.kill(-item.processGroupId, "SIGTERM");
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (!(error instanceof Error && "code" in error && error.code === "ESRCH"))
|
|
174
|
+
throw error;
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
178
|
+
if (defaultIsPidAlive(item.pid)) {
|
|
179
|
+
try {
|
|
180
|
+
process.kill(-item.processGroupId, "SIGKILL");
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
if (!(error instanceof Error && "code" in error && error.code === "ESRCH"))
|
|
184
|
+
throw error;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return !defaultIsPidAlive(item.pid);
|
|
188
|
+
}
|
|
189
|
+
async function inspectProcess(pid) {
|
|
190
|
+
try {
|
|
191
|
+
const { stdout } = await execFileAsync("ps", ["-o", "pid=,ppid=,pgid=,comm=,args=", "-p", String(pid)]);
|
|
192
|
+
return parseProcessList(stdout).find((item) => item.pid === pid);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
async function readProcessGroupId(pid) {
|
|
199
|
+
try {
|
|
200
|
+
const { stdout } = await execFileAsync("ps", ["-o", "pgid=", "-p", String(pid)]);
|
|
201
|
+
const value = Number.parseInt(stdout.trim(), 10);
|
|
202
|
+
return Number.isInteger(value) && value > 0 ? value : undefined;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function readExemptBrowserPids() {
|
|
209
|
+
return (process.env.PIBO_RESOURCE_REAPER_EXEMPT_BROWSER_PIDS ?? "")
|
|
210
|
+
.split(",")
|
|
211
|
+
.map((value) => Number.parseInt(value.trim(), 10))
|
|
212
|
+
.filter((value) => Number.isInteger(value) && value > 0);
|
|
213
|
+
}
|
|
214
|
+
function buildBrowserReapPlanItem(record, now, idleTimeoutMinutes) {
|
|
215
|
+
const { state } = record;
|
|
216
|
+
let action = "skip";
|
|
217
|
+
let reason = "not idle long enough";
|
|
218
|
+
if (state.activeLeaseId || (state.activeLeaseCount ?? 0) > 0 || state.state === "leased") {
|
|
219
|
+
reason = state.activeLeaseId ? `active lease ${state.activeLeaseId}` : "active leases";
|
|
220
|
+
}
|
|
221
|
+
else if (state.state === "empty" || (!state.pid && !state.cdpUrl && !state.userDataDir)) {
|
|
222
|
+
reason = "no recorded browser";
|
|
223
|
+
}
|
|
224
|
+
else if (state.state === "stale" || state.state === "dirty") {
|
|
225
|
+
action = "reap";
|
|
226
|
+
reason = `pool state is ${state.state}`;
|
|
227
|
+
}
|
|
228
|
+
else if (hasExpired(state.idleExpiresAt, now)) {
|
|
229
|
+
action = "reap";
|
|
230
|
+
reason = `idle expiry ${state.idleExpiresAt} has passed`;
|
|
231
|
+
}
|
|
232
|
+
else if (isOlderThan(state.lastUsedAt, now, idleTimeoutMinutes * 60_000)) {
|
|
233
|
+
action = "reap";
|
|
234
|
+
reason = `last used at ${state.lastUsedAt} exceeds idle timeout`;
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
workerId: state.workerId,
|
|
238
|
+
poolId: state.poolId,
|
|
239
|
+
statePath: record.statePath,
|
|
240
|
+
lockPath: record.lockPath,
|
|
241
|
+
action,
|
|
242
|
+
reason,
|
|
243
|
+
preservesWorktree: true,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
async function planComputeReapSafely(options) {
|
|
247
|
+
try {
|
|
248
|
+
return await planReapWorkers(options);
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
|
|
252
|
+
throw error;
|
|
253
|
+
const plan = buildComputeWorkerReapPlan([], options);
|
|
254
|
+
plan.nextCommands = ["Docker CLI is unavailable in this runtime; browser and stale-file cleanup remain active."];
|
|
255
|
+
return plan;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
async function planStaleCdpFiles(browserUseHome, isPidAlive = defaultIsPidAlive) {
|
|
259
|
+
const stateDir = join(browserUseHome, "pibo-cdp");
|
|
260
|
+
let files;
|
|
261
|
+
try {
|
|
262
|
+
files = await readdir(stateDir);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
return [];
|
|
266
|
+
}
|
|
267
|
+
const items = [];
|
|
268
|
+
for (const file of files) {
|
|
269
|
+
if (file.endsWith(".pid")) {
|
|
270
|
+
const path = join(stateDir, file);
|
|
271
|
+
const pid = await readPid(path);
|
|
272
|
+
if (pid === undefined || !isPidAlive(pid))
|
|
273
|
+
items.push({ path, kind: "pid", action: "remove", reason: pid === undefined ? "invalid pid file" : `pid ${pid} is not alive` });
|
|
274
|
+
}
|
|
275
|
+
else if (file.endsWith(".port")) {
|
|
276
|
+
const pidPath = join(stateDir, `${file.slice(0, -5)}.pid`);
|
|
277
|
+
if (!existsSync(pidPath))
|
|
278
|
+
items.push({ path: join(stateDir, file), kind: "port", action: "remove", reason: "matching pid file is missing" });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return items;
|
|
282
|
+
}
|
|
283
|
+
async function applyStaleCdpFilePlan(items, isPidAlive = defaultIsPidAlive) {
|
|
284
|
+
const removed = [];
|
|
285
|
+
for (const item of items) {
|
|
286
|
+
if (item.kind === "pid") {
|
|
287
|
+
const pid = await readPid(item.path);
|
|
288
|
+
if (pid !== undefined && isPidAlive(pid))
|
|
289
|
+
continue;
|
|
290
|
+
await rm(item.path, { force: true });
|
|
291
|
+
removed.push(item.path);
|
|
292
|
+
const portPath = `${item.path.slice(0, -4)}.port`;
|
|
293
|
+
if (existsSync(portPath)) {
|
|
294
|
+
await rm(portPath, { force: true });
|
|
295
|
+
removed.push(portPath);
|
|
296
|
+
}
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
const pidPath = `${item.path.slice(0, -5)}.pid`;
|
|
300
|
+
if (existsSync(pidPath))
|
|
301
|
+
continue;
|
|
302
|
+
await rm(item.path, { force: true });
|
|
303
|
+
removed.push(item.path);
|
|
304
|
+
}
|
|
305
|
+
return removed;
|
|
306
|
+
}
|
|
307
|
+
async function findStateFiles(rootDir) {
|
|
308
|
+
const found = [];
|
|
309
|
+
async function walk(dir) {
|
|
310
|
+
let entries;
|
|
311
|
+
try {
|
|
312
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
for (const entry of entries) {
|
|
318
|
+
const path = join(dir, entry.name);
|
|
319
|
+
if (entry.isDirectory())
|
|
320
|
+
await walk(path);
|
|
321
|
+
else if (entry.isFile() && entry.name === "state.json")
|
|
322
|
+
found.push(path);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
await walk(rootDir);
|
|
326
|
+
return found;
|
|
327
|
+
}
|
|
328
|
+
async function readPid(path) {
|
|
329
|
+
const text = await readFile(path, "utf8").catch(() => "");
|
|
330
|
+
const pid = Number.parseInt(text.trim(), 10);
|
|
331
|
+
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
|
|
332
|
+
}
|
|
333
|
+
function hasExpired(value, now) {
|
|
334
|
+
if (!value)
|
|
335
|
+
return false;
|
|
336
|
+
const timestamp = Date.parse(value);
|
|
337
|
+
return !Number.isNaN(timestamp) && timestamp <= now.getTime();
|
|
338
|
+
}
|
|
339
|
+
function isOlderThan(value, now, ageMs) {
|
|
340
|
+
if (!value)
|
|
341
|
+
return false;
|
|
342
|
+
const timestamp = Date.parse(value);
|
|
343
|
+
return !Number.isNaN(timestamp) && timestamp + ageMs <= now.getTime();
|
|
344
|
+
}
|
|
345
|
+
function defaultIsPidAlive(pid) {
|
|
346
|
+
try {
|
|
347
|
+
process.kill(pid, 0);
|
|
348
|
+
return true;
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
return error instanceof Error && "code" in error && error.code === "EPERM";
|
|
352
|
+
}
|
|
353
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { piboHomePath } from "../core/pibo-home.js";
|
|
5
|
+
export function defaultResourceReaperStatePath() {
|
|
6
|
+
return process.env.PIBO_RESOURCE_REAPER_STATE_PATH || piboHomePath("resource-reaper-state.json");
|
|
7
|
+
}
|
|
8
|
+
export async function writeResourceReaperState(path, state) {
|
|
9
|
+
await mkdir(dirname(path), { recursive: true });
|
|
10
|
+
const temporaryPath = `${path}.${process.pid}.tmp`;
|
|
11
|
+
await writeFile(temporaryPath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
12
|
+
await rename(temporaryPath, path);
|
|
13
|
+
}
|
|
14
|
+
export async function claimResourceReaperOwnership(lockPath, pid = process.pid, isPidAlive = defaultIsPidAlive) {
|
|
15
|
+
await mkdir(dirname(lockPath), { recursive: true });
|
|
16
|
+
try {
|
|
17
|
+
const handle = await open(lockPath, "wx", 0o600);
|
|
18
|
+
await handle.writeFile(`${pid}\n`);
|
|
19
|
+
await handle.close();
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (!(error instanceof Error && "code" in error && error.code === "EEXIST"))
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
const owner = Number.parseInt((await readFile(lockPath, "utf8").catch(() => "")).trim(), 10);
|
|
27
|
+
if (Number.isInteger(owner) && owner > 0 && isPidAlive(owner))
|
|
28
|
+
return false;
|
|
29
|
+
await rm(lockPath, { force: true });
|
|
30
|
+
try {
|
|
31
|
+
const handle = await open(lockPath, "wx", 0o600);
|
|
32
|
+
await handle.writeFile(`${pid}\n`);
|
|
33
|
+
await handle.close();
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error instanceof Error && "code" in error && error.code === "EEXIST")
|
|
38
|
+
return false;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export async function releaseResourceReaperOwnership(lockPath, pid = process.pid) {
|
|
43
|
+
const owner = Number.parseInt((await readFile(lockPath, "utf8").catch(() => "")).trim(), 10);
|
|
44
|
+
if (owner === pid)
|
|
45
|
+
await rm(lockPath, { force: true });
|
|
46
|
+
}
|
|
47
|
+
export function readResourceReaperTimerStatus(path = defaultResourceReaperStatePath(), isPidAlive = defaultIsPidAlive) {
|
|
48
|
+
if (!existsSync(path)) {
|
|
49
|
+
return {
|
|
50
|
+
status: "missing",
|
|
51
|
+
details: "No automatic resource reaper state was found.",
|
|
52
|
+
nextCommands: ["pibo resources status --json", "pibo resources reap --dry-run --json"],
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const state = JSON.parse(readFileSync(path, "utf8"));
|
|
57
|
+
if (state.status !== "running" || !Number.isInteger(state.pid) || state.pid <= 0 || !isPidAlive(state.pid)) {
|
|
58
|
+
return {
|
|
59
|
+
status: "unknown",
|
|
60
|
+
details: `Resource reaper state exists but its owner is not running (${path}).`,
|
|
61
|
+
lastRunAt: state.lastRunAt,
|
|
62
|
+
nextRunAt: state.nextRunAt,
|
|
63
|
+
lastResult: state.lastResult,
|
|
64
|
+
lastError: state.lastError,
|
|
65
|
+
nextCommands: ["pibo resources status --json", "pibo resources reap --dry-run --json"],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
status: "configured",
|
|
70
|
+
details: `Automatic resource reaper is running every ${state.intervalMs} ms (pid ${state.pid}).`,
|
|
71
|
+
lastRunAt: state.lastRunAt,
|
|
72
|
+
nextRunAt: state.nextRunAt,
|
|
73
|
+
lastResult: state.lastResult,
|
|
74
|
+
lastError: state.lastError,
|
|
75
|
+
nextCommands: ["pibo resources status --json", "pibo resources reap --dry-run --json"],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
return {
|
|
80
|
+
status: "unknown",
|
|
81
|
+
details: `Resource reaper state could not be read: ${error instanceof Error ? error.message : String(error)}`,
|
|
82
|
+
nextCommands: ["pibo resources status --json", "pibo resources reap --dry-run --json"],
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function defaultIsPidAlive(pid) {
|
|
87
|
+
try {
|
|
88
|
+
process.kill(pid, 0);
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
return error instanceof Error && "code" in error && error.code === "EPERM";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { applyResourceReapPlan, planResourceReap } from "./lifecycle.js";
|
|
2
|
+
import { claimResourceReaperOwnership, defaultResourceReaperStatePath, releaseResourceReaperOwnership, writeResourceReaperState, } from "./reaper-state.js";
|
|
3
|
+
export class ResourceReaperService {
|
|
4
|
+
options;
|
|
5
|
+
intervalMs;
|
|
6
|
+
initialDelayMs;
|
|
7
|
+
statePath;
|
|
8
|
+
lockPath;
|
|
9
|
+
plan;
|
|
10
|
+
apply;
|
|
11
|
+
now;
|
|
12
|
+
timer;
|
|
13
|
+
running = false;
|
|
14
|
+
stopped = true;
|
|
15
|
+
ownsTimer = false;
|
|
16
|
+
state;
|
|
17
|
+
constructor(options = {}) {
|
|
18
|
+
this.options = options;
|
|
19
|
+
this.intervalMs = Math.max(1_000, options.intervalMs ?? readPositiveInteger(process.env.PIBO_RESOURCE_REAPER_INTERVAL_MS) ?? 5 * 60_000);
|
|
20
|
+
this.initialDelayMs = Math.max(0, options.initialDelayMs ?? readNonNegativeInteger(process.env.PIBO_RESOURCE_REAPER_INITIAL_DELAY_MS) ?? 30_000);
|
|
21
|
+
this.statePath = options.statePath ?? defaultResourceReaperStatePath();
|
|
22
|
+
this.lockPath = `${this.statePath}.lock`;
|
|
23
|
+
this.plan = options.plan ?? planResourceReap;
|
|
24
|
+
this.apply = options.apply ?? applyResourceReapPlan;
|
|
25
|
+
this.now = options.clock ?? (() => new Date());
|
|
26
|
+
}
|
|
27
|
+
async start() {
|
|
28
|
+
if (!this.stopped)
|
|
29
|
+
return;
|
|
30
|
+
this.ownsTimer = await claimResourceReaperOwnership(this.lockPath);
|
|
31
|
+
if (!this.ownsTimer)
|
|
32
|
+
return;
|
|
33
|
+
this.stopped = false;
|
|
34
|
+
const now = this.now();
|
|
35
|
+
this.state = {
|
|
36
|
+
status: "running",
|
|
37
|
+
pid: process.pid,
|
|
38
|
+
startedAt: now.toISOString(),
|
|
39
|
+
intervalMs: this.intervalMs,
|
|
40
|
+
nextRunAt: new Date(now.getTime() + this.initialDelayMs).toISOString(),
|
|
41
|
+
};
|
|
42
|
+
await this.persist();
|
|
43
|
+
this.arm(this.initialDelayMs);
|
|
44
|
+
}
|
|
45
|
+
async stop() {
|
|
46
|
+
this.stopped = true;
|
|
47
|
+
if (this.timer)
|
|
48
|
+
clearTimeout(this.timer);
|
|
49
|
+
this.timer = undefined;
|
|
50
|
+
if (this.state && this.ownsTimer) {
|
|
51
|
+
this.state = { ...this.state, status: "stopped", nextRunAt: undefined };
|
|
52
|
+
await this.persist();
|
|
53
|
+
}
|
|
54
|
+
if (this.ownsTimer)
|
|
55
|
+
await releaseResourceReaperOwnership(this.lockPath);
|
|
56
|
+
this.ownsTimer = false;
|
|
57
|
+
}
|
|
58
|
+
async runNow() {
|
|
59
|
+
if (!this.ownsTimer || this.running)
|
|
60
|
+
return undefined;
|
|
61
|
+
this.running = true;
|
|
62
|
+
const runAt = this.now();
|
|
63
|
+
try {
|
|
64
|
+
const plan = await this.plan({
|
|
65
|
+
includeDev: this.options.includeDev,
|
|
66
|
+
maxAgeMinutes: this.options.maxAgeMinutes,
|
|
67
|
+
idleTimeoutMinutes: this.options.idleTimeoutMinutes,
|
|
68
|
+
unmanagedBrowserGraceMinutes: this.options.unmanagedBrowserGraceMinutes,
|
|
69
|
+
browserPoolRoot: this.options.browserPoolRoot,
|
|
70
|
+
browserUseHome: this.options.browserUseHome,
|
|
71
|
+
exemptBrowserPids: this.options.exemptBrowserPids,
|
|
72
|
+
now: runAt,
|
|
73
|
+
});
|
|
74
|
+
const result = await this.apply(plan);
|
|
75
|
+
this.state = {
|
|
76
|
+
...(this.state ?? {
|
|
77
|
+
status: "running",
|
|
78
|
+
pid: process.pid,
|
|
79
|
+
startedAt: runAt.toISOString(),
|
|
80
|
+
intervalMs: this.intervalMs,
|
|
81
|
+
}),
|
|
82
|
+
status: "running",
|
|
83
|
+
lastRunAt: runAt.toISOString(),
|
|
84
|
+
nextRunAt: new Date(this.now().getTime() + this.intervalMs).toISOString(),
|
|
85
|
+
lastResult: {
|
|
86
|
+
browserPools: result.browserResults.filter((item) => item.reaped).length,
|
|
87
|
+
unmanagedBrowsers: result.terminatedUnmanagedBrowsers.length,
|
|
88
|
+
staleFiles: result.removedStaleFiles.length,
|
|
89
|
+
computeWorkers: result.removedComputeWorkers.length,
|
|
90
|
+
},
|
|
91
|
+
lastError: undefined,
|
|
92
|
+
};
|
|
93
|
+
console.error(JSON.stringify({ event: "resource_reaper_finished", at: runAt.toISOString(), ...this.state.lastResult }));
|
|
94
|
+
await this.persist();
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
99
|
+
this.state = {
|
|
100
|
+
...(this.state ?? {
|
|
101
|
+
status: "running",
|
|
102
|
+
pid: process.pid,
|
|
103
|
+
startedAt: runAt.toISOString(),
|
|
104
|
+
intervalMs: this.intervalMs,
|
|
105
|
+
}),
|
|
106
|
+
status: "running",
|
|
107
|
+
lastRunAt: runAt.toISOString(),
|
|
108
|
+
nextRunAt: new Date(this.now().getTime() + this.intervalMs).toISOString(),
|
|
109
|
+
lastError: message,
|
|
110
|
+
};
|
|
111
|
+
console.error(JSON.stringify({ event: "resource_reaper_failed", at: runAt.toISOString(), error: message }));
|
|
112
|
+
await this.persist();
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
this.running = false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
arm(delayMs) {
|
|
120
|
+
if (this.stopped)
|
|
121
|
+
return;
|
|
122
|
+
if (this.timer)
|
|
123
|
+
clearTimeout(this.timer);
|
|
124
|
+
this.timer = setTimeout(() => {
|
|
125
|
+
void this.runNow().finally(() => this.arm(this.intervalMs));
|
|
126
|
+
}, delayMs);
|
|
127
|
+
this.timer.unref?.();
|
|
128
|
+
}
|
|
129
|
+
async persist() {
|
|
130
|
+
if (this.state)
|
|
131
|
+
await writeResourceReaperState(this.statePath, this.state);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function readPositiveInteger(value) {
|
|
135
|
+
if (!value)
|
|
136
|
+
return undefined;
|
|
137
|
+
const parsed = Number(value);
|
|
138
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
|
|
139
|
+
}
|
|
140
|
+
function readNonNegativeInteger(value) {
|
|
141
|
+
if (!value)
|
|
142
|
+
return undefined;
|
|
143
|
+
const parsed = Number(value);
|
|
144
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : undefined;
|
|
145
|
+
}
|