omp-superagent 0.1.6 → 0.1.8
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/DESIGN.md +36 -20
- package/README.ko.md +140 -33
- package/README.md +165 -41
- package/THIRD_PARTY_NOTICES.md +9 -7
- package/config.example.json +3 -1
- package/docs/OPERATIONS.md +395 -157
- package/docs/design/execution.md +156 -22
- package/docs/design/messaging.md +258 -52
- package/docs/discord-voice.md +8 -4
- package/docs/releases/0.1.7.md +25 -0
- package/docs/releases/0.1.8.md +21 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +9 -9
- package/scripts/ci.ts +4 -4
- package/scripts/test-omp.sh +2 -1
- package/skills/head/SKILL.md +26 -5
- package/skills/head/references/routing.md +68 -33
- package/skills/head/references/supervision.md +20 -4
- package/skills/lane/references/workflow.md +16 -7
- package/src/board.ts +5 -3
- package/src/cli.ts +161 -19
- package/src/config.ts +21 -1
- package/src/contracts.ts +63 -8
- package/src/cron-jobs.ts +443 -19
- package/src/cron-pr-intake.ts +257 -0
- package/src/discord-markdown.ts +350 -123
- package/src/extension.ts +78 -13
- package/src/gateway-client.ts +8 -2
- package/src/head-quota.ts +80 -0
- package/src/head-recovery.ts +40 -1
- package/src/host-extension.ts +122 -4
- package/src/host-inventory-manifest.ts +2 -2
- package/src/host-protocol.ts +11 -0
- package/src/host-sdk-helper.ts +121 -12
- package/src/host.ts +175 -57
- package/src/installed-omp.ts +116 -4
- package/src/lane-rows.ts +44 -4
- package/src/lane-watch.ts +339 -0
- package/src/managed-memory-helper.ts +13 -10
- package/src/managed-memory.ts +62 -27
- package/src/managed-ulw-probe.ts +75 -20
- package/src/managed-ulw.ts +174 -21
- package/src/messenger-command-catalog.json +2 -2
- package/src/native-launch-profile.ts +4 -2
- package/src/native-presets.ts +32 -5
- package/src/native-sessions.ts +3 -1
- package/src/native-settings.ts +47 -9
- package/src/observation-request.ts +23 -0
- package/src/omp-usage.ts +254 -36
- package/src/pr-github-schema.ts +5 -1
- package/src/pr-github.ts +68 -19
- package/src/pr-intake-automation.ts +316 -0
- package/src/pr-intake-comment.ts +226 -0
- package/src/pr-intake-fix.ts +233 -0
- package/src/pr-intake-github.ts +480 -0
- package/src/pr-intake-material.ts +230 -0
- package/src/pr-intake-mode.ts +59 -0
- package/src/pr-intake-review.ts +397 -0
- package/src/pr-intake-tree.ts +69 -0
- package/src/pr-intake-work.ts +29 -0
- package/src/pr-watch.ts +91 -32
- package/src/runtime.ts +2702 -391
- package/src/setup-judge.ts +1 -1
- package/src/setup.ts +12 -16
- package/src/store.ts +429 -86
- package/src/topic-history.ts +243 -47
- package/src/worker-checkout.ts +106 -0
- package/src/worker-destination.ts +10 -0
- package/src/worker-doctor.ts +66 -0
- package/src/worker-enrollment.ts +165 -0
- package/src/worker-host.ts +180 -0
- package/src/worker-ledger.ts +188 -0
- package/src/worker-placement.ts +78 -0
- package/src/worker-profile.ts +274 -0
- package/src/worker-registration.ts +288 -0
- package/src/worker-repository.ts +233 -0
- package/src/worker-request.ts +74 -0
- package/src/worker-service.ts +230 -0
- package/src/worker-stdio.ts +61 -0
- package/src/worker-trust.ts +36 -0
- package/src/worker-wire.ts +204 -0
- package/src/workflow.ts +81 -32
- package/src/setup-memory.ts +0 -21
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, realpathSync,
|
|
4
|
+
unlinkSync, writeFileSync,
|
|
5
|
+
} from "node:fs";
|
|
6
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { Type } from "@sinclair/typebox/type";
|
|
9
|
+
import { Value } from "@sinclair/typebox/value";
|
|
10
|
+
import { stagePrivateFile } from "./credentials";
|
|
11
|
+
import {
|
|
12
|
+
checkWorkerFile, readWorkerFile, shellWord, withWorkerWriteLock, workerDirectory,
|
|
13
|
+
workerHash, workerPublicKey, WorkerRegistrationError,
|
|
14
|
+
} from "./worker-registration";
|
|
15
|
+
import { gitWorkerRepository, workerRepositoryIdentity } from "./worker-repository";
|
|
16
|
+
import { trustedWorkerPath, workerInstallRoot } from "./worker-trust";
|
|
17
|
+
import type { WorkerPolicy, WorkerRepo } from "./worker-wire";
|
|
18
|
+
|
|
19
|
+
const policyRoot = ".omp-sa-worker";
|
|
20
|
+
const policyFile = "policy.json";
|
|
21
|
+
const hashPattern = "^[0-9a-f]{64}$";
|
|
22
|
+
const maxRepositories = 128;
|
|
23
|
+
const controls = /[\u0000-\u001f\u007f]/;
|
|
24
|
+
const policySchema = Type.Object({
|
|
25
|
+
fingerprint: Type.String({ pattern: hashPattern }),
|
|
26
|
+
workerId: Type.String({ pattern: "^worker-[0-9a-f-]{36}$" }),
|
|
27
|
+
stateDir: Type.String(),
|
|
28
|
+
repos: Type.Array(Type.Object({ id: Type.String({ pattern: hashPattern }), cwd: Type.String() }, { additionalProperties: false }),
|
|
29
|
+
{ minItems: 1, maxItems: maxRepositories }),
|
|
30
|
+
capacity: Type.Literal(1),
|
|
31
|
+
command: Type.Tuple([Type.String()]),
|
|
32
|
+
}, { additionalProperties: false });
|
|
33
|
+
|
|
34
|
+
function policyAt(path: string) {
|
|
35
|
+
const bytes = readWorkerFile(path);
|
|
36
|
+
if (bytes === undefined) return;
|
|
37
|
+
const stored: unknown = JSON.parse(bytes.toString("utf8"));
|
|
38
|
+
if (!Value.Check(policySchema, stored) || stored.stateDir !== dirname(path) ||
|
|
39
|
+
basename(stored.stateDir) !== stored.fingerprint.slice(0, 16) ||
|
|
40
|
+
controls.test(stored.stateDir) || controls.test(stored.workerId) ||
|
|
41
|
+
!isAbsolute(stored.command[0]) || controls.test(stored.command[0]) ||
|
|
42
|
+
stored.repos.some(repo => !isAbsolute(repo.cwd) || controls.test(repo.cwd) || controls.test(repo.id)) ||
|
|
43
|
+
new Set(stored.repos.map(repo => repo.id)).size !== stored.repos.length)
|
|
44
|
+
throw new WorkerRegistrationError("Invalid target worker policy");
|
|
45
|
+
return stored;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function enrollmentAuthorization(path: string, key: string, repos: WorkerPolicy["repos"]): string {
|
|
49
|
+
trustedWorkerPath(workerInstallRoot, repos, "directory");
|
|
50
|
+
const cli = trustedWorkerPath(fileURLToPath(new URL("./cli.ts", import.meta.url)), repos, "file");
|
|
51
|
+
const bun = trustedWorkerPath(realpathSync(process.execPath), repos, "file");
|
|
52
|
+
const argv = [bun, "--no-env-file", cli, "worker", "serve", "--policy", path].map(shellWord);
|
|
53
|
+
const command = `exec ${argv.join(" ")}`.replaceAll('"', '\\"');
|
|
54
|
+
return `restrict,command="${command}" ${key} omp-sa-worker`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function authorizationSnapshot(path: string, key: string, expected: string, hasPolicy: boolean) {
|
|
58
|
+
const baseline = readWorkerFile(path, 0o644);
|
|
59
|
+
const text = baseline ? new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(baseline) : "";
|
|
60
|
+
if (text.includes("\0")) throw new WorkerRegistrationError("Invalid target authorized_keys");
|
|
61
|
+
// OpenSSH permits whitespace between the key fields, comments, and options.
|
|
62
|
+
// Conservatively refuse any noncomment occurrence except our exact sole entry.
|
|
63
|
+
const blob = key.slice("ssh-ed25519 ".length).replaceAll("+", "\\+");
|
|
64
|
+
const keyFields = new RegExp(`(?:^|\\s)ssh-ed25519\\s+${blob}(?=\\s|$)`);
|
|
65
|
+
const sameKey = text.split(/\r?\n/).filter(line => !line.trimStart().startsWith("#") && keyFields.test(line));
|
|
66
|
+
if (sameKey.length) {
|
|
67
|
+
if (hasPolicy && sameKey.length === 1 && sameKey[0] === expected) return null;
|
|
68
|
+
throw new WorkerRegistrationError("The supplied key already exists with a different or duplicate authorization; no authorization was overwritten");
|
|
69
|
+
}
|
|
70
|
+
return { baseline };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Never replace or rewrite an existing authorization file, including its permissions. */
|
|
74
|
+
function appendAuthorization(path: string, expected: string, baseline: Buffer | undefined): void {
|
|
75
|
+
const flags = constants.O_APPEND | constants.O_NONBLOCK | constants.O_NOFOLLOW;
|
|
76
|
+
const fd = baseline ? openSync(path, flags | constants.O_RDWR)
|
|
77
|
+
: openSync(path, flags | constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
|
|
78
|
+
try {
|
|
79
|
+
if (baseline) {
|
|
80
|
+
const original = fstatSync(fd);
|
|
81
|
+
checkWorkerFile(original, 0o644);
|
|
82
|
+
const named = lstatSync(path);
|
|
83
|
+
if (original.dev !== named.dev || original.ino !== named.ino || !readFileSync(fd).equals(baseline))
|
|
84
|
+
throw new WorkerRegistrationError("authorized_keys changed during enrollment; no authorization was overwritten");
|
|
85
|
+
}
|
|
86
|
+
writeFileSync(fd, `${baseline?.length && baseline.at(-1) !== 10 ? "\n" : ""}${expected}\n`);
|
|
87
|
+
fsyncSync(fd);
|
|
88
|
+
} finally { closeSync(fd); }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function targetRepositories(paths: readonly string[], directory: string): Promise<WorkerRepo[]> {
|
|
92
|
+
const repos: WorkerRepo[] = [];
|
|
93
|
+
const inside = (root: string, path: string) => root === path || path.startsWith(root === "/" ? "/" : `${root}/`);
|
|
94
|
+
for (const path of paths) {
|
|
95
|
+
const cwd = realpathSync(path);
|
|
96
|
+
if (controls.test(cwd) || !lstatSync(cwd).isDirectory() ||
|
|
97
|
+
await gitWorkerRepository(cwd, ["rev-parse", "--show-toplevel"]) !== `${cwd}\n`)
|
|
98
|
+
throw new WorkerRegistrationError("Each --repo must be the root of an existing non-bare Git checkout");
|
|
99
|
+
if (inside(cwd, directory) || inside(directory, cwd))
|
|
100
|
+
throw new WorkerRegistrationError("Worker state and enrolled Git checkouts must not overlap");
|
|
101
|
+
const id = await workerRepositoryIdentity(cwd);
|
|
102
|
+
if (!id || repos.some(repo => repo.id === id))
|
|
103
|
+
throw new WorkerRegistrationError("Each enrolled Git checkout needs a distinct verifiable network origin");
|
|
104
|
+
repos.push({ id, cwd });
|
|
105
|
+
}
|
|
106
|
+
return repos.sort((left, right) => left.id.localeCompare(right.id));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Explicit target-side authorization; the CLI separately checks native prerequisites. */
|
|
110
|
+
export async function enrollWorker(options: {
|
|
111
|
+
readonly home: string; readonly headKey: string; readonly repositories: readonly string[]; readonly executable: string;
|
|
112
|
+
}): Promise<WorkerPolicy> {
|
|
113
|
+
const key = workerPublicKey(options.headKey);
|
|
114
|
+
const fingerprint = workerHash(key);
|
|
115
|
+
workerDirectory(options.home, 0o755);
|
|
116
|
+
const home = realpathSync(options.home);
|
|
117
|
+
const root = join(home, policyRoot);
|
|
118
|
+
const stateDir = join(root, fingerprint.slice(0, 16));
|
|
119
|
+
const path = join(stateDir, policyFile);
|
|
120
|
+
const ssh = join(home, ".ssh");
|
|
121
|
+
if (controls.test(stateDir) || Buffer.byteLength(join(stateDir, "run", `lane-${"0".repeat(24)}.sock`)) > 100)
|
|
122
|
+
throw new WorkerRegistrationError("Target account home cannot be used for worker Unix sockets");
|
|
123
|
+
if (!options.repositories.length || options.repositories.length > maxRepositories)
|
|
124
|
+
throw new WorkerRegistrationError(`Target enrollment requires 1–${maxRepositories} Git checkouts`);
|
|
125
|
+
const repos = await targetRepositories(options.repositories, stateDir);
|
|
126
|
+
const executable = trustedWorkerPath(realpathSync(options.executable), repos, "file");
|
|
127
|
+
const command = [executable];
|
|
128
|
+
const line = enrollmentAuthorization(path, key, repos);
|
|
129
|
+
// Run every trust check before making policy, lock, or SSH directories.
|
|
130
|
+
trustedWorkerPath(stateDir, repos, "profile");
|
|
131
|
+
trustedWorkerPath(ssh, repos, "profile");
|
|
132
|
+
workerDirectory(root, 0o700, true);
|
|
133
|
+
return await withWorkerWriteLock(join(root, "init.lock"), () => {
|
|
134
|
+
workerDirectory(stateDir, 0o700, true);
|
|
135
|
+
workerDirectory(ssh, 0o755, true);
|
|
136
|
+
const previous = policyAt(path);
|
|
137
|
+
if (previous && (previous.fingerprint !== fingerprint ||
|
|
138
|
+
!Bun.deepEquals(previous.repos, repos) || !Bun.deepEquals(previous.command, command)))
|
|
139
|
+
throw new WorkerRegistrationError("Enrollment already has a different policy; no policy or authorization was overwritten");
|
|
140
|
+
const auth = join(ssh, "authorized_keys");
|
|
141
|
+
const snapshot = authorizationSnapshot(auth, key, line, previous !== undefined);
|
|
142
|
+
const policy: WorkerPolicy = { workerId: previous?.workerId ?? `worker-${randomUUID()}`, stateDir, repos, capacity: 1, command };
|
|
143
|
+
if (!previous) {
|
|
144
|
+
const temporary = stagePrivateFile(path, `${JSON.stringify({ fingerprint, ...policy }, null, 2)}\n`);
|
|
145
|
+
try { linkSync(temporary, path); }
|
|
146
|
+
finally { unlinkSync(temporary); }
|
|
147
|
+
}
|
|
148
|
+
if (snapshot) appendAuthorization(auth, line, snapshot.baseline);
|
|
149
|
+
return policy;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** This path comes from authorized_keys, never from SSH_ORIGINAL_COMMAND. */
|
|
154
|
+
export function readWorkerPolicy(home: string, path: string): WorkerPolicy {
|
|
155
|
+
workerDirectory(home, 0o755);
|
|
156
|
+
const root = join(realpathSync(home), policyRoot);
|
|
157
|
+
if (!/^[0-9a-f]{16}$/.test(basename(dirname(path))) || path !== join(root, basename(dirname(path)), policyFile))
|
|
158
|
+
throw new WorkerRegistrationError("Worker serve requires its exact enrolled policy path");
|
|
159
|
+
workerDirectory(root, 0o700);
|
|
160
|
+
workerDirectory(dirname(path), 0o700);
|
|
161
|
+
const stored = policyAt(path);
|
|
162
|
+
if (!stored) throw new WorkerRegistrationError("The enrolled worker policy is missing");
|
|
163
|
+
const { fingerprint: _fingerprint, ...policy } = stored;
|
|
164
|
+
return policy;
|
|
165
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync, type Stats } from "node:fs";
|
|
2
|
+
import { createConnection, type Socket } from "node:net";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { Value } from "@sinclair/typebox/value";
|
|
5
|
+
import { HostConnection } from "./host";
|
|
6
|
+
import { ownsCheckout, privateWorkerDirectory } from "./worker-checkout";
|
|
7
|
+
import { workerExit, type WorkerIdentity, type WorkerLedger, type WorkerReceipt } from "./worker-ledger";
|
|
8
|
+
import { WorkerRefusal } from "./worker-request";
|
|
9
|
+
import { remoteLanePaths, type WorkerPolicy, type WorkerProbe } from "./worker-wire";
|
|
10
|
+
|
|
11
|
+
export const WORKER_ATTEMPT_ENV = "OMP_SUPERAGENT_WORKER_ATTEMPT";
|
|
12
|
+
export const WORKER_SESSION_ENV = "OMP_SUPERAGENT_WORKER_EXPECTED_SESSION";
|
|
13
|
+
const SOCKET_TIMEOUT_MS = 5_000;
|
|
14
|
+
|
|
15
|
+
export function workerPaths(policy: WorkerPolicy, laneId: string) {
|
|
16
|
+
const { socketPath, sessionFile } = remoteLanePaths(policy, laneId);
|
|
17
|
+
if (Buffer.byteLength(socketPath) > 100) throw new WorkerRefusal("Worker socket path exceeds 100 bytes");
|
|
18
|
+
return { socketPath, sessionFile, exitPath: `${socketPath}.exit.json`, logPath: join(dirname(socketPath), `${laneId}.log`) };
|
|
19
|
+
}
|
|
20
|
+
type WorkerPaths = ReturnType<typeof workerPaths>;
|
|
21
|
+
type WorkerFiles = Awaited<ReturnType<typeof readWorkerFiles>>;
|
|
22
|
+
|
|
23
|
+
function checkedFile(path: string): Stats | undefined {
|
|
24
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
25
|
+
if (stat && (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o022) !== 0))
|
|
26
|
+
throw new WorkerRefusal("Worker session or exit record is not an owned regular file");
|
|
27
|
+
return stat;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function checkedSocket(path: string): Stats | undefined {
|
|
31
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
32
|
+
if (stat && (!stat.isSocket() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600))
|
|
33
|
+
throw new WorkerRefusal("Worker endpoint is not an owned private socket");
|
|
34
|
+
return stat;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function sameFile(expected: Pick<Stats, "dev" | "ino">, observed: Stats | undefined): boolean {
|
|
38
|
+
return observed !== undefined && expected.dev === observed.dev && expected.ino === observed.ino;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function pidAlive(pid: number): boolean {
|
|
42
|
+
try { process.kill(pid, 0); return true; }
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error instanceof Error && "code" in error && error.code === "ESRCH") return false;
|
|
45
|
+
// Other errors do not prove absence.
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function readWorkerFiles(paths: WorkerPaths) {
|
|
51
|
+
privateWorkerDirectory(dirname(paths.socketPath));
|
|
52
|
+
privateWorkerDirectory(dirname(dirname(paths.sessionFile)));
|
|
53
|
+
privateWorkerDirectory(dirname(paths.sessionFile));
|
|
54
|
+
const socket = checkedSocket(paths.socketPath);
|
|
55
|
+
const exit = checkedFile(paths.exitPath);
|
|
56
|
+
const session = checkedFile(paths.sessionFile);
|
|
57
|
+
let sessionId: string | null = null;
|
|
58
|
+
if (session) {
|
|
59
|
+
const { readSessionHeaderId } = await import("@oh-my-pi/pi-coding-agent/session/session-loader");
|
|
60
|
+
sessionId = await readSessionHeaderId(paths.sessionFile) ?? null;
|
|
61
|
+
if (!sameFile(session, checkedFile(paths.sessionFile))) throw new WorkerRefusal("Worker journal changed while reading its identity");
|
|
62
|
+
}
|
|
63
|
+
return { socket, exit, session, sessionId };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function provenExit(paths: WorkerPaths, files: WorkerFiles, receipt: WorkerReceipt) {
|
|
67
|
+
if (!files.exit || !files.sessionId || files.exit.size > 4096 || (files.exit.mode & 0o077) !== 0) return null;
|
|
68
|
+
const fd = openSync(paths.exitPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
69
|
+
try {
|
|
70
|
+
const stat = fstatSync(fd);
|
|
71
|
+
if (!sameFile(files.exit, stat) || stat.size !== files.exit.size) return null;
|
|
72
|
+
let exit: unknown;
|
|
73
|
+
try { exit = JSON.parse(readFileSync(fd, "utf8")); }
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error instanceof SyntaxError) return null;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
if (!Value.Check(workerExit, exit) || exit.workerAttempt !== receipt.attempt || exit.sessionFile !== paths.sessionFile
|
|
79
|
+
|| exit.sessionId !== files.sessionId || receipt.sessionId !== null && exit.sessionId !== receipt.sessionId
|
|
80
|
+
|| receipt.phase === "live" && (exit.pid !== receipt.identity.pid || exit.ownerPid !== receipt.identity.ownerPid)
|
|
81
|
+
|| exit.pid === exit.ownerPid) return null;
|
|
82
|
+
return exit;
|
|
83
|
+
} finally { closeSync(fd); }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function absentWorkerHost(files: WorkerFiles, receipt: WorkerReceipt | null): WorkerProbe {
|
|
87
|
+
const expected = receipt?.sessionId ?? null;
|
|
88
|
+
const uncertain = !!files.socket || files.sessionId !== expected || !!files.session !== (expected !== null)
|
|
89
|
+
|| (!!files.exit && expected === null);
|
|
90
|
+
return { socket: !!files.socket, sessionFile: !!files.session, sessionId: uncertain ? null : files.sessionId,
|
|
91
|
+
pid: null, pidAlive: false, ownerAlive: false, uncertain,
|
|
92
|
+
...(!uncertain && receipt?.phase === "released" && receipt.exitVerified && { exitGeneration: receipt.generation }) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function attestWorkerHost(paths: WorkerPaths, files: WorkerFiles, receipt: WorkerReceipt): Promise<WorkerIdentity> {
|
|
96
|
+
if (!files.socket || !files.sessionId || !ownsCheckout(receipt)) throw new WorkerRefusal("No owned worker socket/journal/checkout");
|
|
97
|
+
const { connection, identity, state } = await HostConnection.open(paths.socketPath);
|
|
98
|
+
try {
|
|
99
|
+
if (!("workerAttempt" in state) || state.workerAttempt !== receipt.attempt ||
|
|
100
|
+
typeof state.loadedSuperkitPath !== "string" || !state.loadedSuperkitPath.startsWith("/") || identity.pid === identity.ownerPid ||
|
|
101
|
+
identity.sessionFile !== paths.sessionFile || identity.sessionId !== files.sessionId ||
|
|
102
|
+
receipt.sessionId !== null && identity.sessionId !== receipt.sessionId || !sameFile(identity, files.socket) ||
|
|
103
|
+
!sameFile(identity, checkedSocket(paths.socketPath)) || !pidAlive(identity.pid) || !pidAlive(identity.ownerPid) ||
|
|
104
|
+
receipt.phase === "live" && (receipt.identity.pid !== identity.pid || receipt.identity.ownerPid !== identity.ownerPid
|
|
105
|
+
|| !sameFile(receipt.identity, files.socket)))
|
|
106
|
+
throw new WorkerRefusal("Worker native Host identity or launch receipt does not match");
|
|
107
|
+
return identity;
|
|
108
|
+
} finally { await connection.close(); }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function inspectWorkerHost(ledger: WorkerLedger, paths: WorkerPaths, receipt: WorkerReceipt | null, attest = true): Promise<WorkerProbe> {
|
|
112
|
+
const files = await readWorkerFiles(paths);
|
|
113
|
+
if (!receipt || receipt.phase === "released") return absentWorkerHost(files, receipt);
|
|
114
|
+
if (receipt.phase === "reserved") {
|
|
115
|
+
const untouched = absentWorkerHost(files, receipt);
|
|
116
|
+
if (!pidAlive(receipt.launcherPid) && !untouched.uncertain && ledger.retire(receipt))
|
|
117
|
+
return untouched;
|
|
118
|
+
return { ...untouched, uncertain: true };
|
|
119
|
+
}
|
|
120
|
+
const exit = provenExit(paths, files, receipt);
|
|
121
|
+
const pid = receipt.phase === "live" ? receipt.identity.pid : exit?.pid ?? null;
|
|
122
|
+
const owner = receipt.phase === "live" ? receipt.identity.ownerPid : exit?.ownerPid ?? null;
|
|
123
|
+
const nativeAlive = pid !== null && pidAlive(pid);
|
|
124
|
+
const ownerAlive = owner !== null && pidAlive(owner);
|
|
125
|
+
if (exit && !nativeAlive && !ownerAlive && (!files.socket || receipt.phase === "live" && sameFile(receipt.identity, files.socket))) {
|
|
126
|
+
const cleanup = () => {
|
|
127
|
+
if (!files.session || !sameFile(files.session, checkedFile(paths.sessionFile))
|
|
128
|
+
|| !files.exit || !sameFile(files.exit, checkedFile(paths.exitPath))
|
|
129
|
+
|| pidAlive(exit.pid) || pidAlive(exit.ownerPid)) throw new WorkerRefusal("Worker native exit evidence changed");
|
|
130
|
+
const socket = checkedSocket(paths.socketPath);
|
|
131
|
+
if (!socket) return;
|
|
132
|
+
if (!files.socket || !sameFile(files.socket, socket)) throw new WorkerRefusal("Worker socket changed before exit cleanup");
|
|
133
|
+
unlinkSync(paths.socketPath);
|
|
134
|
+
};
|
|
135
|
+
const clean = exit.code === 0 && exit.signal === null;
|
|
136
|
+
if (ledger.retire(receipt, { sessionId: exit.sessionId, clean, cleanup }))
|
|
137
|
+
return { socket: false, sessionFile: true, sessionId: exit.sessionId, pid: null, pidAlive: false, ownerAlive: false,
|
|
138
|
+
uncertain: false, ...(clean ? { exitGeneration: receipt.generation } : {}) };
|
|
139
|
+
}
|
|
140
|
+
if (attest && files.socket && !exit) {
|
|
141
|
+
try {
|
|
142
|
+
const identity = await attestWorkerHost(paths, files, receipt);
|
|
143
|
+
const live = { ...receipt, phase: "live", sessionId: identity.sessionId, identity } as const;
|
|
144
|
+
const saved = receipt.phase === "live" || ledger.transition(receipt, live) ? live : ledger.get(receipt.laneId);
|
|
145
|
+
if (saved?.phase === "live" && saved.attempt === receipt.attempt &&
|
|
146
|
+
saved.identity.pid === identity.pid && saved.identity.ownerPid === identity.ownerPid &&
|
|
147
|
+
saved.identity.sessionId === identity.sessionId && sameFile(saved.identity, files.socket)) {
|
|
148
|
+
return { socket: true, sessionFile: true, sessionId: identity.sessionId, pid: identity.pid,
|
|
149
|
+
pidAlive: true, ownerAlive: true, uncertain: false };
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (!(error instanceof Error)) throw error;
|
|
153
|
+
// Neither a refused identity nor a dead socket establishes native exit.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { socket: !!files.socket, sessionFile: !!files.session, sessionId: null,
|
|
157
|
+
pid, pidAlive: nativeAlive, ownerAlive, uncertain: true };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function rawWorkerSocket(path: string, identity: WorkerIdentity): Promise<Socket> {
|
|
161
|
+
if (!sameFile(identity, checkedSocket(path))) throw new WorkerRefusal("Worker socket changed before attach");
|
|
162
|
+
const socket = createConnection(path);
|
|
163
|
+
socket.pause();
|
|
164
|
+
try {
|
|
165
|
+
await new Promise<void>((resolve, reject) => {
|
|
166
|
+
const timer = setTimeout(() => socket.destroy(new WorkerRefusal("Worker socket attach timed out")), SOCKET_TIMEOUT_MS);
|
|
167
|
+
socket.once("error", reject);
|
|
168
|
+
socket.once("connect", () => { clearTimeout(timer); resolve(); });
|
|
169
|
+
socket.once("close", () => {
|
|
170
|
+
clearTimeout(timer);
|
|
171
|
+
reject(new WorkerRefusal("Worker socket closed during attach"));
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
if (!sameFile(identity, checkedSocket(path))) throw new WorkerRefusal("Worker socket changed during attach");
|
|
175
|
+
return socket;
|
|
176
|
+
} catch (error) {
|
|
177
|
+
socket.destroy();
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { Type, type Static } from "@sinclair/typebox/type";
|
|
5
|
+
import { Value } from "@sinclair/typebox/value";
|
|
6
|
+
import { releaseCheckout } from "./worker-checkout";
|
|
7
|
+
import { WorkerRefusal } from "./worker-request";
|
|
8
|
+
import type { WorkerLaneRef, WorkerPolicy } from "./worker-wire";
|
|
9
|
+
|
|
10
|
+
export const workerPid = Type.Integer({ minimum: 1, maximum: 0x7fffffff });
|
|
11
|
+
const sessionId = Type.String({ minLength: 1, maxLength: 512 });
|
|
12
|
+
const identityFields = {
|
|
13
|
+
pid: workerPid,
|
|
14
|
+
ownerPid: workerPid,
|
|
15
|
+
sessionId,
|
|
16
|
+
sessionFile: Type.String({ minLength: 1 }),
|
|
17
|
+
};
|
|
18
|
+
const identity = Type.Object({
|
|
19
|
+
...identityFields,
|
|
20
|
+
dev: Type.Number(),
|
|
21
|
+
ino: Type.Number(),
|
|
22
|
+
});
|
|
23
|
+
export const workerExit = Type.Object({
|
|
24
|
+
...identityFields,
|
|
25
|
+
workerAttempt: Type.String(),
|
|
26
|
+
code: Type.Union([Type.Integer(), Type.Null()]),
|
|
27
|
+
signal: Type.Union([Type.String(), Type.Null()]),
|
|
28
|
+
persisted: Type.Literal(true),
|
|
29
|
+
observationsFlushed: Type.Literal(true),
|
|
30
|
+
});
|
|
31
|
+
const receiptFields = {
|
|
32
|
+
laneId: Type.String(),
|
|
33
|
+
generation: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
|
|
34
|
+
repoId: Type.String(),
|
|
35
|
+
revision: Type.String(),
|
|
36
|
+
subdir: Type.String(),
|
|
37
|
+
repoRoot: Type.String(),
|
|
38
|
+
gitDir: Type.String(),
|
|
39
|
+
launchDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
|
|
40
|
+
attempt: Type.String({ pattern: "^[0-9a-f-]{36}$" }),
|
|
41
|
+
launcherPid: workerPid,
|
|
42
|
+
sessionId: Type.Union([sessionId, Type.Null()]),
|
|
43
|
+
};
|
|
44
|
+
const receipt = Type.Union([
|
|
45
|
+
Type.Object({ ...receiptFields, phase: Type.Literal("reserved") }),
|
|
46
|
+
Type.Object({ ...receiptFields, phase: Type.Literal("launching") }),
|
|
47
|
+
Type.Object({ ...receiptFields, phase: Type.Literal("live"), identity }),
|
|
48
|
+
Type.Object({ ...receiptFields, phase: Type.Literal("released"), exitVerified: Type.Optional(Type.Literal(true)) }),
|
|
49
|
+
]);
|
|
50
|
+
export type WorkerReceipt = Readonly<Static<typeof receipt>>;
|
|
51
|
+
export type WorkerIdentity = Readonly<Static<typeof identity>>;
|
|
52
|
+
type ReservedReceipt = Extract<WorkerReceipt, { phase: "reserved" }>;
|
|
53
|
+
type WorkerSeal = Pick<WorkerLaneRef, "generation" | "repoId" | "revision" | "subdir"> & { readonly repoRoot: string };
|
|
54
|
+
|
|
55
|
+
function decode(row: { readonly data: string } | null): WorkerReceipt | null {
|
|
56
|
+
if (!row) return null;
|
|
57
|
+
const value: unknown = JSON.parse(row.data);
|
|
58
|
+
if (!Value.Check(receipt, value)) throw new WorkerRefusal("Worker launch ledger has an invalid receipt");
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class WorkerLedger {
|
|
63
|
+
readonly #db: Database;
|
|
64
|
+
readonly #capacity: number;
|
|
65
|
+
|
|
66
|
+
static count(policy: WorkerPolicy): number {
|
|
67
|
+
if (!lstatSync(join(policy.stateDir, "worker.sqlite"), { throwIfNoEntry: false })) return 0;
|
|
68
|
+
const ledger = new WorkerLedger(policy, "read");
|
|
69
|
+
try { return ledger.active().length; } finally { ledger.close(); }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
constructor(policy: WorkerPolicy, mode: "read" | "write" = "write") {
|
|
73
|
+
const path = join(policy.stateDir, "worker.sqlite");
|
|
74
|
+
const access = mode === "read" ? constants.O_RDONLY : constants.O_RDWR | constants.O_CREAT;
|
|
75
|
+
const fd = openSync(path, access | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
|
|
76
|
+
try {
|
|
77
|
+
const stat = fstatSync(fd);
|
|
78
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600)
|
|
79
|
+
throw new WorkerRefusal("Worker ledger must be a private regular file (0600)");
|
|
80
|
+
} finally { closeSync(fd); }
|
|
81
|
+
this.#capacity = policy.capacity;
|
|
82
|
+
this.#db = new Database(path, { strict: true, readonly: mode === "read" });
|
|
83
|
+
try {
|
|
84
|
+
this.#db.exec("PRAGMA busy_timeout = 5000;");
|
|
85
|
+
if (mode === "write") this.#db.exec(`
|
|
86
|
+
PRAGMA synchronous = FULL;
|
|
87
|
+
CREATE TABLE IF NOT EXISTS worker_identity (singleton INTEGER PRIMARY KEY CHECK(singleton = 1), worker_id TEXT NOT NULL);
|
|
88
|
+
CREATE TABLE IF NOT EXISTS worker_lanes (id TEXT PRIMARY KEY, phase TEXT NOT NULL, data TEXT NOT NULL);
|
|
89
|
+
CREATE TABLE IF NOT EXISTS worker_seals (
|
|
90
|
+
id TEXT PRIMARY KEY, generation INTEGER NOT NULL, repoId TEXT NOT NULL,
|
|
91
|
+
revision TEXT NOT NULL, subdir TEXT NOT NULL, repoRoot TEXT NOT NULL
|
|
92
|
+
);
|
|
93
|
+
`);
|
|
94
|
+
if (mode === "write") this.#db.transaction(() => {
|
|
95
|
+
this.#db.query("INSERT OR IGNORE INTO worker_identity VALUES (1, ?)").run(policy.workerId);
|
|
96
|
+
}).immediate();
|
|
97
|
+
const row = this.#db.query<{ worker_id: string }, []>("SELECT worker_id FROM worker_identity WHERE singleton = 1").get();
|
|
98
|
+
if (row?.worker_id !== policy.workerId) throw new WorkerRefusal("Worker storage belongs to a different enrollment");
|
|
99
|
+
} catch (error) {
|
|
100
|
+
this.#db.close();
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
close(): void { this.#db.close(); }
|
|
106
|
+
|
|
107
|
+
get(laneId: string): WorkerReceipt | null {
|
|
108
|
+
return decode(this.#db.query<{ data: string }, [string]>("SELECT data FROM worker_lanes WHERE id = ?").get(laneId));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
active(): WorkerReceipt[] {
|
|
112
|
+
return this.#db.query<{ data: string }, []>("SELECT data FROM worker_lanes WHERE phase != 'released'")
|
|
113
|
+
.all().flatMap(row => decode(row) ?? []);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
#write(value: WorkerReceipt): void {
|
|
117
|
+
this.#db.query("INSERT OR REPLACE INTO worker_lanes (id, phase, data) VALUES (?, ?, ?)")
|
|
118
|
+
.run(value.laneId, value.phase, JSON.stringify(value));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
#sealedGeneration(ref: WorkerLaneRef, repoRoot: string): number | undefined {
|
|
122
|
+
const seal = this.#db.query<WorkerSeal, [string]>(
|
|
123
|
+
"SELECT generation, repoId, revision, subdir, repoRoot FROM worker_seals WHERE id = ?").get(ref.laneId);
|
|
124
|
+
if (seal && (seal.repoId !== ref.repoId || seal.revision !== ref.revision || seal.subdir !== ref.subdir || seal.repoRoot !== repoRoot))
|
|
125
|
+
throw new WorkerRefusal("Worker lane has a different durable checkout binding");
|
|
126
|
+
return seal?.generation;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
confirmRelease(ref: WorkerLaneRef, repoRoot: string, options: {
|
|
130
|
+
readonly observed: WorkerReceipt | null; readonly reconcile: boolean;
|
|
131
|
+
}): boolean {
|
|
132
|
+
const confirm = this.#db.transaction(() => {
|
|
133
|
+
const current = this.get(ref.laneId);
|
|
134
|
+
if (current?.attempt !== options.observed?.attempt || current && current.phase !== "released") return false;
|
|
135
|
+
const sealed = this.#sealedGeneration(ref, repoRoot);
|
|
136
|
+
if (ref.generation < (sealed ?? 0) || ref.generation < (current?.generation ?? 0))
|
|
137
|
+
throw new WorkerRefusal("Worker lane generation is stale");
|
|
138
|
+
if (sealed === ref.generation || current?.generation === ref.generation) return true;
|
|
139
|
+
if (!options.reconcile) return false;
|
|
140
|
+
// Keep any previous exit/session receipt intact. Reserve and seal use the
|
|
141
|
+
// same immediate transaction: either a launch is already admitted, or
|
|
142
|
+
// even an open request that arrives after this reply must refuse.
|
|
143
|
+
this.#db.query("INSERT OR REPLACE INTO worker_seals VALUES (?, ?, ?, ?, ?, ?)")
|
|
144
|
+
.run(ref.laneId, ref.generation, ref.repoId, ref.revision, ref.subdir, repoRoot);
|
|
145
|
+
return true;
|
|
146
|
+
});
|
|
147
|
+
return options.reconcile ? confirm.immediate() : confirm();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
reserve(ref: WorkerLaneRef, binding: { readonly repoRoot: string; readonly gitDir: string; readonly launchDigest: string }, previous: WorkerReceipt | null): ReservedReceipt {
|
|
151
|
+
return this.#db.transaction(() => {
|
|
152
|
+
if ((this.#sealedGeneration(ref, binding.repoRoot) ?? 0) >= ref.generation)
|
|
153
|
+
throw new WorkerRefusal("Worker lane generation was sealed and cannot open");
|
|
154
|
+
const current = this.get(ref.laneId);
|
|
155
|
+
if (current && (current.phase !== "released" || current.generation >= ref.generation)
|
|
156
|
+
|| current?.attempt !== previous?.attempt || current?.phase !== previous?.phase)
|
|
157
|
+
throw new WorkerRefusal("Worker lane generation is already reserved or no longer current");
|
|
158
|
+
const active = this.#db.query<{ count: number }, []>("SELECT count(*) AS count FROM worker_lanes WHERE phase != 'released'").get();
|
|
159
|
+
if (!active || active.count >= this.#capacity) throw new WorkerRefusal("Worker Host capacity is occupied");
|
|
160
|
+
const value: ReservedReceipt = { ...ref, ...binding, attempt: crypto.randomUUID(), launcherPid: process.pid,
|
|
161
|
+
phase: "reserved", sessionId: current?.sessionId ?? null };
|
|
162
|
+
this.#write(value);
|
|
163
|
+
return value;
|
|
164
|
+
}).immediate();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
transition(current: WorkerReceipt, next: WorkerReceipt): boolean {
|
|
168
|
+
return this.#db.transaction(() => {
|
|
169
|
+
const actual = this.get(current.laneId);
|
|
170
|
+
if (actual?.attempt !== current.attempt || actual.phase !== current.phase) return false;
|
|
171
|
+
this.#write(next);
|
|
172
|
+
return true;
|
|
173
|
+
}).immediate();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
retire(current: WorkerReceipt, exit?: { readonly sessionId: string; readonly clean: boolean; readonly cleanup: () => void }): boolean {
|
|
177
|
+
return this.#db.transaction(() => {
|
|
178
|
+
const actual = this.get(current.laneId);
|
|
179
|
+
if (actual?.attempt !== current.attempt || actual.phase !== current.phase) return false;
|
|
180
|
+
exit?.cleanup();
|
|
181
|
+
releaseCheckout(current);
|
|
182
|
+
const { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest } = current;
|
|
183
|
+
this.#write({ laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
|
|
184
|
+
phase: "released", sessionId: exit?.sessionId ?? current.sessionId, ...(exit?.clean && { exitVerified: true }) });
|
|
185
|
+
return true;
|
|
186
|
+
}).immediate();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { Config } from "./config";
|
|
2
|
+
import { workerRepositoryHead } from "./worker-repository";
|
|
3
|
+
import { listWorkers } from "./worker-registration";
|
|
4
|
+
import { workerDescribe, type RemotePlacement, type WorkerLaneRef, type WorkerRegistration, type WorkerSelector } from "./worker-wire";
|
|
5
|
+
|
|
6
|
+
class WorkerPlacementError extends Error {}
|
|
7
|
+
type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
|
|
8
|
+
|
|
9
|
+
async function availableSlots(registration: WorkerRegistration, { repoId, revision, subdir }: Workspace): Promise<number> {
|
|
10
|
+
const saved = registration.description;
|
|
11
|
+
const approved = saved.repos.find(repo => repo.id === repoId);
|
|
12
|
+
if (!approved) return 0;
|
|
13
|
+
try {
|
|
14
|
+
const live = await workerDescribe(registration, { repoId, revision, subdir });
|
|
15
|
+
const inventory = live.repos.filter(repo => repo.id === repoId);
|
|
16
|
+
return live.workerId === saved.workerId && live.platform === saved.platform && live.stateDir === saved.stateDir
|
|
17
|
+
&& inventory.length === 1 && inventory[0]?.cwd === approved.cwd ? Math.max(0, Math.min(saved.capacity, live.capacity) - live.active) : 0;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error instanceof Error) return 0; // No readiness receipt; no permission to open.
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Observe only the enrolled worker; do not open or retarget an unavailable checkout. */
|
|
25
|
+
export async function workerPlacementReady(registration: WorkerRegistration, workspace: Workspace): Promise<boolean> {
|
|
26
|
+
return await availableSlots(registration, workspace) > 0;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Admission only: read approved inventory and live capacity; never start work here. */
|
|
30
|
+
export async function selectWorkerPlacement(
|
|
31
|
+
config: Pick<Config, "stateDir">, cwd: string, placement?: WorkerSelector,
|
|
32
|
+
admission?: { queued(): ReadonlyMap<string, number>; reserve(workerId: string): void },
|
|
33
|
+
): Promise<RemotePlacement | null> {
|
|
34
|
+
if (placement?.target === "local") {
|
|
35
|
+
if (placement.platform !== undefined || placement.worker !== undefined) {
|
|
36
|
+
throw new WorkerPlacementError("Local placement cannot specify a remote worker or worker platform");
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
const required = placement?.target === "remote" || placement?.platform !== undefined || placement?.worker !== undefined;
|
|
41
|
+
const registered = listWorkers(config.stateDir).filter(({ description, defaultRepository }) =>
|
|
42
|
+
(required || defaultRepository !== undefined) && (placement?.worker === undefined || description.workerId === placement.worker)
|
|
43
|
+
&& (placement?.platform === undefined || description.platform === placement.platform));
|
|
44
|
+
if (!registered.length) {
|
|
45
|
+
if (!required) return null;
|
|
46
|
+
throw new WorkerPlacementError("No paired worker matches the requested worker or platform");
|
|
47
|
+
}
|
|
48
|
+
const source = await workerRepositoryHead(cwd);
|
|
49
|
+
if (!source) {
|
|
50
|
+
if (!required) return null;
|
|
51
|
+
throw new WorkerPlacementError("Remote placement requires a clean Git checkout with a verifiable network origin and a committed workspace directory");
|
|
52
|
+
}
|
|
53
|
+
const { root, ...workspace } = source;
|
|
54
|
+
const candidates = registered.filter(({ description, defaultRepository }) =>
|
|
55
|
+
description.repos.some(repo => repo.id === workspace.repoId) &&
|
|
56
|
+
(required || (defaultRepository?.root === root && defaultRepository.repoId === workspace.repoId)));
|
|
57
|
+
if (!candidates.length) {
|
|
58
|
+
if (!required) return null;
|
|
59
|
+
throw new WorkerPlacementError("No matching paired worker is approved for this repository identity");
|
|
60
|
+
}
|
|
61
|
+
const observed = await Promise.all(candidates.map(async worker => ({ worker, free: await availableSlots(worker, workspace) })));
|
|
62
|
+
// Read and reserve synchronously after the SSH round trips: concurrent
|
|
63
|
+
// admissions see each other's decisions without serializing network I/O.
|
|
64
|
+
const queued = admission?.queued();
|
|
65
|
+
const waiting = (worker: WorkerRegistration) => queued?.get(worker.description.workerId) ?? 0;
|
|
66
|
+
observed.sort(({ worker: left }, { worker: right }) => {
|
|
67
|
+
const a = left.description.workerId, b = right.description.workerId;
|
|
68
|
+
return waiting(left) - waiting(right) || Number(right.defaultRepository !== undefined) - Number(left.defaultRepository !== undefined)
|
|
69
|
+
|| (a === b ? 0 : a < b ? -1 : 1);
|
|
70
|
+
});
|
|
71
|
+
// Explicit placement freezes its worker even when no candidate is ready now.
|
|
72
|
+
// The runtime repeats this preflight on the selected worker before open.
|
|
73
|
+
const selected = (observed.find(({ worker, free }) => free > waiting(worker)) ?? (required ? observed[0] : null))?.worker;
|
|
74
|
+
if (!selected) return null;
|
|
75
|
+
const { workerId, stateDir } = selected.description;
|
|
76
|
+
admission?.reserve(workerId);
|
|
77
|
+
return { workerId, stateDir, ...workspace };
|
|
78
|
+
}
|