omp-superagent 0.1.18 → 0.1.19

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 (63) hide show
  1. package/docs/OPERATIONS.en.md +127 -30
  2. package/docs/OPERATIONS.md +114 -27
  3. package/docs/design/execution.md +90 -23
  4. package/docs/design/messaging.md +34 -2
  5. package/docs/releases/0.1.19.md +10 -0
  6. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  7. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  8. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  9. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  10. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  11. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  12. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  13. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  14. package/package.json +1 -1
  15. package/skills/head/SKILL.md +4 -3
  16. package/skills/head/references/model-selection.md +8 -22
  17. package/skills/head/references/routing.md +19 -11
  18. package/skills/lane/SKILL.md +24 -76
  19. package/skills/lane/references/workflow.md +7 -94
  20. package/src/cli.ts +36 -16
  21. package/src/config/config.ts +6 -2
  22. package/src/contracts.ts +20 -4
  23. package/src/extension.ts +10 -5
  24. package/src/host-extension.ts +76 -8
  25. package/src/lane/lane-report.ts +1 -1
  26. package/src/lane/lane-rows.ts +2 -1
  27. package/src/lane-extension.ts +4 -21
  28. package/src/messaging/result-attachment.ts +77 -19
  29. package/src/messaging/written-directives.ts +56 -0
  30. package/src/omp/exit-record.ts +27 -0
  31. package/src/omp/host-protocol.ts +20 -0
  32. package/src/omp/host.ts +73 -20
  33. package/src/omp/installed-omp.ts +15 -12
  34. package/src/omp/managed-super.ts +135 -65
  35. package/src/routing/topic-request.ts +7 -4
  36. package/src/runtime/controller.ts +512 -165
  37. package/src/runtime/inbound-attachments.ts +70 -0
  38. package/src/runtime/local-host-fence.ts +85 -0
  39. package/src/runtime/model-journal.ts +14 -9
  40. package/src/runtime/native-frames.ts +5 -1
  41. package/src/runtime/result-attachments.ts +151 -24
  42. package/src/runtime/worker-result-download.ts +36 -0
  43. package/src/storage/store.ts +79 -26
  44. package/src/worker/worker-checkout.ts +89 -9
  45. package/src/worker/worker-destination.ts +8 -7
  46. package/src/worker/worker-doctor.ts +29 -9
  47. package/src/worker/worker-enrollment.ts +44 -12
  48. package/src/worker/worker-git-startup.ts +157 -0
  49. package/src/worker/worker-host.ts +16 -26
  50. package/src/worker/worker-ledger.ts +42 -18
  51. package/src/worker/worker-placement-intent.ts +13 -0
  52. package/src/worker/worker-placement.ts +204 -28
  53. package/src/worker/worker-profile.ts +18 -65
  54. package/src/worker/worker-project-startup.ts +106 -0
  55. package/src/worker/worker-registration.ts +85 -30
  56. package/src/worker/worker-repository.ts +55 -6
  57. package/src/worker/worker-request.ts +13 -6
  58. package/src/worker/worker-result-attachments.ts +185 -0
  59. package/src/worker/worker-result-wire.ts +12 -0
  60. package/src/worker/worker-service.ts +51 -23
  61. package/src/worker/worker-trust.ts +19 -4
  62. package/src/worker/worker-wire.ts +47 -14
  63. package/upstream/super.json +2 -3
@@ -1,50 +1,209 @@
1
+ import { lstatSync, readlinkSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
1
3
  import type { Config } from "../config/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";
4
+ import { workerRepositoryHead, workerRepositoryLocation } from "./worker-repository";
5
+ import { defaultCheckoutContains, listWorkers, matchWorkerDescription, verifyCurrentDefaultCheckout, workerPathSpelling } from "./worker-registration";
6
+ import { workerDescribe, workerDescribeCurrent, type RemotePlacement, type WorkerLaneRef, type WorkerRegistration, type WorkerSelector,
7
+ type WorkerWorkspace } from "./worker-wire";
5
8
 
6
9
  class WorkerPlacementError extends Error {}
7
- type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
8
10
 
9
- async function availableSlots(registration: WorkerRegistration, { repoId, revision, subdir }: Workspace): Promise<number> {
11
+ export type WorkerAssignment = RemotePlacement & (
12
+ { readonly laneId?: never; readonly generation?: never } | Pick<WorkerLaneRef, "laneId" | "generation">
13
+ );
14
+
15
+ function matchesPathSpelling(expected: string, spelled: string): boolean {
16
+ if (spelled === expected) return true;
17
+ const names = expected.split(sep).slice(1);
18
+ const spellings = spelled.split(sep).slice(1);
19
+ if (names.length !== spellings.length) return false;
20
+ let parent: string = sep;
21
+ // Compare alternate names under the same parent before following any link.
22
+ // The final entry can be a replacement symlink: matching its spelling
23
+ // identifies which pin must be verified, not permission to use its target.
24
+ try {
25
+ for (const [index, name] of names.entries()) {
26
+ const spelling = spellings[index];
27
+ if (spelling === undefined) return false;
28
+ const path = `${parent === sep ? "" : parent}${sep}${name}`;
29
+ if (spelling !== name) {
30
+ const entry = lstatSync(`${parent === sep ? "" : parent}${sep}${spelling}`, { bigint: true, throwIfNoEntry: false });
31
+ if (!entry) return false;
32
+ const other = lstatSync(path, { bigint: true, throwIfNoEntry: false });
33
+ if (other?.dev !== entry.dev || other.ino !== entry.ino) return false;
34
+ }
35
+ parent = path;
36
+ }
37
+ } catch (error) {
38
+ if (error instanceof Error && "code" in error && error.code === "ENOTDIR") return false;
39
+ throw error;
40
+ }
41
+ return true;
42
+ }
43
+
44
+ function applicableCurrentDefault(registered: readonly WorkerRegistration[], cwd: string) {
45
+ const defaults = registered.flatMap(registration => {
46
+ const checkout = registration.defaultRepository;
47
+ if (checkout?.mode !== "current") return [];
48
+ const roots = checkout.localPath && checkout.localPath !== checkout.root ? [checkout.localPath, checkout.root] : [checkout.root];
49
+ return roots.map(root => ({ registration, checkout, root }));
50
+ });
51
+ if (!defaults.length) return undefined;
52
+ const applicable = (requested: string) => {
53
+ const inside = (match: (typeof defaults)[number], suffix: string) => {
54
+ const projected = join(match.checkout.root, suffix);
55
+ return defaultCheckoutContains(match.checkout.root, projected) ? { ...match, requested: projected } : undefined;
56
+ };
57
+ const parts = requested.split(sep);
58
+ for (const match of defaults) {
59
+ if (defaultCheckoutContains(match.root, requested)) {
60
+ const location = inside(match, requested.slice(match.root.length));
61
+ if (location) return location;
62
+ }
63
+ }
64
+ for (const match of defaults) {
65
+ const depth = match.root.split(sep).length;
66
+ const requestedRoot = parts.slice(0, depth).join(sep);
67
+ if (matchesPathSpelling(match.root, requestedRoot)) {
68
+ const location = inside(match, parts.slice(depth).join(sep));
69
+ if (location) return location;
70
+ }
71
+ }
72
+ return undefined;
73
+ };
74
+ const direct = applicable(workerPathSpelling(cwd));
75
+ if (direct) return direct;
76
+ // Follow one link at a time. Full realpath would erase a pinned path in
77
+ // the middle of an alias chain, before checking whether it was replaced.
78
+ const parts = cwd.split(sep);
79
+ let prefix = isAbsolute(cwd) ? sep : resolve(".");
80
+ let symlinks = 0;
81
+ while (parts.length) {
82
+ const part = parts.shift();
83
+ if (!part || part === ".") continue;
84
+ if (part === "..") {
85
+ prefix = dirname(prefix);
86
+ const match = applicable(workerPathSpelling([prefix, ...parts].join(sep)));
87
+ if (match) return match;
88
+ continue;
89
+ }
90
+ const path = join(prefix, part);
91
+ try {
92
+ const entry = lstatSync(path, { throwIfNoEntry: false });
93
+ if (!entry) return undefined;
94
+ if (!entry.isSymbolicLink()) {
95
+ prefix = path;
96
+ continue;
97
+ }
98
+ if (++symlinks > 40) throw new WorkerPlacementError("Cannot verify a current default through this symlink chain");
99
+ const target = readlinkSync(path);
100
+ if (isAbsolute(target)) prefix = sep;
101
+ parts.unshift(...target.split(sep));
102
+ const match = applicable(workerPathSpelling([prefix, ...parts].join(sep)));
103
+ if (match) return match;
104
+ } catch (error) {
105
+ if (error instanceof Error && "code" in error && error.code === "ENOTDIR") return undefined;
106
+ throw error;
107
+ }
108
+ }
109
+ return undefined;
110
+ }
111
+
112
+ async function verifiedCurrentPlacement(registration: WorkerRegistration, scope: NonNullable<WorkerSelector["currentWorkspace"]>): Promise<RemotePlacement> {
113
+ const { repoId, subdir } = scope;
114
+ const { workerId, stateDir } = registration.description;
115
+ if (!registration.description.repos.some(repo => repo.id === repoId && repo.currentWorkspace))
116
+ throw new WorkerPlacementError("The paired worker is not approved for current-workspace placement on this repository");
117
+ try {
118
+ const reply = await workerDescribeCurrent(registration, { repoId, subdir });
119
+ if (matchWorkerDescription(registration.description, reply)) {
120
+ const { revision, workerCheckout } = reply.workspace;
121
+ return { workerId, stateDir, repoId, subdir, revision, workerCheckout };
122
+ }
123
+ } catch (error) {
124
+ if (!(error instanceof Error)) throw error;
125
+ }
126
+ throw new WorkerPlacementError("Could not verify the named worker's current checkout; no lane was placed");
127
+ }
128
+
129
+ async function workerAvailability(registration: WorkerRegistration, { repoId, revision, subdir, workerCheckout }: WorkerWorkspace) {
10
130
  const saved = registration.description;
11
131
  const approved = saved.repos.find(repo => repo.id === repoId);
12
- if (!approved) return 0;
132
+ if (!approved || workerCheckout && !approved.currentWorkspace) return null;
13
133
  try {
14
- const live = await workerDescribe(registration, { repoId, revision, subdir });
134
+ const live = await workerDescribe(registration, { repoId, revision, subdir, ...(workerCheckout && { workerCheckout }) });
15
135
  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;
136
+ const verified = workerCheckout ? matchWorkerDescription(saved, live)
137
+ : live.workerId === saved.workerId && live.platform === saved.platform && live.stateDir === saved.stateDir
138
+ && inventory.length === 1 && inventory[0]?.cwd === approved.cwd
139
+ && inventory[0].trustedCheckout === approved.trustedCheckout && inventory[0].currentWorkspace === approved.currentWorkspace;
140
+ if (!verified) return null;
141
+ const occupancy = live.occupancy && new Map(live.occupancy.map(ref => [ref.laneId, ref]));
142
+ return { free: Math.max(0, Math.min(saved.capacity, live.capacity) - live.active), checkoutBusy: live.checkoutBusy === true,
143
+ occupancy: occupancy?.size === live.active && live.occupancy?.length === live.active ? occupancy : undefined };
18
144
  } catch (error) {
19
- if (error instanceof Error) return 0; // No readiness receipt; no permission to open.
145
+ if (error instanceof Error) return null; // No readiness receipt; no permission to open.
20
146
  throw error;
21
147
  }
22
148
  }
23
149
 
24
150
  /** 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;
151
+ export async function workerPlacementReady(registration: WorkerRegistration, workspace: WorkerWorkspace): Promise<boolean> {
152
+ const available = await workerAvailability(registration, workspace);
153
+ return available !== null && !available.checkoutBusy && available.free > 0;
27
154
  }
28
155
 
29
156
  /** Admission only: read approved inventory and live capacity; never start work here. */
30
157
  export async function selectWorkerPlacement(
31
158
  config: Pick<Config, "stateDir">, cwd: string, placement?: WorkerSelector,
32
- admission?: { queued(): ReadonlyMap<string, number>; reserve(workerId: string): void },
159
+ admission?: { queued(): readonly WorkerAssignment[]; reserve(assignment: WorkerAssignment): void },
33
160
  ): Promise<RemotePlacement | null> {
34
161
  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");
162
+ if (placement.platform !== undefined || placement.worker !== undefined || placement.currentWorkspace) {
163
+ throw new WorkerPlacementError("Local placement cannot specify a remote worker, worker platform, or current worker checkout");
37
164
  }
38
165
  return null;
39
166
  }
167
+ const current = placement?.currentWorkspace;
168
+ if (current && !placement?.worker) throw new WorkerPlacementError("Worker-current placement requires one exact paired worker ID");
40
169
  const required = placement?.target === "remote" || placement?.platform !== undefined || placement?.worker !== undefined;
41
170
  const registered = listWorkers(config.stateDir).filter(({ description, defaultRepository }) =>
42
171
  (required || defaultRepository !== undefined) && (placement?.worker === undefined || description.workerId === placement.worker)
43
172
  && (placement?.platform === undefined || description.platform === placement.platform));
44
- if (!registered.length) {
173
+ const [first] = registered;
174
+ if (!first) {
45
175
  if (!required) return null;
46
176
  throw new WorkerPlacementError("No paired worker matches the requested worker or platform");
47
177
  }
178
+ if (current) {
179
+ const { repoId, subdir } = current;
180
+ const source = await workerRepositoryLocation(cwd);
181
+ if (source?.repoId !== repoId || source.subdir !== subdir)
182
+ throw new WorkerPlacementError("Worker-current placement requires a local directory matching the approved repository identity and subdirectory");
183
+ const selected = await verifiedCurrentPlacement(first, current);
184
+ admission?.reserve(selected);
185
+ return selected;
186
+ }
187
+ if (placement === undefined) {
188
+ const match = applicableCurrentDefault(registered, cwd);
189
+ if (match) {
190
+ const { registration, checkout, requested } = match;
191
+ const verifyLocal = async () => {
192
+ const source = await workerRepositoryLocation(cwd);
193
+ if (!source || source.root !== checkout.root || source.repoId !== checkout.repoId || source.localCheckout !== checkout.localCheckout
194
+ || !matchesPathSpelling(join(source.root, source.subdir), requested)
195
+ || checkout.localPath && checkout.localPath !== checkout.root && !await verifyCurrentDefaultCheckout(checkout))
196
+ throw new WorkerPlacementError("The configured current default does not match the original local checkout; no lane was placed");
197
+ return source.subdir;
198
+ };
199
+ const subdir = await verifyLocal();
200
+ const selected = await verifiedCurrentPlacement(registration, { repoId: checkout.repoId, subdir });
201
+ if (await verifyLocal() !== subdir)
202
+ throw new WorkerPlacementError("The selected local workspace changed during current placement; no lane was placed");
203
+ admission?.reserve(selected);
204
+ return selected;
205
+ }
206
+ }
48
207
  const source = await workerRepositoryHead(cwd);
49
208
  if (!source) {
50
209
  if (!required) return null;
@@ -53,26 +212,43 @@ export async function selectWorkerPlacement(
53
212
  const { root, ...workspace } = source;
54
213
  const candidates = registered.filter(({ description, defaultRepository }) =>
55
214
  description.repos.some(repo => repo.id === workspace.repoId) &&
56
- (required || (defaultRepository?.root === root && defaultRepository.repoId === workspace.repoId)));
215
+ (required || (!defaultRepository?.mode && defaultRepository?.root === root && defaultRepository.repoId === workspace.repoId)));
57
216
  if (!candidates.length) {
58
217
  if (!required) return null;
59
218
  throw new WorkerPlacementError("No matching paired worker is approved for this repository identity");
60
219
  }
61
- const observed = await Promise.all(candidates.map(async worker => ({ worker, free: await availableSlots(worker, workspace) })));
220
+ const observed = await Promise.all(candidates.map(async worker => ({ worker, available: await workerAvailability(worker, workspace) })));
62
221
  // Read and reserve synchronously after the SSH round trips: concurrent
63
222
  // 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)
223
+ const waiting = new Map<string, WorkerAssignment[]>();
224
+ for (const assignment of admission?.queued() ?? []) {
225
+ const pending = waiting.get(assignment.workerId);
226
+ if (pending) pending.push(assignment);
227
+ else waiting.set(assignment.workerId, [assignment]);
228
+ }
229
+ const ranked = observed.map(({ worker, available }) => {
230
+ const pending = waiting.get(worker.description.workerId) ?? [];
231
+ const checkoutRank = pending.some(assignment => assignment.repoId === workspace.repoId) || available?.checkoutBusy ? 2 : available ? 0 : 1;
232
+ const queued = pending.filter(assignment => {
233
+ const counted = assignment.laneId === undefined || assignment.stateDir !== worker.description.stateDir
234
+ ? undefined : available?.occupancy?.get(assignment.laneId);
235
+ return !counted || counted.generation !== assignment.generation || counted.repoId !== assignment.repoId
236
+ || counted.revision !== assignment.revision || counted.subdir !== assignment.subdir || counted.workerCheckout !== assignment.workerCheckout;
237
+ }).length;
238
+ return { worker, checkoutRank, queued, free: available?.free ?? 0 };
239
+ }).sort((left, right) => {
240
+ const a = left.worker.description.workerId, b = right.worker.description.workerId;
241
+ return left.checkoutRank - right.checkoutRank || left.queued - right.queued
242
+ || Number(right.worker.defaultRepository !== undefined) - Number(left.worker.defaultRepository !== undefined)
69
243
  || (a === b ? 0 : a < b ? -1 : 1);
70
244
  });
71
245
  // Explicit placement freezes its worker even when no candidate is ready now.
72
246
  // 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 };
247
+ const chosen = (ranked.find(({ checkoutRank, free, queued }) => checkoutRank === 0 && free > queued)
248
+ ?? (required ? ranked[0] : null))?.worker;
249
+ if (!chosen) return null;
250
+ const { workerId, stateDir } = chosen.description;
251
+ const selected = { workerId, stateDir, ...workspace };
252
+ admission?.reserve(selected);
253
+ return selected;
78
254
  }
@@ -1,25 +1,26 @@
1
1
  import { Database } from "bun:sqlite";
2
2
  import { lstatSync, realpathSync } from "node:fs";
3
- import { delimiter, dirname, isAbsolute, join } from "node:path";
3
+ import { join } from "node:path";
4
4
  import { readWorkerFile } from "./worker-registration";
5
- import { gitWorkerRepository } from "./worker-repository";
5
+ import { assertWorkerWorkspaceStartup, workerDotenvFiles } from "./worker-project-startup";
6
6
  import { WorkerRefusal } from "./worker-request";
7
- import { trustedWorkerPath, workerInstallRoot } from "./worker-trust";
8
- import type { WorkerPolicy, WorkerRepo } from "./worker-wire";
7
+ import { trustedWorkerPath, workerCommandPath, workerInstallRoot, workerPathContains } from "./worker-trust";
8
+ import type { WorkerPolicy } from "./worker-wire";
9
9
  import type { WorkerMemoryLaunch } from "./worker-memory-storage";
10
10
 
11
11
  export interface WorkerHostProfile {
12
- readonly config: Readonly<Record<string, unknown>>;
12
+ readonly config: Readonly<Record<string, unknown> & ReturnType<typeof assertWorkerWorkspaceStartup>>;
13
13
  readonly flags: readonly string[];
14
14
  readonly extensionPaths: readonly string[];
15
15
  readonly managedUlwPath: string;
16
+ readonly trustedWorkspaceRoot?: string;
16
17
  readonly memory?: WorkerMemoryLaunch;
17
18
  }
18
19
 
19
20
  const flags = ["--no-extensions", "--no-lsp"] as const;
20
21
  // --no-extensions is necessary but does not suppress all stock custom tool and
21
22
  // MCP discovery. Keep only the explicitly composed OMP extension roots and
22
- // builtin resources. Reject independent project config before the CLI starts.
23
+ // builtin resources; opting in to project data never enables executable discovery.
23
24
  const config = {
24
25
  disabledProviders: ["native", "agent-plugins", "agents", "agents-md", "claude", "claude-md", "claude-plugins",
25
26
  "cline", "codex", "cursor", "custom-context", "gemini", "github", "mcp-json", "opencode", "skillshare",
@@ -28,11 +29,6 @@ const config = {
28
29
  marketplace: { autoUpdate: false },
29
30
  skills: { customDirectories: [], enablePiProject: false, enableAgentsProject: false, enableClaudeProject: false },
30
31
  };
31
- const dotenv = [".env", ".env.local", ".env.development", ".env.development.local",
32
- ".env.production", ".env.production.local", ".env.test", ".env.test.local"];
33
- const projectInputs = [...dotenv, "bunfig.toml", ".omp", ".pi", ".claude", ".codex", ".cursor", ".gemini",
34
- ".opencode", ".agent", ".agents", ".cline", ".windsurf", ".codeium", ".omp-plugin", ".claude-plugin",
35
- "mcp.json", ".mcp.json", ".vscode/mcp.json", "opencode.json", "opencode.jsonc", "WATCHDOG.yml", "WATCHDOG.yaml"];
36
32
  const providerEnvironment = [
37
33
  "ANTHROPIC_API_KEY", "ANTHROPIC_OAUTH_TOKEN", "OPENAI_API_KEY", "GEMINI_API_KEY", "COPILOT_GITHUB_TOKEN",
38
34
  "AZURE_OPENAI_API_KEY", "GROQ_API_KEY", "CEREBRAS_API_KEY", "XAI_API_KEY", "OPENROUTER_API_KEY",
@@ -43,27 +39,7 @@ const providerEnvironment = [
43
39
  "SCW_SECRET_KEY", "OTARI_API_KEY",
44
40
  ] as const;
45
41
 
46
- const controls = /[\u0000-\u001f\u007f]/;
47
42
  const appData = ["XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME"] as const;
48
- const gitSettings = [
49
- /^core\.(repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|symlinks|autocrlf|eol|safecrlf)$/,
50
- /^extensions\.objectformat$/,
51
- /^remote\.[A-Za-z0-9._/-]+\.(url|pushurl|fetch|push|tagopt|prune|prunetags|mirror|followremotehead)$/,
52
- /^branch\.[A-Za-z0-9._/-]+\.(remote|merge|rebase|pushremote|description)$/,
53
- /^user\.(name|email|useconfigonly)$/,
54
- ];
55
-
56
- /** Stock sources read cwd, its Git root and, for plugin registries, ancestors above the root. */
57
- export function assertWorkerWorkspaceStartup(cwd: string, home: string): void {
58
- for (let dir = cwd; ; dir = dirname(dir)) {
59
- if (dir === home || (dir !== cwd && ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"].includes(dir))) break;
60
- for (const name of projectInputs) {
61
- if (lstatSync(join(dir, name), { throwIfNoEntry: false }))
62
- throw new WorkerRefusal(`Worker startup refuses project configuration (${name}); use a checkout without ambient OMP inputs`);
63
- }
64
- if (dirname(dir) === dir) break;
65
- }
66
- }
67
43
 
68
44
  function readProfileFile(path: string, mode?: number): Buffer | undefined {
69
45
  try { return readWorkerFile(path, mode); }
@@ -159,20 +135,6 @@ function workerProfileInputs(agent: string, repos: WorkerPolicy["repos"]) {
159
135
  return { disabledProviders: [...disabledProviders], extensionPaths };
160
136
  }
161
137
 
162
- function pathEnvironment(source: NodeJS.ProcessEnv, repos: WorkerPolicy["repos"]): string {
163
- const dirs = new Set<string>();
164
- for (const raw of (source.PATH ?? "").split(delimiter)) {
165
- if (!isAbsolute(raw) || controls.test(raw)) continue;
166
- try { dirs.add(trustedWorkerPath(realpathSync(raw), repos, "directory")); }
167
- catch (error) {
168
- if (!(error instanceof WorkerRefusal) && !(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
169
- }
170
- }
171
- for (const dir of ["/usr/bin", "/bin", "/usr/sbin", "/sbin"])
172
- if (lstatSync(dir, { throwIfNoEntry: false })) dirs.add(realpathSync(dir));
173
- return [...dirs].join(delimiter);
174
- }
175
-
176
138
  /** Project checks and target profile checks run before either OMP or the SDK preparation process starts. */
177
139
  export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: NodeJS.ProcessEnv = process.env) {
178
140
  const { repos, stateDir, command } = policy;
@@ -180,7 +142,10 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
180
142
  if (command.length !== 1 || executable === undefined)
181
143
  throw new WorkerRefusal("Worker startup requires one enrolled stock OMP executable, with no extra arguments");
182
144
  const home = trustedWorkerPath(source.HOME ?? "", repos, "directory");
183
- assertWorkerWorkspaceStartup(cwd, home);
145
+ const repo = repos.filter(repo => workerPathContains(repo.cwd, cwd))
146
+ .sort((left, right) => right.cwd.length - left.cwd.length)[0];
147
+ const trustedWorkspaceRoot = repo?.trustedCheckout ? repo.cwd : undefined;
148
+ const projectSettings = assertWorkerWorkspaceStartup(cwd, home, trustedWorkspaceRoot);
184
149
  assertWorkerWorkspaceStartup(stateDir, home);
185
150
  trustedWorkerPath(executable, repos, "file");
186
151
  trustedWorkerPath(workerInstallRoot, repos, "directory");
@@ -196,14 +161,17 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
196
161
  const defaultAgent = join(root, "agent");
197
162
  const agent = trustedWorkerPath((profileName ? undefined : source.PI_CODING_AGENT_DIR) || defaultAgent, repos, "profile");
198
163
  const env: Record<string, string> = {
199
- HOME: home, PATH: pathEnvironment(source, repos), PI_CODING_AGENT_DIR: agent,
164
+ HOME: home, PATH: workerCommandPath(source, repos), PI_CODING_AGENT_DIR: agent,
200
165
  ...(profileName ? { OMP_PROFILE: profileName } : {}),
201
166
  // Stock OMP can also ask Git about the current workspace during startup.
202
167
  GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null",
203
168
  GIT_CONFIG_COUNT: "2", GIT_CONFIG_KEY_0: "core.fsmonitor", GIT_CONFIG_VALUE_0: "false",
204
169
  GIT_CONFIG_KEY_1: "core.hooksPath", GIT_CONFIG_VALUE_1: "/dev/null",
205
170
  };
206
- for (const name of ["LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", ...providerEnvironment]) {
171
+ // An opted-in project can have local Git filters and ordinary project scripts.
172
+ // Authenticate OMP from its private stored profile, not secrets inherited by subprocesses.
173
+ const providerEnv = trustedWorkspaceRoot ? [] : providerEnvironment;
174
+ for (const name of ["LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", ...providerEnv]) {
207
175
  const value = source[name];
208
176
  if (value && !value.includes("\0")) env[name] = value;
209
177
  }
@@ -225,7 +193,7 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
225
193
  }
226
194
  }
227
195
  for (const dir of new Set([home, base, root, agent])) {
228
- if ([...dotenv, ".bunfig.toml", "bunfig.toml"].some(name => lstatSync(join(dir, name), { throwIfNoEntry: false })))
196
+ if ([...workerDotenvFiles, ".bunfig.toml", "bunfig.toml"].some(name => lstatSync(join(dir, name), { throwIfNoEntry: false })))
229
197
  throw new WorkerRefusal("Worker startup does not read target dotenv or Bun preload configuration; use the target profile's stored auth");
230
198
  }
231
199
  for (const dir of pluginRoots) {
@@ -241,7 +209,7 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
241
209
  }
242
210
  const { disabledProviders, extensionPaths } = workerProfileInputs(agent, repos);
243
211
  assertWorkerAuthDatabase(join(authDbRoot, "agent.db"));
244
- return { env, profile: { config: { ...config, disabledProviders }, flags, extensionPaths }, executable };
212
+ return { env, profile: { config: { ...projectSettings, ...config, disabledProviders }, flags, extensionPaths, trustedWorkspaceRoot }, executable };
245
213
  }
246
214
 
247
215
  export async function workerManagedUlwPath(repos: WorkerPolicy["repos"]): Promise<string> {
@@ -250,21 +218,6 @@ export async function workerManagedUlwPath(repos: WorkerPolicy["repos"]): Promis
250
218
  catch (cause) { throw new WorkerRefusal("Worker requires an active operator-installed managed superkit outside enrolled checkouts", { cause }); }
251
219
  }
252
220
 
253
- /** Stock Git may interpret more configuration than the read-only checkout verifier. */
254
- export async function assertWorkerGitStartup(repo: WorkerRepo): Promise<void> {
255
- const metadata = join(repo.cwd, ".git");
256
- const configFile = join(metadata, "config");
257
- const stat = lstatSync(configFile, { throwIfNoEntry: false });
258
- if (!stat?.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o022) !== 0 ||
259
- lstatSync(join(metadata, "config.worktree"), { throwIfNoEntry: false }))
260
- throw new WorkerRefusal("Worker startup requires an owned regular Git config without worktree overrides");
261
- const values = await gitWorkerRepository(repo.cwd, ["config", "--local", "--no-includes", "--null", "--list"]);
262
- if (!values?.endsWith("\0") || values.slice(0, -1).split("\0").some(entry => {
263
- const key = entry.split("\n", 1)[0] ?? "";
264
- return !gitSettings.some(allowed => allowed.test(key));
265
- })) throw new WorkerRefusal("Worker startup refuses nonstandard local Git configuration (including hooks, filters and includes)");
266
- }
267
-
268
221
  /** Required public launch switches must be advertised by the enrolled binary, not the bundled SDK. */
269
222
  export async function requireWorkerStartupFlags(executable: string, cwd: string, env: Record<string, string>): Promise<void> {
270
223
  const child = Bun.spawn([executable, "--help"], {
@@ -0,0 +1,106 @@
1
+ import { lstatSync, readdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { checkWorkerFile, readWorkerFile } from "./worker-registration";
4
+ import { WorkerRefusal } from "./worker-request";
5
+ import { workerPathContains } from "./worker-trust";
6
+
7
+ export const workerDotenvFiles = [".env", ".env.local", ".env.development", ".env.development.local",
8
+ ".env.production", ".env.production.local", ".env.test", ".env.test.local"];
9
+ const projectInputs = [...workerDotenvFiles, ".bunfig.toml", "bunfig.toml", ".omp", ".pi", ".claude", ".codex", ".cursor", ".gemini",
10
+ ".opencode", ".agent", ".agents", ".cline", ".windsurf", ".codeium", ".omp-plugin", ".claude-plugin",
11
+ "mcp.json", ".mcp.json", ".vscode/mcp.json", "opencode.json", "opencode.jsonc", "WATCHDOG.yml", "WATCHDOG.yaml"];
12
+ const thinkingLevels = new Set(["auto", "minimal", "low", "medium", "high", "xhigh", "max"]);
13
+ const rolePattern = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}(?![\s\S])/u;
14
+ const modelPattern = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*\/[^\s\u0000-\u001f\u007f]+(?![\s\S])/u;
15
+
16
+ type ProjectSettings<Role extends string | null = string> = { defaultThinkingLevel?: string; modelRoles?: Record<string, Role> };
17
+
18
+ function inputRefusal(name: string) {
19
+ return new WorkerRefusal(`Worker startup refuses project configuration (${name}); only supported data in an operator-trusted checkout is allowed`);
20
+ }
21
+
22
+ function plainObject(value: unknown): value is Record<string, unknown> {
23
+ if (value === null || typeof value !== "object") return false;
24
+ const prototype = Object.getPrototypeOf(value);
25
+ return prototype === Object.prototype || prototype === null;
26
+ }
27
+
28
+ /** Keep the native provider disabled: allow only these typed values into the private launch overlay. */
29
+ function readProjectSettings(path: string, json: boolean): ProjectSettings<string | null> {
30
+ const bytes = readWorkerFile(path, 0o644);
31
+ if (!bytes) throw inputRefusal(".omp");
32
+ const content = bytes.toString("utf8");
33
+ const settings: unknown = !content.trim() ? {} : json ? JSON.parse(content) : Bun.YAML.parse(content);
34
+ if (!plainObject(settings)) throw inputRefusal(".omp");
35
+ const result: ProjectSettings<string | null> = {};
36
+ for (const [key, value] of Object.entries(settings)) {
37
+ if (key === "defaultThinkingLevel" && typeof value === "string" && thinkingLevels.has(value)) {
38
+ result.defaultThinkingLevel = value;
39
+ } else if (key === "modelRoles" && plainObject(value)) {
40
+ const roles: Record<string, string | null> = {};
41
+ for (const [role, model] of Object.entries(value)) {
42
+ if (!rolePattern.test(role) || model !== null && !(typeof model === "string" && modelPattern.test(model)))
43
+ throw inputRefusal(".omp");
44
+ roles[role] = model;
45
+ }
46
+ result.modelRoles = roles;
47
+ } else throw inputRefusal(".omp");
48
+ }
49
+ return result;
50
+ }
51
+
52
+ function readProjectOmp(path: string): ProjectSettings {
53
+ const info = lstatSync(path);
54
+ if (!info.isDirectory() || info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0) throw inputRefusal(".omp");
55
+ let yaml: ProjectSettings<string | null> = {}, json: ProjectSettings<string | null> = {};
56
+ for (const name of readdirSync(path)) {
57
+ const file = join(path, name);
58
+ if (name === "config.yml") yaml = readProjectSettings(file, false);
59
+ else if (name === "settings.json") json = readProjectSettings(file, true);
60
+ else if (["AGENTS.md", "RULES.md", "README.md", ".gitignore"].includes(name)) checkWorkerFile(lstatSync(file), 0o644);
61
+ else throw inputRefusal(".omp");
62
+ }
63
+ const { modelRoles: jsonRoles, ...jsonSettings } = json;
64
+ const { modelRoles: yamlRoles, ...yamlSettings } = yaml;
65
+ const settings: ProjectSettings = { ...jsonSettings, ...yamlSettings };
66
+ if (jsonRoles || yamlRoles) {
67
+ // Stock OMP clears a project role back to the profile. A null in --config
68
+ // would instead mask that profile role. Resolve the project layer first.
69
+ const roles: Record<string, string> = {};
70
+ for (const [name, model] of Object.entries({ ...jsonRoles, ...yamlRoles })) {
71
+ if (model !== null) roles[name] = model;
72
+ }
73
+ settings.modelRoles = roles;
74
+ }
75
+ return settings;
76
+ }
77
+
78
+ /** Stock discovery can read ancestors; the opt-in extends no higher than the exact enrolled root. */
79
+ export function assertWorkerWorkspaceStartup(cwd: string, home: string, trustedRoot?: string): ProjectSettings {
80
+ let settings: ProjectSettings = {};
81
+ for (let dir = cwd; ; dir = dirname(dir)) {
82
+ if (dir === home || (dir !== cwd && ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"].includes(dir))) break;
83
+ const trusted = trustedRoot !== undefined && workerPathContains(trustedRoot, dir);
84
+ for (const name of projectInputs) {
85
+ const path = join(dir, name);
86
+ const info = lstatSync(path, { throwIfNoEntry: false });
87
+ if (!info) continue;
88
+ if (!trusted) throw inputRefusal(name);
89
+ try {
90
+ if (name === ".omp") {
91
+ const project = readProjectOmp(path);
92
+ if (dir === cwd) settings = project; // Stock settings scope is exactly the selected cwd.
93
+ } else if (workerDotenvFiles.includes(name)) {
94
+ // The CLI/SDK bootstrap outside the checkout. Do not copy, evaluate, or
95
+ // load dotenv values into the worker environment; project tools can read them.
96
+ checkWorkerFile(info, 0o644);
97
+ } else throw inputRefusal(name);
98
+ } catch {
99
+ // Parser/OS messages can contain settings values or dotenv paths.
100
+ throw inputRefusal(name);
101
+ }
102
+ }
103
+ if (dirname(dir) === dir) break;
104
+ }
105
+ return settings;
106
+ }