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.
Files changed (90) hide show
  1. package/DESIGN.md +36 -20
  2. package/README.ko.md +140 -33
  3. package/README.md +165 -41
  4. package/THIRD_PARTY_NOTICES.md +9 -7
  5. package/config.example.json +3 -1
  6. package/docs/OPERATIONS.md +395 -157
  7. package/docs/design/execution.md +156 -22
  8. package/docs/design/messaging.md +258 -52
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.7.md +25 -0
  11. package/docs/releases/0.1.8.md +21 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  17. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  19. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  20. package/package.json +9 -9
  21. package/scripts/ci.ts +4 -4
  22. package/scripts/test-omp.sh +2 -1
  23. package/skills/head/SKILL.md +26 -5
  24. package/skills/head/references/routing.md +68 -33
  25. package/skills/head/references/supervision.md +20 -4
  26. package/skills/lane/references/workflow.md +16 -7
  27. package/src/board.ts +5 -3
  28. package/src/cli.ts +161 -19
  29. package/src/config.ts +21 -1
  30. package/src/contracts.ts +63 -8
  31. package/src/cron-jobs.ts +443 -19
  32. package/src/cron-pr-intake.ts +257 -0
  33. package/src/discord-markdown.ts +350 -123
  34. package/src/extension.ts +78 -13
  35. package/src/gateway-client.ts +8 -2
  36. package/src/head-quota.ts +80 -0
  37. package/src/head-recovery.ts +40 -1
  38. package/src/host-extension.ts +122 -4
  39. package/src/host-inventory-manifest.ts +2 -2
  40. package/src/host-protocol.ts +11 -0
  41. package/src/host-sdk-helper.ts +121 -12
  42. package/src/host.ts +175 -57
  43. package/src/installed-omp.ts +116 -4
  44. package/src/lane-rows.ts +44 -4
  45. package/src/lane-watch.ts +339 -0
  46. package/src/managed-memory-helper.ts +13 -10
  47. package/src/managed-memory.ts +62 -27
  48. package/src/managed-ulw-probe.ts +75 -20
  49. package/src/managed-ulw.ts +174 -21
  50. package/src/messenger-command-catalog.json +2 -2
  51. package/src/native-launch-profile.ts +4 -2
  52. package/src/native-presets.ts +32 -5
  53. package/src/native-sessions.ts +3 -1
  54. package/src/native-settings.ts +47 -9
  55. package/src/observation-request.ts +23 -0
  56. package/src/omp-usage.ts +254 -36
  57. package/src/pr-github-schema.ts +5 -1
  58. package/src/pr-github.ts +68 -19
  59. package/src/pr-intake-automation.ts +316 -0
  60. package/src/pr-intake-comment.ts +226 -0
  61. package/src/pr-intake-fix.ts +233 -0
  62. package/src/pr-intake-github.ts +480 -0
  63. package/src/pr-intake-material.ts +230 -0
  64. package/src/pr-intake-mode.ts +59 -0
  65. package/src/pr-intake-review.ts +397 -0
  66. package/src/pr-intake-tree.ts +69 -0
  67. package/src/pr-intake-work.ts +29 -0
  68. package/src/pr-watch.ts +91 -32
  69. package/src/runtime.ts +2702 -391
  70. package/src/setup-judge.ts +1 -1
  71. package/src/setup.ts +12 -16
  72. package/src/store.ts +429 -86
  73. package/src/topic-history.ts +243 -47
  74. package/src/worker-checkout.ts +106 -0
  75. package/src/worker-destination.ts +10 -0
  76. package/src/worker-doctor.ts +66 -0
  77. package/src/worker-enrollment.ts +165 -0
  78. package/src/worker-host.ts +180 -0
  79. package/src/worker-ledger.ts +188 -0
  80. package/src/worker-placement.ts +78 -0
  81. package/src/worker-profile.ts +274 -0
  82. package/src/worker-registration.ts +288 -0
  83. package/src/worker-repository.ts +233 -0
  84. package/src/worker-request.ts +74 -0
  85. package/src/worker-service.ts +230 -0
  86. package/src/worker-stdio.ts +61 -0
  87. package/src/worker-trust.ts +36 -0
  88. package/src/worker-wire.ts +204 -0
  89. package/src/workflow.ts +81 -32
  90. package/src/setup-memory.ts +0 -21
@@ -0,0 +1,233 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, readlink, realpath } from "node:fs/promises";
4
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
+ import type { WorkerLaneRef } from "./worker-wire";
6
+
7
+ const gitOid = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
8
+ const controls = /[\u0000-\u001f\u007f]/;
9
+ const gitTimeoutMs = 10_000;
10
+
11
+ function gitProcess(cwd: string, args: readonly string[], timeout?: number) {
12
+ return Bun.spawn(["/usr/bin/git", "--no-pager", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null",
13
+ "-c", "core.untrackedCache=false", "-c", "core.excludesFile=/dev/null", ...args], {
14
+ cwd, env: {
15
+ PATH: "/usr/bin:/bin", LC_ALL: "C", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null",
16
+ GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1",
17
+ GIT_NO_REPLACE_OBJECTS: "1", GIT_ALLOW_PROTOCOL: "",
18
+ },
19
+ stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout, killSignal: "SIGKILL",
20
+ });
21
+ }
22
+
23
+ /** Read the local Git repository without ambient Git configuration, hooks, or network access. */
24
+ export async function gitWorkerRepository(cwd: string, args: readonly string[]): Promise<string | null> {
25
+ const git = gitProcess(cwd, args, gitTimeoutMs);
26
+ const reader = git.stdout.getReader();
27
+ const decoder = new TextDecoder();
28
+ let size = 0;
29
+ let output = "";
30
+ try {
31
+ for (;;) {
32
+ const { done, value } = await reader.read();
33
+ if (done) break;
34
+ size += value.byteLength;
35
+ if (size > 256 * 1024) {
36
+ git.kill("SIGKILL");
37
+ await reader.cancel();
38
+ await git.exited;
39
+ return null;
40
+ }
41
+ output += decoder.decode(value, { stream: true });
42
+ }
43
+ return await git.exited === 0 ? output + decoder.decode() : null;
44
+ } finally {
45
+ reader.releaseLock();
46
+ }
47
+ }
48
+
49
+ function unavailablePath(error: unknown): boolean {
50
+ return error instanceof Error && "code" in error && typeof error.code === "string"
51
+ && ["ENOENT", "ENOTDIR", "ELOOP", "EACCES", "EPERM", "EINVAL"].includes(error.code);
52
+ }
53
+
54
+ async function checkoutRoot(canonical: string): Promise<string | null> {
55
+ const layout = await gitWorkerRepository(canonical,
56
+ ["rev-parse", "--path-format=absolute", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"]);
57
+ const [root, gitDir, commonDir, end, ...extra] = layout?.split("\n") ?? [];
58
+ if (!root || !isAbsolute(root) || controls.test(root) || end !== "" || extra.length) return null;
59
+ const metadata = join(root, ".git");
60
+ // Keep both the index and objects in the checkout approved by the operator.
61
+ // A gitfile, linked worktree, symlink or changed effective layout is not that checkout.
62
+ if (gitDir !== metadata || commonDir !== metadata || await realpath(root) !== root
63
+ || !(await lstat(metadata)).isDirectory()) return null;
64
+ return root;
65
+ }
66
+
67
+ async function repositoryIdentity(root: string): Promise<string | null> {
68
+ // Resolve effective fetch URLs locally, including insteadOf rules. Require
69
+ // exactly one URL, and omit credentials from the hashed identity.
70
+ const output = await gitWorkerRepository(root, ["remote", "get-url", "--all", "origin"]);
71
+ if (output === null) return null;
72
+ const [origin, end, ...extra] = output.split("\n");
73
+ if (!origin || end !== "" || extra.length || /[\s?#\\]/u.test(origin)) return null;
74
+ const scp = /^(?:([A-Za-z0-9_.-]+)@)?([A-Za-z0-9.-]+):([^/][^:]*)$/.exec(origin);
75
+ const url = URL.parse(scp ? `ssh://${scp[1] ? `${scp[1]}@` : ""}${scp[2]}/${scp[3]}` : origin);
76
+ if (!url || !["http:", "https:", "ssh:"].includes(url.protocol)
77
+ || !/^[A-Za-z0-9.-]+$/.test(url.hostname)
78
+ || (url.protocol === "ssh:" && (!url.username || url.password))) return null;
79
+ // Check the spelling before URL's dot-segment normalization. Do not guess
80
+ // whether an escaping form or URL query names another repo.
81
+ const rawPath = scp?.[3] ?? /^[A-Za-z]+:\/\/[^/]+\/(.+)$/.exec(origin)?.[1];
82
+ const path = rawPath?.replace(/\/$/, "");
83
+ if (!path || !/^[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/.test(path)
84
+ || path.split("/").some(part => part === "." || part === "..")) return null;
85
+ const host = url.hostname.toLowerCase();
86
+ // These public forges use the same repository paths across SSH/HTTPS. For
87
+ // other servers, different transports can map identical paths differently.
88
+ const publicForge = ["github.com", "gitlab.com", "bitbucket.org"].includes(host) && !url.port
89
+ && (url.protocol === "https:" || (url.protocol === "ssh:" && url.username === "git"));
90
+ // Never interpret a private server's relative SCP path as an absolute SSH path.
91
+ const repoPath = publicForge ? path.replace(/\.git$/, "") : path;
92
+ if (!repoPath || (publicForge && (!repoPath.includes("/") || repoPath.endsWith("/")))) return null;
93
+ const identity = publicForge
94
+ ? JSON.stringify(["forge", host, repoPath])
95
+ : JSON.stringify([scp ? "scp" : url.protocol, host, url.port, repoPath, url.protocol === "ssh:" ? url.username : ""]);
96
+ return createHash("sha256").update(identity).digest("hex");
97
+ }
98
+
99
+ /** Match only a full, unambiguous network origin. Never expose it or its credentials. */
100
+ export async function workerRepositoryIdentity(cwd: string): Promise<string | null> {
101
+ try {
102
+ const root = await checkoutRoot(await realpath(cwd));
103
+ return root && await repositoryIdentity(root);
104
+ } catch (error) {
105
+ if (unavailablePath(error)) return null;
106
+ throw error;
107
+ }
108
+ }
109
+
110
+ function withinTree(path: string): boolean {
111
+ return path === "" || (!isAbsolute(path) && path.split(sep).every(part =>
112
+ part && part !== ".." && part !== "." && part.toLowerCase() !== ".git"));
113
+ }
114
+
115
+ async function matchesBlob(root: string, indexed: Buffer, committed: Buffer): Promise<boolean> {
116
+ const tab = indexed.indexOf(9);
117
+ if (tab < 0) return false;
118
+ // Only ordinary, stage-zero entries. Lowercase tags and S hide changes;
119
+ // unsupported modes include submodules, which can select another Git config.
120
+ const [, mode, oid] = /^H (100644|100755|120000) ([0-9a-f]+) 0$/.exec(indexed.toString("latin1", 0, tab)) ?? [];
121
+ const name = indexed.subarray(tab + 1);
122
+ const path = name.toString("utf8");
123
+ if (!oid || !gitOid.test(oid) || !path || !withinTree(path) || !Buffer.from(path).equals(name)) return false;
124
+ const treeHeader = Buffer.from(`${mode} blob ${oid}\t`);
125
+ if (!committed.subarray(0, treeHeader.length).equals(treeHeader)
126
+ || !committed.subarray(treeHeader.length).equals(name)) return false;
127
+ const absolute = join(root, path);
128
+ const parent = dirname(absolute);
129
+ if (await realpath(parent) !== parent) return false;
130
+ const hash = createHash(oid.length === 40 ? "sha1" : "sha256");
131
+ if (mode === "120000") {
132
+ const target = await readlink(absolute, { encoding: "buffer" });
133
+ return hash.update(`blob ${target.length}\0`).update(target).digest("hex") === oid;
134
+ }
135
+ const file = await open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
136
+ try {
137
+ const stat = await file.stat();
138
+ if (!stat.isFile() || !Number.isSafeInteger(stat.size) || Boolean(stat.mode & 0o100) !== (mode === "100755")) return false;
139
+ hash.update(`blob ${stat.size}\0`);
140
+ const buffer = Buffer.allocUnsafe(Math.min(stat.size, 64 * 1024));
141
+ for (let remaining = stat.size; remaining > 0;) {
142
+ const { bytesRead } = await file.read(buffer, 0, Math.min(remaining, buffer.length), null);
143
+ if (!bytesRead) return false;
144
+ hash.update(buffer.subarray(0, bytesRead));
145
+ remaining -= bytesRead;
146
+ }
147
+ const after = await file.stat();
148
+ return stat.size === after.size && stat.mtimeMs === after.mtimeMs && stat.ctimeMs === after.ctimeMs
149
+ && hash.digest("hex") === oid;
150
+ } finally { await file.close(); }
151
+ }
152
+
153
+ async function* gitRecords(root: string, args: readonly string[]): AsyncGenerator<Buffer, boolean> {
154
+ const git = gitProcess(root, args);
155
+ const kill = () => {
156
+ if (git.exitCode === null && git.signalCode === null) git.kill("SIGKILL");
157
+ };
158
+ let timedOut = false;
159
+ const expire = () => {
160
+ timedOut = true;
161
+ kill();
162
+ };
163
+ let deadline = setTimeout(expire, gitTimeoutMs);
164
+ let pending = Buffer.alloc(0);
165
+ try {
166
+ for await (const bytes of git.stdout) {
167
+ // While we yield records, Git may be blocked on its pipe while the caller
168
+ // hashes files. Only time waits for a new chunk or for Git to exit.
169
+ clearTimeout(deadline);
170
+ if (timedOut) return false;
171
+ const chunk = Buffer.from(bytes);
172
+ const records = pending.length ? Buffer.concat([pending, chunk]) : chunk;
173
+ let offset = 0;
174
+ for (let end = records.indexOf(0); end !== -1; end = records.indexOf(0, offset)) {
175
+ yield records.subarray(offset, end);
176
+ offset = end + 1;
177
+ }
178
+ pending = records.subarray(offset);
179
+ if (pending.length > 256 * 1024) return false;
180
+ deadline = setTimeout(expire, gitTimeoutMs);
181
+ }
182
+ return pending.length === 0 && await git.exited === 0 && !timedOut;
183
+ } finally {
184
+ clearTimeout(deadline);
185
+ kill();
186
+ await git.exited;
187
+ }
188
+ }
189
+
190
+ async function matchesCommit(root: string, gitArgs: readonly string[], revision: string): Promise<boolean> {
191
+ const index = gitRecords(root, [...gitArgs, "ls-files", "--stage", "-v", "-z"]);
192
+ const tree = gitRecords(root, [...gitArgs, "ls-tree", "-r", "-z", revision]);
193
+ try {
194
+ for (;;) {
195
+ // Both Git inventories are ordered by the raw, full pathname.
196
+ const [indexed, committed] = await Promise.all([index.next(), tree.next()]);
197
+ if (indexed.done || committed.done) return indexed.done === true && committed.done === true
198
+ && indexed.value && committed.value;
199
+ if (!await matchesBlob(root, indexed.value, committed.value)) return false;
200
+ }
201
+ } finally {
202
+ await Promise.all([index.return(false), tree.return(false)]);
203
+ }
204
+ }
205
+
206
+ /** Inspect metadata through Git, and read tracked bytes without Git's content converters. */
207
+ export async function workerRepositoryHead(cwd: string): Promise<(Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">
208
+ & { readonly root: string }) | null> {
209
+ try {
210
+ const canonical = await realpath(cwd);
211
+ const root = await checkoutRoot(canonical);
212
+ if (!root) return null;
213
+ const subdir = relative(root, canonical);
214
+ if (subdir.length > 2048 || !withinTree(subdir) || controls.test(subdir) || subdir.includes("\\")) return null;
215
+ const gitArgs = [`--git-dir=${join(root, ".git")}`, `--work-tree=${root}`];
216
+ const head = [...gitArgs, "rev-parse", "--verify", "HEAD^{commit}"];
217
+ const [repoId, headOutput] = await Promise.all([repositoryIdentity(root), gitWorkerRepository(root, head)]);
218
+ const revision = headOutput?.replace(/\n$/, "");
219
+ if (!repoId || !revision || !gitOid.test(revision)) return null;
220
+ // None of these plumbing commands refresh the index or pass working-tree
221
+ // bytes to a filter. Compare the same parsed index entries to HEAD and disk.
222
+ if (await gitWorkerRepository(root, [...gitArgs, "ls-files", "--others", "--exclude-standard",
223
+ "--directory", "--no-empty-directory", "-z"]) !== "") return null;
224
+ if (!await matchesCommit(root, gitArgs, revision)) return null;
225
+ if (subdir && await gitWorkerRepository(root, [...gitArgs, "cat-file", "-t", `${revision}:${subdir}`]) !== "tree\n") return null;
226
+ const [stableHead, stableRepo] = await Promise.all([gitWorkerRepository(root, head), repositoryIdentity(root)]);
227
+ if (stableHead !== headOutput || stableRepo !== repoId) return null;
228
+ return { root, repoId, revision, subdir };
229
+ } catch (error) {
230
+ if (unavailablePath(error)) return null;
231
+ throw error;
232
+ }
233
+ }
@@ -0,0 +1,74 @@
1
+ import { THINKING_EFFORTS } from "@oh-my-pi/pi-catalog/effort";
2
+ import { AUTO_THINKING } from "@oh-my-pi/pi-tui/thinking";
3
+ import { Type, type Static } from "@sinclair/typebox/type";
4
+ import { Value } from "@sinclair/typebox/value";
5
+ import type { WorkerPolicy } from "./worker-wire";
6
+
7
+ export class WorkerRefusal extends Error {}
8
+
9
+ const strict = { additionalProperties: false } as const;
10
+ const end = "(?![\\s\\S])";
11
+ const text = Type.String({ minLength: 1, maxLength: 4096, pattern: `^[^\\u0000-\\u001f\\u007f]+${end}` });
12
+ const absolute = Type.String({ maxLength: 4096, pattern: `^/[^\\u0000-\\u001f\\u007f]*${end}` });
13
+ const id = Type.String({ minLength: 1, maxLength: 128, pattern: `^[a-zA-Z0-9][a-zA-Z0-9_-]*${end}` });
14
+ const repoId = Type.String({ pattern: `^[0-9a-f]{64}${end}` });
15
+ const generation = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
16
+ const workspaceFields = {
17
+ repoId,
18
+ revision: Type.String({ pattern: `^(?:[0-9a-f]{40}|[0-9a-f]{64})${end}` }),
19
+ subdir: Type.String({ maxLength: 2048, pattern: `^[^\\\\\\u0000-\\u001f\\u007f]*${end}` }),
20
+ };
21
+ const workspace = Type.Object(workspaceFields, strict);
22
+ const laneRefSchema = Type.Object({
23
+ ...workspaceFields, generation,
24
+ laneId: Type.String({ pattern: `^lane-[A-Za-z0-9_-]{1,48}${end}` }),
25
+ }, strict);
26
+ const role = Type.String({ pattern: `^[a-zA-Z][a-zA-Z0-9_-]{0,127}${end}` });
27
+ const launch = Type.Object({
28
+ model: Type.Optional(Type.String({ maxLength: 1024, pattern: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*/[^\\s\\u0000-\\u001f\\u007f]+${end}` })),
29
+ modelPreset: Type.Optional(Type.Object({
30
+ name: role,
31
+ preset: Type.Object({
32
+ modelRoles: Type.Record(role, text, { ...strict, maxProperties: 128 }),
33
+ defaultThinkingLevel: Type.Optional(Type.Union(
34
+ [AUTO_THINKING, ...THINKING_EFFORTS].map(level => Type.Literal(level)),
35
+ )),
36
+ }, strict),
37
+ }, strict)),
38
+ subagentConcurrency: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
39
+ }, strict);
40
+ const envelope = { version: Type.Literal(1) };
41
+ const bound = { ...envelope, workerId: id, ref: laneRefSchema };
42
+ const request = Type.Union([
43
+ Type.Object({ ...envelope, op: Type.Literal("describe"), workspace: Type.Optional(workspace) }, strict),
44
+ Type.Object({ ...bound, op: Type.Literal("probe"), reconcile: Type.Optional(Type.Literal(true)) }, strict),
45
+ Type.Object({ ...bound, op: Type.Literal("open"), launch }, strict),
46
+ Type.Object({ ...bound, op: Type.Literal("attach") }, strict),
47
+ ]);
48
+ const policySchema = Type.Object({
49
+ workerId: id, stateDir: absolute,
50
+ repos: Type.Array(Type.Object({ id: repoId, cwd: absolute }, strict), { minItems: 1, maxItems: 128 }),
51
+ capacity: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
52
+ command: Type.Array(text, { minItems: 1, maxItems: 64 }),
53
+ }, strict);
54
+
55
+ export function parseWorkerRequest(line: Buffer): Static<typeof request> {
56
+ let payload: unknown;
57
+ try { payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line)); }
58
+ catch { throw new WorkerRefusal("Invalid worker request JSON"); }
59
+ if (!Value.Check(request, payload)) throw new WorkerRefusal("Invalid worker request");
60
+ if ((payload.op === "open" || payload.op === "attach" || payload.op === "probe" && payload.reconcile) && payload.ref.generation === 0)
61
+ throw new WorkerRefusal("Invalid worker generation");
62
+ const subdir = payload.op === "describe" ? payload.workspace?.subdir : payload.ref.subdir;
63
+ if (subdir && subdir.split("/").some(part => part === "" || part === "." || part === ".." || part.toLowerCase() === ".git"))
64
+ throw new WorkerRefusal("Invalid worker subdirectory");
65
+ return payload;
66
+ }
67
+
68
+ export function parseWorkerPolicy(value: unknown): WorkerPolicy {
69
+ if (!Value.Check(policySchema, value) || !value.command[0]?.startsWith("/"))
70
+ throw new WorkerRefusal("Invalid worker policy");
71
+ if (new Set(value.repos.map(repo => repo.id)).size !== value.repos.length)
72
+ throw new WorkerRefusal("Worker policy has duplicate repository identities");
73
+ return value;
74
+ }
@@ -0,0 +1,230 @@
1
+ import { createHash } from "node:crypto";
2
+ import { dirname } from "node:path";
3
+ import type { Readable, Writable } from "node:stream";
4
+ import { fileURLToPath } from "node:url";
5
+ import { startHost } from "./host";
6
+ import { boundWorkspace, enrolledRepo, privateWorkerDirectory, reserveCheckout } from "./worker-checkout";
7
+ import { absentWorkerHost, attestWorkerHost, inspectWorkerHost, rawWorkerSocket, readWorkerFiles,
8
+ WORKER_ATTEMPT_ENV, WORKER_SESSION_ENV, workerPaths } from "./worker-host";
9
+ import { WorkerLedger, type WorkerReceipt } from "./worker-ledger";
10
+ import { assertWorkerGitStartup, requireWorkerStartupFlags, workerLaunchProfile, workerManagedUlwPath } from "./worker-profile";
11
+ import { parseWorkerPolicy, parseWorkerRequest, WorkerRefusal } from "./worker-request";
12
+ import { bridgeWorker, workerHeader, workerReply } from "./worker-stdio";
13
+ import type { WorkerDescription, WorkerLaneRef, WorkerLaunch, WorkerPolicy, WorkerProbe, WorkerRepo } from "./worker-wire";
14
+
15
+ type WorkerLane = {
16
+ readonly ref: WorkerLaneRef;
17
+ readonly repo: WorkerRepo;
18
+ readonly paths: ReturnType<typeof workerPaths>;
19
+ };
20
+ type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
21
+
22
+ function validateStorage(policy: WorkerPolicy): void {
23
+ if (!privateWorkerDirectory(policy.stateDir)) throw new WorkerRefusal("Private worker storage is missing");
24
+ // Check the portable limit using a production lane ID before advertising the worker.
25
+ workerPaths(policy, `lane-${"0".repeat(24)}`);
26
+ }
27
+
28
+ function findRepo(policy: WorkerPolicy, repoId: string): WorkerRepo {
29
+ const repo = policy.repos.find(candidate => candidate.id === repoId);
30
+ if (!repo) throw new WorkerRefusal("Worker repository is not enrolled for this key");
31
+ return repo;
32
+ }
33
+
34
+ async function describeWorker(policy: WorkerPolicy, workspace?: Workspace): Promise<WorkerDescription> {
35
+ const platform = process.platform;
36
+ if (platform !== "linux" && platform !== "darwin") throw new WorkerRefusal("Unsupported worker platform");
37
+ const { workerId, stateDir, repos, capacity } = policy;
38
+ // Keep process/Git subprocess counts bounded even when the policy lists many repos.
39
+ for (const repo of repos) await enrolledRepo(policy, repo);
40
+ if (workspace) await boundWorkspace(findRepo(policy, workspace.repoId), workspace);
41
+ return { workerId, platform, stateDir, repos, capacity, active: WorkerLedger.count(policy) };
42
+ }
43
+
44
+ class WorkerService {
45
+ readonly #policy: WorkerPolicy;
46
+ readonly #ledger: WorkerLedger;
47
+
48
+ constructor(policy: WorkerPolicy) {
49
+ this.#policy = policy;
50
+ this.#ledger = new WorkerLedger(policy);
51
+ }
52
+
53
+ close(): void { this.#ledger.close(); }
54
+
55
+ #lane(ref: WorkerLaneRef): WorkerLane {
56
+ return { ref, repo: findRepo(this.#policy, ref.repoId), paths: workerPaths(this.#policy, ref.laneId) };
57
+ }
58
+
59
+ #receipt({ ref, repo }: WorkerLane): WorkerReceipt | null {
60
+ const current = this.#ledger.get(ref.laneId);
61
+ if (current && (current.repoId !== ref.repoId || current.revision !== ref.revision
62
+ || current.subdir !== ref.subdir || current.repoRoot !== repo.cwd))
63
+ throw new WorkerRefusal("Worker lane has a different durable checkout binding");
64
+ if (current && ref.generation < current.generation) throw new WorkerRefusal("Worker lane generation is stale");
65
+ return current;
66
+ }
67
+
68
+ async #reap(): Promise<void> {
69
+ for (const receipt of this.#ledger.active()) {
70
+ if (!this.#policy.repos.some(repo => repo.id === receipt.repoId && repo.cwd === receipt.repoRoot)) continue;
71
+ try { await inspectWorkerHost(this.#ledger, workerPaths(this.#policy, receipt.laneId), receipt, false); }
72
+ catch (error) {
73
+ if (!(error instanceof Error)) throw error;
74
+ // Damaged or unobservable evidence still consumes capacity.
75
+ }
76
+ }
77
+ }
78
+
79
+ async probe(ref: WorkerLaneRef, reconcile = false): Promise<WorkerProbe> {
80
+ const lane = this.#lane(ref);
81
+ const observed = this.#receipt(lane);
82
+ const { exitGeneration, ...probe } = await inspectWorkerHost(this.#ledger, lane.paths, observed);
83
+ // Do not claim ownership or absence for a newer generation unless the current
84
+ // resident was positively released and no different attempt raced this probe.
85
+ if (this.#receipt(lane)?.attempt !== observed?.attempt ||
86
+ (observed && observed.generation < ref.generation && (probe.socket || probe.pidAlive || probe.ownerAlive)))
87
+ return { ...probe, uncertain: true, pid: null, sessionId: null };
88
+ const absent = !probe.uncertain && !probe.socket && !probe.pidAlive && !probe.ownerAlive && probe.pid === null;
89
+ const sealed = absent && this.#ledger.confirmRelease(ref, lane.repo.cwd, { observed, reconcile });
90
+ return { ...probe, ...(sealed && { sealedGeneration: ref.generation }),
91
+ ...(sealed && exitGeneration === ref.generation && { exitGeneration }) };
92
+ }
93
+
94
+ async open(ref: WorkerLaneRef, launch: WorkerLaunch): Promise<{ pid: number }> {
95
+ const lane = this.#lane(ref);
96
+ const preset = launch.modelPreset;
97
+ const launchDigest = createHash("sha256").update(JSON.stringify([launch.model, launch.subagentConcurrency,
98
+ preset?.name, preset?.preset.defaultThinkingLevel, Object.entries(preset?.preset.modelRoles ?? {}).sort()])).digest("hex");
99
+ const observed = this.#receipt(lane);
100
+ if (observed?.generation === ref.generation) {
101
+ if (observed.launchDigest !== launchDigest)
102
+ throw new WorkerRefusal("Worker lane generation was opened with different launch settings");
103
+ const probe = await this.probe(ref);
104
+ if (!probe.uncertain && probe.socket && probe.pidAlive && probe.ownerAlive && probe.pid !== null)
105
+ return { pid: probe.pid };
106
+ throw new WorkerRefusal("Worker lane generation has no verified live Host; it cannot reopen");
107
+ }
108
+ await this.#reap();
109
+ const previous = this.#receipt(lane);
110
+ if (observed?.attempt !== previous?.attempt || (previous && previous.phase !== "released"))
111
+ throw new WorkerRefusal("Worker lane has a resident or uncertain launch");
112
+ if (previous && ref.generation <= previous.generation)
113
+ throw new WorkerRefusal("Worker does not reopen a previous lane generation");
114
+ const gitDir = await enrolledRepo(this.#policy, lane.repo);
115
+ if (previous && previous.gitDir !== gitDir) throw new WorkerRefusal("Worker checkout metadata directory changed");
116
+ const initial = await readWorkerFiles(lane.paths);
117
+ if (absentWorkerHost(initial, previous).uncertain) throw new WorkerRefusal("Worker lane has an unverified socket or journal");
118
+ // Commit admission before reserving the checkout, publishing any session
119
+ // artifacts, or starting the stock OMP process.
120
+ const reservation = this.#ledger.reserve(ref, { repoRoot: lane.repo.cwd, gitDir, launchDigest }, previous);
121
+ let cwd: string;
122
+ let target: ReturnType<typeof workerLaunchProfile>;
123
+ let managedUlwPath: string;
124
+ try {
125
+ reserveCheckout(reservation);
126
+ cwd = await boundWorkspace(lane.repo, ref);
127
+ await assertWorkerGitStartup(lane.repo);
128
+ target = workerLaunchProfile(this.#policy, cwd);
129
+ managedUlwPath = await workerManagedUlwPath(this.#policy.repos);
130
+ await requireWorkerStartupFlags(target.executable, this.#policy.stateDir, target.env);
131
+ if (absentWorkerHost(await readWorkerFiles(lane.paths), reservation).uncertain)
132
+ throw new WorkerRefusal("Worker socket or journal changed before launch");
133
+ privateWorkerDirectory(dirname(lane.paths.socketPath), true);
134
+ privateWorkerDirectory(dirname(dirname(lane.paths.sessionFile)), true);
135
+ privateWorkerDirectory(dirname(lane.paths.sessionFile), true);
136
+ } catch (error) {
137
+ this.#ledger.retire(reservation);
138
+ throw error;
139
+ }
140
+ const launching = { ...reservation, phase: "launching" } as const;
141
+ let preparingSession = false;
142
+ try {
143
+ const { pid } = await startHost({
144
+ ...launch, cwd, command: [target.executable], socketPath: lane.paths.socketPath,
145
+ sessionFile: lane.paths.sessionFile, logPath: lane.paths.logPath,
146
+ extensionPath: fileURLToPath(new URL("./lane-extension.ts", import.meta.url)),
147
+ worker: { ...target.profile, managedUlwPath },
148
+ env: { ...target.env, OMP_SUPERAGENT_ROLE: "lane", OMP_SUPERAGENT_LANE: launching.laneId,
149
+ [WORKER_ATTEMPT_ENV]: launching.attempt, [WORKER_SESSION_ENV]: launching.sessionId ?? "" },
150
+ }, () => {
151
+ if (!this.#ledger.transition(reservation, launching)) throw new WorkerRefusal("Worker launch reservation is no longer current");
152
+ preparingSession = true;
153
+ });
154
+ const probe = await inspectWorkerHost(this.#ledger, lane.paths, launching);
155
+ const actual = this.#ledger.get(ref.laneId);
156
+ if (actual?.attempt !== launching.attempt || actual.phase !== "live" || actual.identity.pid !== pid ||
157
+ !probe.socket || probe.uncertain || probe.pid !== pid)
158
+ throw new WorkerRefusal("Stock worker Host did not confirm the reserved launch identity");
159
+ return { pid };
160
+ } catch (error) {
161
+ if (!preparingSession) {
162
+ this.#ledger.retire(reservation);
163
+ throw new WorkerRefusal("Worker Host preflight failed before session preparation; no Host was launched", { cause: error });
164
+ }
165
+ if (error instanceof WorkerRefusal) throw error;
166
+ throw new WorkerRefusal("Stock worker Host launch is unresolved; inspect the private worker log and probe the same generation", { cause: error });
167
+ }
168
+ }
169
+
170
+ async attach(ref: WorkerLaneRef) {
171
+ const lane = this.#lane(ref);
172
+ const observed = this.#receipt(lane);
173
+ if (observed?.generation !== ref.generation) throw new WorkerRefusal("No worker launch receipt for this generation");
174
+ const probe = await inspectWorkerHost(this.#ledger, lane.paths, observed, observed.phase === "launching");
175
+ const receipt = this.#receipt(lane);
176
+ if (receipt?.attempt !== observed.attempt || receipt.phase !== "live" ||
177
+ !probe.socket || !probe.pidAlive || !probe.ownerAlive)
178
+ throw new WorkerRefusal("Worker lane does not have an attachable native Host");
179
+ const identity = await attestWorkerHost(lane.paths, await readWorkerFiles(lane.paths), receipt);
180
+ const socket = await rawWorkerSocket(lane.paths.socketPath, identity);
181
+ const current = this.#receipt(lane);
182
+ if (current?.phase !== "live" || current.attempt !== receipt.attempt) {
183
+ socket.destroy();
184
+ throw new WorkerRefusal("Worker lane changed before attach");
185
+ }
186
+ return { socket, value: { pid: identity.pid, sessionId: identity.sessionId, sessionFile: identity.sessionFile } };
187
+ }
188
+ }
189
+
190
+ /** One authorized forced-command invocation; never reads commands after the header except an attested native bridge. */
191
+ export async function serveWorker(policy: WorkerPolicy, input: Readable = process.stdin, output: Writable = process.stdout): Promise<void> {
192
+ let service: WorkerService | undefined;
193
+ let attach: Awaited<ReturnType<WorkerService["attach"]>> | undefined;
194
+ let reply: Parameters<typeof workerReply>[1];
195
+ // Broken SSH output is handled by the write callback or the bridge. It is
196
+ // never a death signal to the detached native processes.
197
+ const outputLost = () => input.pause();
198
+ input.on("error", outputLost);
199
+ output.on("error", outputLost);
200
+ try {
201
+ try {
202
+ const request = parseWorkerRequest(await workerHeader(input));
203
+ const bound = parseWorkerPolicy(policy);
204
+ if (request.op !== "describe" && request.workerId !== bound.workerId)
205
+ throw new WorkerRefusal("Worker request names a different enrollment");
206
+ validateStorage(bound);
207
+ if (request.op === "describe") reply = { ok: true, value: await describeWorker(bound, request.workspace) };
208
+ else {
209
+ service = new WorkerService(bound);
210
+ switch (request.op) {
211
+ case "probe": reply = { ok: true, value: await service.probe(request.ref, request.reconcile) }; break;
212
+ case "open": reply = { ok: true, value: await service.open(request.ref, request.launch) }; break;
213
+ case "attach":
214
+ attach = await service.attach(request.ref);
215
+ reply = { ok: true, value: attach.value };
216
+ break;
217
+ }
218
+ }
219
+ } catch (error) {
220
+ reply = { ok: false, error: error instanceof WorkerRefusal ? error.message : "Worker could not verify the operation" };
221
+ } finally { service?.close(); }
222
+ await workerReply(output, reply);
223
+ if (attach) await bridgeWorker(input, output, attach.socket);
224
+ } finally {
225
+ attach?.socket.destroy();
226
+ input.pause();
227
+ input.off("error", outputLost);
228
+ output.off("error", outputLost);
229
+ }
230
+ }
@@ -0,0 +1,61 @@
1
+ import type { Socket } from "node:net";
2
+ import type { Readable, Writable } from "node:stream";
3
+ import { WorkerRefusal } from "./worker-request";
4
+ import { WORKER_HEADER_BYTES } from "./worker-wire";
5
+
6
+ export function workerHeader(input: Readable): Promise<Buffer> {
7
+ return new Promise((resolve, reject) => {
8
+ const chunks: Buffer[] = [];
9
+ let length = 0;
10
+ const stop = () => {
11
+ clearTimeout(timer);
12
+ input.off("readable", read).off("end", closed).off("close", closed).off("error", fail);
13
+ };
14
+ const fail = (error: Error) => { stop(); reject(error); };
15
+ const closed = () => fail(new WorkerRefusal("Worker request ended before its header"));
16
+ const read = () => {
17
+ let chunk: Buffer | null;
18
+ while ((chunk = input.read()) !== null) {
19
+ const end = chunk.indexOf(10);
20
+ length += end < 0 ? chunk.length : end + 1;
21
+ if (length > WORKER_HEADER_BYTES) { fail(new WorkerRefusal("Worker request exceeds header limit")); return; }
22
+ chunks.push(end < 0 ? chunk : chunk.subarray(0, end));
23
+ if (end < 0) continue;
24
+ stop();
25
+ if (end + 1 < chunk.length) input.unshift(chunk.subarray(end + 1));
26
+ resolve(Buffer.concat(chunks, length - 1));
27
+ return;
28
+ }
29
+ };
30
+ const timer = setTimeout(() => fail(new WorkerRefusal("Worker request header timed out")), 10_000);
31
+ input.once("end", closed).once("close", closed).once("error", fail).on("readable", read);
32
+ });
33
+ }
34
+
35
+ export function workerReply(output: Writable, reply: { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly error: string }): Promise<void> {
36
+ const line = `${JSON.stringify(reply)}\n`;
37
+ const framed = Buffer.byteLength(line) <= WORKER_HEADER_BYTES ? line
38
+ : `${JSON.stringify({ ok: false, error: "Worker response exceeds header limit" })}\n`;
39
+ return new Promise((resolve, reject) => output.write(framed, error => error ? reject(error) : resolve()));
40
+ }
41
+
42
+ /** An EOF on either transport detaches only this client. It is not a native exit receipt. */
43
+ export async function bridgeWorker(input: Readable, output: Writable, socket: Socket): Promise<void> {
44
+ const { promise, resolve } = Promise.withResolvers<void>();
45
+ const detach = () => resolve();
46
+ input.once("end", detach).once("close", detach).once("error", detach);
47
+ output.once("close", detach).once("error", detach);
48
+ socket.once("close", detach).once("error", detach);
49
+ try {
50
+ if (input.destroyed || input.readableEnded || output.destroyed || socket.destroyed) return;
51
+ socket.pipe(output, { end: false });
52
+ input.pipe(socket, { end: false });
53
+ await promise;
54
+ } finally {
55
+ input.unpipe(socket).pause();
56
+ socket.unpipe(output).destroy();
57
+ input.off("end", detach).off("close", detach).off("error", detach);
58
+ output.off("close", detach).off("error", detach);
59
+ socket.off("close", detach).off("error", detach);
60
+ }
61
+ }
@@ -0,0 +1,36 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { WorkerRefusal } from "./worker-request";
5
+ import type { WorkerPolicy } from "./worker-wire";
6
+
7
+ const controls = /[\u0000-\u001f\u007f]/;
8
+ export const workerInstallRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));
9
+
10
+ function within(root: string, candidate: string): boolean {
11
+ const suffix = relative(root, candidate);
12
+ return !isAbsolute(suffix) && suffix !== ".." && !suffix.startsWith(`..${sep}`);
13
+ }
14
+
15
+ /** A trusted input is a local account/system path that no enrolled tree or other user can replace. */
16
+ export function trustedWorkerPath(path: string, repos: WorkerPolicy["repos"], kind: "file" | "directory" | "profile"): string {
17
+ const fail = () => new WorkerRefusal(`Worker ${kind} input must be an owned canonical path outside enrolled checkouts`);
18
+ if (!isAbsolute(path) || resolve(path) !== path || controls.test(path) || repos.some(repo => within(repo.cwd, path)))
19
+ throw fail();
20
+ // realpath can preserve the caller's spelling on a case-insensitive volume.
21
+ const enrolled = new Set(repos.flatMap(repo => {
22
+ const stat = lstatSync(repo.cwd, { throwIfNoEntry: false });
23
+ return stat ? [`${stat.dev}:${stat.ino}`] : [];
24
+ }));
25
+ for (let dir = path; ; dir = dirname(dir)) {
26
+ const stat = lstatSync(dir, { throwIfNoEntry: false });
27
+ if (stat) {
28
+ const stickyRoot = dir !== path && stat.uid === 0 && stat.isDirectory() && (stat.mode & 0o1000) !== 0;
29
+ if (enrolled.has(`${stat.dev}:${stat.ino}`) || (stat.uid !== 0 && stat.uid !== process.getuid?.()) ||
30
+ ((stat.mode & 0o022) !== 0 && !stickyRoot) ||
31
+ (dir === path && kind === "file" ? !stat.isFile() : !stat.isDirectory())) throw fail();
32
+ } else if (dir === path && kind !== "profile") throw fail();
33
+ if (dirname(dir) === dir) break;
34
+ }
35
+ return path;
36
+ }