@vite-hub/presets 0.0.0 → 0.3.1

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.
@@ -0,0 +1,724 @@
1
+ import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-BTBW9sZx.js";
2
+ import { d as resolveBabysitterAdmissionLimits, o as createPullRequestWorkspaces, r as resolveBabysitterLifecycleFilter, u as createBabysitterAdmission } from "./babysitter-C71pgjkv.js";
3
+ import { a as pullRequestThreadId, i as budgetParks, o as createGitHubAppCredentials, s as createGitHubHost, t as createBabysitterRuntime } from "./server-CIgjUG63.js";
4
+ import { defineAgent } from "@vite-hub/agent";
5
+ import { forgeErrorStatus, githubInstallationRouting } from "@vite-hub/forge";
6
+ import { channelEnv } from "@vite-hub/agent/channels";
7
+ import { execFile } from "node:child_process";
8
+ import { access, lstat, mkdtemp, open, readFile, readdir, rename, rm, stat } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
11
+ import { promisify } from "node:util";
12
+ import { constants } from "node:fs";
13
+ import { createProcessAgentCapacity, createProcessAgentHost, registerAgentProcessHostIntake } from "@vite-hub/agent/process";
14
+ /** Removes every entry of the cwd, after it checks that the cwd is still the claimed checkout pool (dev and inode in argv). */
15
+ const cleanCheckoutPoolScript = `
16
+ import { lstat, readdir, rm } from "node:fs/promises";
17
+ const info = await lstat(".", { bigint: true });
18
+ if (String(info.dev) !== process.argv[1] || String(info.ino) !== process.argv[2]) {
19
+ throw new Error(${JSON.stringify("Refusing to clean replaced Babysitter checkout pool")});
20
+ }
21
+ for (const entry of await readdir(".")) {
22
+ await rm(entry, { force: true, recursive: true, maxRetries: 5, retryDelay: 100 });
23
+ }
24
+ `;
25
+ //#endregion
26
+ //#region src/babysitter/preflight.ts
27
+ const execute = promisify(execFile);
28
+ async function validateExecutable(path) {
29
+ await access(path, constants.X_OK);
30
+ if (!(await stat(path)).isFile()) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_HOST_EXECUTABLE_UNAVAILABLE({
31
+ program: path,
32
+ problem: "is not a file"
33
+ });
34
+ if (process.platform !== "win32") {
35
+ const file = await open(path, "r");
36
+ const buffer = Buffer.alloc(256);
37
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0).finally(() => file.close());
38
+ const bytes = buffer.subarray(0, bytesRead);
39
+ if (!(bytes[0] === 35 && bytes[1] === 33)) {
40
+ const elf = bytes[0] === 127 && bytes[1] === 69 && bytes[2] === 76 && bytes[3] === 70;
41
+ const macho = [
42
+ [
43
+ 254,
44
+ 237,
45
+ 250,
46
+ 206
47
+ ],
48
+ [
49
+ 206,
50
+ 250,
51
+ 237,
52
+ 254
53
+ ],
54
+ [
55
+ 254,
56
+ 237,
57
+ 250,
58
+ 207
59
+ ],
60
+ [
61
+ 207,
62
+ 250,
63
+ 237,
64
+ 254
65
+ ],
66
+ [
67
+ 202,
68
+ 254,
69
+ 186,
70
+ 190
71
+ ],
72
+ [
73
+ 190,
74
+ 186,
75
+ 254,
76
+ 202
77
+ ],
78
+ [
79
+ 202,
80
+ 254,
81
+ 186,
82
+ 191
83
+ ],
84
+ [
85
+ 191,
86
+ 186,
87
+ 254,
88
+ 202
89
+ ]
90
+ ].some((magic) => magic.every((byte, index) => bytes[index] === byte));
91
+ if (!elf && !macho) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_HOST_EXECUTABLE_UNAVAILABLE({
92
+ program: path,
93
+ problem: "has no interpreter"
94
+ });
95
+ } else {
96
+ const header = bytes.toString("utf8");
97
+ const parts = header.slice(2, header.indexOf("\n") < 0 ? void 0 : header.indexOf("\n")).trim().split(/\s+/).filter(Boolean);
98
+ const interpreter = parts[0] === "/usr/bin/env" || parts[0] === "/bin/env" ? parts.slice(1).find((part) => !part.startsWith("-") && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(part)) : parts[0];
99
+ if (!interpreter) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_HOST_EXECUTABLE_UNAVAILABLE({
100
+ program: path,
101
+ problem: "has no interpreter"
102
+ });
103
+ await resolveExecutable(interpreter);
104
+ }
105
+ }
106
+ }
107
+ async function resolveExecutable(program) {
108
+ if (isAbsolute(program) || program.includes("/") || program.includes("\\")) {
109
+ await validateExecutable(program);
110
+ return;
111
+ }
112
+ const path = process.env.PATH ?? "";
113
+ const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").some((extension) => program.toLowerCase().endsWith(extension.toLowerCase())) ? [""] : ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";")] : [""];
114
+ for (const directory of path.split(delimiter)) for (const extension of extensions) {
115
+ const candidate = join(directory || ".", `${program}${extension}`);
116
+ try {
117
+ await access(candidate, constants.X_OK);
118
+ } catch {
119
+ continue;
120
+ }
121
+ await validateExecutable(candidate);
122
+ return;
123
+ }
124
+ throw presetsErrorDiagnostics.PRESETS_BABYSITTER_HOST_EXECUTABLE_UNAVAILABLE({
125
+ program,
126
+ problem: "is not on PATH"
127
+ });
128
+ }
129
+ /** Cached host prerequisites. Failed checks recover without restarting webhook intake. */
130
+ function createBabysitterPreflight(install, checkCommand = async (program, probe = "version") => {
131
+ if (probe === "path") await resolveExecutable(program);
132
+ else await execute(program, ["--version"], {
133
+ timeout: 5e3,
134
+ maxBuffer: 65536
135
+ });
136
+ }) {
137
+ let cached;
138
+ let expiresAt = 0;
139
+ let pending;
140
+ return async () => {
141
+ if (cached && Date.now() < expiresAt) return cached;
142
+ pending ??= (async () => {
143
+ const diagnostics = [];
144
+ const commands = ["git"];
145
+ if (install !== false) {
146
+ const installer = (isRuntimeRecord(install) ? install.command : void 0) ?? "corepack";
147
+ if (installer) {
148
+ if ((isAbsolute(installer) || !installer.includes("/") && !installer.includes("\\")) && !commands.includes(installer)) commands.push(installer);
149
+ }
150
+ }
151
+ for (const program of commands) try {
152
+ await checkCommand(program, program === "git" || program === "corepack" ? "version" : "path");
153
+ diagnostics.push({
154
+ label: `Host ${program}`,
155
+ status: "ok",
156
+ value: "Available"
157
+ });
158
+ } catch {
159
+ const display = program === "git" ? "Git" : program === "corepack" ? "Corepack" : program;
160
+ diagnostics.push({
161
+ label: `Host ${program}`,
162
+ status: "warning",
163
+ value: "Unavailable",
164
+ detail: `Install ${display} in the trusted host service PATH. Model passes wait until this check succeeds.`
165
+ });
166
+ }
167
+ const failures = diagnostics.filter((item) => item.status === "warning");
168
+ const result = {
169
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
170
+ diagnostics
171
+ };
172
+ if (failures.length) result.pause = {
173
+ reason: "host-prerequisite",
174
+ detail: failures.map((item) => item.detail).join(" "),
175
+ retryAt: Date.now() + 3e4
176
+ };
177
+ cached = result;
178
+ expiresAt = Date.now() + (failures.length ? 3e4 : 3e5);
179
+ return result;
180
+ })();
181
+ try {
182
+ return await pending;
183
+ } finally {
184
+ pending = void 0;
185
+ }
186
+ };
187
+ }
188
+ //#endregion
189
+ //#region src/babysitter/queue-health.ts
190
+ /** Derive bounded operational counters from the durable queue, including scheduled retries. */
191
+ function babysitterQueueHealth(items, now = Date.now()) {
192
+ const mergedTerminal = (result) => result?.startsWith("Merged ") || result === "Asynchronous merge confirmed by GitHub." || result === "Direct merge outcome reconciled: GitHub reports the pull request merged.";
193
+ const ready = items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt <= now);
194
+ const waiting = items.filter((item) => item.status === "waiting");
195
+ return {
196
+ working: items.filter((item) => item.status === "working").length,
197
+ ready: ready.length,
198
+ scheduled: items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt > now).length,
199
+ stackBlocked: items.filter((item) => item.stackBlocked).length,
200
+ waiting: waiting.length,
201
+ suppressed: items.filter((item) => item.status === "terminal" && item.state === "open" && !mergedTerminal(item.lastResult)).length,
202
+ oldestReadyAgeMs: ready.reduce((age, item) => Math.max(age, item.dirtyAt === void 0 ? 0 : now - item.dirtyAt), 0),
203
+ blockers: {
204
+ checks: waiting.filter((item) => item.wait && item.wait.kind !== "external" && !item.wait.wake).length,
205
+ dependency: waiting.filter((item) => item.wait?.wake).length,
206
+ manual: waiting.filter((item) => item.wait?.kind === "external" && !item.wait.wake && item.wait.retryAt === void 0).length,
207
+ timed: waiting.filter((item) => item.wait?.retryAt !== void 0).length,
208
+ installCapacity: waiting.filter((item) => item.wait?.reasonCode === "install-capacity").length,
209
+ noProgress: waiting.filter((item) => item.progressBudget?.exhausted && item.progressBudget.head === item.head).length
210
+ }
211
+ };
212
+ }
213
+ //#endregion
214
+ //#region src/babysitter/repositories.ts
215
+ /** How long the installation repository list stays fresh without an installation webhook. */
216
+ const installationRepositoriesTtlMs = 6e5;
217
+ const repositoryName = /^[\w.-]+\/[\w.-]+$/;
218
+ function lowercaseNames(values) {
219
+ return Array.isArray(values) ? values.filter((value) => hasRuntimeType(value, "string")).map((value) => value.toLowerCase()) : [];
220
+ }
221
+ /**
222
+ * Resolves `filter.repository`. A non-empty `allow` list is used as given. Without one, the Babysitter
223
+ * serves every repository that `read` returns, except archived ones and those in `deny`.
224
+ */
225
+ function babysitterRepositories(filter, read, { ttlMs = installationRepositoriesTtlMs, now = Date.now } = {}) {
226
+ const rules = isRuntimeRecord(filter) && isRuntimeRecord(filter.repository) ? filter.repository : void 0;
227
+ const allow = Array.isArray(rules?.allow) ? rules.allow : [];
228
+ if (allow.length) {
229
+ const repositories = allow.filter((value) => hasRuntimeType(value, "string") && repositoryName.test(value)).map((value) => value.toLowerCase());
230
+ if (!repositories.length) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_REPOSITORIES_INVALID();
231
+ return {
232
+ source: "allow",
233
+ known: () => repositories,
234
+ current: async () => repositories,
235
+ observe: () => false
236
+ };
237
+ }
238
+ const deny = new Set(lowercaseNames(rules?.deny));
239
+ const accepted = (repository) => repositoryName.test(repository) && !deny.has(repository);
240
+ let repositories = [];
241
+ let loadedAt;
242
+ let refreshing;
243
+ let installationEvents = 0;
244
+ const set = (next) => {
245
+ const sorted = [...new Set(next)].sort();
246
+ const changed = sorted.length !== repositories.length || sorted.some((repository, index) => repository !== repositories[index]);
247
+ repositories = sorted;
248
+ return changed;
249
+ };
250
+ const refresh = () => refreshing ??= (async () => {
251
+ try {
252
+ const events = installationEvents;
253
+ const installed = await read();
254
+ if (events !== installationEvents) return repositories;
255
+ set(installed.filter((item) => !item.archived).map((item) => item.repository.toLowerCase()).filter(accepted));
256
+ loadedAt = now();
257
+ return repositories;
258
+ } finally {
259
+ refreshing = void 0;
260
+ }
261
+ })();
262
+ return {
263
+ source: "installations",
264
+ known: () => repositories,
265
+ async current() {
266
+ if (loadedAt !== void 0 && now() - loadedAt < ttlMs) return repositories;
267
+ return await refresh();
268
+ },
269
+ observe(event, payload) {
270
+ if (!isRuntimeRecord(payload)) return false;
271
+ if (event === "installation" || event === "installation_repositories") {
272
+ loadedAt = void 0;
273
+ installationEvents++;
274
+ const names = (value) => Array.isArray(value) ? lowercaseNames(value.map((item) => isRuntimeRecord(item) ? item.full_name : void 0)) : [];
275
+ const removed = /* @__PURE__ */ new Set([...names(payload.repositories_removed), ...["deleted", "suspend"].includes(String(payload.action)) ? names(payload.repositories) : []]);
276
+ const added = [...names(payload.repositories_added), ...["created", "unsuspend"].includes(String(payload.action)) ? names(payload.repositories) : []].filter(accepted);
277
+ return set([...repositories.filter((repository) => !removed.has(repository)), ...added]);
278
+ }
279
+ const repository = isRuntimeRecord(payload.repository) ? payload.repository : void 0;
280
+ const name = hasRuntimeType(repository?.full_name, "string") ? repository.full_name.toLowerCase() : void 0;
281
+ if (!name || !isRuntimeRecord(payload.installation) || repository?.archived === true || !accepted(name) || repositories.includes(name)) return false;
282
+ return set([...repositories, name]);
283
+ }
284
+ };
285
+ }
286
+ //#endregion
287
+ //#region src/babysitter/webhook-redelivery.ts
288
+ /**
289
+ * Progress events that a later event of the same run replaces. A lost `check_run.created` or
290
+ * `workflow_run.in_progress` changes nothing once its `completed` event arrives, and change detection
291
+ * reads running checks anyway. On 2026-11-16 they were 80% of the failed deliveries, and sending them
292
+ * first delayed the `completed` events that let a green PR merge.
293
+ */
294
+ const superseded = /* @__PURE__ */ new Set([
295
+ "check_run.created",
296
+ "check_run.rerequested",
297
+ "check_suite.requested",
298
+ "check_suite.rerequested",
299
+ "workflow_run.requested",
300
+ "workflow_run.in_progress",
301
+ "workflow_job.queued",
302
+ "workflow_job.in_progress",
303
+ "workflow_job.waiting"
304
+ ]);
305
+ /** Lower sends first: results and PR state before comments and the rest. */
306
+ function priority(name) {
307
+ if (name.endsWith(".completed") || name === "status") return 0;
308
+ if (name.startsWith("pull_request.") || name.startsWith("pull_request_review") || name === "push") return 1;
309
+ return 2;
310
+ }
311
+ /**
312
+ * Sends failed GitHub App webhook deliveries again. GitHub does not retry a delivery that timed out
313
+ * after 10 seconds or failed. On 2026-11-16 about a third of deliveries timed out while the disk was
314
+ * busy, so `check_suite.completed` events got lost and green pull requests waited 30 minutes or more
315
+ * for the change detection to find them. The inbox deduplicates by delivery ID, so an event that the
316
+ * receiver stored after GitHub stopped waiting is not processed twice.
317
+ */
318
+ function createWebhookRedelivery(options) {
319
+ const now = options.now ?? Date.now;
320
+ const windowMs = options.windowMs ?? 72e5;
321
+ const overlapMs = options.overlapMs ?? 12e5;
322
+ const maxAttempts = options.maxAttempts ?? 3;
323
+ const limit = options.limit ?? 200;
324
+ const pauseMs = options.pauseMs ?? 250;
325
+ const sent = /* @__PURE__ */ new Map();
326
+ let watermark;
327
+ let running = false;
328
+ return {
329
+ /** Redelivers the failed deliveries since the last sweep. Returns how many it sent. */
330
+ async sweep(signal) {
331
+ if (running) return 0;
332
+ running = true;
333
+ const start = now();
334
+ try {
335
+ const since = Math.max(start - windowMs, watermark ?? -Infinity);
336
+ const failed = await options.source.failedDeliveries(since, signal);
337
+ let redelivered = 0, abandoned = 0, errors = 0, skipped = 0;
338
+ const events = {};
339
+ const name = (delivery) => delivery.action ? `${delivery.event}.${delivery.action}` : delivery.event;
340
+ const ordered = failed.filter((delivery) => !superseded.has(name(delivery)) || (skipped++, false)).sort((a, b) => priority(name(a)) - priority(name(b)) || a.deliveredAt - b.deliveredAt);
341
+ for (const delivery of ordered) {
342
+ if (redelivered + errors >= limit) break;
343
+ const attempts = sent.get(delivery.guid) ?? 0;
344
+ if (attempts >= maxAttempts) {
345
+ abandoned++;
346
+ continue;
347
+ }
348
+ signal?.throwIfAborted();
349
+ try {
350
+ await options.source.redeliver(delivery.id, signal);
351
+ sent.set(delivery.guid, attempts + 1);
352
+ redelivered++;
353
+ events[name(delivery)] = (events[name(delivery)] ?? 0) + 1;
354
+ } catch (error) {
355
+ if (signal?.aborted) throw error;
356
+ errors++;
357
+ options.error("babysitter.webhook.redeliver_failed", error, {
358
+ delivery: delivery.id,
359
+ event: delivery.event
360
+ });
361
+ }
362
+ if (pauseMs > 0) await new Promise((resolve) => setTimeout(resolve, pauseMs));
363
+ }
364
+ if (sent.size > 2e4) for (const guid of [...sent.keys()].slice(0, sent.size - 1e4)) sent.delete(guid);
365
+ const remaining = failed.length - redelivered - abandoned - skipped;
366
+ watermark = remaining > 0 ? since : start - overlapMs;
367
+ if (failed.length) options.event("babysitter.webhook.redelivered", {
368
+ failed: failed.length,
369
+ redelivered,
370
+ abandoned,
371
+ skipped,
372
+ errors,
373
+ remaining,
374
+ events
375
+ });
376
+ return redelivered;
377
+ } finally {
378
+ running = false;
379
+ }
380
+ } };
381
+ }
382
+ //#endregion
383
+ //#region src/babysitter/host.ts
384
+ /** Reads a plain or sealed Server Env value. */
385
+ function envString(value) {
386
+ const plain = isRuntimeRecord(value) && hasRuntimeType(value.unseal, "function") ? value.unseal() : value;
387
+ if (hasRuntimeType(plain, "number")) return String(plain);
388
+ return hasRuntimeType(plain, "string") && plain.trim() ? plain.trim() : void 0;
389
+ }
390
+ /** Accept PEM secrets from systemd and dotenv files that encode newlines as `\\n`. */
391
+ function normalizePrivateKey(value) {
392
+ return value?.replace(/\\n/g, "\n");
393
+ }
394
+ /**
395
+ * Remove the persistent checkout pool created by older Babysitter releases.
396
+ *
397
+ * Current GitHub hosts use a disposable checkout for each pass. The old pool
398
+ * retained merged and closed PR workspaces, including installed dependencies,
399
+ * under the owning process host data directory; remove that pool as one unit.
400
+ */
401
+ async function cleanupLegacyBabysitterCheckouts(dataDir) {
402
+ const root = join(dataDir, "checkouts");
403
+ const info = await lstat(root, { bigint: true }).catch((error) => {
404
+ if (error.code === "ENOENT") return void 0;
405
+ throw error;
406
+ });
407
+ if (!info) return 0;
408
+ if (!info.isDirectory() || info.isSymbolicLink()) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_CHECKOUT_POOL_UNSAFE({ root });
409
+ const quarantine = await mkdtemp(join(dataDir, ".checkouts-cleanup-"));
410
+ const claimed = join(quarantine, "checkouts");
411
+ await rename(root, claimed);
412
+ const claimedInfo = await lstat(claimed, { bigint: true });
413
+ if (!claimedInfo.isDirectory() || claimedInfo.dev !== info.dev || claimedInfo.ino !== info.ino) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_CHECKOUT_POOL_REPLACED({ path: claimed });
414
+ const entries = await readdir(claimed, { withFileTypes: true });
415
+ try {
416
+ await promisify(execFile)(process.execPath, [
417
+ "--input-type=module",
418
+ "--eval",
419
+ cleanCheckoutPoolScript,
420
+ String(info.dev),
421
+ String(info.ino)
422
+ ], { cwd: claimed });
423
+ } catch (error) {
424
+ if (isRuntimeRecord(error) && String(error.stderr ?? "").includes("Refusing to clean replaced Babysitter checkout pool")) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_CHECKOUT_POOL_REPLACED({
425
+ path: claimed,
426
+ cause: error
427
+ });
428
+ throw error;
429
+ }
430
+ const remaining = await lstat(claimed, { bigint: true });
431
+ if (remaining.dev !== info.dev || remaining.ino !== info.ino) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_CHECKOUT_POOL_REPLACED({ path: claimed });
432
+ return entries.length;
433
+ }
434
+ /**
435
+ * GitHub App settings from `env.server.github` or the VITEHUB_GITHUB_* variables. With `webhookSecret`,
436
+ * a missing webhook secret is reported together with the other missing variables.
437
+ */
438
+ async function readGitHubAppEnvironment(context = {}, required = {}) {
439
+ const env = await channelEnv("github", context);
440
+ const appId = Number(envString(env.appId));
441
+ const keyPath = envString(env.privateKeyPath);
442
+ const privateKey = normalizePrivateKey(envString(env.privateKey) ?? (keyPath ? (await readFile(keyPath, "utf8")).trim() : void 0));
443
+ const missing = [
444
+ ...Number.isSafeInteger(appId) && appId > 0 ? [] : ["VITEHUB_GITHUB_APP_ID"],
445
+ ...privateKey ? [] : ["VITEHUB_GITHUB_PRIVATE_KEY (or VITEHUB_GITHUB_PRIVATE_KEY_PATH)"],
446
+ ...required.webhookSecret && !envString(env.webhookSecret) ? ["VITEHUB_GITHUB_WEBHOOK_SECRET"] : []
447
+ ];
448
+ if (missing.length || !privateKey) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_ENV_MISSING({ variables: missing });
449
+ return {
450
+ appId,
451
+ privateKey,
452
+ ...githubInstallationRouting({
453
+ installationId: envString(env.installationId),
454
+ appOwner: envString(env.appOwner),
455
+ appInstallations: envString(env.appInstallations)
456
+ })
457
+ };
458
+ }
459
+ /**
460
+ * Creates the labels that the PR filter names in each served repository, so a person can apply
461
+ * `babysitter:skip` without creating it first. GitHub answers 422 for a label that exists; that and
462
+ * any other failure leave the repository as it is. Returns the labels created.
463
+ */
464
+ async function ensureBabysitterLabels(github, repositories, labels) {
465
+ const created = [], failed = [];
466
+ for (const repository of labels.length ? repositories : []) {
467
+ const provider = await github.forge({ repository }).catch(() => void 0);
468
+ for (const name of labels) {
469
+ if (!provider) {
470
+ failed.push(`${repository}:${name}`);
471
+ continue;
472
+ }
473
+ await provider.request("POST", `/repos/${repository}/labels`, { body: {
474
+ name,
475
+ color: "ededed",
476
+ description: "Selects or pauses Babysitter work on a pull request"
477
+ } }).then(() => created.push(`${repository}:${name}`), (error) => {
478
+ if (forgeErrorStatus(error) !== 422) failed.push(`${repository}:${name}`);
479
+ });
480
+ }
481
+ }
482
+ return {
483
+ created,
484
+ failed
485
+ };
486
+ }
487
+ const passWorkspace = /^(?:vitehub-provider-(?:launch-|tmp-|inspection-)?[A-Za-z0-9]{6}|vitehub-baseline-[A-Za-z0-9]{6}|vitehub-[\w.-]+-pr-\d+-[A-Za-z0-9]{6}(?:\.meta\.json|\.cleanup-\d+-\d+)?|t3-provider-runtime-[A-Za-z0-9]{6})$/;
488
+ /**
489
+ * Removes pass workspaces that an interrupted process left in `root`. It sweeps only a temporary
490
+ * directory inside the service's working directory, which no other process shares, and keeps
491
+ * anything this process created.
492
+ */
493
+ async function sweepBabysitterWorkspaces(root = tmpdir(), startedAt = performance.timeOrigin, cwd = process.cwd()) {
494
+ if (!resolve(root).startsWith(`${resolve(cwd)}${sep}`)) return 0;
495
+ let removed = 0;
496
+ for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
497
+ if (!passWorkspace.test(entry.name)) continue;
498
+ const path = join(root, entry.name);
499
+ const info = await lstat(path).catch(() => void 0);
500
+ if (!info || info.mtimeMs >= startedAt) continue;
501
+ await rm(path, {
502
+ force: true,
503
+ recursive: true,
504
+ maxRetries: 3
505
+ }).then(() => removed++, () => {});
506
+ }
507
+ return removed;
508
+ }
509
+ /** Builds the GitHub host, process host, inbox, and reconciler for one discovered Babysitter Agent. */
510
+ async function createBabysitterProcessHost(context) {
511
+ const agent = context.agent;
512
+ await cleanupLegacyBabysitterCheckouts(context.dataDir);
513
+ const app = await readGitHubAppEnvironment({}, { webhookSecret: true });
514
+ const credentials = createGitHubAppCredentials(app);
515
+ const repositories = babysitterRepositories(agent.options.filter, () => credentials.repositories());
516
+ const identity = await credentials.identity();
517
+ const github = createGitHubHost({
518
+ credentials: credentials.credentials,
519
+ identity
520
+ });
521
+ let runtime;
522
+ const capacity = {
523
+ ...agent.options.capacity,
524
+ ...agent.options.placement?.remoteActive ? { remoteActive: () => agent.options.placement?.remoteActive?.() ?? 0 } : {},
525
+ concurrency: agent.options.concurrency
526
+ };
527
+ const hostSample = createProcessAgentCapacity(capacity).adaptive;
528
+ const host = await createProcessAgentHost({
529
+ name: context.agentName,
530
+ dataDir: context.dataDir,
531
+ invocations: agent.invocations,
532
+ invocationAgentName: `${context.agentName}-worker`,
533
+ capacity: {
534
+ ...capacity,
535
+ queue: {
536
+ maxPending: agent.options.concurrency,
537
+ timeout: 36e5
538
+ }
539
+ },
540
+ intervalMs: 1e4,
541
+ run: async (reason, run, accepting) => await runtime?.reconcile(reason, run, accepting)
542
+ });
543
+ const preflight = createBabysitterPreflight(agent.options.install ?? true);
544
+ const buildRevision = "36cb7f3d81a66e753f82ebfb46bda4f9cdcc713a9a7ab3953bc1baa6b2c1bd26";
545
+ const admission = createBabysitterAdmission({
546
+ invocations: host.invocations,
547
+ limits: resolveBabysitterAdmissionLimits(agent.options.admission),
548
+ check: async () => (await preflight()).pause ?? await agent.options.admission?.check?.()
549
+ });
550
+ let admissionPrerequisiteSample;
551
+ const warmWorkspaces = agent.options.warmWorkspaces;
552
+ const resumeThreads = typeof warmWorkspaces === "object" && warmWorkspaces.resumeThreads === true;
553
+ const workspaces = warmWorkspaces ? createPullRequestWorkspaces({
554
+ root: join(context.dataDir, "pr-workspaces"),
555
+ ...warmWorkspaces === true ? {} : warmWorkspaces,
556
+ ...resumeThreads ? { deleteSession: (repository, number, session) => host.deleteProviderSession(`${pullRequestThreadId(repository, number)}:${session}`) } : {}
557
+ }) : void 0;
558
+ const worker = defineAgent({
559
+ extends: agent,
560
+ invocations: host.invocations,
561
+ driver: {
562
+ capacity: host.capacity,
563
+ ...resumeThreads ? { sessionStorePath: host.providerSessionStorePath } : {}
564
+ }
565
+ });
566
+ runtime = createBabysitterRuntime({
567
+ workspaces,
568
+ agent: worker,
569
+ agentName: context.agentName,
570
+ github,
571
+ inboxStorage: context.state.extension("babysitter"),
572
+ inboxScope: context.agentName,
573
+ repositories,
574
+ concurrency: agent.options.concurrency,
575
+ activityAuthors: [identity.login],
576
+ event: host.event,
577
+ error: host.error,
578
+ wake: () => host.wake(),
579
+ admission,
580
+ hostCapacity: async ({ active, signal }) => {
581
+ try {
582
+ return await hostSample.sample({
583
+ active,
584
+ concurrency: capacity.concurrency,
585
+ pending: 0,
586
+ signal: AbortSignal.any([signal, AbortSignal.timeout(hostSample.sampleTimeoutMs ?? 1e3)])
587
+ });
588
+ } catch (error) {
589
+ if (signal.aborted) throw error;
590
+ return {
591
+ concurrency: hostSample.fallbackConcurrency ?? 1,
592
+ reason: `sample-error: ${error instanceof Error ? error.message : String(error)}`
593
+ };
594
+ }
595
+ }
596
+ });
597
+ const inbox = runtime.inbox;
598
+ const swept = await sweepBabysitterWorkspaces();
599
+ const workspaceStatus = async (repository, number) => {
600
+ if (!repositories.known().includes(repository.toLowerCase())) return "unknown";
601
+ const snapshot = await inbox.get(repository, number);
602
+ return !snapshot ? "unknown" : snapshot.status === "terminal" ? "terminal" : "open";
603
+ };
604
+ const sweepWorkspaces = (reason) => workspaces?.sweep(workspaceStatus).then((result) => host.event("babysitter.workspaces.pruned", {
605
+ reason,
606
+ removed: result.removed.length,
607
+ reasons: result.removed.map((entry) => entry.reason),
608
+ keptBytes: result.keptBytes,
609
+ kept: result.kept
610
+ }), (error) => host.error("babysitter.workspaces.prune_failed", error, { reason }));
611
+ let workspaceSweep;
612
+ const redelivery = createWebhookRedelivery({
613
+ source: credentials,
614
+ event: host.event,
615
+ error: host.error
616
+ });
617
+ let redeliverySweep;
618
+ return {
619
+ start() {
620
+ registerAgentProcessHostIntake(context.agentName, async ({ deliveryId, event, payload }) => {
621
+ const enrolled = repositories.observe(event, payload);
622
+ if (enrolled) host.event("babysitter.repositories.changed", {
623
+ event,
624
+ repositories: repositories.known().length
625
+ });
626
+ const result = await inbox.ingest(deliveryId, event, payload);
627
+ const mainRepair = await runtime?.observeMainRepair(event, payload).catch((error) => {
628
+ host.error("babysitter.main_repair.observe_failed", error);
629
+ return false;
630
+ });
631
+ if (result.updated.length || enrolled || mainRepair || event === "installation" || event === "installation_repositories") host.wake("webhook");
632
+ return Response.json(result, { status: 202 });
633
+ });
634
+ inbox.importLegacyFile(".vitehub/pull-request-inbox.sqlite").catch((error) => host.error("babysitter.legacy-import.failed", error)).then(() => inbox.releaseLeases()).then((released) => {
635
+ if (released) host.event("babysitter.leases.released", { released });
636
+ }, (error) => host.error("babysitter.leases.release-failed", error)).finally(() => {
637
+ if (swept) host.event("babysitter.workspaces.swept", { removed: swept });
638
+ host.start();
639
+ redeliverySweep = setInterval(() => void redelivery.sweep().catch((error) => host.error("babysitter.webhook.redelivery_failed", error)), 3e5);
640
+ redeliverySweep.unref();
641
+ if (workspaces) {
642
+ sweepWorkspaces("startup");
643
+ if (workspaces.sweepMs > 0) {
644
+ workspaceSweep = setInterval(() => void sweepWorkspaces("interval"), workspaces.sweepMs);
645
+ workspaceSweep.unref();
646
+ }
647
+ }
648
+ });
649
+ const labels = resolveBabysitterLifecycleFilter(agent.options.filter, agent.options.lifecycle).labels;
650
+ repositories.current().then((current) => ensureBabysitterLabels(github, current, [...labels?.allow ?? [], ...labels?.deny ?? []])).then(({ created, failed }) => {
651
+ if (created.length || failed.length) host.event("babysitter.labels.ensured", {
652
+ created,
653
+ failed
654
+ });
655
+ }, (error) => host.error("babysitter.labels.failed", error));
656
+ },
657
+ async close() {
658
+ clearInterval(workspaceSweep);
659
+ clearInterval(redeliverySweep);
660
+ registerAgentProcessHostIntake(context.agentName, void 0);
661
+ await host.close();
662
+ await inbox.close();
663
+ },
664
+ wake: (reason) => host.wake(reason),
665
+ status: () => host.status(),
666
+ async health() {
667
+ const health = await host.health();
668
+ const queue = await inbox.summary();
669
+ const prerequisites = await preflight();
670
+ if (admissionPrerequisiteSample !== prerequisites.checkedAt) {
671
+ admissionPrerequisiteSample = prerequisites.checkedAt;
672
+ admission.invalidate();
673
+ }
674
+ const guard = await admission.health();
675
+ const lastSkip = await inbox.meta("admission-skipped");
676
+ return {
677
+ ...health,
678
+ status: prerequisites.pause ? "degraded" : health.status,
679
+ diagnostics: [...health.diagnostics, ...prerequisites.diagnostics],
680
+ release: agent.version,
681
+ framework: { buildRevision },
682
+ concurrency: agent.options.concurrency,
683
+ repositories: repositories.known(),
684
+ repositorySource: repositories.source,
685
+ queue: {
686
+ ...babysitterQueueHealth(queue),
687
+ parked: budgetParks(queue)
688
+ },
689
+ admission: {
690
+ accepting: guard.accepting,
691
+ hostOnly: guard.hostOnly,
692
+ reason: guard.reason,
693
+ retryAt: guard.retryAt,
694
+ detail: guard.detail,
695
+ lastSkip,
696
+ history: { lastSkip }
697
+ },
698
+ budget: {
699
+ accounting: guard.accounting,
700
+ observedAt: new Date(guard.observedAt).toISOString(),
701
+ hourly: {
702
+ inputTokens: guard.state.hourlyInputTokens,
703
+ limit: guard.limits.hourlyInputTokens,
704
+ resetsAt: guard.state.windows.hourEnd
705
+ },
706
+ daily: {
707
+ inputTokens: guard.state.dailyInputTokens,
708
+ limit: guard.limits.dailyInputTokens,
709
+ resetsAt: guard.state.windows.dayEnd
710
+ },
711
+ tmp: {
712
+ dir: guard.state.tmpDir,
713
+ freeBytes: guard.state.freeTmpBytes,
714
+ minFreeBytes: guard.limits.minFreeTmpBytes
715
+ },
716
+ pause: guard.state.pause,
717
+ errors: guard.state.errors
718
+ }
719
+ };
720
+ }
721
+ };
722
+ }
723
+ //#endregion
724
+ export { createBabysitterProcessHost };