omp-superagent 0.1.17 → 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 (82) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +205 -59
  4. package/docs/OPERATIONS.md +173 -47
  5. package/docs/design/execution.md +119 -37
  6. package/docs/design/messaging.md +160 -45
  7. package/docs/releases/0.1.18.md +10 -0
  8. package/docs/releases/0.1.19.md +10 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +6 -5
  19. package/skills/head/references/model-selection.md +8 -22
  20. package/skills/head/references/routing.md +36 -17
  21. package/skills/lane/SKILL.md +24 -76
  22. package/skills/lane/references/workflow.md +7 -94
  23. package/src/cli.ts +36 -16
  24. package/src/config/config.ts +21 -2
  25. package/src/contracts.ts +66 -7
  26. package/src/cron/cron-jobs.ts +135 -92
  27. package/src/cron/cron-pr-intake.ts +18 -11
  28. package/src/extension.ts +25 -10
  29. package/src/gateway/gateway-client.ts +3 -1
  30. package/src/host-extension.ts +76 -8
  31. package/src/lane/lane-report.ts +1 -1
  32. package/src/lane/lane-rows.ts +2 -1
  33. package/src/lane/workflow.ts +12 -6
  34. package/src/lane-extension.ts +4 -21
  35. package/src/managed-super-probe.ts +21 -15
  36. package/src/messaging/messenger-command-catalog.json +1 -1
  37. package/src/messaging/messenger-commands.ts +8 -3
  38. package/src/messaging/result-attachment.ts +77 -19
  39. package/src/messaging/slack-context.ts +50 -0
  40. package/src/messaging/written-directives.ts +56 -0
  41. package/src/omp/exit-record.ts +27 -0
  42. package/src/omp/host-protocol.ts +20 -0
  43. package/src/omp/host.ts +73 -20
  44. package/src/omp/installed-omp.ts +15 -12
  45. package/src/omp/managed-super.ts +135 -65
  46. package/src/omp/superkit-skills.ts +15 -2
  47. package/src/pr/pr-intake-order.ts +62 -0
  48. package/src/pr/pr-intake-review.ts +49 -31
  49. package/src/pr/pr-intake-work.ts +3 -2
  50. package/src/routing/message-order.ts +22 -1
  51. package/src/routing/topic-request.ts +48 -4
  52. package/src/runtime/controller.ts +968 -338
  53. package/src/runtime/deferred-routing.ts +12 -4
  54. package/src/runtime/dm-timeline.ts +3 -3
  55. package/src/runtime/inbound-attachments.ts +70 -0
  56. package/src/runtime/local-host-fence.ts +85 -0
  57. package/src/runtime/model-journal.ts +14 -9
  58. package/src/runtime/native-frames.ts +5 -1
  59. package/src/runtime/result-attachments.ts +151 -24
  60. package/src/runtime/worker-result-download.ts +36 -0
  61. package/src/storage/deferred-routing.ts +25 -4
  62. package/src/storage/store.ts +445 -75
  63. package/src/worker/worker-checkout.ts +89 -9
  64. package/src/worker/worker-destination.ts +8 -7
  65. package/src/worker/worker-doctor.ts +29 -9
  66. package/src/worker/worker-enrollment.ts +44 -12
  67. package/src/worker/worker-git-startup.ts +157 -0
  68. package/src/worker/worker-host.ts +16 -26
  69. package/src/worker/worker-ledger.ts +42 -18
  70. package/src/worker/worker-placement-intent.ts +13 -0
  71. package/src/worker/worker-placement.ts +204 -28
  72. package/src/worker/worker-profile.ts +18 -65
  73. package/src/worker/worker-project-startup.ts +106 -0
  74. package/src/worker/worker-registration.ts +85 -30
  75. package/src/worker/worker-repository.ts +55 -6
  76. package/src/worker/worker-request.ts +13 -6
  77. package/src/worker/worker-result-attachments.ts +185 -0
  78. package/src/worker/worker-result-wire.ts +12 -0
  79. package/src/worker/worker-service.ts +51 -23
  80. package/src/worker/worker-trust.ts +19 -4
  81. package/src/worker/worker-wire.ts +47 -14
  82. package/upstream/super.json +2 -3
@@ -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 };
@@ -3,21 +3,24 @@ import { lstatSync, type Stats } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { startHost } from "../omp/host";
6
- import { boundWorkspace, enrolledRepo, privateWorkerDirectory, reserveCheckout, workerCheckoutIdentity } from "./worker-checkout";
6
+ import { boundWorkspace, checkoutClaimed, enrolledRepo, privateWorkerDirectory, reserveCheckout,
7
+ workerCheckoutIdentity, workerCurrentCheckout, type WorkerCheckoutPin } from "./worker-checkout";
7
8
  import { absentWorkerHost, attestWorkerHost, inspectWorkerHost, prepareWorkerJournalDirectory, readWorkerFiles,
8
- WORKER_ATTEMPT_ENV, WORKER_SESSION_ENV, workerPaths } from "./worker-host";
9
+ WORKER_ATTEMPT_ENV, WORKER_SESSION_ENV, workerCheckoutPin, workerPaths } from "./worker-host";
9
10
  import { WorkerLedger, type WorkerJournalDirectory, type WorkerReceipt } from "./worker-ledger";
10
11
  import { WORKER_MEMORY_WIRE_ENV } from "./worker-memory-storage";
11
- import { assertWorkerGitStartup, requireWorkerStartupFlags, workerLaunchProfile, workerManagedUlwPath } from "./worker-profile";
12
+ import { assertWorkerGitStartup } from "./worker-git-startup";
13
+ import { requireWorkerStartupFlags, workerLaunchProfile, workerManagedUlwPath } from "./worker-profile";
12
14
  import { parseWorkerPolicy, parseWorkerRequest, WorkerRefusal } from "./worker-request";
13
- import type { WorkerDescription, WorkerLaneRef, WorkerLaunch, WorkerPolicy, WorkerProbe, WorkerRepo } from "./worker-wire";
15
+ import { WORKER_HEADER_BYTES, type WorkerDescription, type WorkerLaneRef, type WorkerLaunch, type WorkerPolicy, type WorkerProbe,
16
+ type WorkerRepo, type WorkerWorkspace } from "./worker-wire";
14
17
 
15
18
  type WorkerLane = {
16
19
  readonly ref: WorkerLaneRef;
17
20
  readonly repo: WorkerRepo;
18
21
  readonly paths: ReturnType<typeof workerPaths>;
19
22
  };
20
- type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
23
+ type DescribeWorkspace = WorkerWorkspace | { readonly repoId: string; readonly subdir: string; readonly current: true };
21
24
  type WorkerFileIdentity = Pick<Stats, "dev" | "ino">;
22
25
  type AttachPermit = {
23
26
  readonly generation: number; readonly workerAttempt: string;
@@ -26,6 +29,7 @@ type AttachPermit = {
26
29
  readonly socket: { readonly dev: string; readonly ino: string };
27
30
  readonly journal: { readonly dev: string; readonly ino: string };
28
31
  readonly journalDirectory?: WorkerJournalDirectory;
32
+ readonly checkoutPin?: WorkerCheckoutPin;
29
33
  };
30
34
  type WorkerReply = { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly error: string };
31
35
  type WorkerPreparation = { readonly kind: "reply"; readonly reply: WorkerReply } | ({ readonly kind: "attach" } & AttachPermit);
@@ -49,24 +53,40 @@ function findRepo(policy: WorkerPolicy, repoId: string): WorkerRepo {
49
53
  return repo;
50
54
  }
51
55
 
52
- async function describeWorker(policy: WorkerPolicy, workspace?: Workspace): Promise<WorkerDescription> {
56
+ async function describeWorker(policy: WorkerPolicy, workspace?: DescribeWorkspace): Promise<WorkerDescription & {
57
+ readonly workspace?: Awaited<ReturnType<typeof workerCurrentCheckout>>;
58
+ readonly checkoutBusy?: true;
59
+ readonly occupancy?: readonly WorkerLaneRef[];
60
+ }> {
53
61
  const platform = process.platform;
54
62
  if (platform !== "linux" && platform !== "darwin") throw new WorkerRefusal("Unsupported worker platform");
55
63
  const { workerId, stateDir, repos, capacity } = policy;
64
+ let current: Awaited<ReturnType<typeof workerCurrentCheckout>> | undefined;
65
+ let checkoutBusy = false;
56
66
  if (workspace) {
57
67
  const repo = findRepo(policy, workspace.repoId);
58
68
  const gitDir = await enrolledRepo(policy, repo);
59
- await boundWorkspace(repo, workspace);
69
+ if ("current" in workspace) current = await workerCurrentCheckout(repo, workspace.subdir, gitDir);
70
+ else await boundWorkspace(repo, workspace);
60
71
  if (lstatSync(join(stateDir, "worker.sqlite"), { throwIfNoEntry: false })) {
61
72
  const service = new WorkerService(policy);
62
73
  try { await service.reap({ repoId: repo.id, repoRoot: repo.cwd, gitDir }); }
63
74
  finally { service.close(); }
64
75
  }
76
+ checkoutBusy = checkoutClaimed(gitDir);
65
77
  } else {
66
78
  // Enrollment-wide inventory still validates all its registered checkouts.
67
79
  for (const repo of repos) await enrolledRepo(policy, repo);
68
80
  }
69
- return { workerId, platform, stateDir, repos, capacity, active: WorkerLedger.count(policy) };
81
+ const occupancy = WorkerLedger.occupancy(policy);
82
+ // The ledger can reserve the workspace before the physical checkout lock is written.
83
+ if (workspace && occupancy.some(ref => ref.repoId === workspace.repoId)) checkoutBusy = true;
84
+ const description = { workerId, platform, stateDir, repos, capacity, active: occupancy.length,
85
+ ...(current && { workspace: current }), ...(checkoutBusy && { checkoutBusy: true as const }) };
86
+ // Publish identities only as a complete snapshot of the same count. If the
87
+ // full inventory would exceed the wire frame, keep count-only semantics.
88
+ const scoped = { ...description, occupancy };
89
+ return workspace && Buffer.byteLength(JSON.stringify({ ok: true, value: scoped })) <= WORKER_HEADER_BYTES ? scoped : description;
70
90
  }
71
91
 
72
92
  class WorkerService {
@@ -87,7 +107,7 @@ class WorkerService {
87
107
  #receipt({ ref, repo }: WorkerLane): WorkerReceipt | null {
88
108
  const current = this.#ledger.get(ref.laneId);
89
109
  if (current && (current.repoId !== ref.repoId || current.revision !== ref.revision
90
- || current.subdir !== ref.subdir || current.repoRoot !== repo.cwd))
110
+ || current.subdir !== ref.subdir || current.repoRoot !== repo.cwd || current.workerCheckout !== ref.workerCheckout))
91
111
  throw new WorkerRefusal("Worker lane has a different durable checkout binding");
92
112
  if (current && ref.generation < current.generation) throw new WorkerRefusal("Worker lane generation is stale");
93
113
  return current;
@@ -129,7 +149,7 @@ class WorkerService {
129
149
  await boundWorkspace(lane.repo, ref, { gitDir: released.gitDir, checkoutIdentity: released.checkoutIdentity });
130
150
  const current = this.#receipt(lane);
131
151
  const active = this.#ledger.active().length;
132
- if (current?.attempt === released.attempt && current.phase === "released" && active < this.#policy.capacity)
152
+ if (current?.attempt === released.attempt && current.phase === "released" && active < this.#policy.capacity && !checkoutClaimed(released.gitDir))
133
153
  reopenActive = active;
134
154
  }
135
155
  } catch (error) {
@@ -137,7 +157,7 @@ class WorkerService {
137
157
  // Exit is independent of checkout readiness; keep its proof intact.
138
158
  }
139
159
  }
140
- const memoryLaunch = process.env[WORKER_MEMORY_WIRE_ENV] === "1" && absent && !probe.sessionFile && !sealed;
160
+ const memoryLaunch = !ref.workerCheckout && process.env[WORKER_MEMORY_WIRE_ENV] === "1" && absent && !probe.sessionFile && !sealed;
141
161
  return { ...probe, ...(sealed && { sealedGeneration: ref.generation }),
142
162
  ...(sealed && exitGeneration === ref.generation && { exitGeneration }),
143
163
  ...(reopenActive !== undefined && { reopenActive }),
@@ -174,6 +194,8 @@ class WorkerService {
174
194
  if (previous && previous.gitDir !== gitDir) throw new WorkerRefusal("Worker checkout metadata directory changed");
175
195
  const initial = await readWorkerFiles(lane.paths, previous?.journalDirectory);
176
196
  if (absentWorkerHost(initial, previous).uncertain) throw new WorkerRefusal("Worker lane has an unverified socket or journal");
197
+ if (ref.workerCheckout && launch.memorySync)
198
+ throw new WorkerRefusal("Worker-current placement does not authorize synchronization of a different workspace's memory");
177
199
  if (launch.memorySync && process.env[WORKER_MEMORY_WIRE_ENV] !== "1")
178
200
  throw new WorkerRefusal("Worker memory is not supported by this transport");
179
201
  if (launch.memorySync && initial.session && !previous?.memory)
@@ -195,7 +217,7 @@ class WorkerService {
195
217
  if (previous?.checkoutIdentity && previous.checkoutIdentity !== checkoutIdentity)
196
218
  throw new WorkerRefusal("Worker continuation no longer matches the original checkout directories");
197
219
  cwd = await boundWorkspace(lane.repo, ref, continuation);
198
- await assertWorkerGitStartup(lane.repo);
220
+ if (!ref.workerCheckout && !continuation) await assertWorkerGitStartup(lane.repo);
199
221
  target = workerLaunchProfile(this.#policy, cwd);
200
222
  managedUlwPath = await workerManagedUlwPath(this.#policy.repos);
201
223
  await requireWorkerStartupFlags(target.executable, this.#policy.stateDir, target.env);
@@ -206,15 +228,12 @@ class WorkerService {
206
228
  // Authorize stock-created modes only after establishing custody of a
207
229
  // new private namespace, before either SDK preparation or OMP opens it.
208
230
  const directory = prepareWorkerJournalDirectory(lane.paths, reservation.journalDirectory);
209
- if (continuation) {
210
- await assertWorkerGitStartup(lane.repo);
211
- await boundWorkspace(lane.repo, ref, continuation);
212
- }
231
+ if (continuation || ref.workerCheckout) await boundWorkspace(lane.repo, ref, continuation);
213
232
  const pin = checkoutIdentity && workerCheckoutIdentity(lane.repo.cwd, gitDir, cwd) === checkoutIdentity ? checkoutIdentity : null;
214
- if (previous?.checkoutIdentity && pin !== previous.checkoutIdentity)
233
+ if (!pin || previous?.checkoutIdentity && pin !== previous.checkoutIdentity || ref.workerCheckout && pin !== ref.workerCheckout)
215
234
  throw new WorkerRefusal("Worker checkout directories changed before launch");
216
- if ((pin && pin !== reservation.checkoutIdentity) || (directory && !reservation.journalDirectory)) {
217
- const prepared = { ...reservation, ...(pin && { checkoutIdentity: pin }), ...(directory && { journalDirectory: directory }) };
235
+ if (pin !== reservation.checkoutIdentity || directory && !reservation.journalDirectory) {
236
+ const prepared = { ...reservation, checkoutIdentity: pin, ...(directory && { journalDirectory: directory }) };
218
237
  if (!this.#ledger.transition(reservation, prepared)) throw new WorkerRefusal("Worker launch reservation is no longer current");
219
238
  reservation = prepared;
220
239
  }
@@ -223,9 +242,13 @@ class WorkerService {
223
242
  throw error;
224
243
  }
225
244
  let launching = { ...reservation, phase: "launching" } as const;
226
- let preparingSession = false;
245
+ let launchFenced = false;
227
246
  try {
228
247
  const { memorySync: _memorySync, ...hostLaunch } = launch;
248
+ const checkoutPin = workerCheckoutPin(launching);
249
+ // The helper copies from the admitted cwd identity, never one sampled
250
+ // from the same pathname after preparation or native startup.
251
+ const workerResultWorkspace = checkoutPin ? undefined : launching.checkoutIdentity?.split("/")[2];
229
252
  const { pid } = await startHost({
230
253
  ...hostLaunch, cwd, command: [target.executable], socketPath: lane.paths.socketPath,
231
254
  sessionFile: lane.paths.sessionFile, logPath: lane.paths.logPath,
@@ -233,12 +256,13 @@ class WorkerService {
233
256
  worker: { ...target.profile, managedUlwPath,
234
257
  ...(memoryKey && { memory: { key: memoryKey, previous: previous?.memory,
235
258
  checkout: { repoRoot: lane.repo.cwd, gitDir, repoId: ref.repoId, revision: ref.revision, subdir: ref.subdir } } }) },
259
+ ...(checkoutPin ? { workerCheckoutPin: checkoutPin } : { workerResultWorkspace }),
236
260
  env: { ...target.env, OMP_SUPERAGENT_ROLE: "lane", OMP_SUPERAGENT_LANE: launching.laneId,
237
261
  [WORKER_ATTEMPT_ENV]: launching.attempt, [WORKER_SESSION_ENV]: launching.sessionId ?? "" },
238
262
  }, memory => {
239
263
  if (memory) launching = { ...launching, memory, privateMemoryPrepared: true };
240
264
  if (!this.#ledger.transition(reservation, launching)) throw new WorkerRefusal("Worker launch reservation is no longer current");
241
- preparingSession = true;
265
+ launchFenced = true;
242
266
  });
243
267
  const probe = await inspectWorkerHost(this.#ledger, lane.paths, launching);
244
268
  const actual = this.#ledger.get(ref.laneId);
@@ -247,10 +271,12 @@ class WorkerService {
247
271
  throw new WorkerRefusal("Stock worker Host did not confirm the reserved launch identity");
248
272
  return { pid };
249
273
  } catch (error) {
250
- if (!preparingSession) {
274
+ if (!launchFenced) {
251
275
  this.#ledger.retire(reservation);
252
276
  throw new WorkerRefusal("Worker Host preflight failed before session preparation; no Host was launched", { cause: error });
253
277
  }
278
+ if (this.#ledger.retire(launching, { unspawnedError: error }))
279
+ throw new WorkerRefusal("Worker Host launch failed before spawning its owner; the original journal remains unverified and cannot reopen", { cause: error });
254
280
  if (error instanceof WorkerRefusal) throw error;
255
281
  throw new WorkerRefusal("Stock worker Host launch is unresolved; inspect the private worker log and probe the same generation", { cause: error });
256
282
  }
@@ -274,9 +300,11 @@ class WorkerService {
274
300
  const current = this.#receipt(lane);
275
301
  if (current?.phase !== "live" || current.generation !== ref.generation || current.attempt !== receipt.attempt)
276
302
  throw new WorkerRefusal("Worker lane changed before attach");
303
+ const checkoutPin = workerCheckoutPin(current);
277
304
  return { generation: receipt.generation, workerAttempt: receipt.attempt,
278
305
  socketPath, sessionFile, sessionId, pid, ownerPid, socket, journal,
279
- ...(receipt.journalDirectory && { journalDirectory: receipt.journalDirectory }) };
306
+ ...(receipt.journalDirectory && { journalDirectory: receipt.journalDirectory }),
307
+ ...(checkoutPin && { checkoutPin }) };
280
308
  }
281
309
  }
282
310
 
@@ -1,5 +1,5 @@
1
- import { lstatSync } from "node:fs";
2
- import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
1
+ import { lstatSync, realpathSync } from "node:fs";
2
+ import { delimiter, dirname, isAbsolute, relative, resolve, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { WorkerRefusal } from "./worker-request";
5
5
  import type { WorkerPolicy } from "./worker-wire";
@@ -7,7 +7,7 @@ import type { WorkerPolicy } from "./worker-wire";
7
7
  const controls = /[\u0000-\u001f\u007f]/;
8
8
  export const workerInstallRoot = resolve(fileURLToPath(new URL("../..", import.meta.url)));
9
9
 
10
- function within(root: string, candidate: string): boolean {
10
+ export function workerPathContains(root: string, candidate: string): boolean {
11
11
  const suffix = relative(root, candidate);
12
12
  return !isAbsolute(suffix) && suffix !== ".." && !suffix.startsWith(`..${sep}`);
13
13
  }
@@ -15,7 +15,7 @@ function within(root: string, candidate: string): boolean {
15
15
  /** A trusted input is a local account/system path that no enrolled tree or other user can replace. */
16
16
  export function trustedWorkerPath(path: string, repos: WorkerPolicy["repos"], kind: "file" | "directory" | "profile"): string {
17
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)))
18
+ if (!isAbsolute(path) || resolve(path) !== path || controls.test(path) || repos.some(repo => workerPathContains(repo.cwd, path)))
19
19
  throw fail();
20
20
  // realpath can preserve the caller's spelling on a case-insensitive volume.
21
21
  const enrolled = new Set(repos.flatMap(repo => {
@@ -34,3 +34,18 @@ export function trustedWorkerPath(path: string, repos: WorkerPolicy["repos"], ki
34
34
  }
35
35
  return path;
36
36
  }
37
+
38
+ /** PATH lookup cannot delegate bootstrap to an executable in an enrolled checkout. */
39
+ export function workerCommandPath(source: NodeJS.ProcessEnv, repos: WorkerPolicy["repos"]): string {
40
+ const dirs = new Set<string>();
41
+ for (const raw of (source.PATH ?? "").split(delimiter)) {
42
+ if (!isAbsolute(raw) || controls.test(raw)) continue;
43
+ try { dirs.add(trustedWorkerPath(realpathSync(raw), repos, "directory")); }
44
+ catch (error) {
45
+ if (!(error instanceof WorkerRefusal) && !(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
46
+ }
47
+ }
48
+ for (const dir of ["/usr/bin", "/bin", "/usr/sbin", "/sbin"])
49
+ if (lstatSync(dir, { throwIfNoEntry: false })) dirs.add(realpathSync(dir));
50
+ return [...dirs].join(delimiter);
51
+ }
@@ -7,30 +7,42 @@ import type { HostOptions } from "../omp/host";
7
7
  import { parseWorkerDestination } from "./worker-destination";
8
8
 
9
9
  /** Only the enrollment CLI chooses destinations/keys. Lane prompts never supply SSH argv. */
10
- export interface WorkerRepo { readonly id: string; readonly cwd: string }
10
+ export interface WorkerRepo {
11
+ readonly id: string; readonly cwd: string;
12
+ readonly currentWorkspace?: true;
13
+ readonly trustedCheckout?: true;
14
+ }
11
15
  export interface WorkerDescription {
12
16
  readonly workerId: string; readonly platform: "linux" | "darwin"; readonly stateDir: string;
13
17
  readonly repos: readonly WorkerRepo[]; readonly capacity: number; readonly active: number;
14
18
  }
19
+ export type WorkerDefaultRepository = { readonly root: string; readonly repoId: string } & (
20
+ | { readonly mode?: never }
21
+ | { readonly mode: "current"; readonly localCheckout: string; readonly localPath?: string }
22
+ );
15
23
  export interface WorkerRegistration {
16
24
  readonly destination: string; readonly identityFile: string; readonly description: WorkerDescription;
17
25
  readonly default?: boolean;
18
- readonly defaultRepository?: { readonly root: string; readonly repoId: string };
26
+ readonly defaultRepository?: WorkerDefaultRepository;
19
27
  }
20
28
  export interface WorkerPolicy {
21
29
  readonly workerId: string; readonly stateDir: string; readonly repos: readonly WorkerRepo[];
22
30
  readonly capacity: number; readonly command: string[];
23
31
  }
24
- export interface RemotePlacement {
25
- readonly workerId: string; readonly repoId: string; readonly revision: string;
26
- readonly subdir: string; readonly stateDir: string;
32
+ export interface WorkerWorkspace {
33
+ readonly repoId: string; readonly revision: string; readonly subdir: string;
34
+ /** Explicit worker-owned checkout; its contents are not a copy of the head's workspace. */
35
+ readonly workerCheckout?: string;
36
+ }
37
+ export interface RemotePlacement extends WorkerWorkspace {
38
+ readonly workerId: string; readonly stateDir: string;
27
39
  }
28
40
  export interface WorkerSelector {
29
41
  readonly target?: "local" | "remote"; readonly platform?: "linux" | "darwin"; readonly worker?: string;
42
+ readonly currentWorkspace?: { readonly repoId: string; readonly subdir: string };
30
43
  }
31
- export interface WorkerLaneRef {
32
- readonly laneId: string; readonly generation: number; readonly repoId: string;
33
- readonly revision: string; readonly subdir: string;
44
+ export interface WorkerLaneRef extends WorkerWorkspace {
45
+ readonly laneId: string; readonly generation: number;
34
46
  }
35
47
  export interface WorkerProbe {
36
48
  readonly socket: boolean; readonly sessionFile: boolean; readonly pidAlive: boolean; readonly ownerAlive: boolean;
@@ -56,11 +68,27 @@ const natural = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
56
68
  const positive = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
57
69
  const text = Type.String({ minLength: 1 });
58
70
  const absolute = Type.String({ pattern: "^/[^\\u0000]*$" });
71
+ export const workerRevisionSchema = Type.String({ pattern: "^(?:[0-9a-f]{40}|[0-9a-f]{64})(?![\\s\\S])" });
72
+ export const workerCheckoutSchema = Type.String({ maxLength: 128, pattern: "^[0-9]+:[0-9]+/[0-9]+:[0-9]+/[0-9]+:[0-9]+(?![\\s\\S])" });
73
+ export const workerLaneIdSchema = Type.String({ pattern: "^lane-[A-Za-z0-9_-]{1,48}(?![\\s\\S])" });
74
+ const occupiedLane = Type.Object({
75
+ laneId: workerLaneIdSchema,
76
+ generation: positive, repoId: Type.String({ pattern: "^[0-9a-f]{64}(?![\\s\\S])" }),
77
+ revision: workerRevisionSchema, subdir: Type.String({ maxLength: 2048 }), workerCheckout: Type.Optional(workerCheckoutSchema),
78
+ });
59
79
  export const WorkerDescriptionSchema = Type.Object({
60
80
  workerId: text, platform: Type.Union([Type.Literal("linux"), Type.Literal("darwin")]),
61
- stateDir: absolute, repos: Type.Array(Type.Object({ id: text, cwd: absolute }), { minItems: 1 }),
62
- capacity: positive, active: natural,
81
+ stateDir: absolute, repos: Type.Array(Type.Object({
82
+ id: text, cwd: absolute,
83
+ currentWorkspace: Type.Optional(Type.Literal(true)),
84
+ trustedCheckout: Type.Optional(Type.Literal(true)),
85
+ }), { minItems: 1 }),
86
+ capacity: positive, active: natural, checkoutBusy: Type.Optional(Type.Literal(true)),
87
+ occupancy: Type.Optional(Type.Array(occupiedLane)),
63
88
  });
89
+ const currentWorkspaceDescription = Type.Intersect([WorkerDescriptionSchema, Type.Object({
90
+ workspace: Type.Object({ revision: workerRevisionSchema, workerCheckout: workerCheckoutSchema }, { additionalProperties: false }),
91
+ })]);
64
92
  const probe = Type.Object({
65
93
  socket: Type.Boolean(), sessionFile: Type.Boolean(), pidAlive: Type.Boolean(), ownerAlive: Type.Boolean(),
66
94
  uncertain: Type.Boolean(), pid: Type.Union([positive, Type.Null()]), sessionId: Type.Union([text, Type.Null()]),
@@ -94,6 +122,7 @@ function startSSH(endpoint: Endpoint) {
94
122
  "-o", "ClearAllForwardings=yes", "-o", "ForwardAgent=no", "-o", "ForwardX11=no",
95
123
  "-o", "ControlPath=none", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none",
96
124
  "-o", "PreferredAuthentications=publickey", "-o", "ConnectTimeout=8",
125
+ ...(destination.tailnet ? ["-o", "ProxyCommand=tailscale nc %h %p"] : []),
97
126
  ...(destination.port ? ["-p", destination.port] : []),
98
127
  "-i", endpoint.identityFile, "--", destination.login, "omp-sa-worker-v1"], { stdio: "pipe" });
99
128
  // Drain diagnostics without collecting or relaying possibly sensitive peer output.
@@ -174,16 +203,20 @@ async function exchange<S extends TSchema>(endpoint: Endpoint, request: object,
174
203
  }
175
204
  }
176
205
 
177
- export async function workerDescribe(endpoint: Endpoint, workspace?: Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">): Promise<WorkerDescription> {
206
+ export async function workerDescribe(endpoint: Endpoint, workspace?: WorkerWorkspace) {
178
207
  return (await exchange(endpoint, { op: "describe", workspace }, WorkerDescriptionSchema, false)).value;
179
208
  }
180
209
 
210
+ export async function workerDescribeCurrent(endpoint: Endpoint, workspace: NonNullable<WorkerSelector["currentWorkspace"]>) {
211
+ return (await exchange(endpoint, { op: "describe", workspace: { ...workspace, current: true } }, currentWorkspaceDescription, false)).value;
212
+ }
213
+
181
214
  export async function lookupWorker(stateDir: string, remote: RemotePlacement): Promise<WorkerRegistration> {
182
215
  const { listWorkers } = await import("./worker-registration");
183
216
  const matches = (await listWorkers(stateDir)).filter(reg => reg.description.workerId === remote.workerId);
184
217
  const [reg] = matches;
185
218
  if (matches.length !== 1 || !reg || reg.description.stateDir !== remote.stateDir
186
- || !reg.description.repos.some(repo => repo.id === remote.repoId)) {
219
+ || !reg.description.repos.some(repo => repo.id === remote.repoId && (!remote.workerCheckout || repo.currentWorkspace))) {
187
220
  throw new Error("Remote lane has no matching verified worker registration");
188
221
  }
189
222
  return reg;
@@ -196,8 +229,8 @@ export function remoteLanePaths(remote: Pick<RemotePlacement, "stateDir">, laneI
196
229
 
197
230
  export function workerRef(lane: Pick<Lane, "id" | "remote" | "generation">): WorkerLaneRef {
198
231
  if (!lane.remote) throw new Error("Lane is not assigned to a worker");
199
- const { repoId, revision, subdir } = lane.remote;
200
- return { laneId: lane.id, generation: lane.generation, repoId, revision, subdir };
232
+ const { repoId, revision, subdir, workerCheckout } = lane.remote;
233
+ return { laneId: lane.id, generation: lane.generation, repoId, revision, subdir, ...(workerCheckout && { workerCheckout }) };
201
234
  }
202
235
 
203
236
  export async function workerProbe(reg: WorkerRegistration, ref: WorkerLaneRef, reconcile = false, signal?: AbortSignal): Promise<WorkerProbe> {
@@ -1,9 +1,8 @@
1
1
  {
2
2
  "repository": "https://github.com/dbc-hbin/omp-superkit.git",
3
- "ref": "HEAD",
3
+ "releaseApi": "https://api.github.com/repos/dbc-hbin/omp-superkit/releases/latest",
4
4
  "directory": ".upstream/ulw",
5
5
  "checkIntervalMs": 3600000,
6
6
  "commandTimeoutMs": 180000,
7
- "probeTimeoutMs": 30000,
8
- "materialize": "upstream/materialize-frontend-refs.mjs"
7
+ "probeTimeoutMs": 30000
9
8
  }