omp-superagent 0.1.7 → 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 (52) hide show
  1. package/DESIGN.md +21 -14
  2. package/README.ko.md +33 -15
  3. package/README.md +35 -14
  4. package/THIRD_PARTY_NOTICES.md +3 -3
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +232 -74
  7. package/docs/design/execution.md +54 -10
  8. package/docs/design/messaging.md +177 -43
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  13. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  17. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  19. package/package.json +8 -8
  20. package/scripts/ci.ts +3 -3
  21. package/scripts/test-omp.sh +2 -1
  22. package/src/cli.ts +3 -0
  23. package/src/config.ts +5 -0
  24. package/src/contracts.ts +26 -5
  25. package/src/cron-jobs.ts +443 -19
  26. package/src/cron-pr-intake.ts +257 -0
  27. package/src/discord-markdown.ts +350 -123
  28. package/src/extension.ts +9 -1
  29. package/src/head-quota.ts +80 -0
  30. package/src/head-recovery.ts +40 -1
  31. package/src/host-extension.ts +120 -4
  32. package/src/host-protocol.ts +11 -0
  33. package/src/host-sdk-helper.ts +105 -10
  34. package/src/host.ts +111 -29
  35. package/src/installed-omp.ts +116 -4
  36. package/src/managed-ulw.ts +137 -24
  37. package/src/messenger-command-catalog.json +1 -1
  38. package/src/native-presets.ts +32 -5
  39. package/src/omp-usage.ts +254 -36
  40. package/src/pr-github.ts +4 -2
  41. package/src/pr-intake-automation.ts +316 -0
  42. package/src/pr-intake-comment.ts +226 -0
  43. package/src/pr-intake-fix.ts +233 -0
  44. package/src/pr-intake-github.ts +480 -0
  45. package/src/pr-intake-material.ts +230 -0
  46. package/src/pr-intake-mode.ts +59 -0
  47. package/src/pr-intake-review.ts +397 -0
  48. package/src/pr-intake-tree.ts +69 -0
  49. package/src/pr-intake-work.ts +29 -0
  50. package/src/runtime.ts +1504 -192
  51. package/src/store.ts +249 -49
  52. package/src/topic-history.ts +30 -17
package/src/host.ts CHANGED
@@ -10,20 +10,42 @@ import {
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
17
  import type { WorkerHostProfile } from "./worker-profile";
18
- import { activeManagedUlw, managedUlwLaunchExtensions, MANAGED_ULW_ENV, MANAGED_ULW_FIXTURE_ENV, MANAGED_ULW_FIXTURE_ROOT_ENV, validateManagedUlwPackage } from "./managed-ulw";
18
+ import { activeManagedUlw, managedUlwLaunch, MANAGED_ULW_ENV, MANAGED_ULW_FIXTURE_ENV, MANAGED_ULW_FIXTURE_ROOT_ENV, validateManagedUlwPackage } from "./managed-ulw";
19
19
 
20
20
  const CONNECT_TIMEOUT_MS = 5_000;
21
21
  const START_TIMEOUT_MS = 30_000;
22
22
  const MAX_PENDING_BYTES = 16 * 1024 * 1024;
23
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
+ };
24
44
 
25
45
  export interface HostOptions {
26
46
  command: string[];
47
+ /** Local managed static review lane; cwd must be a private empty non-checkout. */
48
+ readonly prReviewOnly?: true;
27
49
  /** Target-owned launch policy, never decoded from an SSH request. */
28
50
  readonly worker?: WorkerHostProfile;
29
51
  socketPath: string;
@@ -176,7 +198,8 @@ export class HostConnection {
176
198
  const timeout = setTimeout(disconnect, CONNECT_TIMEOUT_MS);
177
199
  try {
178
200
  const state = await connection.#handshake();
179
- if (state.hostPid !== expected.pid || state.sessionId !== expected.sessionId || state.sessionFile !== expected.sessionFile) {
201
+ if (state.prReviewPolicy !== undefined || state.hostPid !== expected.pid || state.sessionId !== expected.sessionId ||
202
+ state.sessionFile !== expected.sessionFile) {
180
203
  throw new Error("Remote Host identity differs from its worker registration");
181
204
  }
182
205
  await connection.#enableActivityUpdates(state);
@@ -229,7 +252,8 @@ export class HostConnection {
229
252
  }
230
253
 
231
254
  async #enableActivityUpdates(state: HostState): Promise<void> {
232
- if (typeof state.loadedSuperkitPath !== "string" || !path.isAbsolute(state.loadedSuperkitPath))
255
+ if (state.prReviewPolicy?.version !== 1 &&
256
+ (typeof state.loadedSuperkitPath !== "string" || !path.isAbsolute(state.loadedSuperkitPath)))
233
257
  throw new Error("Native Host has not verified its omp-superkit extension; stop and start the Host");
234
258
  const capability = await this.request({ type: "get_host_admission", messageUpdateCapability: true });
235
259
  if (!capability.success || capability.command !== "get_host_admission") {
@@ -244,6 +268,12 @@ export class HostConnection {
244
268
  }
245
269
  }
246
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
+
247
277
  /** Private adapter correlation. Stock RpcClient deliberately has no generic request API. */
248
278
  request(command: Record<string, unknown>, id?: string): Promise<HostResponse> {
249
279
  if (typeof command.type !== "string" || !command.type) throw new Error("RPC command requires a type");
@@ -284,6 +314,23 @@ export function connect(socketPath: string): Promise<HostConnection> {
284
314
  return HostConnection.connect(socketPath);
285
315
  }
286
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
+
287
334
  export async function buildHostArgs(options: HostOptions, configPath = `${options.socketPath}.config.json`,
288
335
  composition?: { extensionPaths: string[]; noExtensions: boolean }): Promise<string[]> {
289
336
  assertSocketPath(options.socketPath);
@@ -299,6 +346,14 @@ export async function buildHostArgs(options: HostOptions, configPath = `${option
299
346
  if (!Number.isSafeInteger(options.subagentConcurrency) || options.subagentConcurrency < 1) {
300
347
  throw new Error("subagentConcurrency must be a positive integer");
301
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
+ }
302
357
  if (options.modelPreset) {
303
358
  // Only named lane presets need the SDK's model resolver. HEAD launches
304
359
  // (including restored model settings) must not load it just to build argv.
@@ -341,7 +396,30 @@ export async function startHost(options: HostOptions, beforeSessionPrepare?: ()
341
396
  async function launchHost(options: HostOptions, beforeSessionPrepare?: () => void): Promise<{ pid: number }> {
342
397
  // Snapshot once before any awaits; an updater may activate a newer revision
343
398
  // during startup, but this Host must load one exact immutable package.
344
- 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);
345
423
  const fixture = options.managedUlwPath ?? options.env[MANAGED_ULW_FIXTURE_ENV];
346
424
  const hostOwnerExecutable = await requireHostOwner();
347
425
  const fixtureRoot = options.managedUlwRoot ?? options.env[MANAGED_ULW_FIXTURE_ROOT_ENV];
@@ -349,7 +427,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
349
427
  : Bun.which("bun", { PATH: options.env.PATH ?? process.env.PATH }));
350
428
  if (!bun || !path.isAbsolute(bun)) throw new Error("Managed Host launch requires an explicit installed Bun executable");
351
429
  options = { ...options, command: resolveOmpCommand(options.command, options.env.PATH ?? ""), managedUlwPath,
352
- env: { ...options.env, [MANAGED_ULW_ENV]: managedUlwPath,
430
+ env: { ...options.env, ...(managedUlwPath ? { [MANAGED_ULW_ENV]: managedUlwPath } : {}),
353
431
  OMP_SUPERAGENT_BUN: bun,
354
432
  ...(fixture ? { [MANAGED_ULW_FIXTURE_ENV]: fixture } : {}),
355
433
  ...(fixtureRoot ? { [MANAGED_ULW_FIXTURE_ROOT_ENV]: fixtureRoot } : {}) } };
@@ -382,6 +460,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
382
460
  ...options.worker?.config,
383
461
  task: { maxConcurrency: options.subagentConcurrency },
384
462
  goal: { continuationModes: [RPC_GOAL_CONTINUATION_MODE] },
463
+ ...(options.prReviewOnly ? prReviewSettings : {}),
385
464
  ...(options.modelPreset ? { modelPresets: { [options.modelPreset.name]: options.modelPreset.preset } } : {}),
386
465
  ...(initialSettings ? {
387
466
  modelRoles: {
@@ -398,36 +477,38 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
398
477
  throw new Error("Host log must be a private regular file owned by this user");
399
478
  }
400
479
  const manifestPath = path.join(launchDirectory, "owner.json");
401
- const extensionPaths = [fileURLToPath(new URL("../", import.meta.url)), managedUlwPath, options.extensionPath,
402
- fileURLToPath(new URL("./board-extension.ts", import.meta.url)),
480
+ const { env: _inheritedEnvironment, worker: _workerProfile, ...launchOptions } = options;
481
+ const helperPath = fileURLToPath(new URL("./host-sdk-helper.ts", import.meta.url));
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)),
403
485
  fileURLToPath(new URL("./host-extension.ts", import.meta.url))];
404
- const composition = await managedUlwLaunchExtensions({ cwd: options.cwd, managedUlwPath,
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,
405
490
  extensionPaths, configPath, parentConfigPath: process.env.OMP_SUPERAGENT_HOST_CONFIG, commandArgs: options.command.slice(1),
406
491
  ...(options.worker ? { worker: { extensionPaths: options.worker.extensionPaths } } : {}),
407
- launchArgs: [...options.command.slice(1), ...await buildHostArgs(options, configPath)],
408
- env: options.env, bunCommand: [bun, "--no-env-file"] });
409
- const { env: _inheritedEnvironment, worker: _workerProfile, ...launchOptions } = options;
410
- const helperPath = fileURLToPath(new URL("./host-sdk-helper.ts", import.meta.url));
411
- const manifest = { options: launchOptions, args: await buildHostArgs(options, configPath, composition), configPath, memoryWriteDir: composition.memoryWriteDir,
412
- processBackend, helperPath, nativeSocket: path.join(path.dirname(options.socketPath), `.n-${crypto.randomUUID().slice(0, 8)}.sock`) };
413
- // Preparation used to run inside the owner; it shares the same startup budget.
414
- const deadline = Date.now() + START_TIMEOUT_MS;
415
- // The SDK helper is the first operation that can create or publish this
416
- // session. A worker must persist its launch fence before spawning it.
417
- beforeSessionPrepare?.();
418
- const prepare = Bun.spawn([bun, "--no-env-file", helperPath, "prepare"], {
419
- cwd: options.worker ? launchDirectory : options.cwd, env: options.env, stdin: new Blob([JSON.stringify(manifest)]), stdout: "pipe", stderr: log.fd,
420
- timeout: START_TIMEOUT_MS, killSignal: "SIGKILL",
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
+ },
421
501
  });
422
- const [prepared, code] = await Promise.all([new Response(prepare.stdout).text(), prepare.exited]);
423
- if (Date.now() >= deadline) throw new Error("Native session preparation timed out");
424
- 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");
425
504
  const flags = JSON.parse(prepared);
426
505
  if (typeof flags?.toolsExplicitlySelected !== "boolean" || typeof flags.noTools !== "boolean")
427
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");
428
509
  await fs.writeFile(manifestPath, JSON.stringify({ ...manifest, toolsExplicitlySelected: flags.toolsExplicitlySelected,
429
510
  noTools: flags.noTools, inventory: flags.inventory }), { flag: "wx", mode: 0o600 });
430
- 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");
431
512
  child = spawn(hostOwnerExecutable, [manifestPath], {
432
513
  cwd: options.cwd, env: options.env,
433
514
  detached: true, stdio: ["ignore", log.fd, log.fd], shell: false,
@@ -441,7 +522,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
441
522
  await log.close();
442
523
  log = undefined;
443
524
  let startingSocket: Stats | undefined;
444
- while (Date.now() < deadline) {
525
+ while (performance.now() < deadline) {
445
526
  if (failure) throw failure;
446
527
  let observed: Stats;
447
528
  try {
@@ -466,7 +547,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
466
547
  await Bun.sleep(50);
467
548
  continue;
468
549
  }
469
- 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()));
470
551
  try {
471
552
  if (identity.dev !== startingSocket.dev || identity.ino !== startingSocket.ino) {
472
553
  throw new Error("Launched RPC socket identity changed while connecting");
@@ -475,6 +556,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
475
556
  if (path.resolve(identity.sessionFile) !== path.resolve(options.sessionFile)) {
476
557
  throw new Error("Launched RPC host identified a different session file");
477
558
  }
559
+ if (options.prReviewOnly) await assertPrReviewState(state, options.cwd);
478
560
  if (failure) throw failure;
479
561
  return { pid: identity.pid };
480
562
  } finally { await connection.close(); }
@@ -1,5 +1,5 @@
1
- import { realpathSync } from "node:fs";
2
- import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
1
+ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync, statSync } from "node:fs";
2
+ import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
5
  const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@@ -27,14 +27,126 @@ export function resolveOmpCommand(command: string[], path = process.env.PATH ??
27
27
  return [executable, ...args];
28
28
  }
29
29
 
30
- /** Inspect CLI metadata only; never open an agent or provider session. */
30
+ type InstalledOmp = Awaited<ReturnType<typeof probeInstalledOmp>>;
31
+ const inspected = new Map<string, { identity: string; result: Promise<InstalledOmp> }>();
32
+ const EXECUTION_ENV_KEYS = [
33
+ "PATH",
34
+ "LD_LIBRARY_PATH",
35
+ "LD_PRELOAD",
36
+ "DYLD_LIBRARY_PATH",
37
+ "DYLD_FALLBACK_LIBRARY_PATH",
38
+ "DYLD_INSERT_LIBRARIES",
39
+ ] as const;
40
+
41
+ function fileIdentity(filePath: string): [string, ...string[]] {
42
+ const target = realpathSync(filePath);
43
+ const { dev, ino, size, mtimeNs, ctimeNs } = statSync(target, { bigint: true });
44
+ return [target, dev.toString(), ino.toString(), size.toString(), mtimeNs.toString(), ctimeNs.toString()];
45
+ }
46
+
47
+ function readShebangTokens(filePath: string): string[] | null {
48
+ const fd = openSync(filePath, constants.O_RDONLY | constants.O_NONBLOCK);
49
+ try {
50
+ if (!fstatSync(fd).isFile()) throw new Error("OMP executable must be a regular file");
51
+ const buffer = Buffer.allocUnsafe(256);
52
+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);
53
+ if (bytes < 2 || buffer[0] !== 0x23 || buffer[1] !== 0x21) return null;
54
+ const line = buffer.subarray(2, bytes).toString("utf8");
55
+ const newline = line.indexOf("\n");
56
+ if (newline < 0 && bytes === buffer.length) return [];
57
+ const trimmed = (newline >= 0 ? line.slice(0, newline) : line).replace(/\r$/, "").trim();
58
+ return trimmed ? trimmed.split(/[ \t]+/) : [];
59
+ } finally {
60
+ closeSync(fd);
61
+ }
62
+ }
63
+
64
+ function resolveEnvCommand(tokens: readonly string[], path: string): string | null {
65
+ // Only cache forms whose interpreter search uses the provided PATH
66
+ // unchanged. env options, assignments, quoting and substitutions can
67
+ // change the interpreter; use the uncached real probe for those forms.
68
+ const target = tokens[1] === "-S" ? tokens[2] : tokens.length === 2 ? tokens[1] : undefined;
69
+ if (!target || target.startsWith("-") || !/^[\w./+-]+$/.test(target)) return null;
70
+ if (isAbsolute(target) || target.includes("/")) return resolve(target);
71
+ return Bun.which(target, { PATH: path });
72
+ }
73
+
74
+ /**
75
+ * The kernel-executed file plus its shebang interpreter and loader environment:
76
+ * replacing, rewriting or retargeting the binary/script, or changing PATH/LD_*
77
+ * changes this identity. Returns null when a required shebang target is missing.
78
+ */
79
+ function executionIdentity(
80
+ executable: string, path: string, credentials: readonly string[], environment: NodeJS.ProcessEnv,
81
+ ): string | null {
82
+ const files: [string, ...string[]][] = [];
83
+ const seen = new Set<string>();
84
+ let current: string | null = executable;
85
+ for (let depth = 0; current; depth++) {
86
+ if (depth === 4) return null;
87
+ const id = fileIdentity(current);
88
+ if (seen.has(id[0])) return null;
89
+ seen.add(id[0]);
90
+ files.push(id);
91
+ const tokens = readShebangTokens(id[0]);
92
+ if (!tokens) break;
93
+ const interpreter = tokens[0];
94
+ if (!interpreter) return null;
95
+ const resolvedInterp = isAbsolute(interpreter) || interpreter.includes("/")
96
+ ? resolve(interpreter)
97
+ : Bun.which(interpreter, { PATH: path });
98
+ if (!resolvedInterp) return null;
99
+ if (basename(interpreter) === "env") {
100
+ files.push(fileIdentity(resolvedInterp));
101
+ const target = resolveEnvCommand(tokens, path);
102
+ if (!target) return null;
103
+ current = target;
104
+ continue;
105
+ }
106
+ current = resolvedInterp;
107
+ }
108
+ const env = EXECUTION_ENV_KEYS.map(name => credentials.includes(name) ? null : environment[name] ?? null);
109
+ return JSON.stringify({ files, env });
110
+ }
111
+
112
+ /**
113
+ * Inspect CLI metadata only; never open an agent or provider session.
114
+ * Results are reused in this process while the configured executable's file
115
+ * identity, shebang interpreter, and execution environment are unchanged, so
116
+ * repeated Host starts do not respawn the probes.
117
+ */
31
118
  export async function inspectInstalledOmp(
32
119
  command: string[], credentials: string[] = [], environment: NodeJS.ProcessEnv = process.env,
33
- ) {
120
+ ): Promise<InstalledOmp> {
34
121
  const path = environment.PATH ?? "";
35
122
  const [entry] = resolveOmpCommand(command, path);
36
123
  const executable = entry && (isAbsolute(entry) ? entry : Bun.which(entry, { PATH: path }));
37
124
  if (!executable) throw new Error(`Cannot find the configured OMP executable ${entry ?? ""} on PATH`);
125
+ let identity: string | null;
126
+ try { identity = executionIdentity(executable, path, credentials, environment); }
127
+ catch { return probeInstalledOmp(executable, credentials, environment); }
128
+ if (identity === null) return probeInstalledOmp(executable, credentials, environment);
129
+ const cached = inspected.get(executable);
130
+ if (cached?.identity === identity) return cached.result;
131
+ const result = probeInstalledOmp(executable, credentials, environment);
132
+ inspected.set(executable, { identity, result });
133
+ const forget = () => { if (inspected.get(executable)?.result === result) inspected.delete(executable); };
134
+ try {
135
+ const value = await result;
136
+ // A file replaced while it was probed may not be the one that answered.
137
+ let unchanged = false;
138
+ try { unchanged = executionIdentity(executable, path, credentials, environment) === identity; } catch {}
139
+ if (!unchanged) forget();
140
+ return value;
141
+ } catch (error) {
142
+ forget();
143
+ throw error;
144
+ }
145
+ }
146
+
147
+ async function probeInstalledOmp(
148
+ executable: string, credentials: string[], environment: NodeJS.ProcessEnv,
149
+ ) {
38
150
  const env = { ...environment };
39
151
  for (const name of credentials) delete env[name];
40
152
  const probe = async (...args: string[]) => {
@@ -189,8 +189,7 @@ async function probe(packagePath: string, stage: string, manifest: UlwManifest):
189
189
  home, manifest.probeTimeoutMs, env);
190
190
  }
191
191
 
192
- /** Snapshot native discovery in the exact environment the installed CLI will use. */
193
- export async function managedUlwLaunchExtensions(options: {
192
+ export type ManagedUlwLaunchInput = {
194
193
  cwd: string;
195
194
  managedUlwPath: string;
196
195
  extensionPaths: string[];
@@ -200,26 +199,144 @@ export async function managedUlwLaunchExtensions(options: {
200
199
  commandArgs: string[];
201
200
  /** Exact native OMP argv, including the original command's flags and generated Host args; no executable prefix. */
202
201
  launchArgs: string[];
202
+ worker?: Pick<WorkerHostProfile, "extensionPaths">;
203
+ };
204
+ type ManagedUlwLaunchOptions = Omit<ManagedUlwLaunchInput, "managedUlwPath"> & {
205
+ managedUlwPath?: string;
203
206
  env: Record<string, string | undefined>;
204
207
  bunCommand: string[];
205
- worker?: Pick<WorkerHostProfile, "extensionPaths">;
206
- }): Promise<{ extensionPaths: string[]; noExtensions: boolean; memoryWriteDir: string | null }> {
208
+ discoveryTimeoutMs?: number;
209
+ };
210
+ export type ManagedUlwLaunchComposition = { extensionPaths: string[]; noExtensions: boolean; memoryWriteDir: string | null };
211
+
212
+ const LAUNCH_DISCOVERY_TIMEOUT_MS = 30_000;
213
+ const LAUNCH_OUTPUT_LIMIT = 16 * 1024 * 1024; // Same bound as the Rust Gateway.
214
+ const LAUNCH_MARKER = "MANAGED_ULW_LAUNCH ";
215
+ const LAUNCH_ERROR_MARKER = "MANAGED_ULW_LAUNCH_ERROR ";
216
+
217
+ async function launchPhase<T>(deadline: number, message: string, run: (assertActive: () => void) => Promise<T>): Promise<T> {
218
+ let timer: ReturnType<typeof setTimeout> | undefined;
219
+ let timedOut = false;
220
+ const assertActive = () => {
221
+ if (timedOut || performance.now() >= deadline) throw new Error(message);
222
+ };
223
+ try {
224
+ const timeout = new Promise<never>((_, reject) => {
225
+ timer = setTimeout(() => {
226
+ // Once reported, timeout is final even if a caller observes the clock
227
+ // before the absolute deadline (timer granularity or rounding).
228
+ timedOut = true;
229
+ reject(new Error(message));
230
+ }, Math.max(0, Math.ceil(deadline - performance.now())));
231
+ });
232
+ const result = await Promise.race([timeout, run(assertActive)]);
233
+ assertActive();
234
+ return result;
235
+ } finally { clearTimeout(timer); }
236
+ }
237
+
238
+ /** Snapshot native discovery in the exact environment the installed CLI will use. */
239
+ export async function managedUlwLaunchExtensions(options: ManagedUlwLaunchOptions & { managedUlwPath: string }): Promise<ManagedUlwLaunchComposition> {
240
+ return (await managedUlwLaunch(options)).composition;
241
+ }
242
+
243
+ /**
244
+ * Run native launch discovery in the Host SDK helper. With `prepare`, the same
245
+ * helper process then prepares the native session from the manifest the caller
246
+ * builds after seeing the composition, so one launch costs one helper spawn.
247
+ * The helper prepares nothing until that manifest arrives on its stdin.
248
+ */
249
+ export async function managedUlwLaunch(options: ManagedUlwLaunchOptions, prepare?: {
250
+ /** Native stderr destination; preparation output may contain session data. */
251
+ stderr: number;
252
+ timeoutMs: number;
253
+ beforeManifest?: () => void;
254
+ manifest: (composition: ManagedUlwLaunchComposition) => unknown;
255
+ }): Promise<{ composition: ManagedUlwLaunchComposition; prepared?: string; deadline?: number }> {
207
256
  if (!options.bunCommand.length) throw new Error("Managed ULW discovery requires the launcher's Bun command");
208
- const { env, bunCommand, ...input } = options;
209
- const output = await run([...bunCommand, ...(input.worker ? ["--no-install"] : []), fileURLToPath(import.meta.url),
210
- input.worker ? "--worker-launch-extensions" : "--launch-extensions", JSON.stringify(input)],
211
- input.worker ? dirname(options.configPath) : options.cwd, 30_000,
212
- Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)));
213
- const result = output.split("\n").findLast(line => line.startsWith("MANAGED_ULW_LAUNCH "));
214
- if (!result) throw new Error("Stock OMP discovery did not return a launch composition");
215
- return JSON.parse(result.slice("MANAGED_ULW_LAUNCH ".length));
257
+ const { env, bunCommand, discoveryTimeoutMs = LAUNCH_DISCOVERY_TIMEOUT_MS, ...input } = options;
258
+ const helper = fileURLToPath(new URL("./host-sdk-helper.ts", import.meta.url));
259
+ const child = Bun.spawn([...bunCommand, ...(input.worker ? ["--no-install"] : []), helper, "launch"], {
260
+ cwd: input.worker ? dirname(options.configPath) : options.cwd,
261
+ env: Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)),
262
+ stdin: "pipe", stdout: "pipe", stderr: prepare?.stderr ?? "ignore",
263
+ });
264
+ const reader = child.stdout.getReader();
265
+ const decoder = new TextDecoder();
266
+ let output = "";
267
+ let bytes = 0;
268
+ const read = async () => {
269
+ const chunk = await reader.read();
270
+ if (chunk.done) return false;
271
+ bytes += chunk.value.byteLength;
272
+ if (bytes > LAUNCH_OUTPUT_LIMIT) throw new Error("Host SDK launch output exceeded its bound");
273
+ output += decoder.decode(chunk.value, { stream: true });
274
+ return true;
275
+ };
276
+ try {
277
+ const discoveryDeadline = performance.now() + Math.max(1, discoveryTimeoutMs);
278
+ const composition = await launchPhase(discoveryDeadline, "Stock OMP discovery timed out", async () => {
279
+ child.stdin.write(JSON.stringify(input.managedUlwPath === undefined ? null : input) + "\n");
280
+ child.stdin.flush();
281
+ let scan = 0;
282
+ for (;;) {
283
+ const newline = output.indexOf("\n", scan);
284
+ if (newline < 0) {
285
+ scan = output.length;
286
+ if (await read()) continue;
287
+ throw new Error("Stock OMP discovery did not return a launch composition");
288
+ }
289
+ const line = output.slice(0, newline);
290
+ output = output.slice(newline + 1);
291
+ scan = 0;
292
+ if (line.startsWith(LAUNCH_ERROR_MARKER)) throw new Error(JSON.parse(line.slice(LAUNCH_ERROR_MARKER.length)));
293
+ if (line.startsWith(LAUNCH_MARKER)) {
294
+ const result: ManagedUlwLaunchComposition = JSON.parse(line.slice(LAUNCH_MARKER.length));
295
+ if (!prepare) {
296
+ child.stdin.end();
297
+ // Discovery-only mode has no further output to consume.
298
+ if (await child.exited !== 0) throw new Error("Stock OMP discovery failed");
299
+ }
300
+ return result;
301
+ }
302
+ }
303
+ });
304
+ if (!prepare) return { composition };
305
+
306
+ const deadline = performance.now() + Math.max(1, prepare.timeoutMs);
307
+ const timeout = "Native session preparation timed out";
308
+ bytes = Buffer.byteLength(output);
309
+ const prepared = await launchPhase(deadline, timeout, async assertActive => {
310
+ const payload = JSON.stringify(await prepare.manifest(composition));
311
+ // A timed-out manifest builder must never cross the worker launch fence.
312
+ assertActive();
313
+ prepare.beforeManifest?.();
314
+ child.stdin.write(payload);
315
+ child.stdin.end();
316
+ while (await read()) {}
317
+ if (await child.exited !== 0) throw new Error("Native session preparation failed");
318
+ return output + decoder.decode();
319
+ });
320
+ return { composition, prepared, deadline };
321
+ } finally {
322
+ // A descendant can hold a pipe open after the helper exits. Stop observing
323
+ // its stdout rather than waiting on it (or stderr) past a phase deadline.
324
+ if (child.exitCode === null && child.signalCode === null) {
325
+ try { child.kill("SIGKILL"); } catch {} // The child may have just exited.
326
+ }
327
+ void reader.cancel().catch(() => {});
328
+ }
216
329
  }
217
330
 
218
- if (import.meta.main && process.argv[2] === "--worker-launch-extensions") {
219
- const input: {
220
- cwd: string; managedUlwPath: string; extensionPaths: string[]; launchArgs: string[];
221
- worker: Pick<WorkerHostProfile, "extensionPaths">;
222
- } = JSON.parse(process.argv[3] ?? "");
331
+ /**
332
+ * Native discovery for one launch, run inside the short-lived Host SDK helper
333
+ * process: it imports SDK modules and mutates process-global discovery state.
334
+ */
335
+ export async function managedUlwLaunchComposition(input: ManagedUlwLaunchInput): Promise<ManagedUlwLaunchComposition> {
336
+ return input.worker ? workerLaunchComposition({ ...input, worker: input.worker }) : launchComposition(input);
337
+ }
338
+
339
+ async function workerLaunchComposition(input: ManagedUlwLaunchInput & { worker: Pick<WorkerHostProfile, "extensionPaths"> }): Promise<ManagedUlwLaunchComposition> {
223
340
  const { assertWorkerWorkspaceStartup } = await import("./worker-profile");
224
341
  const { homedir } = await import("node:os");
225
342
  assertWorkerWorkspaceStartup(input.cwd, homedir());
@@ -236,14 +353,10 @@ if (import.meta.main && process.argv[2] === "--worker-launch-extensions") {
236
353
  // opt-in modules as files, while managed packages retain their own resources.
237
354
  const managed = validateManagedUlwPackage(input.managedUlwPath);
238
355
  const extensionPaths = [...new Set([...input.extensionPaths, managed, ...input.worker.extensionPaths])];
239
- console.log(`MANAGED_ULW_LAUNCH ${JSON.stringify({ extensionPaths, noExtensions: true, memoryWriteDir: null })}`);
356
+ return { extensionPaths, noExtensions: true, memoryWriteDir: null };
240
357
  }
241
358
 
242
- if (import.meta.main && process.argv[2] === "--launch-extensions") {
243
- const input = JSON.parse(process.argv[3]!) as {
244
- cwd: string; managedUlwPath: string; extensionPaths: string[]; parentConfigPath?: string;
245
- commandArgs: string[]; launchArgs: string[];
246
- };
359
+ async function launchComposition(input: ManagedUlwLaunchInput): Promise<ManagedUlwLaunchComposition> {
247
360
  const { parseNativeLaunch } = await import("./native-launch-profile");
248
361
  const parsed = await parseNativeLaunch(input.launchArgs);
249
362
  const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
@@ -399,7 +512,7 @@ if (import.meta.main && process.argv[2] === "--launch-extensions") {
399
512
  const current = await readNativeSettings(settings).catch(() => { throw new Error(memoryBlockReason({ status: "unknown" })); });
400
513
  const { memory } = await ensureManagedMemory(current, memoryWriteDir);
401
514
  if (memory.status !== "enabled") throw new Error(memoryBlockReason(memory));
402
- console.log(`MANAGED_ULW_LAUNCH ${JSON.stringify({ ...composition, memoryWriteDir })}`);
515
+ return { ...composition, memoryWriteDir };
403
516
  }
404
517
 
405
518
  /** Serialized source preparation only. No Gateway, account adapter, or Host starts here. */
@@ -4,7 +4,7 @@
4
4
  { "name": "status", "description": "Inspect Superagent HEAD and this conversation's lane, including while busy." },
5
5
  { "name": "restart", "description": "Interrupt HEAD work and restart Superagent Gateway and HEAD with the same session and memory." },
6
6
  { "name": "context", "description": "Inspect Superagent HEAD context without starting a model turn." },
7
- { "name": "usage", "description": "Show Superagent's OMP account quotas and reset times." },
7
+ { "name": "usage", "description": "Show Superagent's OMP quotas or open the saved reset picker.", "text": "Omit to view quotas, or enter reset to choose an account and confirm using one saved reset." },
8
8
  { "name": "cron", "description": "Schedule and manage Superagent jobs in this conversation.", "text": "Use help, add, list, show, edit, pause, resume, run or remove." },
9
9
  { "name": "resume", "description": "Resume the Superagent lane bound to this conversation." },
10
10
  { "name": "resolve", "description": "Close an uncertain Superagent HEAD or bound lane input without replay.", "text": "Exact uncertain HEAD input ID, or --lane followed by the bound lane's exact input ID." },