@vite-hub/presets 0.0.0-stage → 0.1.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.
@@ -0,0 +1,246 @@
1
+ import { a as Snapshot, n as BabysitterAdmissionPause, t as BabysitterAdmissionOptions } from "./admission-DBJdt-CX.js";
2
+ import { AgentDefinition, AgentInvocationContextValues, AgentInvokerProfile, AgentRuntimeConfig, AgentSandboxDefinition, BuiltInAgentDriverName, ConfiguredAgentDefinition } from "@vite-hub/agent";
3
+ import { GitHubPullRequestFilter } from "@vite-hub/agent/channels";
4
+ import { GitHubRequiredCheckState } from "@vite-hub/agent/server/github";
5
+ //#region src/babysitter/result.d.ts
6
+ interface BabysitterResultDiagnostic {
7
+ code: "invalid-wait" | "invalid-wake" | "invalid-reviewed-head" | "invalid-check-head";
8
+ field: string;
9
+ }
10
+ /**
11
+ * Provider output is an untrusted boundary. Keep the required disposition, but
12
+ * normalize optional coordination fields so an invalid wait hint cannot discard
13
+ * an otherwise useful park/retry result (older models frequently omit `kind`).
14
+ */
15
+ declare function createBabysitterPassResultSchema(report?: (diagnostic: BabysitterResultDiagnostic) => void): {
16
+ "~standard": {
17
+ version: 1;
18
+ vendor: string;
19
+ validate(value: unknown): {
20
+ value: BabysitterPassResult;
21
+ } | {
22
+ issues: Array<{
23
+ message: string;
24
+ }>;
25
+ };
26
+ };
27
+ };
28
+ //#endregion
29
+ //#region src/babysitter/merge.d.ts
30
+ type BabysitterMergeMethod = "squash" | "merge" | "rebase";
31
+ interface BabysitterMergeReadinessInput {
32
+ repository: string;
33
+ number: number;
34
+ /** The head SHA that the merge will require. */
35
+ head: string;
36
+ snapshot: Snapshot;
37
+ requiredChecks: GitHubRequiredCheckState;
38
+ }
39
+ /** Return `true` to allow the merge, or a reason that sends the PR to a normal pass. */
40
+ type BabysitterMergeReady = (input: BabysitterMergeReadinessInput) => true | string | Promise<true | string>;
41
+ /**
42
+ * - `false`: never merge.
43
+ * - `"auto"`: the worker may request GitHub native auto-merge.
44
+ * - `"direct"`: the host merges a ready PR before any model pass.
45
+ */
46
+ type BabysitterMerge = false | "auto" | "direct" | {
47
+ strategy: "direct";
48
+ method?: BabysitterMergeMethod;
49
+ ready?: BabysitterMergeReady;
50
+ };
51
+ //#endregion
52
+ //#region src/babysitter.d.ts
53
+ export interface BabysitterLifecycleLabels {
54
+ /** At least one of these labels must be present for the PR to be eligible. */
55
+ require?: readonly string[];
56
+ /** Any of these labels suppresses the PR, even when a required label is present. */
57
+ deny?: readonly string[];
58
+ }
59
+ export interface BabysitterLifecycleOptions {
60
+ labels?: BabysitterLifecycleLabels;
61
+ }
62
+ /** Where one pass runs. A pass without a Sandbox uses the host checkout and the configured `sandbox`. */
63
+ export interface BabysitterPlacementLease {
64
+ /** Sandbox for this pass, for example a custom runtime on another host. */
65
+ sandbox?: AgentSandboxDefinition;
66
+ /** Called once when the pass finishes, fails or is cancelled. */
67
+ release(): void;
68
+ }
69
+ /** Chooses a host for each pass before the Babysitter installs dependencies on this one. */
70
+ export interface BabysitterPlacement {
71
+ place(pullRequest: {
72
+ repository: string;
73
+ number: number;
74
+ }): BabysitterPlacementLease | Promise<BabysitterPlacementLease>;
75
+ /** Passes currently placed on other hosts. They hold a concurrency slot but no local memory. */
76
+ remoteActive?(): number;
77
+ }
78
+ export interface BabysitterOptions {
79
+ /** Process admission policy. Concurrency remains the preset hard maximum. */
80
+ capacity?: Pick<import("@vite-hub/agent/runtime/process").ProcessAgentCapacityOptions, "memory" | "cpu" | "fallbackConcurrency">;
81
+ /**
82
+ * Places each pass on this host or in a Sandbox before host dependency installation. Sandbox passes
83
+ * skip the host install; the Sandbox installs through `refreshDependencies` when it provides one.
84
+ */
85
+ placement?: BabysitterPlacement;
86
+ /** Select PRs with the same rules as the GitHub Channel. */
87
+ filter: GitHubPullRequestFilter;
88
+ /** Additional lifecycle admission rules. Use labels to pause or resume a PR without changing the filter. */
89
+ lifecycle: BabysitterLifecycleOptions;
90
+ /** Provider Driver that repairs each PR in its checkout. Defaults to `"codex"`. Set the model with `driver.model`. */
91
+ driver: BuiltInAgentDriverName;
92
+ /**
93
+ * Merge policy. Defaults to `false`. `"auto"` lets the worker request GitHub native auto-merge.
94
+ * `"direct"` merges a ready PR into its default branch before any model pass.
95
+ */
96
+ merge: BabysitterMerge;
97
+ /**
98
+ * Check names whose pending run means a review is in progress, such as a review bot's check.
99
+ * A parked PR keeps waiting while one runs. Defaults to none.
100
+ */
101
+ reviewChecks: string[];
102
+ /**
103
+ * Body prefixes of comment-only reviews that report no findings, such as a review bot's
104
+ * `"> ✅ No new issues found."`. These reviews do not wake a parked PR. Defaults to none.
105
+ */
106
+ noFindingsReviews: string[];
107
+ /**
108
+ * Logins whose comments and reviews never need an assessment, such as deployment preview bots.
109
+ * Their items do not block a direct merge or wake a waiting PR. Defaults to none.
110
+ */
111
+ ignoreFeedbackAuthors: string[];
112
+ /**
113
+ * Passes on one head that may end without a push or a recorded wait before the PR stops until its
114
+ * head changes or a person comments. `false` disables the budget. Defaults to 3.
115
+ */
116
+ noProgressBudget: number | false;
117
+ /**
118
+ * Review-driven pushes on one PR after which bot feedback and failed `reviewChecks` no longer wake a
119
+ * model pass. A push is review-driven when its pass had no merge conflict and no failing check outside
120
+ * `reviewChecks`. A person's comment or review, another failing check, a conflict or a head that
121
+ * someone else pushed still start a pass. The PR then merges on its required checks or parks with
122
+ * the reason. `false` disables the budget. Defaults to 3.
123
+ */
124
+ reviewPushBudget: number | false;
125
+ /**
126
+ * Model passes on one PR in a rolling 24 hours. After that many, the PR parks until the oldest pass
127
+ * is 24 hours old; its result and the health route show that time. A person's comment or review, the
128
+ * first failing required check on a head and a merge conflict on a PR without failing checks or open
129
+ * threads still start a pass, and count. `false` disables the budget. Defaults to 16.
130
+ */
131
+ dailyPassBudget: number | false;
132
+ /**
133
+ * Wait for running required checks and review checks before a pass, unless a failure or conflict
134
+ * already needs repair. One pass then handles CI and review results together. Defaults to `true`.
135
+ */
136
+ deferWhilePending: boolean;
137
+ /**
138
+ * Install dependencies on the host before the provider starts. `true` detects pnpm, npm or
139
+ * Yarn from the lockfile and installs it frozen. A command overrides the detection. A detected pnpm
140
+ * install reuses the trees of earlier passes. A failed install does not stop the pass unless
141
+ * `required` is set. Defaults to `true`.
142
+ */
143
+ install: BabysitterInstall;
144
+ /** Rerun failed GitHub Actions runs once before a model pass repairs them. Defaults to `true`. */
145
+ ciRecovery: boolean;
146
+ /**
147
+ * Model passes that run at the same time. Set it to what the provider accounts can serve; host
148
+ * work such as merges and stack retargets still uses `concurrency`. Defaults to `concurrency`.
149
+ */
150
+ modelConcurrency?: number;
151
+ /**
152
+ * First cooldown after a pass runs out of provider rate-limit retries. Model passes pause; host work
153
+ * continues. Each further cooldown doubles, up to one hour, and halves model concurrency. A
154
+ * success 30 minutes after the last cooldown removes one step. Defaults to 300000 (five minutes).
155
+ */
156
+ providerCooldownMs: number;
157
+ /** GitHub logins the worker may notify through its explicit mention capability. Defaults to none. */
158
+ mentionAllowlist: string[];
159
+ /** PRs repaired at the same time. Defaults to 1. */
160
+ concurrency: number;
161
+ /**
162
+ * Token budgets, a free-space guard and custom checks that gate model passes. A spent limit
163
+ * stops model passes; direct merges and recorded waits continue. Defaults to no token limit
164
+ * and 4096 MiB of free temporary space.
165
+ */
166
+ admission: BabysitterAdmissionOptions;
167
+ }
168
+ /**
169
+ * Dependency install before each pass. `true` detects the package manager from the lockfile;
170
+ * `false` skips the install.
171
+ */
172
+ export type BabysitterInstall = boolean | {
173
+ /** Install command. Defaults to the package manager detected from the lockfile. */
174
+ command?: string;
175
+ args?: string[];
176
+ /**
177
+ * Reuse the node_modules trees of a detected pnpm install across passes with the same lockfile,
178
+ * using independent copy-on-write copies on Linux. `directory` defaults to `BABYSITTER_INSTALL_CACHE` or
179
+ * `<tmpdir>/vitehub-install-cache` and must share a filesystem with the pass workspaces. The default
180
+ * directory is used only when it supports reflinks; a configured `directory` is used on any filesystem.
181
+ * `entries` defaults to `BABYSITTER_INSTALL_CACHE_ENTRIES` or 8. `false` disables the cache.
182
+ */
183
+ cache?: false | {
184
+ directory?: string;
185
+ entries?: number;
186
+ };
187
+ /**
188
+ * Detected installs that run at the same time across passes. A pass waits up to ten minutes for a
189
+ * free slot and keeps its checkout while it waits. Defaults to 2.
190
+ */
191
+ concurrency?: number;
192
+ /**
193
+ * `false` continues a pass without dependencies when the install fails: the model reads the
194
+ * failure in `.git/vitehub-install.json`, repairs the PR's lockfile or manifests or relies on hosted
195
+ * CI, and commits without local dependency verification. `true` parks the PR on the failure until
196
+ * its inputs change. Defaults to `false`.
197
+ */
198
+ required?: boolean;
199
+ };
200
+ export type BabysitterPassWake = {
201
+ kind: "checks";
202
+ repository: string;
203
+ headSha: string;
204
+ } | {
205
+ kind: "pull-request";
206
+ repository: string;
207
+ number: number;
208
+ };
209
+ export type BabysitterPassWait = {
210
+ kind: "checks";
211
+ headSha: string;
212
+ } | {
213
+ kind: "external";
214
+ reason: string;
215
+ wake?: BabysitterPassWake;
216
+ };
217
+ export interface BabysitterPassResult {
218
+ disposition: "park" | "retry";
219
+ text: string;
220
+ /** Structured external dependency. The host never interprets result prose as control flow. */
221
+ wait?: BabysitterPassWait;
222
+ /** Current HEAD whose full feedback and failed checks were inspected and addressed. */
223
+ reviewedHead?: string;
224
+ /** Legacy explicit check checkpoint, accepted while existing provider output migrates. */
225
+ waitForChecksHead?: string;
226
+ }
227
+ export declare const babysitterPassResultSchema: ReturnType<typeof createBabysitterPassResultSchema>;
228
+ /** A repair workflow. Connections, provider settings and host resources stay in the application. */
229
+ type BabysitterDefinition = AgentDefinition<AgentRuntimeConfig, unknown, AgentInvokerProfile, AgentInvocationContextValues, BabysitterPassResult> & {
230
+ reviewChecks: string[];
231
+ noFindingsReviews: string[];
232
+ ignoreFeedbackAuthors: string[];
233
+ noProgressBudget: number | false;
234
+ reviewPushBudget: number | false;
235
+ dailyPassBudget: number | false;
236
+ deferWhilePending: boolean;
237
+ install: BabysitterInstall;
238
+ mentionAllowlist: string[];
239
+ lifecycle: BabysitterLifecycleOptions;
240
+ };
241
+ export type BabysitterAgent = ConfiguredAgentDefinition<BabysitterOptions, BabysitterDefinition>;
242
+ /** Combines explicit lifecycle labels with the shared GitHub PR filter. */
243
+ export declare function resolveBabysitterLifecycleFilter(filter: GitHubPullRequestFilter, lifecycle: BabysitterLifecycleOptions | undefined): GitHubPullRequestFilter;
244
+ export declare const babysitter: BabysitterAgent;
245
+ //#endregion
246
+ export type { BabysitterAdmissionOptions, BabysitterAdmissionPause, BabysitterMerge, BabysitterMergeMethod, BabysitterMergeReadinessInput, BabysitterMergeReady };
@@ -0,0 +1,2 @@
1
+ import { n as babysitterPassResultSchema, r as resolveBabysitterLifecycleFilter, t as babysitter } from "./babysitter-B4D1zeYf.js";
2
+ export { babysitter, babysitterPassResultSchema, resolveBabysitterLifecycleFilter };
@@ -0,0 +1,438 @@
1
+ import { _ as hasRuntimeType, a as createBabysitterAdmission, o as resolveBabysitterAdmissionLimits, y as isRuntimeRecord } from "./babysitter-B4D1zeYf.js";
2
+ import { r as budgetParks, t as createBabysitterRuntime } from "./server-DDmyZ98B.js";
3
+ import { defineAgent } from "@vite-hub/agent";
4
+ import { access, lstat, mkdtemp, open, readFile, readdir, rename, rm, stat } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { channelEnv } from "@vite-hub/agent/channels";
7
+ import { registerAgentProcessHostIntake } from "@vite-hub/agent/process-host";
8
+ import { execFile } from "node:child_process";
9
+ import { promisify } from "node:util";
10
+ import { constants } from "node:fs";
11
+ import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
12
+ import { createGitHubAppCredentials, createGitHubHost } from "@vite-hub/agent/server/github";
13
+ import { createProcessAgentHost } from "@vite-hub/agent/runtime/process";
14
+ //#region src/babysitter/preflight.ts
15
+ const execute = promisify(execFile);
16
+ async function validateExecutable(path) {
17
+ await access(path, constants.X_OK);
18
+ if (!(await stat(path)).isFile()) throw new Error(`Executable is not a file: ${path}`);
19
+ if (process.platform !== "win32") {
20
+ const file = await open(path, "r");
21
+ const buffer = Buffer.alloc(256);
22
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0).finally(() => file.close());
23
+ const bytes = buffer.subarray(0, bytesRead);
24
+ if (!(bytes[0] === 35 && bytes[1] === 33)) {
25
+ const elf = bytes[0] === 127 && bytes[1] === 69 && bytes[2] === 76 && bytes[3] === 70;
26
+ const macho = [
27
+ [
28
+ 254,
29
+ 237,
30
+ 250,
31
+ 206
32
+ ],
33
+ [
34
+ 206,
35
+ 250,
36
+ 237,
37
+ 254
38
+ ],
39
+ [
40
+ 254,
41
+ 237,
42
+ 250,
43
+ 207
44
+ ],
45
+ [
46
+ 207,
47
+ 250,
48
+ 237,
49
+ 254
50
+ ],
51
+ [
52
+ 202,
53
+ 254,
54
+ 186,
55
+ 190
56
+ ],
57
+ [
58
+ 190,
59
+ 186,
60
+ 254,
61
+ 202
62
+ ],
63
+ [
64
+ 202,
65
+ 254,
66
+ 186,
67
+ 191
68
+ ],
69
+ [
70
+ 191,
71
+ 186,
72
+ 254,
73
+ 202
74
+ ]
75
+ ].some((magic) => magic.every((byte, index) => bytes[index] === byte));
76
+ if (!elf && !macho) throw new Error(`Executable has no interpreter: ${path}`);
77
+ } else {
78
+ const header = bytes.toString("utf8");
79
+ const parts = header.slice(2, header.indexOf("\n") < 0 ? void 0 : header.indexOf("\n")).trim().split(/\s+/).filter(Boolean);
80
+ 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];
81
+ if (!interpreter) throw new Error(`Executable has no interpreter: ${path}`);
82
+ await resolveExecutable(interpreter);
83
+ }
84
+ }
85
+ }
86
+ async function resolveExecutable(program) {
87
+ if (isAbsolute(program) || program.includes("/") || program.includes("\\")) {
88
+ await validateExecutable(program);
89
+ return;
90
+ }
91
+ const path = process.env.PATH ?? "";
92
+ 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(";")] : [""];
93
+ for (const directory of path.split(delimiter)) for (const extension of extensions) {
94
+ const candidate = join(directory || ".", `${program}${extension}`);
95
+ try {
96
+ await access(candidate, constants.X_OK);
97
+ } catch {
98
+ continue;
99
+ }
100
+ await validateExecutable(candidate);
101
+ return;
102
+ }
103
+ throw new Error(`Executable not found: ${program}`);
104
+ }
105
+ /** Cached host prerequisites. Failed checks recover without restarting webhook intake. */
106
+ function createBabysitterPreflight(install, checkCommand = async (program, probe = "version") => {
107
+ if (probe === "path") await resolveExecutable(program);
108
+ else await execute(program, ["--version"], {
109
+ timeout: 5e3,
110
+ maxBuffer: 65536
111
+ });
112
+ }) {
113
+ let cached;
114
+ let expiresAt = 0;
115
+ let pending;
116
+ return async () => {
117
+ if (cached && Date.now() < expiresAt) return cached;
118
+ pending ??= (async () => {
119
+ const diagnostics = [];
120
+ const commands = ["git"];
121
+ if (install !== false) {
122
+ const installer = (isRuntimeRecord(install) ? install.command : void 0) ?? "corepack";
123
+ if (installer) {
124
+ if ((isAbsolute(installer) || !installer.includes("/") && !installer.includes("\\")) && !commands.includes(installer)) commands.push(installer);
125
+ }
126
+ }
127
+ for (const program of commands) try {
128
+ await checkCommand(program, program === "git" || program === "corepack" ? "version" : "path");
129
+ diagnostics.push({
130
+ label: `Host ${program}`,
131
+ status: "ok",
132
+ value: "Available"
133
+ });
134
+ } catch {
135
+ const display = program === "git" ? "Git" : program === "corepack" ? "Corepack" : program;
136
+ diagnostics.push({
137
+ label: `Host ${program}`,
138
+ status: "warning",
139
+ value: "Unavailable",
140
+ detail: `Install ${display} in the trusted host service PATH. Model passes wait until this check succeeds.`
141
+ });
142
+ }
143
+ const failures = diagnostics.filter((item) => item.status === "warning");
144
+ const result = {
145
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
146
+ diagnostics
147
+ };
148
+ if (failures.length) result.pause = {
149
+ reason: "host-prerequisite",
150
+ detail: failures.map((item) => item.detail).join(" "),
151
+ retryAt: Date.now() + 3e4
152
+ };
153
+ cached = result;
154
+ expiresAt = Date.now() + (failures.length ? 3e4 : 3e5);
155
+ return result;
156
+ })();
157
+ try {
158
+ return await pending;
159
+ } finally {
160
+ pending = void 0;
161
+ }
162
+ };
163
+ }
164
+ //#endregion
165
+ //#region src/babysitter/queue-health.ts
166
+ /** Derive bounded operational counters from the durable queue, including scheduled retries. */
167
+ function babysitterQueueHealth(items, now = Date.now()) {
168
+ const mergedTerminal = (result) => result?.startsWith("Merged ") || result === "Asynchronous merge confirmed by GitHub." || result === "Direct merge outcome reconciled: GitHub reports the pull request merged.";
169
+ const ready = items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt <= now);
170
+ const waiting = items.filter((item) => item.status === "waiting");
171
+ return {
172
+ working: items.filter((item) => item.status === "working").length,
173
+ ready: ready.length,
174
+ scheduled: items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt > now).length,
175
+ stackBlocked: items.filter((item) => item.stackBlocked).length,
176
+ waiting: waiting.length,
177
+ suppressed: items.filter((item) => item.status === "terminal" && item.state === "open" && !mergedTerminal(item.lastResult)).length,
178
+ oldestReadyAgeMs: ready.reduce((age, item) => Math.max(age, item.dirtyAt === void 0 ? 0 : now - item.dirtyAt), 0),
179
+ blockers: {
180
+ checks: waiting.filter((item) => item.wait && item.wait.kind !== "external" && !item.wait.wake).length,
181
+ dependency: waiting.filter((item) => item.wait?.wake).length,
182
+ manual: waiting.filter((item) => item.wait?.kind === "external" && !item.wait.wake && item.wait.retryAt === void 0).length,
183
+ timed: waiting.filter((item) => item.wait?.retryAt !== void 0).length,
184
+ installCapacity: waiting.filter((item) => item.wait?.reasonCode === "install-capacity").length,
185
+ noProgress: waiting.filter((item) => item.progressBudget?.exhausted && item.progressBudget.head === item.head).length
186
+ }
187
+ };
188
+ }
189
+ //#endregion
190
+ //#region src/babysitter/host.ts
191
+ /** Reads a plain or sealed Server Env value. */
192
+ function envString(value) {
193
+ const plain = isRuntimeRecord(value) && hasRuntimeType(value.unseal, "function") ? value.unseal() : value;
194
+ if (hasRuntimeType(plain, "number")) return String(plain);
195
+ return hasRuntimeType(plain, "string") && plain.trim() ? plain.trim() : void 0;
196
+ }
197
+ /** Accept PEM secrets from systemd and dotenv files that encode newlines as `\\n`. */
198
+ function normalizePrivateKey(value) {
199
+ return value?.replace(/\\n/g, "\n");
200
+ }
201
+ /**
202
+ * Remove the persistent checkout pool created by older Babysitter releases.
203
+ *
204
+ * Current GitHub hosts use a disposable checkout for each pass. The old pool
205
+ * retained merged and closed PR workspaces, including installed dependencies,
206
+ * under the owning process host data directory; remove that pool as one unit.
207
+ */
208
+ async function cleanupLegacyBabysitterCheckouts(dataDir) {
209
+ const root = join(dataDir, "checkouts");
210
+ const info = await lstat(root, { bigint: true }).catch((error) => {
211
+ if (error.code === "ENOENT") return void 0;
212
+ throw error;
213
+ });
214
+ if (!info) return 0;
215
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`[vitehub] Refusing to clean unsafe Babysitter checkout pool: ${root}`);
216
+ const quarantine = await mkdtemp(join(dataDir, ".checkouts-cleanup-"));
217
+ const claimed = join(quarantine, "checkouts");
218
+ await rename(root, claimed);
219
+ const claimedInfo = await lstat(claimed, { bigint: true });
220
+ if (!claimedInfo.isDirectory() || claimedInfo.dev !== info.dev || claimedInfo.ino !== info.ino) throw new Error(`[vitehub] Refusing to clean replaced Babysitter checkout pool: ${claimed}`);
221
+ const entries = await readdir(claimed, { withFileTypes: true });
222
+ await promisify(execFile)(process.execPath, [
223
+ "--input-type=module",
224
+ "--eval",
225
+ `
226
+ import { lstat, readdir, rm } from "node:fs/promises";
227
+ const info = await lstat(".", { bigint: true });
228
+ if (String(info.dev) !== process.argv[1] || String(info.ino) !== process.argv[2]) {
229
+ throw new Error("Refusing to clean replaced Babysitter checkout pool");
230
+ }
231
+ for (const entry of await readdir(".")) {
232
+ await rm(entry, { force: true, recursive: true, maxRetries: 5, retryDelay: 100 });
233
+ }
234
+ `,
235
+ String(info.dev),
236
+ String(info.ino)
237
+ ], { cwd: claimed });
238
+ const remaining = await lstat(claimed, { bigint: true });
239
+ if (remaining.dev !== info.dev || remaining.ino !== info.ino) throw new Error(`[vitehub] Refusing to clean replaced Babysitter checkout pool: ${claimed}`);
240
+ return entries.length;
241
+ }
242
+ /** GitHub App settings from `env.server.github` or the VITEHUB_GITHUB_* variables. */
243
+ async function readGitHubAppEnvironment(context = {}) {
244
+ const env = await channelEnv("github", context);
245
+ const appId = Number(envString(env.appId));
246
+ const keyPath = envString(env.privateKeyPath);
247
+ const privateKey = normalizePrivateKey(envString(env.privateKey) ?? (keyPath ? (await readFile(keyPath, "utf8")).trim() : void 0));
248
+ const installation = envString(env.installationId);
249
+ if (!Number.isSafeInteger(appId) || appId <= 0 || !privateKey) throw new Error("[vitehub] The Babysitter needs a GitHub App: set VITEHUB_GITHUB_APP_ID and VITEHUB_GITHUB_PRIVATE_KEY (or VITEHUB_GITHUB_PRIVATE_KEY_PATH).");
250
+ const app = {
251
+ appId,
252
+ privateKey
253
+ };
254
+ if (installation) app.installationId = Number(installation);
255
+ app.owner = envString(env.appOwner)?.toLowerCase();
256
+ const configuredInstallations = envString(env.appInstallations);
257
+ if (configuredInstallations) {
258
+ const mappings = JSON.parse(configuredInstallations);
259
+ if (!isRuntimeRecord(mappings) || Array.isArray(mappings)) throw new Error("VITEHUB_GITHUB_APP_INSTALLATIONS must be an owner-to-installation object.");
260
+ app.installations = Object.fromEntries(Object.entries(mappings).map(([owner, id]) => {
261
+ const installationId = Number(id);
262
+ if (!Number.isSafeInteger(installationId) || installationId <= 0) throw new Error(`Invalid GitHub installation for ${owner}.`);
263
+ return [owner.toLowerCase(), installationId];
264
+ }));
265
+ }
266
+ if (!app.owner) delete app.installationId;
267
+ return app;
268
+ }
269
+ /** The repositories that the PR filter allows. The Babysitter discovers open PRs only there. */
270
+ function babysitterRepositories(filter) {
271
+ const allow = isRuntimeRecord(filter) && isRuntimeRecord(filter.repository) ? filter.repository.allow : void 0;
272
+ const repositories = Array.isArray(allow) ? allow.filter((value) => hasRuntimeType(value, "string") && /^[\w.-]+\/[\w.-]+$/.test(value)) : [];
273
+ if (!repositories.length) throw new Error("[vitehub] Set options.filter.repository.allow to the \"owner/name\" repositories that the Babysitter serves.");
274
+ return repositories.map((repository) => repository.toLowerCase());
275
+ }
276
+ 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})$/;
277
+ /**
278
+ * Removes pass workspaces that an interrupted process left in `root`. It sweeps only a temporary
279
+ * directory inside the service's working directory, which no other process shares, and keeps
280
+ * anything this process created.
281
+ */
282
+ async function sweepBabysitterWorkspaces(root = tmpdir(), startedAt = performance.timeOrigin, cwd = process.cwd()) {
283
+ if (!resolve(root).startsWith(`${resolve(cwd)}${sep}`)) return 0;
284
+ let removed = 0;
285
+ for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
286
+ if (!passWorkspace.test(entry.name)) continue;
287
+ const path = join(root, entry.name);
288
+ const info = await lstat(path).catch(() => void 0);
289
+ if (!info || info.mtimeMs >= startedAt) continue;
290
+ await rm(path, {
291
+ force: true,
292
+ recursive: true,
293
+ maxRetries: 3
294
+ }).then(() => removed++, () => {});
295
+ }
296
+ return removed;
297
+ }
298
+ /** Builds the GitHub host, process host, inbox, and reconciler for one discovered Babysitter Agent. */
299
+ async function createBabysitterProcessHost(context) {
300
+ const agent = context.agent;
301
+ const repositories = babysitterRepositories(agent.options.filter);
302
+ await cleanupLegacyBabysitterCheckouts(context.dataDir);
303
+ const app = await readGitHubAppEnvironment();
304
+ const credentials = createGitHubAppCredentials(app);
305
+ const identity = await credentials.identity();
306
+ const github = createGitHubHost({
307
+ credentials: credentials.credentials,
308
+ identity
309
+ });
310
+ let runtime;
311
+ const host = await createProcessAgentHost({
312
+ name: context.agentName,
313
+ dataDir: context.dataDir,
314
+ invocations: agent.invocations,
315
+ invocationAgentName: `${context.agentName}-worker`,
316
+ capacity: {
317
+ ...agent.options.capacity,
318
+ ...agent.options.placement?.remoteActive ? { remoteActive: () => agent.options.placement?.remoteActive?.() ?? 0 } : {},
319
+ concurrency: agent.options.concurrency,
320
+ queue: {
321
+ maxPending: agent.options.concurrency,
322
+ timeout: 36e5
323
+ }
324
+ },
325
+ intervalMs: 1e4,
326
+ run: async (reason, run, accepting) => await runtime?.reconcile(reason, run, accepting)
327
+ });
328
+ const preflight = createBabysitterPreflight(agent.options.install ?? true);
329
+ const buildRevision = "6c9df4004457f5ecbb5c864a1de27e4864828d9125592c9c89c99bd88fc810b2";
330
+ const admission = createBabysitterAdmission({
331
+ invocations: host.invocations,
332
+ limits: resolveBabysitterAdmissionLimits(agent.options.admission),
333
+ check: async () => (await preflight()).pause ?? await agent.options.admission?.check?.()
334
+ });
335
+ let admissionPrerequisiteSample;
336
+ const worker = defineAgent({
337
+ extends: agent,
338
+ invocations: host.invocations,
339
+ driver: {
340
+ capacity: host.capacity,
341
+ sessionStorePath: host.providerSessionStorePath
342
+ }
343
+ });
344
+ runtime = createBabysitterRuntime({
345
+ agent: worker,
346
+ agentName: context.agentName,
347
+ github,
348
+ inboxStorage: context.state.extension("babysitter"),
349
+ inboxScope: context.agentName,
350
+ repositories,
351
+ concurrency: agent.options.concurrency,
352
+ activityAuthors: [identity.login],
353
+ event: host.event,
354
+ error: host.error,
355
+ wake: () => host.wake(),
356
+ admission
357
+ });
358
+ const inbox = runtime.inbox;
359
+ const swept = await sweepBabysitterWorkspaces();
360
+ return {
361
+ start() {
362
+ registerAgentProcessHostIntake(context.agentName, async ({ deliveryId, event, payload }) => {
363
+ const result = await inbox.ingest(deliveryId, event, payload);
364
+ if (result.updated.length) host.wake("webhook");
365
+ return Response.json(result, { status: 202 });
366
+ });
367
+ inbox.importLegacyFile(".vitehub/pull-request-inbox.sqlite").catch((error) => host.error("babysitter.legacy-import.failed", error)).then(() => inbox.releaseLeases()).then((released) => {
368
+ if (released) host.event("babysitter.leases.released", { released });
369
+ }, (error) => host.error("babysitter.leases.release-failed", error)).finally(() => {
370
+ if (swept) host.event("babysitter.workspaces.swept", { removed: swept });
371
+ host.start();
372
+ });
373
+ },
374
+ async close() {
375
+ registerAgentProcessHostIntake(context.agentName, void 0);
376
+ await host.close();
377
+ await inbox.close();
378
+ },
379
+ wake: (reason) => host.wake(reason),
380
+ status: () => host.status(),
381
+ async health() {
382
+ const health = await host.health();
383
+ const queue = await inbox.summary();
384
+ const prerequisites = await preflight();
385
+ if (admissionPrerequisiteSample !== prerequisites.checkedAt) {
386
+ admissionPrerequisiteSample = prerequisites.checkedAt;
387
+ admission.invalidate();
388
+ }
389
+ const guard = await admission.health();
390
+ const lastSkip = await inbox.meta("admission-skipped");
391
+ return {
392
+ ...health,
393
+ status: prerequisites.pause ? "degraded" : health.status,
394
+ diagnostics: [...health.diagnostics, ...prerequisites.diagnostics],
395
+ release: agent.version,
396
+ framework: { buildRevision },
397
+ concurrency: agent.options.concurrency,
398
+ repositories,
399
+ queue: {
400
+ ...babysitterQueueHealth(queue),
401
+ parked: budgetParks(queue)
402
+ },
403
+ admission: {
404
+ accepting: guard.accepting,
405
+ hostOnly: guard.hostOnly,
406
+ reason: guard.reason,
407
+ retryAt: guard.retryAt,
408
+ detail: guard.detail,
409
+ lastSkip,
410
+ history: { lastSkip }
411
+ },
412
+ budget: {
413
+ accounting: guard.accounting,
414
+ observedAt: new Date(guard.observedAt).toISOString(),
415
+ hourly: {
416
+ inputTokens: guard.state.hourlyInputTokens,
417
+ limit: guard.limits.hourlyInputTokens,
418
+ resetsAt: guard.state.windows.hourEnd
419
+ },
420
+ daily: {
421
+ inputTokens: guard.state.dailyInputTokens,
422
+ limit: guard.limits.dailyInputTokens,
423
+ resetsAt: guard.state.windows.dayEnd
424
+ },
425
+ tmp: {
426
+ dir: guard.state.tmpDir,
427
+ freeBytes: guard.state.freeTmpBytes,
428
+ minFreeBytes: guard.limits.minFreeTmpBytes
429
+ },
430
+ pause: guard.state.pause,
431
+ errors: guard.state.errors
432
+ }
433
+ };
434
+ }
435
+ };
436
+ }
437
+ //#endregion
438
+ export { createBabysitterProcessHost };