omp-superagent 0.0.0-stage → 0.1.2

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 (97) hide show
  1. package/DESIGN.md +1502 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +198 -0
  4. package/README.md +224 -2
  5. package/THIRD_PARTY_NOTICES.md +388 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1178 -0
  12. package/docs/discord-voice.md +96 -0
  13. package/docs/releases/0.1.0.md +222 -0
  14. package/docs/releases/0.1.1.md +60 -0
  15. package/docs/releases/0.1.2.md +53 -0
  16. package/package.json +65 -4
  17. package/scripts/ci.ts +33 -0
  18. package/scripts/prepare-ulw.ts +18 -0
  19. package/scripts/release.ts +58 -0
  20. package/scripts/setup.sh +25 -0
  21. package/scripts/test-omp.sh +36 -0
  22. package/skills/head/SKILL.md +100 -0
  23. package/skills/head/references/model-selection.md +83 -0
  24. package/skills/head/references/routing.md +181 -0
  25. package/skills/head/references/supervision.md +122 -0
  26. package/skills/lane/SKILL.md +66 -0
  27. package/skills/lane/references/workflow.md +95 -0
  28. package/src/autostart.ts +295 -0
  29. package/src/board-extension.ts +217 -0
  30. package/src/board.ts +396 -0
  31. package/src/cli.ts +253 -0
  32. package/src/codex-live-bridge.py +73 -0
  33. package/src/codex-live.ts +244 -0
  34. package/src/codex-voice-requirements.txt +5 -0
  35. package/src/codex_live_auth.py +192 -0
  36. package/src/codex_live_media.py +219 -0
  37. package/src/codex_live_provider.py +192 -0
  38. package/src/config.ts +266 -0
  39. package/src/contracts.ts +381 -0
  40. package/src/credentials.ts +172 -0
  41. package/src/decision-tool.ts +59 -0
  42. package/src/decisions.ts +143 -0
  43. package/src/delivery.ts +17 -0
  44. package/src/dialog.ts +73 -0
  45. package/src/discord-command-registration.ts +201 -0
  46. package/src/discord-commands.ts +29 -0
  47. package/src/discord-context.ts +118 -0
  48. package/src/discord-markdown.ts +172 -0
  49. package/src/discord-voice-draft.ts +124 -0
  50. package/src/discord-voice-link.ts +270 -0
  51. package/src/discord-voice.ts +150 -0
  52. package/src/discord.ts +1012 -0
  53. package/src/extension.ts +446 -0
  54. package/src/gateway-client.ts +229 -0
  55. package/src/gateway-protocol.ts +85 -0
  56. package/src/gateway-restart.ts +151 -0
  57. package/src/gateway-server.ts +440 -0
  58. package/src/gateway-store.ts +251 -0
  59. package/src/gateway.ts +654 -0
  60. package/src/head-recovery.ts +61 -0
  61. package/src/host-broker-services.ts +108 -0
  62. package/src/host-extension.ts +561 -0
  63. package/src/host-owner.ts +366 -0
  64. package/src/host-protocol.ts +144 -0
  65. package/src/host-services.ts +54 -0
  66. package/src/host.ts +415 -0
  67. package/src/installed-omp.ts +71 -0
  68. package/src/lane-extension.ts +184 -0
  69. package/src/lane-models.ts +75 -0
  70. package/src/lane-report.ts +70 -0
  71. package/src/lane-rows.ts +12 -0
  72. package/src/managed-ulw-probe.ts +172 -0
  73. package/src/managed-ulw.ts +471 -0
  74. package/src/message-order.ts +21 -0
  75. package/src/messenger-commands.ts +16 -0
  76. package/src/messengers.ts +143 -0
  77. package/src/native-presets.ts +370 -0
  78. package/src/native-sessions.ts +32 -0
  79. package/src/native-settings.ts +131 -0
  80. package/src/openai-live.ts +377 -0
  81. package/src/pr-github-schema.ts +110 -0
  82. package/src/pr-github.ts +170 -0
  83. package/src/pr-watch.ts +200 -0
  84. package/src/repository.ts +12 -0
  85. package/src/runtime.ts +4229 -0
  86. package/src/setup-judge.ts +34 -0
  87. package/src/setup-memory.ts +39 -0
  88. package/src/setup-profiles.ts +84 -0
  89. package/src/setup.ts +300 -0
  90. package/src/slack-command-registration.ts +217 -0
  91. package/src/slack-commands.ts +18 -0
  92. package/src/slack.ts +779 -0
  93. package/src/store.ts +862 -0
  94. package/src/telegram-command-registration.ts +155 -0
  95. package/src/telegram.ts +677 -0
  96. package/src/workflow.ts +94 -0
  97. package/upstream/ulw.json +9 -0
package/src/host.ts ADDED
@@ -0,0 +1,415 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import { constants, type Stats } from "node:fs";
3
+ import * as fs from "node:fs/promises";
4
+ import * as net from "node:net";
5
+ import * as path from "node:path";
6
+ import { Readable } from "node:stream";
7
+ import { fileURLToPath } from "node:url";
8
+ import {
9
+ RpcClient,
10
+ type RpcAgentProcess,
11
+ } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-client";
12
+ import { isValidModelPresetName } from "@oh-my-pi/pi-coding-agent/config/model-presets";
13
+ import { RPC_GOAL_CONTINUATION_MODE } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-goal";
14
+ import { HostChannel, type HostResponse, type HostState } from "./host-protocol";
15
+ import { inspectInstalledOmp, resolveOmpCommand } from "./installed-omp";
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";
18
+
19
+ const CONNECT_TIMEOUT_MS = 5_000;
20
+ const START_TIMEOUT_MS = 30_000;
21
+ const MAX_PENDING_BYTES = 16 * 1024 * 1024;
22
+ const MAX_PENDING_WRITES = 4096;
23
+
24
+ export interface HostOptions {
25
+ command: string[];
26
+ socketPath: string;
27
+ sessionFile: string;
28
+ cwd: string;
29
+ extensionPath: string;
30
+ /** Explicit isolated fixture package; production always resolves the active managed revision. */
31
+ managedUlwPath?: string;
32
+ /** Isolated managed-installation root; unlike package injection, follows its active pointer. */
33
+ managedUlwRoot?: string;
34
+ /** Complete child environment; omitted credentials must never be inherited again. */
35
+ env: Record<string, string>;
36
+ logPath: string;
37
+ model?: string;
38
+ modelPreset?: { name: string; preset: LanePresetSnapshot };
39
+ /** Restore session-local preset roles without overriding the transcript's active model/effort. */
40
+ modelSettings?: LanePresetSnapshot;
41
+ clearedModelRoles?: string[];
42
+ subagentConcurrency: number;
43
+ }
44
+
45
+ export type HostFrame = Record<string, unknown>;
46
+
47
+ export class HostStartError extends Error {
48
+ constructor(message: string, options?: ErrorOptions) {
49
+ super(message, options);
50
+ this.name = "HostStartError";
51
+ }
52
+ }
53
+
54
+ function assertSocketPath(socketPath: string): void {
55
+ // Match the core host's portable limit, including macOS sockaddr_un.
56
+ if (!path.isAbsolute(socketPath) || Buffer.byteLength(socketPath) > 100) {
57
+ throw new Error("RPC socket must be an absolute Unix socket path of at most 100 bytes");
58
+ }
59
+ }
60
+
61
+ async function privateDirectory(directory: string): Promise<void> {
62
+ const stat = await fs.lstat(directory);
63
+ if (!stat.isDirectory() || stat.isSymbolicLink() ||
64
+ stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700) {
65
+ throw new Error(`RPC socket directory must be owned by this user with mode 0700 (no symlink): ${directory}`);
66
+ }
67
+ }
68
+
69
+ async function socketIdentity(socketPath: string): Promise<Stats> {
70
+ assertSocketPath(socketPath);
71
+ await privateDirectory(path.dirname(socketPath));
72
+ const stat = await fs.lstat(socketPath);
73
+ if (!stat.isSocket() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600) {
74
+ throw new Error(`RPC socket must be owned by this user with mode 0600: ${socketPath}`);
75
+ }
76
+ return stat;
77
+ }
78
+
79
+ /** RpcClient owns framing, negotiation, correlation, and events. This only carries bytes. */
80
+ class SocketProcess implements RpcAgentProcess {
81
+ readonly stdout: ReadableStream<Uint8Array>;
82
+ readonly exited: Promise<number>;
83
+ readonly stdin: RpcAgentProcess["stdin"];
84
+ readonly #pending = new Set<(error: Error) => void>();
85
+ #error = "";
86
+
87
+ constructor(readonly socket: net.Socket) {
88
+ // Node and Bun publish incompatible getReader overloads for the same WHATWG stream.
89
+ this.stdout = Readable.toWeb(socket) as unknown as ReadableStream<Uint8Array>;
90
+ const { promise, resolve } = Promise.withResolvers<number>();
91
+ this.exited = promise;
92
+ socket.once("close", () => {
93
+ const error = new Error(this.#error || "RPC socket disconnected; request outcome may be unknown");
94
+ for (const reject of this.#pending) reject(error);
95
+ resolve(this.#error ? 1 : 0);
96
+ });
97
+ socket.on("error", error => { this.#error = error.message; });
98
+ this.stdin = { write: data => this.#write(data) };
99
+ }
100
+
101
+ peekStderr(): string { return this.#error; }
102
+
103
+ // RpcClient.stop() is a detach operation for this transport, never a host signal.
104
+ kill(): void { this.socket.destroy(); }
105
+
106
+ #write(data: string | Uint8Array): Promise<void> {
107
+ if (this.socket.destroyed || !this.socket.writable) {
108
+ return Promise.reject(new Error("RPC socket is disconnected"));
109
+ }
110
+ 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) {
112
+ return Promise.reject(new Error("RPC socket write backlog exceeded its bound"));
113
+ }
114
+ const { promise, resolve, reject } = Promise.withResolvers<void>();
115
+ const finish = (error?: Error | null) => {
116
+ if (!this.#pending.delete(fail)) return;
117
+ clearTimeout(timer);
118
+ if (error) reject(error);
119
+ else resolve();
120
+ };
121
+ const fail = (error: Error) => finish(error);
122
+ const timer = setTimeout(() => {
123
+ const error = new Error("RPC socket write timed out; request outcome may be unknown");
124
+ finish(error);
125
+ this.socket.destroy(error);
126
+ }, CONNECT_TIMEOUT_MS);
127
+ timer.unref();
128
+ this.#pending.add(fail);
129
+ try { this.socket.write(data, finish); }
130
+ catch (error) { finish(error instanceof Error ? error : new Error(String(error))); }
131
+ return promise;
132
+ }
133
+ }
134
+
135
+ class AdapterClient extends RpcClient {
136
+ override async getState(): Promise<HostState> {
137
+ return await super.getState() as HostState;
138
+ }
139
+ }
140
+
141
+ export class HostConnection {
142
+ readonly client: AdapterClient;
143
+ readonly exited: Promise<void>;
144
+ readonly #listeners = new Set<(frame: HostFrame) => void>();
145
+ readonly #channel: HostChannel;
146
+ #close: Promise<void> | undefined;
147
+
148
+ private constructor(transport: SocketProcess) {
149
+ this.exited = transport.exited.then(() => {});
150
+ this.#channel = new HostChannel(transport.socket, transport.socket);
151
+ this.#channel.on("frame", frame => this.#emit(frame));
152
+ this.client = new AdapterClient({ spawn: () => transport });
153
+ }
154
+
155
+ static async connect(socketPath: string, timeoutMs = CONNECT_TIMEOUT_MS): Promise<HostConnection> {
156
+ const before = await socketIdentity(socketPath);
157
+ const socket = net.createConnection(socketPath);
158
+ const transport = new SocketProcess(socket);
159
+ const connection = new HostConnection(transport);
160
+ const timeout = setTimeout(() => socket.destroy(new Error("RPC socket connection/identity probe timed out")), timeoutMs);
161
+ timeout.unref();
162
+ try {
163
+ await connection.client.start();
164
+ const after = await socketIdentity(socketPath);
165
+ if (before.dev !== after.dev || before.ino !== after.ino) {
166
+ throw new Error("RPC socket identity changed while connecting");
167
+ }
168
+ const state = await connection.client.getState();
169
+ if (typeof state.sessionId !== "string" || !state.sessionId ||
170
+ typeof state.sessionFile !== "string" || !path.isAbsolute(state.sessionFile) ||
171
+ !Number.isSafeInteger(state.hostPid) || state.hostPid! < 1 ||
172
+ state.adapterProtocol !== "owned-stock-stdio-v1" || !Number.isSafeInteger(state.adapterOwnerPid)
173
+ || state.adapterOwnerPid < 1) {
174
+ throw new Error("Endpoint did not identify an owned stock-stdio adapter and persistent OMP session");
175
+ }
176
+ return connection;
177
+ } catch (error) {
178
+ await connection.close();
179
+ throw error;
180
+ } finally {
181
+ clearTimeout(timeout);
182
+ }
183
+ }
184
+
185
+ /** Private adapter correlation. Stock RpcClient deliberately has no generic request API. */
186
+ request(command: Record<string, unknown>, id?: string): Promise<HostResponse> {
187
+ if (typeof command.type !== "string" || !command.type) throw new Error("RPC command requires a type");
188
+ if (Object.hasOwn(command, "id")) throw new Error("Pass the persisted request id as the second argument");
189
+ return this.#channel.request(command, id, command.type === "compact" ? 0 : 30_000).then(response => {
190
+ if (response.type !== "response" || response.command !== command.type || typeof response.success !== "boolean"
191
+ || !response.success && typeof response.error !== "string") throw new Error("Invalid owned Host response envelope");
192
+ return response as HostResponse;
193
+ });
194
+ }
195
+
196
+ uiResponse(id: string, response: DialogResponse): void {
197
+ if (!id) throw new Error("UI response requires its original request id");
198
+ this.#channel.send({ ...response, type: "extension_ui_response", id });
199
+ }
200
+
201
+ onFrame(listener: (frame: HostFrame) => void): () => void {
202
+ this.#listeners.add(listener);
203
+ return () => { this.#listeners.delete(listener); };
204
+ }
205
+
206
+ #emit(frame: object): void {
207
+ for (const listener of this.#listeners) listener(frame as HostFrame);
208
+ }
209
+
210
+ close(): Promise<void> {
211
+ if (!this.#close) {
212
+ this.#close = this.client.stop().finally(() => {
213
+ this.#channel.removeAllListeners();
214
+ this.#listeners.clear();
215
+ });
216
+ }
217
+ return this.#close;
218
+ }
219
+ }
220
+
221
+ export function connect(socketPath: string): Promise<HostConnection> {
222
+ return HostConnection.connect(socketPath);
223
+ }
224
+
225
+ export function buildHostArgs(options: HostOptions, configPath = `${options.socketPath}.config.json`,
226
+ composition?: { extensionPaths: string[]; noExtensions: boolean }): string[] {
227
+ assertSocketPath(options.socketPath);
228
+ for (const [name, value] of Object.entries({
229
+ sessionFile: options.sessionFile, cwd: options.cwd, extensionPath: options.extensionPath,
230
+ logPath: options.logPath, configPath,
231
+ })) {
232
+ if (!value || !path.isAbsolute(value)) throw new Error(`${name} must be an explicit absolute path`);
233
+ }
234
+ if (!options.command.length || options.command.some(arg => !arg || arg.includes("\0"))) {
235
+ throw new Error("Host command must be a nonempty argv without NUL bytes");
236
+ }
237
+ if (!Number.isSafeInteger(options.subagentConcurrency) || options.subagentConcurrency < 1) {
238
+ throw new Error("subagentConcurrency must be a positive integer");
239
+ }
240
+ if (options.modelPreset && !isValidModelPresetName(options.modelPreset.name))
241
+ throw new Error("A native model preset must have a valid name");
242
+ const managedUlwPath = selectManagedUlw(options);
243
+ const extensions = composition?.extensionPaths ?? [
244
+ fileURLToPath(new URL("../", import.meta.url)), managedUlwPath, options.extensionPath,
245
+ fileURLToPath(new URL("./board-extension.ts", import.meta.url)),
246
+ fileURLToPath(new URL("./host-extension.ts", import.meta.url)),
247
+ ];
248
+ return [
249
+ "--mode", "rpc-ui",
250
+ "--session", options.sessionFile, "--cwd", options.cwd,
251
+ ...(composition?.noExtensions ? ["--no-extensions"] : []),
252
+ ...extensions.flatMap(extension => ["-e", extension]),
253
+ "--config", configPath,
254
+ ];
255
+ }
256
+
257
+ function selectManagedUlw(options: HostOptions): string {
258
+ const fixture = options.managedUlwPath ?? options.env[MANAGED_ULW_FIXTURE_ENV];
259
+ const root = options.managedUlwRoot ?? options.env[MANAGED_ULW_FIXTURE_ROOT_ENV];
260
+ return fixture ? validateManagedUlwPackage(fixture) : activeManagedUlw(root ? { root } : {});
261
+ }
262
+
263
+ /** Launch only a new host. Existing endpoints require the caller's explicit adoption decision. */
264
+ export async function startHost(options: HostOptions): Promise<{ pid: number }> {
265
+ try { return await launchHost(options); }
266
+ catch (cause) {
267
+ // Never read child output into errors: logs can contain credentials or prompt content.
268
+ throw new HostStartError(cause instanceof Error ? cause.message : "OMP host startup failed", { cause });
269
+ }
270
+ }
271
+
272
+ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
273
+ // Snapshot once before any awaits; an updater may activate a newer revision
274
+ // during startup, but this Host must load one exact immutable package.
275
+ const managedUlwPath = selectManagedUlw(options);
276
+ const fixture = options.managedUlwPath ?? options.env[MANAGED_ULW_FIXTURE_ENV];
277
+ const fixtureRoot = options.managedUlwRoot ?? options.env[MANAGED_ULW_FIXTURE_ROOT_ENV];
278
+ const bun = options.env.OMP_SUPERAGENT_BUN ?? (path.basename(process.execPath) === "bun" ? process.execPath
279
+ : Bun.which("bun", { PATH: options.env.PATH ?? process.env.PATH }));
280
+ if (!bun || !path.isAbsolute(bun)) throw new Error("Managed Host launch requires an explicit installed Bun executable");
281
+ options = { ...options, command: resolveOmpCommand(options.command, options.env.PATH ?? ""), managedUlwPath,
282
+ env: { ...options.env, [MANAGED_ULW_ENV]: managedUlwPath,
283
+ OMP_SUPERAGENT_BUN: bun,
284
+ ...(fixture ? { [MANAGED_ULW_FIXTURE_ENV]: fixture } : {}),
285
+ ...(fixtureRoot ? { [MANAGED_ULW_FIXTURE_ROOT_ENV]: fixtureRoot } : {}) } };
286
+ buildHostArgs(options);
287
+ await fs.mkdir(path.dirname(options.socketPath), { recursive: true, mode: 0o700 });
288
+ await privateDirectory(path.dirname(options.socketPath));
289
+ let existing = false;
290
+ try { await fs.lstat(options.socketPath); existing = true; }
291
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
292
+ if (existing) {
293
+ const connection = await connect(options.socketPath);
294
+ try {
295
+ const state = await connection.client.getState();
296
+ throw new Error(`RPC socket already hosts session ${state.sessionId} at ${state.sessionFile}; explicit adoption required`);
297
+ } finally { await connection.close(); }
298
+ }
299
+ const { executable, processBackend } = await inspectInstalledOmp(options.command, [], options.env);
300
+ options = { ...options, command: [executable, ...options.command.slice(1)] };
301
+
302
+ const launchDirectory = await fs.mkdtemp(path.join(path.dirname(options.socketPath), ".launch-"));
303
+ const configPath = path.join(launchDirectory, "config.json");
304
+ let child: ChildProcess | undefined;
305
+ let log: fs.FileHandle | undefined;
306
+ let failure: Error | undefined;
307
+ let cleanup: Promise<void> | undefined;
308
+ const cleanLaunch = () => cleanup ??= fs.rm(launchDirectory, { recursive: true });
309
+ try {
310
+ const initialSettings = options.modelPreset?.preset ?? options.modelSettings;
311
+ await fs.writeFile(configPath, JSON.stringify({
312
+ task: { maxConcurrency: options.subagentConcurrency },
313
+ goal: { continuationModes: [RPC_GOAL_CONTINUATION_MODE] },
314
+ ...(options.modelPreset ? { modelPresets: { [options.modelPreset.name]: options.modelPreset.preset } } : {}),
315
+ ...(initialSettings ? {
316
+ modelRoles: {
317
+ ...Object.fromEntries((options.clearedModelRoles ?? []).map(role => [role, null])),
318
+ ...initialSettings.modelRoles,
319
+ },
320
+ ...(initialSettings.defaultThinkingLevel !== undefined
321
+ ? { defaultThinkingLevel: initialSettings.defaultThinkingLevel } : {}),
322
+ } : options.model ? { modelRoles: { default: options.model } } : {}),
323
+ }), { flag: "wx", mode: 0o600 });
324
+ log = await fs.open(options.logPath, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
325
+ const stat = await log.stat();
326
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0) {
327
+ throw new Error("Host log must be a private regular file owned by this user");
328
+ }
329
+ const manifestPath = path.join(launchDirectory, "owner.json");
330
+ const extensionPaths = [fileURLToPath(new URL("../", import.meta.url)), managedUlwPath, options.extensionPath,
331
+ fileURLToPath(new URL("./board-extension.ts", import.meta.url)),
332
+ fileURLToPath(new URL("./host-extension.ts", import.meta.url))];
333
+ const composition = await managedUlwLaunchExtensions({ cwd: options.cwd, managedUlwPath,
334
+ extensionPaths, configPath, commandArgs: options.command.slice(1),
335
+ launchArgs: [...options.command.slice(1), ...buildHostArgs(options, configPath)],
336
+ env: options.env, bunCommand: [bun, "--no-env-file"] });
337
+ const { env: _inheritedEnvironment, ...launchOptions } = options;
338
+ await fs.writeFile(manifestPath, JSON.stringify({ options: launchOptions, args: buildHostArgs(options, configPath, composition), configPath, processBackend,
339
+ nativeSocket: path.join(path.dirname(options.socketPath), `.n-${crypto.randomUUID().slice(0, 8)}.sock`) }),
340
+ { flag: "wx", mode: 0o600 });
341
+ child = spawn(bun, ["--no-env-file", fileURLToPath(new URL("./host-owner.ts", import.meta.url)), manifestPath], {
342
+ cwd: options.cwd, env: options.env,
343
+ detached: true, stdio: ["ignore", log.fd, log.fd], shell: false,
344
+ });
345
+ child.once("error", error => { failure = error; });
346
+ child.once("exit", (code, signal) => {
347
+ failure = new Error(`OMP host exited during startup (${signal ?? code}); see ${options.logPath}`);
348
+ void cleanLaunch().catch(() => {});
349
+ });
350
+ child.unref();
351
+ await log.close();
352
+ log = undefined;
353
+ const deadline = Date.now() + START_TIMEOUT_MS;
354
+ let startingSocket: Stats | undefined;
355
+ while (Date.now() < deadline) {
356
+ if (failure) throw failure;
357
+ let observed: Stats;
358
+ try {
359
+ observed = await fs.lstat(options.socketPath);
360
+ } catch (error) {
361
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
362
+ if (startingSocket) throw new Error("Launched RPC socket disappeared during startup");
363
+ await Bun.sleep(50);
364
+ continue;
365
+ }
366
+ if (!observed.isSocket() || observed.uid !== process.getuid?.()) {
367
+ throw new Error("Launched RPC endpoint is not a socket owned by this user");
368
+ }
369
+ if (startingSocket && (startingSocket.dev !== observed.dev || startingSocket.ino !== observed.ino)) {
370
+ throw new Error("Launched RPC socket identity changed during startup");
371
+ }
372
+ startingSocket ??= observed;
373
+ // Native bind creates the inode before its asynchronous chmod completes.
374
+ // Only this new, unchanged owned socket gets a bounded readiness wait;
375
+ // never connect to a permissive endpoint or relax ordinary connect checks.
376
+ if ((observed.mode & 0o777) !== 0o600) {
377
+ await Bun.sleep(50);
378
+ continue;
379
+ }
380
+ const connection = await HostConnection.connect(options.socketPath, Math.max(1, deadline - Date.now()));
381
+ try {
382
+ const connectedSocket = await socketIdentity(options.socketPath);
383
+ if (connectedSocket.dev !== startingSocket.dev || connectedSocket.ino !== startingSocket.ino) {
384
+ throw new Error("Launched RPC socket identity changed while connecting");
385
+ }
386
+ const response = await connection.request({ type: "get_state" });
387
+ if (!response.success || response.command !== "get_state") {
388
+ throw new Error("Launched RPC host did not confirm its session identity");
389
+ }
390
+ const state = response.data as HostState;
391
+ if (state.adapterOwnerPid !== child.pid) throw new Error("Endpoint does not belong to the launched pipe owner");
392
+ if (path.resolve(state.sessionFile!) !== path.resolve(options.sessionFile)) {
393
+ throw new Error("Launched RPC host identified a different session file");
394
+ }
395
+ if (failure) throw failure;
396
+ if (!Number.isSafeInteger(state.hostPid) || state.hostPid < 1) throw new Error("OMP host did not receive a process id");
397
+ return { pid: state.hostPid };
398
+ } finally { await connection.close(); }
399
+ }
400
+ throw new Error(`OMP host startup timed out; see ${options.logPath}`);
401
+ } catch (error) {
402
+ if (child?.pid && child.exitCode === null && child.signalCode === null) {
403
+ child.kill("SIGTERM");
404
+ const force = setTimeout(() => {
405
+ if (child?.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
406
+ }, 1_000);
407
+ force.unref();
408
+ }
409
+ // Never unlink the socket: it may still belong to an active or racing host.
410
+ if (!child?.pid || child.exitCode !== null || child.signalCode !== null) {
411
+ await cleanLaunch();
412
+ }
413
+ throw error;
414
+ } finally { await log?.close(); }
415
+ }
@@ -0,0 +1,71 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
6
+
7
+ /** Resolve outside dependency shims, including PATH injected by bun run/install. */
8
+ export function discoverInstalledOmp(path = process.env.PATH ?? ""): string {
9
+ for (const directory of path.split(delimiter)) {
10
+ if (!directory || /(?:^|[/\\])node_modules(?:[/\\]|$)/.test(directory)) continue;
11
+ const candidate = Bun.which("omp", { PATH: directory });
12
+ if (!candidate) continue;
13
+ const executable = realpathSync(candidate);
14
+ if (executable.startsWith(join(root, "node_modules") + "/")) continue;
15
+ return executable;
16
+ }
17
+ throw new Error("An installed stock OMP is required on PATH, or configure its executable directly");
18
+ }
19
+
20
+ /** Resolve path-like executables before any change to the launch working directory. */
21
+ export function resolveOmpCommand(command: string[], path = process.env.PATH ?? "", cwd = process.cwd()): string[] {
22
+ const [entry, ...args] = command;
23
+ if (!entry) throw new Error("Configure an installed OMP executable");
24
+ const executable = entry === "omp" ? discoverInstalledOmp(path) : entry.includes("/") ? resolve(cwd, entry) : entry;
25
+ if ([executable, ...args].some(arg => isAbsolute(arg) && resolve(arg).startsWith(join(root, "node_modules") + "/")))
26
+ throw new Error("Configure a separately installed OMP executable, not this project's SDK dependency");
27
+ return [executable, ...args];
28
+ }
29
+
30
+ /** Inspect CLI metadata only; never open an agent or provider session. */
31
+ export async function inspectInstalledOmp(
32
+ command: string[], credentials: string[] = [], environment: NodeJS.ProcessEnv = process.env,
33
+ ) {
34
+ const path = environment.PATH ?? "";
35
+ const [entry] = resolveOmpCommand(command, path);
36
+ const executable = entry && (isAbsolute(entry) ? entry : Bun.which(entry, { PATH: path }));
37
+ if (!executable) throw new Error(`Cannot find the configured OMP executable ${entry ?? ""} on PATH`);
38
+ const env = { ...environment };
39
+ for (const name of credentials) delete env[name];
40
+ const probe = async (...args: string[]) => {
41
+ // Require the CLI itself, not a runtime/script wrapper with an ambiguous
42
+ // native argv boundary. Metadata inspection never loads launch extensions.
43
+ const child = Bun.spawn([executable, ...args], {
44
+ // Unlike --version, root help loads the CLI's bundled native addon.
45
+ // Its first extraction and load on macOS can take more than ten seconds.
46
+ env, stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: args[0] === "--version" ? 10_000 : 30_000,
47
+ });
48
+ const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
49
+ if (code !== 0) throw new Error(`OMP executable ${executable}: ${args.join(" ")} failed (${code}); diagnostic output suppressed to protect credentials`);
50
+ return stdout;
51
+ };
52
+ const version = (await probe("--version")).trim().match(/^omp\/(\S+)$/)?.[1];
53
+ if (!version)
54
+ throw new Error(`${executable} did not identify as OMP; configure its executable directly, not a runtime/script wrapper`);
55
+ const help = await probe("--help");
56
+ const flags = ["--mode", "--resume", "--extension", "--model"];
57
+ if (!flags.every(flag => new RegExp(`${flag}(?=[\\s,=])`).test(help)) || !/(?<![\w-])rpc-ui(?![\w-])/.test(help))
58
+ throw new Error(`OMP ${version} at ${executable} must support public stdio RPC (rpc-ui), session resume, extensions, and model selection`);
59
+ // Match the selected executable's process interface, not the package SDK or
60
+ // a failed/empty daemon observation. Both CLIs advertise these on ps only.
61
+ const processes = await probe("ps", "--help");
62
+ const broker = /--global(?=[\s,=])/.test(processes);
63
+ const daemon = /--signal(?=[\s,=])/.test(processes);
64
+ if (broker === daemon)
65
+ throw new Error(`OMP ${version} at ${executable} has an unrecognized process ownership interface (ps --help)`);
66
+ const processBackend = broker ? "broker" as const : "daemon" as const;
67
+ return {
68
+ executable, version, processBackend,
69
+ stdioRpc: true, sessions: true, extensions: true, modelSelection: true,
70
+ };
71
+ }
@@ -0,0 +1,184 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
5
+ import { type Static, Type } from "@sinclair/typebox";
6
+ import { type LaneEvidence, type LaneReportEvent, type LaneWaitTarget, parseLaneReportResult } from "./lane-report";
7
+ import { registerDecisionAsk } from "./decision-tool";
8
+
9
+ const instructions = readFileSync(new URL("../skills/lane/SKILL.md", import.meta.url), "utf8");
10
+ const nonempty = Type.String({ minLength: 1, pattern: "\\S" });
11
+ const evidenceReference = Type.Union([
12
+ Type.Object({ kind: Type.Literal("file"), path: nonempty }, { additionalProperties: false }),
13
+ Type.Object({ kind: Type.Literal("tool"), toolCallId: nonempty }, { additionalProperties: false }),
14
+ ]);
15
+ const evidence = Type.Array(evidenceReference, { maxItems: 32 });
16
+ const requiredEvidence = Type.Array(evidenceReference, { minItems: 1, maxItems: 32 });
17
+ const waiting = Type.Union([
18
+ Type.Object({ kind: Type.Union([Type.Literal("tool"), Type.Literal("approval"), Type.Literal("job")]),
19
+ id: nonempty, target: nonempty }, { additionalProperties: false }),
20
+ Type.Object({ kind: Type.Literal("dependency"), target: nonempty }, { additionalProperties: false }),
21
+ ]);
22
+ const summary = Type.String({ minLength: 1, maxLength: 4000, pattern: "\\S" });
23
+ const parameters = Type.Union([
24
+ Type.Object({ status: Type.Literal("progress"), summary, evidence: requiredEvidence },
25
+ { additionalProperties: false }),
26
+ Type.Object({ status: Type.Literal("waiting"), summary, waiting, evidence: Type.Optional(evidence) },
27
+ { additionalProperties: false }),
28
+ Type.Object({ status: Type.Literal("resolved"), summary, waiting, evidence: requiredEvidence },
29
+ { additionalProperties: false }),
30
+ ]);
31
+ const coordinationTool = (name: string) => name === "lane_report" || name.startsWith("board_");
32
+ const record = (value: unknown): value is Record<string, unknown> =>
33
+ value !== null && typeof value === "object" && !Array.isArray(value);
34
+ const text = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
35
+ const keys = (value: Record<string, unknown>, names: string[]) =>
36
+ Object.keys(value).every(key => names.includes(key));
37
+
38
+ // Direct native/custom-tool dispatch can bypass model argument validation.
39
+ function validInput(input: unknown): input is Static<typeof parameters> {
40
+ if (!record(input) || !keys(input, ["status", "summary", "waiting", "evidence"]) ||
41
+ !text(input.summary) || input.summary.length > 4000 ||
42
+ !["progress", "waiting", "resolved"].includes(input.status as string)) return false;
43
+ if (input.evidence !== undefined && (!Array.isArray(input.evidence) || input.evidence.length > 32 ||
44
+ input.evidence.some(item => !record(item) || (item.kind === "file"
45
+ ? !keys(item, ["kind", "path"]) || !text(item.path)
46
+ : item.kind !== "tool" || !keys(item, ["kind", "toolCallId"]) || !text(item.toolCallId))))) return false;
47
+ if (input.status !== "waiting" && (!Array.isArray(input.evidence) || input.evidence.length === 0)) return false;
48
+ if (input.status === "progress") return !Object.hasOwn(input, "waiting");
49
+ const target = input.waiting;
50
+ return record(target) && text(target.target) && (target.kind === "dependency"
51
+ ? keys(target, ["kind", "target"])
52
+ : ["tool", "approval", "job"].includes(target.kind as string) &&
53
+ keys(target, ["kind", "id", "target"]) && text(target.id));
54
+ }
55
+
56
+ function fileEvidence(path: string, cwd: string): LaneEvidence {
57
+ const source = resolve(cwd, path);
58
+ const ref = realpathSync(source);
59
+ // Nonblocking prevents a raced FIFO from hanging; no-follow pins the canonical file.
60
+ const fd = openSync(ref, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
61
+ try {
62
+ const before = fstatSync(fd, { bigint: true });
63
+ if (!before.isFile()) throw new Error("Lane file evidence must be a regular file");
64
+ const bytes = readFileSync(fd);
65
+ const after = fstatSync(fd, { bigint: true });
66
+ const current = lstatSync(ref, { bigint: true });
67
+ if (!current.isFile() || realpathSync(source) !== ref || BigInt(bytes.length) !== before.size ||
68
+ [after, current].some(stat => stat.dev !== before.dev || stat.ino !== before.ino ||
69
+ stat.size !== before.size || stat.mtimeNs !== before.mtimeNs || stat.ctimeNs !== before.ctimeNs)) {
70
+ throw new Error("Lane file evidence changed while being read");
71
+ }
72
+ return { kind: "file", ref, fingerprint: createHash("sha256").update(bytes).digest("hex") };
73
+ } finally {
74
+ closeSync(fd);
75
+ }
76
+ }
77
+
78
+ function toolRecords(ctx: ExtensionContext, id: string) {
79
+ const branch = ctx.sessionManager.getBranch();
80
+ const call = branch.flatMap(entry => entry.type === "message" && entry.message.role === "assistant"
81
+ ? entry.message.content.filter(block => block.type === "toolCall" && block.id === id) : [])
82
+ .find(block => block.type === "toolCall");
83
+ const result = branch.findLast(entry => entry.type === "message" && entry.message.role === "toolResult" &&
84
+ entry.message.toolCallId === id);
85
+ return { call, result: result?.type === "message" && result.message.role === "toolResult" ? result.message : undefined };
86
+ }
87
+
88
+ function toolEvidence(id: string, ctx: ExtensionContext): LaneEvidence {
89
+ const { call, result } = toolRecords(ctx, id);
90
+ if (!call || !result || result.toolName !== call.name || result.isError !== false ||
91
+ coordinationTool(call.name) || (typeof call.arguments.path === "string" &&
92
+ /^xd:\/\/(?:lane_report|board_[a-z_]+)(?:[/?#]|$)/.test(call.arguments.path)) ||
93
+ parseLaneReportResult(result)) {
94
+ throw new Error("Lane tool evidence requires a completed successful native tool call, not report/board chatter");
95
+ }
96
+ // Native identity/time envelopes are not evidence of changed work.
97
+ const record = { toolName: result.toolName, content: result.content, details: result.details, isError: result.isError };
98
+ return { kind: "tool", ref: id, fingerprint: createHash("sha256").update(JSON.stringify(record)).digest("hex") };
99
+ }
100
+
101
+ /** A worker role entrypoint, never the head's manager or messenger client. */
102
+ export default function laneExtension(pi: ExtensionAPI): void {
103
+ if (process.env.OMP_SUPERAGENT_ROLE !== "lane") return;
104
+ registerDecisionAsk(pi);
105
+ let approvalSessionId: string | undefined;
106
+ const pendingApprovals = new Set<string>();
107
+ const approvals = (ctx: ExtensionContext) => {
108
+ const sessionId = ctx.sessionManager.getSessionId();
109
+ if (approvalSessionId !== sessionId) {
110
+ pendingApprovals.clear();
111
+ approvalSessionId = sessionId;
112
+ }
113
+ return pendingApprovals;
114
+ };
115
+ pi.on("session_start", async (_event, ctx) => {
116
+ approvals(ctx);
117
+ if (ctx.agent.kind !== "main") {
118
+ // Subtract only our tool; never re-enable an operator-excluded native tool.
119
+ const active = pi.getActiveTools();
120
+ if (active.includes("lane_report")) await pi.setActiveTools(active.filter(name => name !== "lane_report"));
121
+ }
122
+ });
123
+ pi.on("tool_call", (event, ctx) => {
124
+ if (event.toolName === "lane_report" && ctx.agent.kind !== "main") {
125
+ return { block: true, reason: "Lane reporting is restricted to the root lane session" };
126
+ }
127
+ if (ctx.agent.kind === "main" && (event.toolName === "ask" || event.toolName === "write" && event.input.path === "xd://ask")) {
128
+ return { block: true, reason: "Use decision_ask so HEAD can review the lane's choices before the owner is interrupted. Native execution approvals are unchanged." };
129
+ }
130
+ });
131
+ pi.on("tool_approval_requested", (event, ctx) => {
132
+ if (ctx.agent.kind === "main" && event.sessionId === ctx.sessionManager.getSessionId()) {
133
+ approvals(ctx).add(event.toolCallId);
134
+ }
135
+ });
136
+ pi.on("tool_approval_resolved", (event, ctx) => {
137
+ if (event.sessionId === ctx.sessionManager.getSessionId()) approvals(ctx).delete(event.toolCallId);
138
+ });
139
+ pi.on("session_shutdown", () => { pendingApprovals.clear(); });
140
+ pi.on("before_agent_start", async (event, ctx) => {
141
+ if (ctx.agent.kind !== "main") return;
142
+ return { systemPrompt: [
143
+ ...event.systemPrompt,
144
+ instructions,
145
+ `Lane identity: ${process.env.OMP_SUPERAGENT_LANE}. Workspace: ${ctx.cwd}.`,
146
+ ] };
147
+ });
148
+ pi.registerTool({
149
+ name: "lane_report", label: "Report lane observations", approval: "read", loadMode: "essential",
150
+ description: "Record an evidence-backed progress, waiting, or resolved observation in this lane's native tool journal. " +
151
+ "Progress/resolved require selected real file paths or completed successful native toolCallIds; hashes are computed here. " +
152
+ "Waiting/resolved name the exact tool/approval/job ID or a dependency label. Native tool/approval/job waiting IDs must be observable now. " +
153
+ "Reports do not send messages, prove acceptance, dispatch, resume, or change execution authority. Board/report chatter is not evidence.",
154
+ parameters,
155
+ async execute(id, params, _signal, _onUpdate, ctx) {
156
+ if (ctx.agent.kind !== "main") throw new Error("Lane reporting is restricted to the root lane session");
157
+ if (!validInput(params)) throw new Error("Invalid lane report parameters");
158
+ if (params.status === "waiting") {
159
+ const target: LaneWaitTarget = params.waiting;
160
+ if (target.kind === "tool") {
161
+ const { call, result } = toolRecords(ctx, target.id);
162
+ if (!call || result || target.id === id || call.name === "lane_report") {
163
+ throw new Error("Lane tool wait requires an actual pending native tool call");
164
+ }
165
+ } else if (target.kind === "approval" && !approvals(ctx).has(target.id)) {
166
+ throw new Error("Lane approval wait requires an observed pending native tool approval");
167
+ } else if (target.kind === "job" && !ctx.getAsyncJobSnapshot()?.running.some(job => job.id === target.id)) {
168
+ throw new Error("Lane job wait requires a running native session job");
169
+ }
170
+ }
171
+ const selected = (params.evidence ?? []).map(item => item.kind === "file"
172
+ ? fileEvidence(item.path, ctx.cwd) : toolEvidence(item.toolCallId, ctx));
173
+ const event: LaneReportEvent = {
174
+ type: "superagent-lane-report", sessionId: ctx.sessionManager.getSessionId(), reportId: id,
175
+ report: { status: params.status, summary: params.summary, evidence: selected,
176
+ ...(params.status === "progress" ? {} : { waiting: params.waiting }) },
177
+ };
178
+ // Eval bridges return nested details to the kernel, not a toolResult
179
+ // message. The same native journal event survives that path and replay.
180
+ pi.appendEntry("superagent-lane-report", event);
181
+ return { content: [{ type: "text", text: `Recorded lane ${params.status} observation in the native tool result.` }], details: event };
182
+ },
183
+ });
184
+ }