omp-superagent 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/DESIGN.md +36 -20
  2. package/README.ko.md +140 -33
  3. package/README.md +165 -41
  4. package/THIRD_PARTY_NOTICES.md +9 -7
  5. package/config.example.json +3 -1
  6. package/docs/OPERATIONS.md +395 -157
  7. package/docs/design/execution.md +156 -22
  8. package/docs/design/messaging.md +258 -52
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.7.md +25 -0
  11. package/docs/releases/0.1.8.md +21 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  17. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  19. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  20. package/package.json +9 -9
  21. package/scripts/ci.ts +4 -4
  22. package/scripts/test-omp.sh +2 -1
  23. package/skills/head/SKILL.md +26 -5
  24. package/skills/head/references/routing.md +68 -33
  25. package/skills/head/references/supervision.md +20 -4
  26. package/skills/lane/references/workflow.md +16 -7
  27. package/src/board.ts +5 -3
  28. package/src/cli.ts +161 -19
  29. package/src/config.ts +21 -1
  30. package/src/contracts.ts +63 -8
  31. package/src/cron-jobs.ts +443 -19
  32. package/src/cron-pr-intake.ts +257 -0
  33. package/src/discord-markdown.ts +350 -123
  34. package/src/extension.ts +78 -13
  35. package/src/gateway-client.ts +8 -2
  36. package/src/head-quota.ts +80 -0
  37. package/src/head-recovery.ts +40 -1
  38. package/src/host-extension.ts +122 -4
  39. package/src/host-inventory-manifest.ts +2 -2
  40. package/src/host-protocol.ts +11 -0
  41. package/src/host-sdk-helper.ts +121 -12
  42. package/src/host.ts +175 -57
  43. package/src/installed-omp.ts +116 -4
  44. package/src/lane-rows.ts +44 -4
  45. package/src/lane-watch.ts +339 -0
  46. package/src/managed-memory-helper.ts +13 -10
  47. package/src/managed-memory.ts +62 -27
  48. package/src/managed-ulw-probe.ts +75 -20
  49. package/src/managed-ulw.ts +174 -21
  50. package/src/messenger-command-catalog.json +2 -2
  51. package/src/native-launch-profile.ts +4 -2
  52. package/src/native-presets.ts +32 -5
  53. package/src/native-sessions.ts +3 -1
  54. package/src/native-settings.ts +47 -9
  55. package/src/observation-request.ts +23 -0
  56. package/src/omp-usage.ts +254 -36
  57. package/src/pr-github-schema.ts +5 -1
  58. package/src/pr-github.ts +68 -19
  59. package/src/pr-intake-automation.ts +316 -0
  60. package/src/pr-intake-comment.ts +226 -0
  61. package/src/pr-intake-fix.ts +233 -0
  62. package/src/pr-intake-github.ts +480 -0
  63. package/src/pr-intake-material.ts +230 -0
  64. package/src/pr-intake-mode.ts +59 -0
  65. package/src/pr-intake-review.ts +397 -0
  66. package/src/pr-intake-tree.ts +69 -0
  67. package/src/pr-intake-work.ts +29 -0
  68. package/src/pr-watch.ts +91 -32
  69. package/src/runtime.ts +2702 -391
  70. package/src/setup-judge.ts +1 -1
  71. package/src/setup.ts +12 -16
  72. package/src/store.ts +429 -86
  73. package/src/topic-history.ts +243 -47
  74. package/src/worker-checkout.ts +106 -0
  75. package/src/worker-destination.ts +10 -0
  76. package/src/worker-doctor.ts +66 -0
  77. package/src/worker-enrollment.ts +165 -0
  78. package/src/worker-host.ts +180 -0
  79. package/src/worker-ledger.ts +188 -0
  80. package/src/worker-placement.ts +78 -0
  81. package/src/worker-profile.ts +274 -0
  82. package/src/worker-registration.ts +288 -0
  83. package/src/worker-repository.ts +233 -0
  84. package/src/worker-request.ts +74 -0
  85. package/src/worker-service.ts +230 -0
  86. package/src/worker-stdio.ts +61 -0
  87. package/src/worker-trust.ts +36 -0
  88. package/src/worker-wire.ts +204 -0
  89. package/src/workflow.ts +81 -32
  90. package/src/setup-memory.ts +0 -21
@@ -1,21 +1,24 @@
1
1
  // Short-lived SDK operations. The Rust owner, not this process, owns native stdin and the reconnectable socket.
2
2
  import { dirname } from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
- import { rename, writeFile } from "node:fs/promises";
4
+ import { chmod, rename, writeFile } from "node:fs/promises";
5
5
  import type { RpcAbortAndRestoreQueueResult } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
6
6
  import type { HostOptions } from "./host";
7
7
  import type { Frame } from "./host-protocol";
8
8
  import type { RotationSelection } from "./head-rotation";
9
+ import type { ManagedUlwLaunchInput } from "./managed-ulw";
9
10
 
10
11
  type Manifest = {
11
12
  readonly options: Omit<HostOptions, "env">;
12
13
  readonly args: string[];
14
+ readonly configPath: string;
13
15
  readonly processBackend: "broker" | "daemon";
14
16
  readonly headRotationSelection?: RotationSelection;
15
17
  };
16
18
  type Exit = {
17
19
  readonly pid: number; readonly ownerPid: number; readonly code: number | null; readonly signal: string | null;
18
20
  readonly sessionId: string; readonly instanceKey?: string | null; readonly runOrdinal: number;
21
+ readonly workerAttempt?: string | null;
19
22
  readonly observationFailure: boolean; readonly expectedObservations: readonly [string, Frame][];
20
23
  };
21
24
 
@@ -47,18 +50,24 @@ async function verifyExit({ options }: Manifest, exit: Exit) {
47
50
  const receipt = `${options.socketPath}.exit.json`;
48
51
  const temporary = `${receipt}.${crypto.randomUUID()}`;
49
52
  await writeFile(temporary, JSON.stringify({ pid, ownerPid, sessionId, sessionFile: options.sessionFile, code,
53
+ ...(exit.workerAttempt ? { workerAttempt: exit.workerAttempt } : {}),
50
54
  signal, persisted, observationsFlushed }), { mode: 0o600, flag: "wx" });
51
55
  await rename(temporary, receipt);
52
56
  if (!persisted || !observationsFlushed) throw new Error("Native exit persistence is unconfirmed");
53
57
  return { persisted, observationsFlushed };
54
58
  }
55
59
 
56
- async function run(operation: string | undefined, manifest: Manifest, input: unknown) {
60
+ async function run(operation: string | undefined, manifest: Manifest, input: unknown, profileResolved = false) {
57
61
  const { options } = manifest;
58
62
  const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
59
- const { setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
60
63
  const bootstrap = extractProfileFlags([...options.command.slice(1), ...manifest.args]);
61
- setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
64
+ // Native discovery already selected the profile and applied dotenv.
65
+ // Rebootstrapping now would re-select from the mutated environment or
66
+ // clear its effective agent directory before publishing the session.
67
+ if (!profileResolved) {
68
+ const { setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
69
+ setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
70
+ }
62
71
  switch (operation) {
63
72
  case "prepare": {
64
73
  const { resolveCliArgv } = await import("@oh-my-pi/pi-coding-agent/cli-commands");
@@ -66,13 +75,68 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
66
75
  const argv = resolveCliArgv(bootstrap.argv);
67
76
  if ("error" in argv) throw new Error(argv.error);
68
77
  const parsed = parseArgs(argv.argv.slice(1));
69
- const { stat } = await import("node:fs/promises");
70
- try { await stat(options.sessionFile); } catch (error) {
78
+ if (options.prReviewOnly) {
79
+ if (parsed.noTools !== true || parsed.tools !== undefined || !parsed.noExtensions ||
80
+ !parsed.noSkills || !parsed.noRules || !parsed.noContextFiles || !parsed.noLsp ||
81
+ !parsed.noTitle || !parsed.noPrewalk || !parsed.offline ||
82
+ parsed.trustedExtensions?.length !== 1 || parsed.config?.length !== 1 || parsed.config[0] !== manifest.configPath)
83
+ throw new Error("Stock CLI arguments do not enforce the static PR review launch policy");
84
+ const { getAgentDir } = await import("@oh-my-pi/pi-utils/dirs");
85
+ const { Settings } = await import("@oh-my-pi/pi-coding-agent/config/settings");
86
+ const { cfgDisabledProviders } = await import("@oh-my-pi/pi-coding-agent/config/model-settings");
87
+ const { getAllCapabilitiesInfo } = await import("@oh-my-pi/pi-coding-agent/discovery");
88
+ const { getAllPluginToolPaths } = await import("@oh-my-pi/pi-coding-agent/extensibility/plugins/loader");
89
+ const { PR_REVIEW_GITHUB_ENV } = await import("./host-protocol");
90
+ if (PR_REVIEW_GITHUB_ENV.some(name => process.env[name]))
91
+ throw new Error("Static PR review cannot load GitHub credentials from the native profile");
92
+ const native = await Settings.loadReadOnly({ cwd: options.cwd, agentDir: getAgentDir() });
93
+ // Stock custom tool loading also has an independent legacy plugin scan,
94
+ // outside the capability-provider switch. Refuse such a profile without
95
+ // importing any of those modules in the SDK preparation process.
96
+ if ((await getAllPluginToolPaths(options.cwd)).length)
97
+ throw new Error("Static PR review cannot isolate this profile's legacy plugin tools");
98
+ const disabled = new Set(cfgDisabledProviders.get(native));
99
+ for (const capability of getAllCapabilitiesInfo()) {
100
+ if (["mcps", "tools", "prompts", "slash-commands", "system-prompt"].includes(capability.id))
101
+ for (const provider of capability.providers) disabled.add(provider.id);
102
+ }
103
+ const overlay = JSON.parse(await Bun.file(manifest.configPath).text());
104
+ const staging = `${manifest.configPath}.${crypto.randomUUID()}`;
105
+ await writeFile(staging, JSON.stringify({ ...overlay, disabledProviders: [...disabled] }), { mode: 0o600, flag: "wx" });
106
+ await rename(staging, manifest.configPath);
107
+ }
108
+ const { lstat, stat } = await import("node:fs/promises");
109
+ const expectedWorkerSession = process.env.OMP_SUPERAGENT_WORKER_EXPECTED_SESSION;
110
+ const missing = await (expectedWorkerSession === undefined && !options.prReviewOnly ? stat : lstat)(options.sessionFile).then(async info => {
111
+ if (expectedWorkerSession !== undefined) {
112
+ const { readSessionHeaderId } = await import("@oh-my-pi/pi-coding-agent/session/session-loader");
113
+ if (!info.isFile() || !expectedWorkerSession || await readSessionHeaderId(options.sessionFile) !== expectedWorkerSession)
114
+ throw new Error("Worker journal no longer matches the reserved session");
115
+ }
116
+ if (options.prReviewOnly) {
117
+ if (!info.isFile() || info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)
118
+ throw new Error("Static PR review journal is not a private owned regular file");
119
+ const { visitEntriesFromFileStream } = await import("@oh-my-pi/pi-coding-agent/session/session-loader");
120
+ let verified = false;
121
+ await visitEntriesFromFileStream(options.sessionFile, entry => {
122
+ if (entry.type === "custom" && entry.customType === "superagent_pr_review_policy" &&
123
+ isDeepStrictEqual(entry.data, { version: 1, cwd: options.cwd })) verified = true;
124
+ }, { throwIfMissing: true, onMalformedRecord: () => { throw new Error("Static PR review journal is malformed"); } });
125
+ if (!verified) throw new Error("Refusing to restore a journal not created for static PR review");
126
+ }
127
+ return false;
128
+ }, error => {
71
129
  if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
130
+ if (expectedWorkerSession) throw new Error("Worker cannot recreate a missing reserved session");
131
+ return true;
132
+ });
133
+ if (missing) {
72
134
  const { SessionManager } = await import("@oh-my-pi/pi-coding-agent/session/session-manager");
73
135
  const session = SessionManager.create(options.cwd, dirname(options.sessionFile));
74
136
  try {
75
137
  await session.setSessionFile(options.sessionFile);
138
+ if (options.prReviewOnly)
139
+ session.appendCustomEntry("superagent_pr_review_policy", { version: 1, cwd: options.cwd });
76
140
  const selection = manifest.headRotationSelection;
77
141
  if (selection) {
78
142
  session.appendModelChange(`${selection.provider}/${selection.modelId}`);
@@ -81,12 +145,15 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
81
145
  await session.ensureOnDisk();
82
146
  session.flushSync();
83
147
  } finally { await session.close(); }
148
+ if (options.prReviewOnly) await chmod(options.sessionFile, 0o600);
149
+ }
150
+ if (!options.prReviewOnly) {
151
+ const { publishNativeSession } = await import("./native-sessions");
152
+ await publishNativeSession(options.sessionFile, options.cwd);
84
153
  }
85
- const { publishNativeSession } = await import("./native-sessions");
86
- await publishNativeSession(options.sessionFile, options.cwd);
87
154
  const { hostInventoryManifest } = await import("./host-inventory-manifest");
88
155
  return { toolsExplicitlySelected: parsed.tools !== undefined, noTools: parsed.noTools === true,
89
- inventory: await hostInventoryManifest(manifest.processBackend) };
156
+ inventory: await hostInventoryManifest(manifest.processBackend, options.cwd) };
90
157
  }
91
158
  case "inventory": {
92
159
  const { projectDir, serviceName } = input as { projectDir?: string; serviceName?: string };
@@ -112,11 +179,53 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
112
179
  }
113
180
  }
114
181
 
182
+ /**
183
+ * Launch discovery, then session preparation, in this one process. Reads the
184
+ * discovery input line, reports the composition, and prepares only after the
185
+ * launcher answers with its manifest; EOF instead means discovery only.
186
+ */
187
+ async function launch() {
188
+ const reader = Bun.stdin.stream().getReader();
189
+ const decoder = new TextDecoder();
190
+ let buffered = "";
191
+ while (!buffered.includes("\n")) {
192
+ const chunk = await reader.read();
193
+ if (chunk.done) throw new Error("Missing launch discovery input");
194
+ buffered += decoder.decode(chunk.value, { stream: true });
195
+ }
196
+ const newline = buffered.indexOf("\n");
197
+ const input: ManagedUlwLaunchInput | null = JSON.parse(buffered.slice(0, newline));
198
+ let rest = buffered.slice(newline + 1);
199
+ let composition;
200
+ if (input === null) {
201
+ composition = { extensionPaths: [], noExtensions: true, memoryWriteDir: null };
202
+ } else {
203
+ const { managedUlwLaunchComposition } = await import("./managed-ulw");
204
+ try { composition = await managedUlwLaunchComposition(input); }
205
+ catch (error) {
206
+ // Discovery refusals name the launch argument or package the operator must change.
207
+ process.stdout.write(`\nMANAGED_ULW_LAUNCH_ERROR ${JSON.stringify(error instanceof Error ? error.message : String(error))}\n`);
208
+ process.exitCode = 1;
209
+ return;
210
+ }
211
+ }
212
+ process.stdout.write(`\nMANAGED_ULW_LAUNCH ${JSON.stringify(composition)}\n`);
213
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) rest += decoder.decode(chunk.value, { stream: true });
214
+ rest += decoder.decode();
215
+ if (!rest) return;
216
+ const manifest: Manifest = JSON.parse(rest);
217
+ process.stdout.write(JSON.stringify(await run("prepare", manifest, manifest, input !== null && !input.worker)));
218
+ }
219
+
115
220
  const [, , operation, path] = process.argv;
116
221
  try {
117
- const input = await Bun.stdin.json();
118
- const manifest: Manifest = operation === "prepare" ? input : await Bun.file(path!).json();
119
- process.stdout.write(JSON.stringify(await run(operation, manifest, input)));
222
+ if (operation === "launch") await launch();
223
+ else if (operation === "prepare") throw new Error("Session preparation follows launch discovery");
224
+ else {
225
+ const input = await Bun.stdin.json();
226
+ const manifest: Manifest = await Bun.file(path!).json();
227
+ process.stdout.write(JSON.stringify(await run(operation, manifest, input)));
228
+ }
120
229
  } catch {
121
230
  // SDK errors may contain native frames, authorization data or prompt content.
122
231
  console.error("Host SDK operation failed");
package/src/host.ts CHANGED
@@ -3,26 +3,51 @@ import { constants, type Stats } from "node:fs";
3
3
  import * as fs from "node:fs/promises";
4
4
  import * as net from "node:net";
5
5
  import * as path from "node:path";
6
- import { Readable } from "node:stream";
6
+ import { Readable, type Writable } from "node:stream";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import {
9
9
  RpcClient,
10
10
  type RpcAgentProcess,
11
11
  } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-client";
12
12
  import { RPC_GOAL_CONTINUATION_MODE } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-goal";
13
- import { HostChannel, type HostResponse, type HostState } from "./host-protocol";
13
+ import { HostChannel, PR_REVIEW_GITHUB_ENV, PR_REVIEW_SYSTEM_PROMPT, type HostResponse, type HostState } from "./host-protocol";
14
14
  import { requireHostOwner } from "./host-owner-path";
15
15
  import { inspectInstalledOmp, resolveOmpCommand } from "./installed-omp";
16
16
  import type { DialogResponse, LanePresetSnapshot } from "./contracts";
17
- import { activeManagedUlw, managedUlwLaunchExtensions, MANAGED_ULW_ENV, MANAGED_ULW_FIXTURE_ENV, MANAGED_ULW_FIXTURE_ROOT_ENV, validateManagedUlwPackage } from "./managed-ulw";
17
+ import type { WorkerHostProfile } from "./worker-profile";
18
+ import { activeManagedUlw, managedUlwLaunch, MANAGED_ULW_ENV, MANAGED_ULW_FIXTURE_ENV, MANAGED_ULW_FIXTURE_ROOT_ENV, validateManagedUlwPackage } from "./managed-ulw";
18
19
 
19
20
  const CONNECT_TIMEOUT_MS = 5_000;
20
21
  const START_TIMEOUT_MS = 30_000;
21
22
  const MAX_PENDING_BYTES = 16 * 1024 * 1024;
22
23
  const MAX_PENDING_WRITES = 4096;
24
+ export const PR_REVIEW_INPUT_PREFIX = "Static PR review input:\n";
25
+
26
+ // These settings are scoped to the private launch overlay. In particular no
27
+ // review text enters the ordinary memory backend or an autonomous side turn.
28
+ const prReviewSettings = {
29
+ memory: { backend: "off" },
30
+ goal: { enabled: false },
31
+ compaction: { enabled: false },
32
+ advisor: { enabled: false },
33
+ autolearn: { enabled: false },
34
+ dev: { autoqa: false },
35
+ skills: { enabled: false, enableSkillCommands: false, customDirectories: [] },
36
+ mcp: { enableProjectConfig: false },
37
+ marketplace: { autoUpdate: "off" },
38
+ magicKeywords: { enabled: false },
39
+ prewalk: { enabled: false, auto: "off" },
40
+ spotlight: { experiment: { enabled: false } },
41
+ providers: { cacheWarming: "off" },
42
+ telemetry: { otlpExportEnabled: false },
43
+ };
23
44
 
24
45
  export interface HostOptions {
25
46
  command: string[];
47
+ /** Local managed static review lane; cwd must be a private empty non-checkout. */
48
+ readonly prReviewOnly?: true;
49
+ /** Target-owned launch policy, never decoded from an SSH request. */
50
+ readonly worker?: WorkerHostProfile;
26
51
  socketPath: string;
27
52
  sessionFile: string;
28
53
  cwd: string;
@@ -84,31 +109,32 @@ class SocketProcess implements RpcAgentProcess {
84
109
  readonly #pending = new Set<(error: Error) => void>();
85
110
  #error = "";
86
111
 
87
- constructor(readonly socket: net.Socket) {
112
+ constructor(readonly input: Readable, readonly output: Writable, readonly disconnect: (error?: Error) => void) {
88
113
  // Node and Bun publish incompatible getReader overloads for the same WHATWG stream.
89
- this.stdout = Readable.toWeb(socket) as unknown as ReadableStream<Uint8Array>;
114
+ this.stdout = Readable.toWeb(input) as unknown as ReadableStream<Uint8Array>;
90
115
  const { promise, resolve } = Promise.withResolvers<number>();
91
116
  this.exited = promise;
92
- socket.once("close", () => {
117
+ input.once("close", () => {
93
118
  const error = new Error(this.#error || "RPC socket disconnected; request outcome may be unknown");
94
119
  for (const reject of this.#pending) reject(error);
95
120
  resolve(this.#error ? 1 : 0);
96
121
  });
97
- socket.on("error", error => { this.#error = error.message; });
122
+ input.on("error", error => { this.#error = error.message; });
123
+ if (input !== (output as NodeJS.EventEmitter)) output.on("error", error => { this.#error = error.message; });
98
124
  this.stdin = { write: data => this.#write(data) };
99
125
  }
100
126
 
101
127
  peekStderr(): string { return this.#error; }
102
128
 
103
129
  // RpcClient.stop() is a detach operation for this transport, never a host signal.
104
- kill(): void { this.socket.destroy(); }
130
+ kill(): void { this.disconnect(); }
105
131
 
106
132
  #write(data: string | Uint8Array): Promise<void> {
107
- if (this.socket.destroyed || !this.socket.writable) {
133
+ if (this.output.destroyed || !this.output.writable) {
108
134
  return Promise.reject(new Error("RPC socket is disconnected"));
109
135
  }
110
136
  const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
111
- if (this.socket.writableLength + bytes > MAX_PENDING_BYTES || this.#pending.size >= MAX_PENDING_WRITES) {
137
+ if (this.output.writableLength + bytes > MAX_PENDING_BYTES || this.#pending.size >= MAX_PENDING_WRITES) {
112
138
  return Promise.reject(new Error("RPC socket write backlog exceeded its bound"));
113
139
  }
114
140
  const { promise, resolve, reject } = Promise.withResolvers<void>();
@@ -121,11 +147,11 @@ class SocketProcess implements RpcAgentProcess {
121
147
  const timer = setTimeout(() => {
122
148
  const error = new Error("RPC socket write timed out; request outcome may be unknown");
123
149
  finish(error);
124
- this.socket.destroy(error);
150
+ this.disconnect(error);
125
151
  }, CONNECT_TIMEOUT_MS);
126
152
  timer.unref();
127
153
  this.#pending.add(finish);
128
- try { this.socket.write(data, finish); }
154
+ try { this.output.write(data, finish); }
129
155
  catch (error) { finish(error instanceof Error ? error : new Error(String(error))); }
130
156
  return promise;
131
157
  }
@@ -146,7 +172,7 @@ export class HostConnection {
146
172
 
147
173
  private constructor(transport: SocketProcess) {
148
174
  this.exited = transport.exited.then(() => {});
149
- this.#channel = new HostChannel(transport.socket, transport.socket);
175
+ this.#channel = new HostChannel(transport.input, transport.output);
150
176
  this.#channel.on("frame", frame => this.#emit(frame));
151
177
  this.client = new AdapterClient({ spawn: () => transport });
152
178
  }
@@ -164,34 +190,58 @@ export class HostConnection {
164
190
  return await HostConnection.#open(socketPath, timeoutMs, "full");
165
191
  }
166
192
 
193
+ /** The enrolled worker verifies the Unix endpoint on its host. Check its attestation
194
+ * again in the native handshake on this exact SSH stream, before sending any input. */
195
+ static async fromWorker(input: Readable, output: Writable, disconnect: () => void,
196
+ expected: { pid: number; sessionId: string; sessionFile: string }) {
197
+ const connection = new HostConnection(new SocketProcess(input, output, disconnect));
198
+ const timeout = setTimeout(disconnect, CONNECT_TIMEOUT_MS);
199
+ try {
200
+ const state = await connection.#handshake();
201
+ if (state.prReviewPolicy !== undefined || state.hostPid !== expected.pid || state.sessionId !== expected.sessionId ||
202
+ state.sessionFile !== expected.sessionFile) {
203
+ throw new Error("Remote Host identity differs from its worker registration");
204
+ }
205
+ await connection.#enableActivityUpdates(state);
206
+ return connection;
207
+ } catch (error) {
208
+ disconnect();
209
+ await connection.close();
210
+ throw error;
211
+ } finally {
212
+ clearTimeout(timeout);
213
+ }
214
+ }
215
+
216
+ async #handshake() {
217
+ await this.client.start();
218
+ const state = await this.client.getState();
219
+ if (typeof state.sessionId !== "string" || !state.sessionId ||
220
+ typeof state.sessionFile !== "string" || !path.isAbsolute(state.sessionFile) ||
221
+ !Number.isSafeInteger(state.hostPid) || state.hostPid < 1 ||
222
+ state.adapterProtocol !== "owned-stock-stdio-v1" || !Number.isSafeInteger(state.adapterOwnerPid)
223
+ || state.adapterOwnerPid < 1) {
224
+ throw new Error("Endpoint did not identify an owned stock-stdio adapter and persistent OMP session");
225
+ }
226
+ return { ...state, sessionFile: state.sessionFile };
227
+ }
228
+
167
229
  /** Identity is captured once per fresh handshake, never reused across probes. */
168
230
  static async #open(socketPath: string, timeoutMs: number, messageUpdates: "full" | "activity-v1") {
169
231
  const before = await socketIdentity(socketPath);
170
232
  const socket = net.createConnection(socketPath);
171
- const transport = new SocketProcess(socket);
233
+ const transport = new SocketProcess(socket, socket, error => socket.destroy(error));
172
234
  const connection = new HostConnection(transport);
173
235
  const timeout = setTimeout(() => socket.destroy(new Error("RPC socket connection/identity probe timed out")), timeoutMs);
174
236
  timeout.unref();
175
237
  try {
176
- await connection.client.start();
177
- const state = await connection.client.getState();
238
+ const state = await connection.#handshake();
178
239
  const after = await socketIdentity(socketPath);
179
240
  if (before.dev !== after.dev || before.ino !== after.ino) {
180
241
  throw new Error("RPC socket identity changed while connecting");
181
242
  }
182
- if (typeof state.sessionId !== "string" || !state.sessionId ||
183
- typeof state.sessionFile !== "string" || !path.isAbsolute(state.sessionFile) ||
184
- !Number.isSafeInteger(state.hostPid) || state.hostPid! < 1 ||
185
- state.adapterProtocol !== "owned-stock-stdio-v1" || !Number.isSafeInteger(state.adapterOwnerPid)
186
- || state.adapterOwnerPid < 1) {
187
- throw new Error("Endpoint did not identify an owned stock-stdio adapter and persistent OMP session");
188
- }
189
- if (messageUpdates === "activity-v1") {
190
- if (typeof state.loadedSuperkitPath !== "string" || !path.isAbsolute(state.loadedSuperkitPath))
191
- throw new Error("Native Host has not verified its omp-superkit extension; stop and start the Host");
192
- await connection.#enableActivityUpdates();
193
- }
194
- return { connection, identity: { pid: state.hostPid, ownerPid: state.adapterOwnerPid,
243
+ if (messageUpdates === "activity-v1") await connection.#enableActivityUpdates(state);
244
+ return { connection, state, identity: { pid: state.hostPid, ownerPid: state.adapterOwnerPid,
195
245
  sessionId: state.sessionId, sessionFile: state.sessionFile, dev: after.dev, ino: after.ino } };
196
246
  } catch (error) {
197
247
  await connection.close();
@@ -201,7 +251,10 @@ export class HostConnection {
201
251
  }
202
252
  }
203
253
 
204
- async #enableActivityUpdates(): Promise<void> {
254
+ async #enableActivityUpdates(state: HostState): Promise<void> {
255
+ if (state.prReviewPolicy?.version !== 1 &&
256
+ (typeof state.loadedSuperkitPath !== "string" || !path.isAbsolute(state.loadedSuperkitPath)))
257
+ throw new Error("Native Host has not verified its omp-superkit extension; stop and start the Host");
205
258
  const capability = await this.request({ type: "get_host_admission", messageUpdateCapability: true });
206
259
  if (!capability.success || capability.command !== "get_host_admission") {
207
260
  throw new Error("Owned Host could not report its message update capability");
@@ -215,6 +268,12 @@ export class HostConnection {
215
268
  }
216
269
  }
217
270
 
271
+ /** Call on the exact local connection before admitting each review round. */
272
+ async assertPrReviewOnly(cwd: string): Promise<void> {
273
+ const state = await this.client.getState();
274
+ await assertPrReviewState(state, cwd);
275
+ }
276
+
218
277
  /** Private adapter correlation. Stock RpcClient deliberately has no generic request API. */
219
278
  request(command: Record<string, unknown>, id?: string): Promise<HostResponse> {
220
279
  if (typeof command.type !== "string" || !command.type) throw new Error("RPC command requires a type");
@@ -255,6 +314,23 @@ export function connect(socketPath: string): Promise<HostConnection> {
255
314
  return HostConnection.connect(socketPath);
256
315
  }
257
316
 
317
+ async function assertPrReviewState(state: HostState, cwd: string): Promise<void> {
318
+ const canonical = await fs.realpath(cwd);
319
+ if (state.prReviewPolicy?.version !== 1 || state.prReviewPolicy.cwd !== canonical ||
320
+ typeof state.prReviewPolicy.modelApi !== "string" || state.prReviewPolicy.modelApi !== state.model?.api ||
321
+ !Array.isArray(state.dumpTools) || state.dumpTools.length !== 0)
322
+ throw new Error("Native Host did not confirm the local static PR review policy");
323
+ }
324
+
325
+ async function assertPrReviewLaunch(options: HostOptions): Promise<void> {
326
+ if (options.worker || options.modelPreset || options.modelSettings || options.env.OMP_SUPERAGENT_WORKER_ATTEMPT)
327
+ throw new Error("Static PR review requires an exact-model local Host, without worker or preset policy");
328
+ const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
329
+ const bootstrap = extractProfileFlags(options.command.slice(1));
330
+ if (bootstrap.argv.length || bootstrap.aliasName !== undefined)
331
+ throw new Error("Static PR review Host accepts only the native --profile launch prefix");
332
+ }
333
+
258
334
  export async function buildHostArgs(options: HostOptions, configPath = `${options.socketPath}.config.json`,
259
335
  composition?: { extensionPaths: string[]; noExtensions: boolean }): Promise<string[]> {
260
336
  assertSocketPath(options.socketPath);
@@ -270,6 +346,14 @@ export async function buildHostArgs(options: HostOptions, configPath = `${option
270
346
  if (!Number.isSafeInteger(options.subagentConcurrency) || options.subagentConcurrency < 1) {
271
347
  throw new Error("subagentConcurrency must be a positive integer");
272
348
  }
349
+ if (options.prReviewOnly) {
350
+ await assertPrReviewLaunch(options);
351
+ return ["--mode", "rpc-ui", "--session", options.sessionFile, "--cwd", options.cwd,
352
+ "--no-tools", "--no-extensions", "--no-lsp", "--no-skills", "--no-rules", "--no-context-files",
353
+ "--no-title", "--no-prewalk", "--offline",
354
+ "--trusted-extension", await fs.realpath(fileURLToPath(new URL("./host-extension.ts", import.meta.url))),
355
+ "--system-prompt", PR_REVIEW_SYSTEM_PROMPT, "--config", configPath];
356
+ }
273
357
  if (options.modelPreset) {
274
358
  // Only named lane presets need the SDK's model resolver. HEAD launches
275
359
  // (including restored model settings) must not load it just to build argv.
@@ -286,31 +370,56 @@ export async function buildHostArgs(options: HostOptions, configPath = `${option
286
370
  return [
287
371
  "--mode", "rpc-ui",
288
372
  "--session", options.sessionFile, "--cwd", options.cwd,
289
- ...(composition?.noExtensions ? ["--no-extensions"] : []),
373
+ ...(options.worker?.flags ?? []),
374
+ ...(composition?.noExtensions && !options.worker ? ["--no-extensions"] : []),
290
375
  ...extensions.flatMap(extension => ["-e", extension]),
291
376
  "--config", configPath,
292
377
  ];
293
378
  }
294
379
 
295
380
  function selectManagedUlw(options: HostOptions): string {
381
+ if (options.worker) return validateManagedUlwPackage(options.worker.managedUlwPath);
296
382
  const fixture = options.managedUlwPath ?? options.env[MANAGED_ULW_FIXTURE_ENV];
297
383
  const root = options.managedUlwRoot ?? options.env[MANAGED_ULW_FIXTURE_ROOT_ENV];
298
384
  return fixture ? validateManagedUlwPackage(fixture) : activeManagedUlw(root ? { root } : {});
299
385
  }
300
386
 
301
387
  /** Launch only a new host. Existing endpoints require the caller's explicit adoption decision. */
302
- export async function startHost(options: HostOptions): Promise<{ pid: number }> {
303
- try { return await launchHost(options); }
388
+ export async function startHost(options: HostOptions, beforeSessionPrepare?: () => void): Promise<{ pid: number }> {
389
+ try { return await launchHost(options, beforeSessionPrepare); }
304
390
  catch (cause) {
305
391
  // Never read child output into errors: logs can contain credentials or prompt content.
306
392
  throw new HostStartError(cause instanceof Error ? cause.message : "OMP host startup failed", { cause });
307
393
  }
308
394
  }
309
395
 
310
- async function launchHost(options: HostOptions): Promise<{ pid: number }> {
396
+ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => void): Promise<{ pid: number }> {
311
397
  // Snapshot once before any awaits; an updater may activate a newer revision
312
398
  // during startup, but this Host must load one exact immutable package.
313
- const managedUlwPath = selectManagedUlw(options);
399
+ if (options.prReviewOnly) {
400
+ await assertPrReviewLaunch(options);
401
+ await privateDirectory(options.cwd);
402
+ const cwd = await fs.realpath(options.cwd);
403
+ if ((await fs.readdir(cwd)).length) throw new Error("Static PR review workspace must be empty");
404
+ // No Git invocation (including hooks or configuration) is needed to
405
+ // distinguish an empty directory from an empty subdirectory of a checkout.
406
+ for (let dir = cwd; ; dir = path.dirname(dir)) {
407
+ if (await fs.lstat(path.join(dir, ".git")).then(() => true, error => {
408
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
409
+ throw error;
410
+ })) throw new Error("Static PR review workspace must be outside a Git checkout");
411
+ if (path.dirname(dir) === dir) break;
412
+ }
413
+ const { assertWorkerWorkspaceStartup } = await import("./worker-profile");
414
+ assertWorkerWorkspaceStartup(cwd, options.env.HOME ?? "");
415
+ const env = { ...options.env };
416
+ for (const name of [...PR_REVIEW_GITHUB_ENV,
417
+ MANAGED_ULW_ENV, MANAGED_ULW_FIXTURE_ENV, MANAGED_ULW_FIXTURE_ROOT_ENV]) delete env[name];
418
+ options = { ...options, cwd, env, managedUlwPath: undefined, managedUlwRoot: undefined };
419
+ }
420
+ // Do not discover, load or preflight Superkit (or persist a global memory
421
+ // fallback) for isolated review lanes.
422
+ const managedUlwPath = options.prReviewOnly ? undefined : selectManagedUlw(options);
314
423
  const fixture = options.managedUlwPath ?? options.env[MANAGED_ULW_FIXTURE_ENV];
315
424
  const hostOwnerExecutable = await requireHostOwner();
316
425
  const fixtureRoot = options.managedUlwRoot ?? options.env[MANAGED_ULW_FIXTURE_ROOT_ENV];
@@ -318,7 +427,7 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
318
427
  : Bun.which("bun", { PATH: options.env.PATH ?? process.env.PATH }));
319
428
  if (!bun || !path.isAbsolute(bun)) throw new Error("Managed Host launch requires an explicit installed Bun executable");
320
429
  options = { ...options, command: resolveOmpCommand(options.command, options.env.PATH ?? ""), managedUlwPath,
321
- env: { ...options.env, [MANAGED_ULW_ENV]: managedUlwPath,
430
+ env: { ...options.env, ...(managedUlwPath ? { [MANAGED_ULW_ENV]: managedUlwPath } : {}),
322
431
  OMP_SUPERAGENT_BUN: bun,
323
432
  ...(fixture ? { [MANAGED_ULW_FIXTURE_ENV]: fixture } : {}),
324
433
  ...(fixtureRoot ? { [MANAGED_ULW_FIXTURE_ROOT_ENV]: fixtureRoot } : {}) } };
@@ -348,8 +457,10 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
348
457
  try {
349
458
  const initialSettings = options.modelPreset?.preset ?? options.modelSettings;
350
459
  await fs.writeFile(configPath, JSON.stringify({
460
+ ...options.worker?.config,
351
461
  task: { maxConcurrency: options.subagentConcurrency },
352
462
  goal: { continuationModes: [RPC_GOAL_CONTINUATION_MODE] },
463
+ ...(options.prReviewOnly ? prReviewSettings : {}),
353
464
  ...(options.modelPreset ? { modelPresets: { [options.modelPreset.name]: options.modelPreset.preset } } : {}),
354
465
  ...(initialSettings ? {
355
466
  modelRoles: {
@@ -366,32 +477,38 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
366
477
  throw new Error("Host log must be a private regular file owned by this user");
367
478
  }
368
479
  const manifestPath = path.join(launchDirectory, "owner.json");
369
- const extensionPaths = [fileURLToPath(new URL("../", import.meta.url)), managedUlwPath, options.extensionPath,
370
- fileURLToPath(new URL("./board-extension.ts", import.meta.url)),
371
- fileURLToPath(new URL("./host-extension.ts", import.meta.url))];
372
- const composition = await managedUlwLaunchExtensions({ cwd: options.cwd, managedUlwPath,
373
- extensionPaths, configPath, commandArgs: options.command.slice(1),
374
- launchArgs: [...options.command.slice(1), ...await buildHostArgs(options, configPath)],
375
- env: options.env, bunCommand: [bun, "--no-env-file"] });
376
- const { env: _inheritedEnvironment, ...launchOptions } = options;
480
+ const { env: _inheritedEnvironment, worker: _workerProfile, ...launchOptions } = options;
377
481
  const helperPath = fileURLToPath(new URL("./host-sdk-helper.ts", import.meta.url));
378
- const manifest = { options: launchOptions, args: await buildHostArgs(options, configPath, composition), configPath,
379
- processBackend, helperPath, nativeSocket: path.join(path.dirname(options.socketPath), `.n-${crypto.randomUUID().slice(0, 8)}.sock`) };
380
- // Preparation used to run inside the owner; it shares the same startup budget.
381
- const deadline = Date.now() + START_TIMEOUT_MS;
382
- const prepare = Bun.spawn([bun, "--no-env-file", helperPath, "prepare"], {
383
- cwd: options.cwd, env: options.env, stdin: new Blob([JSON.stringify(manifest)]), stdout: "pipe", stderr: log.fd,
384
- timeout: START_TIMEOUT_MS, killSignal: "SIGKILL",
482
+ let manifest: Record<string, unknown> | undefined;
483
+ const extensionPaths = managedUlwPath === undefined ? [] : [fileURLToPath(new URL("../", import.meta.url)),
484
+ managedUlwPath, options.extensionPath, fileURLToPath(new URL("./board-extension.ts", import.meta.url)),
485
+ fileURLToPath(new URL("./host-extension.ts", import.meta.url))];
486
+ // The same helper discovers composition and then prepares the session.
487
+ // The worker launch fence is committed only immediately before the manifest
488
+ // is sent. Preparation and owner startup share the same deadline.
489
+ const { prepared, deadline } = await managedUlwLaunch({ cwd: options.cwd, managedUlwPath,
490
+ extensionPaths, configPath, parentConfigPath: process.env.OMP_SUPERAGENT_HOST_CONFIG, commandArgs: options.command.slice(1),
491
+ ...(options.worker ? { worker: { extensionPaths: options.worker.extensionPaths } } : {}),
492
+ launchArgs: managedUlwPath === undefined ? [] : [...options.command.slice(1), ...await buildHostArgs(options, configPath)],
493
+ env: options.env, bunCommand: [bun, "--no-env-file"] }, {
494
+ stderr: log.fd, timeoutMs: START_TIMEOUT_MS, beforeManifest: beforeSessionPrepare,
495
+ manifest: async composition => {
496
+ manifest = { options: launchOptions, args: await buildHostArgs(options, configPath, composition), configPath,
497
+ memoryWriteDir: composition.memoryWriteDir, processBackend, helperPath,
498
+ nativeSocket: path.join(path.dirname(options.socketPath), `.n-${crypto.randomUUID().slice(0, 8)}.sock`) };
499
+ return manifest;
500
+ },
385
501
  });
386
- const [prepared, code] = await Promise.all([new Response(prepare.stdout).text(), prepare.exited]);
387
- if (Date.now() >= deadline) throw new Error("Native session preparation timed out");
388
- if (code !== 0) throw new Error("Native session preparation failed");
502
+ if (deadline === undefined || prepared === undefined) throw new Error("Native session preparation did not confirm tool selection");
503
+ if (performance.now() >= deadline) throw new Error("Native session preparation timed out");
389
504
  const flags = JSON.parse(prepared);
390
505
  if (typeof flags?.toolsExplicitlySelected !== "boolean" || typeof flags.noTools !== "boolean")
391
506
  throw new Error("Native session preparation did not confirm tool selection");
507
+ if (options.prReviewOnly && (!flags.noTools || flags.toolsExplicitlySelected))
508
+ throw new Error("Native launch did not resolve the stock no-tools selection");
392
509
  await fs.writeFile(manifestPath, JSON.stringify({ ...manifest, toolsExplicitlySelected: flags.toolsExplicitlySelected,
393
510
  noTools: flags.noTools, inventory: flags.inventory }), { flag: "wx", mode: 0o600 });
394
- if (Date.now() >= deadline) throw new Error("Native Host startup timed out before launch");
511
+ if (performance.now() >= deadline) throw new Error("Native Host startup timed out before launch");
395
512
  child = spawn(hostOwnerExecutable, [manifestPath], {
396
513
  cwd: options.cwd, env: options.env,
397
514
  detached: true, stdio: ["ignore", log.fd, log.fd], shell: false,
@@ -405,7 +522,7 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
405
522
  await log.close();
406
523
  log = undefined;
407
524
  let startingSocket: Stats | undefined;
408
- while (Date.now() < deadline) {
525
+ while (performance.now() < deadline) {
409
526
  if (failure) throw failure;
410
527
  let observed: Stats;
411
528
  try {
@@ -430,7 +547,7 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
430
547
  await Bun.sleep(50);
431
548
  continue;
432
549
  }
433
- const { connection, identity } = await HostConnection.open(options.socketPath, Math.max(1, deadline - Date.now()));
550
+ const { connection, identity, state } = await HostConnection.open(options.socketPath, Math.max(1, deadline - performance.now()));
434
551
  try {
435
552
  if (identity.dev !== startingSocket.dev || identity.ino !== startingSocket.ino) {
436
553
  throw new Error("Launched RPC socket identity changed while connecting");
@@ -439,6 +556,7 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
439
556
  if (path.resolve(identity.sessionFile) !== path.resolve(options.sessionFile)) {
440
557
  throw new Error("Launched RPC host identified a different session file");
441
558
  }
559
+ if (options.prReviewOnly) await assertPrReviewState(state, options.cwd);
442
560
  if (failure) throw failure;
443
561
  return { pid: identity.pid };
444
562
  } finally { await connection.close(); }