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
@@ -10,23 +10,26 @@ import { Value } from "@sinclair/typebox/value";
10
10
  import { privateDirectory } from "../config/config";
11
11
  import { stagePrivateFile } from "../config/credentials";
12
12
  import { parseWorkerDestination } from "./worker-destination";
13
- import { workerRepositoryHead } from "./worker-repository";
13
+ import { workerRepositoryHead, workerRepositoryLocation } from "./worker-repository";
14
14
  import { trustedWorkerPath } from "./worker-trust";
15
- import { WorkerDescriptionSchema, type WorkerDescription, type WorkerLaneRef, type WorkerRegistration } from "./worker-wire";
15
+ import { WorkerDescriptionSchema, workerDescribeCurrent, type WorkerDefaultRepository, type WorkerDescription,
16
+ type WorkerLaneRef, type WorkerRegistration } from "./worker-wire";
16
17
 
17
18
  export class WorkerRegistrationError extends Error {
18
19
  override readonly name = "WorkerRegistrationError";
19
20
  }
20
21
 
22
+ const repoBinding = { root: Type.String(), repoId: Type.String({ pattern: "^[0-9a-f]{64}$" }) };
21
23
  const inventory = Type.Array(Type.Object({
22
24
  destination: Type.String(),
23
25
  identityFile: Type.String(),
24
26
  description: WorkerDescriptionSchema,
25
27
  default: Type.Optional(Type.Boolean()),
26
- defaultRepository: Type.Optional(Type.Object({
27
- root: Type.String(),
28
- repoId: Type.String({ pattern: "^[0-9a-f]{64}$" }),
29
- }, { additionalProperties: false })),
28
+ defaultRepository: Type.Optional(Type.Union([
29
+ Type.Object(repoBinding, { additionalProperties: false }),
30
+ Type.Object({ ...repoBinding, mode: Type.Literal("current"),
31
+ localCheckout: Type.String({ pattern: "^[0-9a-f]{64}$" }), localPath: Type.Optional(Type.String()) }, { additionalProperties: false }),
32
+ ])),
30
33
  }));
31
34
  const fileLimit = 1024 * 1024;
32
35
  const controls = /[\u0000-\u001f\u007f]/;
@@ -131,7 +134,9 @@ function validateDescription(value: unknown): WorkerDescription {
131
134
  throw new WorkerRegistrationError("Invalid worker description");
132
135
  return {
133
136
  workerId: value.workerId, platform: value.platform, stateDir: value.stateDir,
134
- repos: value.repos.map(({ id, cwd }) => ({ id, cwd })).sort((left, right) => left.id.localeCompare(right.id)),
137
+ repos: value.repos.map(({ id, cwd, currentWorkspace, trustedCheckout }) => ({
138
+ id, cwd, ...(currentWorkspace && { currentWorkspace }), ...(trustedCheckout && { trustedCheckout }),
139
+ })).sort((left, right) => left.id.localeCompare(right.id)),
135
140
  capacity: value.capacity, active: value.active,
136
141
  };
137
142
  }
@@ -140,6 +145,29 @@ function canonicalPath(path: string): boolean {
140
145
  return isAbsolute(path) && normalize(path) === path && !controls.test(path);
141
146
  }
142
147
 
148
+ export function defaultCheckoutContains(root: string, path: string): boolean {
149
+ return path === root || path.startsWith(root === "/" ? "/" : `${root}/`);
150
+ }
151
+
152
+ /** Preserve traversal through an explicitly selected pathname, including symlink ancestors. */
153
+ export function workerPathSpelling(path: string): string {
154
+ const absolute = isAbsolute(path) ? path : `${process.cwd()}/${path}`;
155
+ return `/${absolute.split("/").filter(part => part && part !== ".").join("/")}`;
156
+ }
157
+
158
+ export async function verifyCurrentDefaultCheckout(checkout: Extract<WorkerDefaultRepository, { mode: "current" }>): Promise<boolean> {
159
+ const source = await workerRepositoryLocation(checkout.localPath ?? checkout.root);
160
+ return source !== null && source.root === checkout.root && source.repoId === checkout.repoId
161
+ && source.subdir === "" && source.localCheckout === checkout.localCheckout;
162
+ }
163
+
164
+ function conflictingDefault(left: WorkerDefaultRepository, right: WorkerDefaultRepository): boolean {
165
+ if (!left.mode && !right.mode) return true;
166
+ const paths = (checkout: WorkerDefaultRepository) => checkout.mode && checkout.localPath
167
+ ? [checkout.root, checkout.localPath] : [checkout.root];
168
+ return paths(left).some(a => paths(right).some(b => defaultCheckoutContains(a, b) || defaultCheckoutContains(b, a)));
169
+ }
170
+
143
171
  /** Last verified inventory, not endpoint readiness. Pending keys are not listed. */
144
172
  export function listWorkers(stateDir: string): WorkerRegistration[] {
145
173
  const directory = join(stateDir, "workers");
@@ -151,18 +179,22 @@ export function listWorkers(stateDir: string): WorkerRegistration[] {
151
179
  if (!Value.Check(inventory, parsed)) throw new WorkerRegistrationError("Invalid verified worker inventory");
152
180
  const ids = new Set<string>();
153
181
  const destinations = new Set<string>();
154
- let defaultSeen = false;
182
+ const defaults: WorkerDefaultRepository[] = [];
155
183
  return parsed.map(({ destination, identityFile, description, default: preferred, defaultRepository }) => {
156
184
  const verified = validateDescription(description);
157
185
  if (!parseWorkerDestination(destination) || identityFile !== endpointFor(stateDir, destination).identityFile ||
158
186
  ids.has(verified.workerId) || destinations.has(destination) ||
159
- (defaultRepository && (!preferred || defaultSeen || !canonicalPath(defaultRepository.root)
160
- || !verified.repos.some(repo => repo.id === defaultRepository.repoId))))
187
+ (defaultRepository && (!preferred || !canonicalPath(defaultRepository.root)
188
+ || ("localPath" in defaultRepository && defaultRepository.localPath !== undefined
189
+ && (!isAbsolute(defaultRepository.localPath) || controls.test(defaultRepository.localPath)
190
+ || workerPathSpelling(defaultRepository.localPath) !== defaultRepository.localPath))
191
+ || defaults.some(other => conflictingDefault(other, defaultRepository))
192
+ || !verified.repos.some(repo => repo.id === defaultRepository.repoId && (!("mode" in defaultRepository) || repo.currentWorkspace)))))
161
193
  throw new WorkerRegistrationError("Conflicting verified worker inventory");
162
194
  ids.add(verified.workerId);
163
195
  destinations.add(destination);
164
196
  // Legacy boolean-only entries never authorized disclosure from any local checkout.
165
- defaultSeen ||= defaultRepository !== undefined;
197
+ if (defaultRepository) defaults.push(defaultRepository);
166
198
  return { destination, identityFile, description: verified, ...(defaultRepository && { default: true, defaultRepository }) };
167
199
  });
168
200
  }
@@ -174,11 +206,12 @@ type VerifyWorker = (
174
206
  type EnrollmentResult =
175
207
  | { readonly status: "pending"; readonly destination: string; readonly publicKey: string; readonly initCommand: string;
176
208
  readonly verificationError?: string }
177
- | { readonly status: "verified"; readonly destination: string; readonly description: WorkerDescription; readonly default: boolean };
209
+ | { readonly status: "verified"; readonly destination: string; readonly description: WorkerDescription; readonly default: boolean;
210
+ readonly defaultCurrent?: true };
178
211
 
179
- function pendingEnrollment(destination: string, publicKey: string, verificationError?: string): EnrollmentResult {
212
+ function pendingEnrollment(destination: string, publicKey: string, current: boolean, verificationError?: string): EnrollmentResult {
180
213
  return { status: "pending", destination, publicKey,
181
- initCommand: `omp-sa worker init --head-key ${shellWord(publicKey)} --repo /absolute/path/to/repo`, verificationError };
214
+ initCommand: `omp-sa worker init --head-key ${shellWord(publicKey)} ${current ? "--current-repo" : "--repo"} /absolute/path/to/repo`, verificationError };
182
215
  }
183
216
 
184
217
  function sameEnrollment(before: WorkerDescription, after: WorkerDescription): boolean {
@@ -195,15 +228,27 @@ export function matchWorkerDescription(verified: WorkerDescription, reply: unkno
195
228
 
196
229
  /** Begin without network I/O; a separate invocation verifies the restricted SSH endpoint. */
197
230
  export async function addWorker(
198
- options: { readonly stateDir: string; readonly destination: string; readonly defaultRepositoryRoot?: string },
231
+ options: { readonly stateDir: string; readonly destination: string; readonly defaultRepositoryRoot?: string;
232
+ readonly defaultCurrentRepositoryRoot?: string },
199
233
  describe: VerifyWorker,
234
+ describeCurrent = workerDescribeCurrent,
200
235
  ): Promise<EnrollmentResult> {
201
- const { stateDir, destination, defaultRepositoryRoot } = options;
236
+ const { stateDir, destination, defaultRepositoryRoot, defaultCurrentRepositoryRoot } = options;
202
237
  if (!parseWorkerDestination(destination))
203
- throw new WorkerRegistrationError("Worker destination must be an explicit user@host with an optional numeric port (user@host:port)");
238
+ throw new WorkerRegistrationError("Use user@host[:port] or tailscale://user@host[:port]; enclose an IPv6 address in brackets");
239
+ if (defaultRepositoryRoot !== undefined && defaultCurrentRepositoryRoot !== undefined)
240
+ throw new WorkerRegistrationError("Choose either an exact or a current default repository");
204
241
  const source = defaultRepositoryRoot === undefined ? null : await workerRepositoryHead(defaultRepositoryRoot);
205
242
  if (defaultRepositoryRoot !== undefined && (!source || source.subdir !== ""))
206
243
  throw new WorkerRegistrationError("A default worker requires the root of a clean head-side Git checkout with a verifiable network origin");
244
+ const localPath = defaultCurrentRepositoryRoot === undefined ? undefined : workerPathSpelling(defaultCurrentRepositoryRoot);
245
+ const current = localPath === undefined ? null : await workerRepositoryLocation(localPath);
246
+ if (localPath !== undefined && (controls.test(localPath) || !current || current.subdir !== "" || !canonicalPath(current.root)))
247
+ throw new WorkerRegistrationError("A current default worker requires a head-side Git checkout root with a verifiable network origin");
248
+ const proposed: WorkerDefaultRepository | null = current && localPath !== undefined
249
+ ? { mode: "current", root: current.root, repoId: current.repoId, localCheckout: current.localCheckout,
250
+ ...(localPath !== current.root && { localPath }) }
251
+ : source ? { root: source.root, repoId: source.repoId } : null;
207
252
  trustedWorkerPath(stateDir, [], "profile");
208
253
  privateDirectory(stateDir);
209
254
  const directory = join(stateDir, "workers");
@@ -211,11 +256,12 @@ export async function addWorker(
211
256
  return await withWorkerWriteLock(join(directory, "write.lock"), async () => {
212
257
  const registrations = listWorkers(stateDir);
213
258
  const previous = registrations.find(worker => worker.destination === destination);
214
- if (source && registrations.some(worker => worker.defaultRepository && worker !== previous))
215
- throw new WorkerRegistrationError("A different verified worker is already the default");
259
+ if (proposed && registrations.some(worker => worker.defaultRepository && worker !== previous
260
+ && conflictingDefault(worker.defaultRepository, proposed)))
261
+ throw new WorkerRegistrationError("A different verified worker is already the default for this checkout or placement mode");
216
262
  const endpoint = endpointFor(stateDir, destination);
217
263
  if (!previous && !lstatSync(endpoint.identityFile, { throwIfNoEntry: false }))
218
- return pendingEnrollment(destination, await createIdentity(endpoint.identityFile, directory));
264
+ return pendingEnrollment(destination, await createIdentity(endpoint.identityFile, directory), current !== null);
219
265
  checkWorkerIdentity(endpoint.identityFile);
220
266
 
221
267
  let observed: WorkerDescription;
@@ -223,7 +269,7 @@ export async function addWorker(
223
269
  catch (cause) {
224
270
  const message = "Worker could not be verified using its dedicated key and a known SSH host key";
225
271
  if (previous) throw new WorkerRegistrationError(message, { cause });
226
- return pendingEnrollment(destination, await identityPublicKey(endpoint.identityFile), message);
272
+ return pendingEnrollment(destination, await identityPublicKey(endpoint.identityFile), current !== null, message);
227
273
  }
228
274
  const description = validateDescription(observed);
229
275
  if (previous) {
@@ -232,22 +278,30 @@ export async function addWorker(
232
278
  } else if (registrations.some(worker => worker.description.workerId === description.workerId)) {
233
279
  throw new WorkerRegistrationError("Worker identity is already verified at a different SSH destination");
234
280
  }
235
- let defaultRepository = previous?.defaultRepository;
236
- if (source) {
237
- const { root, ...workspace } = source;
238
- if (!description.repos.some(repo => repo.id === workspace.repoId))
239
- throw new WorkerRegistrationError("Worker is not approved for the default repository identity");
281
+ if (proposed) {
282
+ if (!description.repos.some(repo => repo.id === proposed.repoId && (!proposed.mode || repo.currentWorkspace)))
283
+ throw new WorkerRegistrationError(proposed.mode
284
+ ? "Worker is not approved for a current default on this repository"
285
+ : "Worker is not approved for the default repository identity");
240
286
  // Do not send the head-side path (or a revision for an unapproved repo).
241
287
  let scoped: WorkerDescription;
242
288
  checkWorkerIdentity(endpoint.identityFile);
243
- try { scoped = validateDescription(await describe(endpoint, workspace)); }
289
+ try {
290
+ scoped = validateDescription(source
291
+ ? await describe(endpoint, { repoId: proposed.repoId, subdir: "", revision: source.revision })
292
+ : await describeCurrent(endpoint, { repoId: proposed.repoId, subdir: "" }));
293
+ }
244
294
  catch (cause) {
245
- throw new WorkerRegistrationError("Worker could not verify the default repository at the requested Git revision", { cause });
295
+ throw new WorkerRegistrationError(proposed.mode
296
+ ? "Worker could not verify the current default checkout"
297
+ : "Worker could not verify the default repository at the requested Git revision", { cause });
246
298
  }
247
299
  if (!sameEnrollment(description, scoped))
248
300
  throw new WorkerRegistrationError("Worker description no longer matches the verified enrollment");
249
- defaultRepository = { root, repoId: workspace.repoId };
301
+ if (proposed.mode === "current" && !await verifyCurrentDefaultCheckout(proposed))
302
+ throw new WorkerRegistrationError("The selected local checkout changed during current default enrollment");
250
303
  }
304
+ const defaultRepository = proposed ?? previous?.defaultRepository;
251
305
  const registration = { ...endpoint, description, ...(defaultRepository && { default: true, defaultRepository }) };
252
306
  if (!Bun.deepEquals(registration, previous)) {
253
307
  const updated = previous ? registrations.map(worker => worker === previous ? registration : worker)
@@ -260,7 +314,8 @@ export async function addWorker(
260
314
  catch (error) { if (!isMissing(error)) throw error; }
261
315
  }
262
316
  }
263
- return { status: "verified", destination, description, default: defaultRepository !== undefined };
317
+ return { status: "verified", destination, description, default: defaultRepository !== undefined,
318
+ ...(defaultRepository?.mode === "current" && { defaultCurrent: true }) };
264
319
  });
265
320
  }
266
321
 
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
3
3
  import { lstat, open, readlink, realpath } from "node:fs/promises";
4
4
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
- import type { WorkerLaneRef } from "./worker-wire";
5
+ import type { WorkerWorkspace } from "./worker-wire";
6
6
 
7
7
  const gitOid = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
8
8
  const controls = /[\u0000-\u001f\u007f]/;
@@ -120,8 +120,48 @@ function withinTree(path: string): boolean {
120
120
  part && part !== ".." && part !== "." && part.toLowerCase() !== ".git"));
121
121
  }
122
122
 
123
+ /** Match a real local directory to an enrolled repository without reading its changes. */
124
+ export async function workerRepositoryLocation(cwd: string): Promise<(Pick<WorkerWorkspace, "repoId" | "subdir"> & {
125
+ readonly root: string; readonly localCheckout: string;
126
+ }) | null> {
127
+ try {
128
+ const canonical = await realpath(cwd);
129
+ const root = await checkoutRoot(canonical);
130
+ if (!root) return null;
131
+ const subdir = relative(root, canonical);
132
+ if (subdir.length > 2048 || !withinTree(subdir) || controls.test(subdir) || subdir.includes("\\")) return null;
133
+ const stamp = async () => {
134
+ const dirs = await Promise.all([lstat(root, { bigint: true }), lstat(join(root, ".git"), { bigint: true })]);
135
+ if (dirs.some(stat => !stat.isDirectory())) return null;
136
+ return createHash("sha256").update(dirs.map(stat => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`).join("/")).digest("hex");
137
+ };
138
+ const localCheckout = await stamp();
139
+ const repoId = await repositoryIdentity(root);
140
+ return localCheckout && repoId && await stamp() === localCheckout ? { root, localCheckout, repoId, subdir } : null;
141
+ } catch (error) {
142
+ if (unavailablePath(error)) return null;
143
+ throw error;
144
+ }
145
+ }
146
+
147
+ /** Resolve the selected worker's base commit without comparing or reading worktree bytes. */
148
+ export async function workerCurrentRevision(root: string, gitDir: string, cwd: string, repoId: string): Promise<string | null> {
149
+ try {
150
+ if (await checkoutRoot(cwd) !== root || join(root, ".git") !== gitDir) return null;
151
+ const head = [`--git-dir=${gitDir}`, `--work-tree=${root}`, "rev-parse", "--verify", "HEAD^{commit}"];
152
+ const [origin, output] = await Promise.all([repositoryIdentity(root), gitWorkerRepository(root, head)]);
153
+ const revision = output?.slice(0, -1);
154
+ if (origin !== repoId || !revision || !gitOid.test(revision) || output !== `${revision}\n`) return null;
155
+ const [stableOrigin, stableHead] = await Promise.all([repositoryIdentity(root), gitWorkerRepository(root, head)]);
156
+ return stableOrigin === origin && stableHead === output ? revision : null;
157
+ } catch (error) {
158
+ if (unavailablePath(error)) return null;
159
+ throw error;
160
+ }
161
+ }
162
+
123
163
  /** Re-attest only the workspace's identity, without scanning the index or tracked bytes. */
124
- export async function workerMemoryRepositoryMatches(cwd: string, expected: Pick<WorkerLaneRef, "repoId" | "revision" | "subdir"> & {
164
+ export async function workerMemoryRepositoryMatches(cwd: string, expected: Pick<WorkerWorkspace, "repoId" | "revision" | "subdir"> & {
125
165
  readonly repoRoot: string; readonly gitDir: string;
126
166
  }): Promise<boolean> {
127
167
  try {
@@ -272,15 +312,24 @@ async function* gitRecords(root: string, args: readonly string[]): AsyncGenerato
272
312
  }
273
313
  }
274
314
 
275
- /** Keep the existing non-submodule boundary without comparing worktree or index contents to HEAD. */
276
- export async function workerIndexHasOrdinaryFiles(root: string, gitDir: string): Promise<boolean> {
315
+ /** Validate an index without invoking worktree filters; Gitlinks require a separate verifier. */
316
+ export async function workerIndexHasOrdinaryFiles(
317
+ root: string, gitDir: string, onGitlink?: (path: string) => Promise<boolean>,
318
+ ): Promise<boolean> {
277
319
  const records = gitRecords(root, [`--git-dir=${gitDir}`, `--work-tree=${root}`, "ls-files", "--stage", "-z"]);
278
320
  try {
279
321
  for (;;) {
280
322
  const record = await records.next();
281
323
  if (record.done) return record.value;
282
324
  const tab = record.value.indexOf(9);
283
- if (tab < 0 || !/^(100644|100755|120000) [0-9a-f]+ [0-3]$/.test(record.value.toString("latin1", 0, tab))) return false;
325
+ if (tab < 0) return false;
326
+ const header = record.value.toString("latin1", 0, tab);
327
+ if (/^(100644|100755|120000) [0-9a-f]+ [0-3]$/.test(header)) continue;
328
+ if (!onGitlink || !/^160000 (?:[0-9a-f]{40}|[0-9a-f]{64}) 0$/.test(header)) return false;
329
+ const name = record.value.subarray(tab + 1);
330
+ const path = name.toString("utf8");
331
+ if (!path || !withinTree(path) || controls.test(path) || path.includes("\\") || !Buffer.from(path).equals(name)
332
+ || !await onGitlink(path)) return false;
284
333
  }
285
334
  } finally { await records.return(false); }
286
335
  }
@@ -302,7 +351,7 @@ async function matchesCommit(root: string, gitArgs: readonly string[], revision:
302
351
  }
303
352
 
304
353
  /** Inspect metadata through Git, and read tracked bytes without Git's content converters. */
305
- export async function workerRepositoryHead(cwd: string): Promise<(Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">
354
+ export async function workerRepositoryHead(cwd: string): Promise<(Pick<WorkerWorkspace, "repoId" | "revision" | "subdir">
306
355
  & { readonly root: string }) | null> {
307
356
  try {
308
357
  const canonical = await realpath(cwd);
@@ -1,7 +1,7 @@
1
1
  import { Type, type Static } from "@sinclair/typebox/type";
2
2
  import { Value } from "@sinclair/typebox/value";
3
3
  import type { LanePresetSnapshot } from "../contracts";
4
- import type { WorkerPolicy } from "./worker-wire";
4
+ import { workerCheckoutSchema, workerLaneIdSchema, workerRevisionSchema, type WorkerPolicy } from "./worker-wire";
5
5
 
6
6
  export class WorkerRefusal extends Error {}
7
7
 
@@ -12,15 +12,18 @@ const absolute = Type.String({ maxLength: 4096, pattern: `^/[^\\u0000-\\u001f\\u
12
12
  const id = Type.String({ minLength: 1, maxLength: 128, pattern: `^[a-zA-Z0-9][a-zA-Z0-9_-]*${end}` });
13
13
  const repoId = Type.String({ pattern: `^[0-9a-f]{64}${end}` });
14
14
  const generation = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
15
+ const subdir = Type.String({ maxLength: 2048, pattern: `^[^\\\\\\u0000-\\u001f\\u007f]*${end}` });
15
16
  const workspaceFields = {
16
17
  repoId,
17
- revision: Type.String({ pattern: `^(?:[0-9a-f]{40}|[0-9a-f]{64})${end}` }),
18
- subdir: Type.String({ maxLength: 2048, pattern: `^[^\\\\\\u0000-\\u001f\\u007f]*${end}` }),
18
+ revision: workerRevisionSchema,
19
+ subdir,
20
+ workerCheckout: Type.Optional(workerCheckoutSchema),
19
21
  };
20
22
  const workspace = Type.Object(workspaceFields, strict);
23
+ const currentWorkspace = Type.Object({ repoId, subdir, current: Type.Literal(true) }, strict);
21
24
  const laneRefSchema = Type.Object({
22
25
  ...workspaceFields, generation,
23
- laneId: Type.String({ pattern: `^lane-[A-Za-z0-9_-]{1,48}${end}` }),
26
+ laneId: workerLaneIdSchema,
24
27
  }, strict);
25
28
  const role = Type.String({ pattern: `^[a-zA-Z][a-zA-Z0-9_-]{0,127}${end}` });
26
29
  type NativeLevel = NonNullable<LanePresetSnapshot["defaultThinkingLevel"]>;
@@ -41,14 +44,18 @@ const launch = Type.Object({
41
44
  const envelope = { version: Type.Literal(1) };
42
45
  const bound = { ...envelope, workerId: id, ref: laneRefSchema };
43
46
  const request = Type.Union([
44
- Type.Object({ ...envelope, op: Type.Literal("describe"), workspace: Type.Optional(workspace) }, strict),
47
+ Type.Object({ ...envelope, op: Type.Literal("describe"), workspace: Type.Optional(Type.Union([workspace, currentWorkspace])) }, strict),
45
48
  Type.Object({ ...bound, op: Type.Literal("probe"), reconcile: Type.Optional(Type.Literal(true)) }, strict),
46
49
  Type.Object({ ...bound, op: Type.Literal("open"), launch }, strict),
47
50
  Type.Object({ ...bound, op: Type.Literal("attach") }, strict),
48
51
  ]);
49
52
  const policySchema = Type.Object({
50
53
  workerId: id, stateDir: absolute,
51
- repos: Type.Array(Type.Object({ id: repoId, cwd: absolute }, strict), { minItems: 1, maxItems: 128 }),
54
+ repos: Type.Array(Type.Object({
55
+ id: repoId, cwd: absolute,
56
+ currentWorkspace: Type.Optional(Type.Literal(true)),
57
+ trustedCheckout: Type.Optional(Type.Literal(true)),
58
+ }, strict), { minItems: 1, maxItems: 128 }),
52
59
  capacity: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
53
60
  command: Type.Array(text, { minItems: 1, maxItems: 64 }),
54
61
  }, strict);
@@ -0,0 +1,185 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import { copyNominatedWorkerResult, readResultAttachmentIntent, readResultAttachmentStart, ResultAttachmentError,
3
+ type ResultAttachmentIntent } from "../messaging/result-attachment";
4
+ import { sdkNativeProfilePaths } from "../omp/native-sessions";
5
+ import type { Frame } from "../omp/host-protocol";
6
+ import { WORKER_RESULT_CHUNK, WORKER_RESULT_GRACE_MS, WORKER_RESULT_LIMIT, WORKER_RESULT_MARKER,
7
+ WORKER_RESULT_TRANSFER_MS, type WorkerResultChunk, type WorkerResultSource } from "./worker-result-wire";
8
+
9
+ const unavailable = () => new ResultAttachmentError("No matching live worker result attachment nomination");
10
+ const tokenShape = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
11
+ type Owner = WorkerResultSource & { readonly token: string };
12
+ type Nomination = { readonly intent: ResultAttachmentIntent; readonly owner: Owner };
13
+ type Start = { readonly owner: Owner; readonly toolName: unknown };
14
+ type Scope = {
15
+ readonly cwd: string; readonly sessionId: string; readonly sessionFile: string; readonly agentDir: string; readonly configPath: string;
16
+ };
17
+ type Transfer = {
18
+ readonly toolCallId: string;
19
+ readonly nomination: Nomination;
20
+ readonly snapshot: ReturnType<typeof copyNominatedWorkerResult>;
21
+ readonly expiresAt: number;
22
+ offset: number;
23
+ };
24
+
25
+ /** Per native root. A copy never takes a path or reopens a journal nomination. */
26
+ export class WorkerResultAttachments {
27
+ private active = false;
28
+ private completedUntil = 0;
29
+ private readonly owners = new Map<string, Owner>();
30
+ private readonly starts = new Map<string, Start>();
31
+ private readonly completed = new Map<string, Nomination>();
32
+ private readonly used = new Set<string>();
33
+ private readonly reservations = new Map<string, number>();
34
+ private readonly observing = new Map<string, () => void>();
35
+ private transfer?: Transfer;
36
+
37
+ constructor(private readonly workspaceIdentity: string, private readonly now = () => performance.now()) {}
38
+
39
+ setActive(active: boolean): void {
40
+ this.active = active;
41
+ this.completedUntil = 0;
42
+ this.owners.clear();
43
+ this.starts.clear();
44
+ this.completed.clear();
45
+ this.used.clear();
46
+ this.reservations.clear();
47
+ for (const wake of this.observing.values()) wake();
48
+ this.observing.clear();
49
+ this.transfer = undefined;
50
+ }
51
+
52
+ finishRun(): void {
53
+ if (!this.active) return;
54
+ this.active = false;
55
+ this.owners.clear();
56
+ this.starts.clear();
57
+ for (const wake of this.observing.values()) wake();
58
+ this.observing.clear();
59
+ // Successful tool events may reach HEAD immediately before agent_end.
60
+ // Unclaimed nominations get a short grace; reservations get only their
61
+ // separately bounded queue budget.
62
+ this.completedUntil = this.now() + WORKER_RESULT_GRACE_MS;
63
+ }
64
+
65
+ observeOwnerInput(text: string): void {
66
+ if (!this.active || this.owners.size >= WORKER_RESULT_LIMIT) return;
67
+ // The stock owner adds this inert context to its exact stdin submission
68
+ // and refuses the carrier anywhere on a public worker prompt.
69
+ const match = new RegExp(`\\n\\n\`\`\`superagent-runtime-context\\n${WORKER_RESULT_MARKER}([^\\n]+)\\n\`\`\`$`).exec(text);
70
+ const encoded = match?.[1];
71
+ if (!encoded || encoded.length > 16_384 || !/^[A-Za-z0-9_-]+$/.test(encoded)) return;
72
+ let owner: unknown;
73
+ try { owner = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")); }
74
+ catch (error) { if (error instanceof SyntaxError) return; throw error; }
75
+ if (!owner || typeof owner !== "object" || !("token" in owner) || !("sourceId" in owner) || !("path" in owner)
76
+ || typeof owner.token !== "string" || !tokenShape.test(owner.token) || typeof owner.sourceId !== "string"
77
+ || typeof owner.path !== "string" || this.owners.has(owner.sourceId)) return;
78
+ this.owners.set(owner.sourceId, { token: owner.token, sourceId: owner.sourceId, path: owner.path });
79
+ }
80
+
81
+ observe(frame: Frame): void {
82
+ if (!this.active || typeof frame.toolCallId !== "string") return;
83
+ const id = frame.toolCallId;
84
+ if (frame.type === "tool_execution_start") {
85
+ const args = readResultAttachmentStart(frame);
86
+ const owner = args && this.owners.get(args.sourceId);
87
+ if (owner && owner.path === args?.path && this.starts.size + this.completed.size < WORKER_RESULT_LIMIT
88
+ && !this.used.has(owner.sourceId) && !this.starts.has(id) && !this.completed.has(id))
89
+ this.starts.set(id, { owner, toolName: frame.toolName });
90
+ return;
91
+ }
92
+ const start = this.starts.get(id);
93
+ this.starts.delete(id);
94
+ if (start && start.toolName === frame.toolName) {
95
+ const intent = readResultAttachmentIntent(frame);
96
+ if (intent?.path === start.owner.path && intent.sourceId === start.owner.sourceId && !this.used.has(intent.sourceId)) {
97
+ this.used.add(intent.sourceId);
98
+ this.completed.set(id, { intent, owner: start.owner });
99
+ }
100
+ }
101
+ this.observing.get(id)?.();
102
+ }
103
+
104
+ async reserve(command: Frame, scope: Scope): Promise<WorkerResultChunk | Record<string, never>> {
105
+ const { toolCallId, requestToken, sourceId } = command;
106
+ // The stock stdout subscriber sees tool_end before the extension hook.
107
+ // Join a matching live observation once, rather than racing it or retrying.
108
+ if (typeof toolCallId === "string" && !this.completed.has(toolCallId)) {
109
+ const start = this.starts.get(toolCallId);
110
+ if (!start || start.owner.token !== requestToken || start.owner.sourceId !== sourceId || this.observing.has(toolCallId))
111
+ throw unavailable();
112
+ const observed = Promise.withResolvers<void>();
113
+ const timer = setTimeout(observed.resolve, 5_000);
114
+ timer.unref();
115
+ this.observing.set(toolCallId, observed.resolve);
116
+ try { await observed.promise; }
117
+ finally {
118
+ clearTimeout(timer);
119
+ if (this.observing.get(toolCallId) === observed.resolve) this.observing.delete(toolCallId);
120
+ }
121
+ }
122
+ return this.copy(command, scope);
123
+ }
124
+
125
+ copy(command: Frame, scope: Scope): WorkerResultChunk | Record<string, never> {
126
+ const { sourceId, toolCallId, requestToken, op } = command;
127
+ if (typeof toolCallId !== "string") throw unavailable();
128
+ const now = this.now();
129
+ if (this.transfer && this.transfer.expiresAt <= now) this.transfer = undefined;
130
+ const current = this.transfer?.toolCallId === toolCallId ? this.transfer : undefined;
131
+ const nomination = op === "read" ? current?.nomination
132
+ : this.completed.get(toolCallId) ?? (op === "discard" ? current?.nomination : undefined);
133
+ if (!nomination || nomination.owner.token !== requestToken || nomination.intent.sourceId !== sourceId ||
134
+ nomination.intent.sessionId !== scope.sessionId || nomination.intent.sessionFile !== scope.sessionFile) throw unavailable();
135
+ if (op === "reserve") {
136
+ if ((!this.active && now >= this.completedUntil) || this.reservations.has(toolCallId)) throw unavailable();
137
+ for (const [id, expiresAt] of this.reservations) {
138
+ if (expiresAt <= now) { this.reservations.delete(id); this.completed.delete(id); }
139
+ }
140
+ // Reserve RPCs can arrive in a different order from HEAD's FIFO. Budget
141
+ // every pending item for the observed queue depth, including one bounded
142
+ // cleanup request per earlier transfer. At most 32 sources can nominate.
143
+ const ahead = this.reservations.size + (this.transfer ? 1 : 0);
144
+ const expiresAt = now + WORKER_RESULT_GRACE_MS + WORKER_RESULT_TRANSFER_MS + ahead * (WORKER_RESULT_TRANSFER_MS + 30_000);
145
+ for (const [id, expiry] of this.reservations) if (expiry < expiresAt) this.reservations.set(id, expiresAt);
146
+ this.reservations.set(toolCallId, expiresAt);
147
+ return {};
148
+ }
149
+ if (op === "discard") {
150
+ if (this.transfer?.toolCallId === toolCallId) this.transfer = undefined;
151
+ this.completed.delete(toolCallId);
152
+ this.reservations.delete(toolCallId);
153
+ return {};
154
+ }
155
+ if (op === "begin") {
156
+ const expiry = this.reservations.get(toolCallId);
157
+ if (!expiry || now >= expiry || this.transfer) throw unavailable();
158
+ this.reservations.delete(toolCallId);
159
+ // Burn before I/O. A lost copy receipt or changed file cannot reopen
160
+ // this nomination or allow another execution for the same source.
161
+ this.completed.delete(toolCallId);
162
+ const snapshot = this.snapshot(nomination.intent.path, scope);
163
+ this.transfer = { toolCallId, nomination, snapshot, offset: 0, expiresAt: this.now() + WORKER_RESULT_TRANSFER_MS };
164
+ } else if (op !== "read") throw unavailable();
165
+ const transfer = this.transfer;
166
+ const offset = op === "begin" ? 0 : command.offset;
167
+ if (!transfer || transfer.toolCallId !== toolCallId || offset !== transfer.offset) throw unavailable();
168
+ const { name, data } = transfer.snapshot;
169
+ const chunk = data.slice(transfer.offset, transfer.offset + WORKER_RESULT_CHUNK);
170
+ transfer.offset += chunk.length;
171
+ if (transfer.offset === data.length) {
172
+ this.transfer = undefined;
173
+ }
174
+ return { name, total: data.length, data: chunk };
175
+ }
176
+
177
+ private snapshot(path: string, scope: Scope) {
178
+ const { agentDir, dataDir, sessionsDir } = sdkNativeProfilePaths(scope.agentDir);
179
+ return copyNominatedWorkerResult(path, {
180
+ cwd: scope.cwd, workspaceIdentity: this.workspaceIdentity,
181
+ privatePaths: [dirname(dirname(dirname(scope.configPath))), scope.configPath, `${scope.configPath}.env`,
182
+ scope.sessionFile, agentDir, dataDir, sessionsDir].map(path => resolve(path)),
183
+ });
184
+ }
185
+ }
@@ -0,0 +1,12 @@
1
+ // Base64 characters, not raw bytes. The complete response fits one stock
2
+ // JSONL frame and takes about 2.1 s at 1 Mbit/s. Other native events can flow
3
+ // between reads without waiting for the entire result.
4
+ export const WORKER_RESULT_CHUNK = 256 * 1024;
5
+ export const WORKER_RESULT_MAX_ENCODED = Math.ceil(8 * 1024 * 1024 / 3) * 4;
6
+ export const WORKER_RESULT_TRANSFER_MS = 150_000;
7
+ export const WORKER_RESULT_GRACE_MS = 15_000;
8
+ export const WORKER_RESULT_LIMIT = 32;
9
+ export const WORKER_RESULT_MARKER = "omp-superagent-worker-result-v1:";
10
+
11
+ export type WorkerResultSource = { readonly sourceId: string; readonly path: string };
12
+ export type WorkerResultChunk = { readonly name: string; readonly total: number; readonly data: string };