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
@@ -0,0 +1,471 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
+ import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
4
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const projectRoot = fileURLToPath(new URL("../", import.meta.url));
8
+ const ownership = "omp-superagent-managed-ulw-v1";
9
+ const hash = /^[0-9a-f]{40,64}$/;
10
+ export const MANAGED_ULW_ENV = "OMP_SUPERAGENT_MANAGED_ULW_PATH";
11
+ // Only explicitly injected fixtures propagate. The per-Host revision marker above
12
+ // is informational: a new lane must resolve the current active revision afresh.
13
+ export const MANAGED_ULW_FIXTURE_ENV = "OMP_SUPERAGENT_TEST_MANAGED_ULW_PATH";
14
+ export const MANAGED_ULW_FIXTURE_ROOT_ENV = "OMP_SUPERAGENT_TEST_MANAGED_ULW_ROOT";
15
+
16
+ export interface UlwManifest {
17
+ repository: string;
18
+ ref: "HEAD";
19
+ directory: string;
20
+ checkIntervalMs: number;
21
+ commandTimeoutMs: number;
22
+ probeTimeoutMs: number;
23
+ materialize: string | null;
24
+ }
25
+ export interface ManagedUlwStatus {
26
+ revision: string | null;
27
+ packagePath: string | null;
28
+ upstreamRevision: string | null;
29
+ checkedAt: string | null;
30
+ error: string | null;
31
+ updating: boolean;
32
+ injected?: boolean;
33
+ }
34
+ interface ActiveRevision { revision: string; repository: string; branch: string; preparedAt: string }
35
+ interface PackageManifest {
36
+ name?: string;
37
+ omp?: { extensions?: string[]; skills?: string[]; [key: string]: unknown };
38
+ dependencies?: Record<string, string>;
39
+ optionalDependencies?: Record<string, string>;
40
+ }
41
+ export interface ManagedUlwOptions { manifestPath?: string; root?: string }
42
+
43
+ export function readUlwManifest(manifestPath = join(projectRoot, "upstream/ulw.json")): UlwManifest {
44
+ const value = JSON.parse(readFileSync(manifestPath, "utf8")) as UlwManifest;
45
+ if (!value.repository || value.ref !== "HEAD" || !value.directory ||
46
+ !Number.isSafeInteger(value.checkIntervalMs) || value.checkIntervalMs < 60_000 ||
47
+ !Number.isSafeInteger(value.commandTimeoutMs) || value.commandTimeoutMs < 1_000 ||
48
+ !Number.isSafeInteger(value.probeTimeoutMs) || value.probeTimeoutMs < 1_000 ||
49
+ !(value.materialize === null || typeof value.materialize === "string"))
50
+ throw new Error("Invalid managed ULW manifest");
51
+ return value;
52
+ }
53
+ function rootFor(options: ManagedUlwOptions, manifest = readUlwManifest(options.manifestPath)): string {
54
+ return resolve(options.root ?? resolve(projectRoot, manifest.directory));
55
+ }
56
+ function assertOwned(root: string): void {
57
+ const stat = lstatSync(root);
58
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
59
+ throw new Error("Managed ULW directory must be a private owned directory");
60
+ if (readFileSync(join(root, "owner.json"), "utf8") !== JSON.stringify({ owner: ownership }))
61
+ throw new Error("Refusing to modify an unrelated ULW directory");
62
+ }
63
+ function readActive(root: string): ActiveRevision | null {
64
+ try {
65
+ const value = JSON.parse(readFileSync(join(root, "active.json"), "utf8")) as ActiveRevision;
66
+ if (!hash.test(value.revision) || !value.repository || !value.branch) throw new Error("Invalid managed ULW active pointer");
67
+ return value;
68
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
69
+ }
70
+ export function validateManagedUlwPackage(packagePath: string): string {
71
+ if (!isAbsolute(packagePath)) throw new Error("Managed ULW package must have an absolute path");
72
+ const canonical = realpathSync(packagePath);
73
+ const pkg = JSON.parse(readFileSync(join(canonical, "package.json"), "utf8")) as PackageManifest;
74
+ if (pkg.name !== "omp-ulw" || !Array.isArray(pkg.omp?.extensions) || !pkg.omp.extensions.length)
75
+ throw new Error("Managed ULW package has no native extension manifest");
76
+ for (const entry of pkg.omp.extensions) {
77
+ if (typeof entry !== "string" || !entry || isAbsolute(entry)) throw new Error("Invalid managed ULW extension entry");
78
+ const target = realpathSync(resolve(canonical, entry));
79
+ if (!target.startsWith(canonical + sep) || !lstatSync(target).isFile()) throw new Error("Managed ULW extension leaves its package");
80
+ }
81
+ if (!lstatSync(join(canonical, "skills")).isDirectory()) throw new Error("Managed ULW skills are missing");
82
+ return canonical;
83
+ }
84
+ export function activeManagedUlw(options: ManagedUlwOptions = {}): string {
85
+ const root = rootFor(options);
86
+ try { assertOwned(root); }
87
+ catch (error) {
88
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new Error("Mandatory managed ULW is not installed; run bun run prepare:ulw");
89
+ throw error;
90
+ }
91
+ const active = readActive(root);
92
+ if (!active) throw new Error("Mandatory managed ULW is not installed; run bun run prepare:ulw");
93
+ const revisionRoot = join(root, "revisions", active.revision);
94
+ const provenance = JSON.parse(readFileSync(join(revisionRoot, "provenance.json"), "utf8")) as ActiveRevision;
95
+ if (provenance.revision !== active.revision || provenance.repository !== active.repository)
96
+ throw new Error("Managed ULW provenance does not match its active pointer");
97
+ return validateManagedUlwPackage(join(revisionRoot, "package"));
98
+ }
99
+ export function managedUlwStatus(options: ManagedUlwOptions = {}): ManagedUlwStatus {
100
+ const root = rootFor(options);
101
+ let saved: Partial<ManagedUlwStatus> = {};
102
+ try { saved = JSON.parse(readFileSync(join(root, "status.json"), "utf8")); }
103
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
104
+ const active = readActive(root);
105
+ return { revision: active?.revision ?? null, packagePath: active ? join(root, "revisions", active.revision, "package") : null,
106
+ upstreamRevision: saved.upstreamRevision ?? null, checkedAt: saved.checkedAt ?? null,
107
+ error: saved.error ?? null, updating: saved.updating ?? false };
108
+ }
109
+ async function atomicJson(path: string, value: unknown): Promise<void> {
110
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
111
+ try { await writeFile(temporary, JSON.stringify(value, null, 2) + "\n", { flag: "wx", mode: 0o600 }); await rename(temporary, path); }
112
+ finally { await rm(temporary, { force: true }); }
113
+ }
114
+ async function initialize(root: string): Promise<void> {
115
+ try {
116
+ await mkdir(root, { mode: 0o700 });
117
+ await writeFile(join(root, "owner.json"), JSON.stringify({ owner: ownership }), { flag: "wx", mode: 0o600 });
118
+ } catch (error) {
119
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
120
+ // Concurrent initialization may have created the directory just before its
121
+ // ownership marker. Never claim a pre-existing, unmarked directory.
122
+ for (let attempt = 0; attempt < 20; attempt++) {
123
+ try { assertOwned(root); return; }
124
+ catch (cause) { if ((cause as NodeJS.ErrnoException).code !== "ENOENT") throw cause; }
125
+ await Bun.sleep(10);
126
+ }
127
+ }
128
+ assertOwned(root);
129
+ }
130
+ async function run(args: string[], cwd: string, timeout: number, env?: Record<string, string>): Promise<string> {
131
+ const child = Bun.spawn(args, { cwd, env, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout, killSignal: "SIGKILL" });
132
+ const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
133
+ if (exit !== 0) throw new Error(`${args[0]} ${args[1] ?? ""} failed (${exit}): ${stderr.slice(-2000)}`);
134
+ return stdout.trim();
135
+ }
136
+ async function immutableTree(directory: string): Promise<void> {
137
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
138
+ const path = join(directory, entry.name);
139
+ if (entry.isDirectory()) await immutableTree(path);
140
+ else if (!entry.isSymbolicLink()) { const stat = await lstat(path); await chmod(path, 0o444 | (stat.mode & 0o111)); }
141
+ }
142
+ await chmod(directory, 0o555);
143
+ }
144
+ async function checkLinks(directory: string, root = directory): Promise<void> {
145
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
146
+ const path = join(directory, entry.name);
147
+ if (entry.isDirectory()) await checkLinks(path, root);
148
+ else if (entry.isSymbolicLink()) {
149
+ const target = realpathSync(path);
150
+ if (!target.startsWith(root + sep)) throw new Error("Managed ULW resource symlink leaves its package");
151
+ }
152
+ }
153
+ }
154
+ async function probe(packagePath: string, stage: string, manifest: UlwManifest): Promise<void> {
155
+ const home = join(stage, "probe-home");
156
+ await mkdir(home, { mode: 0o700 });
157
+ const env: Record<string, string> = { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: home, USERPROFILE: home,
158
+ PI_CODING_AGENT_DIR: join(home, "agent"), XDG_CONFIG_HOME: join(home, "config"),
159
+ XDG_DATA_HOME: join(home, "data"), XDG_CACHE_HOME: join(home, "cache"), CI: "true", NO_COLOR: "1" };
160
+ if (process.env.PI_NATIVES_DIR) env.PI_NATIVES_DIR = process.env.PI_NATIVES_DIR;
161
+ await run([process.execPath, fileURLToPath(new URL("./managed-ulw-probe.ts", import.meta.url)), packagePath],
162
+ home, manifest.probeTimeoutMs, env);
163
+ }
164
+
165
+ /** Snapshot native discovery in the exact environment the installed CLI will use. */
166
+ export async function managedUlwLaunchExtensions(options: {
167
+ cwd: string;
168
+ managedUlwPath: string;
169
+ extensionPaths: string[];
170
+ configPath: string;
171
+ /** Native argv prefix retained verbatim by the caller when it replaces the generated Host args. */
172
+ commandArgs: string[];
173
+ /** Exact native OMP argv, including the original command's flags and generated Host args; no executable prefix. */
174
+ launchArgs: string[];
175
+ env: Record<string, string | undefined>;
176
+ bunCommand: string[];
177
+ }): Promise<{ extensionPaths: string[]; noExtensions: boolean }> {
178
+ if (!options.bunCommand.length) throw new Error("Managed ULW discovery requires the launcher's Bun command");
179
+ const { env, bunCommand, ...input } = options;
180
+ const output = await run([...bunCommand, fileURLToPath(import.meta.url), "--launch-extensions", JSON.stringify(input)],
181
+ options.cwd, 30_000, Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)));
182
+ const result = output.split("\n").findLast(line => line.startsWith("MANAGED_ULW_LAUNCH "));
183
+ if (!result) throw new Error("Stock OMP discovery did not return a launch composition");
184
+ return JSON.parse(result.slice("MANAGED_ULW_LAUNCH ".length)) as { extensionPaths: string[]; noExtensions: boolean };
185
+ }
186
+
187
+ if (import.meta.main && process.argv[2] === "--launch-extensions") {
188
+ const input = JSON.parse(process.argv[3]!) as {
189
+ cwd: string; managedUlwPath: string; extensionPaths: string[]; configPath: string;
190
+ commandArgs: string[]; launchArgs: string[];
191
+ };
192
+ // Match cli.ts: choose the profile before importing pi-utils/env or any
193
+ // discovery/settings module that can eagerly read the agent directory.
194
+ const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
195
+ const { setProfile, resolveProfileEnv, getProjectDir } = await import("@oh-my-pi/pi-utils/dirs");
196
+ const bootstrap = extractProfileFlags(input.launchArgs);
197
+ setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
198
+ if (bootstrap.aliasName !== undefined) throw new Error("Managed ULW discovery requires a launch, not --alias installation");
199
+ const { isNativeShell } = await import("@oh-my-pi/pi-coding-agent/cli/native-shell");
200
+ if (isNativeShell(bootstrap.argv[0])) throw new Error("Managed ULW discovery requires native OMP launch argv, not a shell command");
201
+ const { resolveCliArgv } = await import("@oh-my-pi/pi-coding-agent/cli-commands");
202
+ const resolved = resolveCliArgv(bootstrap.argv);
203
+ if ("error" in resolved) throw new Error(resolved.error);
204
+ if (resolved.argv[0] !== "launch") throw new Error("Managed ULW discovery requires native OMP launch argv");
205
+ const { parseArgs } = await import("@oh-my-pi/pi-coding-agent/cli/args");
206
+ const parsed = parseArgs(resolved.argv.slice(1));
207
+ const command = parseArgs(extractProfileFlags(input.commandArgs).argv);
208
+ if (parsed.trustedExtensions?.length) {
209
+ throw new Error("Stock OMP --trusted-extension cannot preserve managed ULW package resources");
210
+ }
211
+ const { applyStartupCwd } = await import("@oh-my-pi/pi-coding-agent/cli/startup-cwd");
212
+ await applyStartupCwd(parsed);
213
+ const cwd = getProjectDir();
214
+ const { Settings } = await import("@oh-my-pi/pi-coding-agent/config/settings");
215
+ const { discoverSessionExtensionPaths } = await import("@oh-my-pi/pi-coding-agent/sdk");
216
+ const { discoverExtensionPaths, listPackageExtensionModules } = await import("@oh-my-pi/pi-coding-agent/extensibility/extensions/loader");
217
+ const { initializeWithSettings } = await import("@oh-my-pi/pi-coding-agent/discovery");
218
+ const { listOmpExtensionRoots, withOmpExtensionRootScope, setInvocationConfiguredExtensions } = await import("@oh-my-pi/pi-coding-agent/discovery/omp-extension-roots");
219
+ const { injectPluginDirRoots, preloadPluginRoots, listClaudePluginRoots } = await import("@oh-my-pi/pi-coding-agent/discovery/helpers");
220
+ const { cfgExtensions } = await import("@oh-my-pi/pi-coding-agent/extensibility/settings");
221
+ const { findRepoRoot } = await import("@oh-my-pi/pi-coding-agent/capability/fs");
222
+ const { discoverCustomCommands } = await import("@oh-my-pi/pi-coding-agent/extensibility/custom-commands/loader");
223
+ const { getAgentDir } = await import("@oh-my-pi/pi-utils");
224
+ const { homedir } = await import("node:os");
225
+ if (parsed.pluginDirs?.length) await injectPluginDirRoots(homedir(), parsed.pluginDirs, cwd);
226
+ else await preloadPluginRoots(homedir(), cwd);
227
+ const settings = await Settings.loadReadOnly({
228
+ cwd, agentDir: getAgentDir(), configFiles: parsed.config,
229
+ });
230
+ const restore = initializeWithSettings(settings);
231
+ try {
232
+ const managed = validateManagedUlwPackage(input.managedUlwPath);
233
+ const ulwRoot = async (entry: string): Promise<string | undefined> => {
234
+ let current: string;
235
+ try { current = await realpath(entry); }
236
+ catch (error) {
237
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
238
+ throw error;
239
+ }
240
+ if (!(await lstat(current)).isDirectory()) current = dirname(current);
241
+ for (;;) {
242
+ try {
243
+ const manifest = JSON.parse(await readFile(join(current, "package.json"), "utf8")) as PackageManifest;
244
+ return manifest.name === "omp-ulw" ? current : undefined;
245
+ } catch (error) {
246
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
247
+ }
248
+ const parent = dirname(current);
249
+ if (parent === current) return undefined;
250
+ current = parent;
251
+ }
252
+ };
253
+ const nativeExplicit = [...new Set([...(parsed.extensions ?? []), ...(parsed.hooks ?? [])])];
254
+ // These argv entries remain in the caller's command. Appending flags cannot
255
+ // revoke an explicit -e/--hook, even with --no-extensions.
256
+ const commandExplicit = [...(command.extensions ?? []), ...(command.hooks ?? [])];
257
+ const commandModules = await listPackageExtensionModules(commandExplicit, cwd, { plugins: false });
258
+ const commandRoots = await withOmpExtensionRootScope(commandExplicit, "explicit-only", () => listOmpExtensionRoots({
259
+ cwd, home: homedir(), repoRoot: null, agentDir: getAgentDir(),
260
+ }));
261
+ for (const entry of [...commandModules, ...commandRoots]) {
262
+ const root = await ulwRoot(entry.path);
263
+ if (root && root !== managed) {
264
+ throw new Error(`Stock OMP cannot exclude another ULW copy explicitly selected by -e/--hook: ${root}; remove that original launch argument`);
265
+ }
266
+ }
267
+ // --no-extensions scopes OMP packages, not the independent marketplace and
268
+ // --plugin-dir resource providers. Their roots cannot be removed by -e.
269
+ for (const plugin of (await listClaudePluginRoots(homedir(), cwd)).roots) {
270
+ const root = await ulwRoot(plugin.path);
271
+ if (root && root !== managed) {
272
+ throw new Error(`Stock OMP cannot exclude another ULW copy's plugin resources: ${root}; remove --plugin-dir or disable that plugin`);
273
+ }
274
+ }
275
+ const mode = parsed.noExtensions ? "explicit-only" : "merge";
276
+ const original = await withOmpExtensionRootScope(nativeExplicit, mode, () => {
277
+ setInvocationConfiguredExtensions(cfgExtensions.get(settings), settings.extensionsSourceLevel());
278
+ return discoverSessionExtensionPaths({
279
+ additionalExtensionPaths: nativeExplicit, disableExtensionDiscovery: parsed.noExtensions,
280
+ }, cwd, settings);
281
+ });
282
+ const roots = await listOmpExtensionRoots({
283
+ cwd, home: homedir(), repoRoot: await findRepoRoot(cwd), agentDir: getAgentDir(),
284
+ extensionRoots: { explicit: nativeExplicit, configured: cfgExtensions.get(settings),
285
+ configuredLevel: settings.extensionsSourceLevel(), mode },
286
+ });
287
+ if (!(await Promise.all(roots.map(root => realpath(root.path)))).includes(managed)) {
288
+ throw new Error("Native OMP launch argv does not select the managed ULW package root; generated Host flags may be after --");
289
+ }
290
+ const retained = [];
291
+ let conflict = false;
292
+ for (const entry of original) {
293
+ const root = await ulwRoot(entry);
294
+ if (!root || root === managed) retained.push(entry);
295
+ else conflict = true;
296
+ }
297
+ const resourceRoots: string[] = [];
298
+ for (const root of roots) {
299
+ const identity = await ulwRoot(root.path);
300
+ if (!identity || identity === managed) resourceRoots.push(root.path);
301
+ else conflict = true;
302
+ }
303
+ if (!conflict) {
304
+ // Ordinary native discovery preserves every native surface, including
305
+ // TypeScript commands, when no other ULW copy needs exclusion.
306
+ console.log(`MANAGED_ULW_LAUNCH ${JSON.stringify({
307
+ extensionPaths: [...new Set([...input.extensionPaths, managed])], noExtensions: !!parsed.noExtensions,
308
+ })}`);
309
+ } else {
310
+ const commands = parsed.noExtensions ? [] : (await discoverCustomCommands({ cwd, agentDir: getAgentDir() })).paths;
311
+ if (commands.length) {
312
+ throw new Error(`Stock OMP --no-extensions cannot preserve TypeScript custom commands while excluding another ULW copy: `
313
+ + JSON.stringify(commands.map(command => command.path)));
314
+ }
315
+ // File paths preserve the authoritative module selection/order. Directory
316
+ // roots preserve all sibling capabilities, not just the skill CLI surface.
317
+ const explicit = [...retained, ...resourceRoots];
318
+ const actualExplicit = [...(command.extensions ?? []), ...explicit, ...(command.hooks ?? [])];
319
+ const expected = retained;
320
+ const actual = await discoverExtensionPaths(actualExplicit, cwd, undefined, { ambient: false });
321
+ const canonical = async (entries: string[]) => Promise.all(entries.map(entry => realpath(entry)));
322
+ const expectedFiles = await canonical(expected);
323
+ const actualFiles = await canonical(actual);
324
+ if (JSON.stringify(actualFiles) !== JSON.stringify(expectedFiles)) {
325
+ throw new Error(`Stock OMP cannot preserve this extension/resource selection with --no-extensions: `
326
+ + `package resources would re-enable disabled modules or change hook order. `
327
+ + `Expected modules ${JSON.stringify(expectedFiles)}; explicit CLI modules ${JSON.stringify(actualFiles)}`);
328
+ }
329
+ const actualRoots = await withOmpExtensionRootScope(actualExplicit, "explicit-only", () => listOmpExtensionRoots({
330
+ cwd, home: homedir(), repoRoot: null, agentDir: getAgentDir(),
331
+ }));
332
+ const expectedRoots = await canonical([...new Set(resourceRoots)]);
333
+ if (JSON.stringify(await canonical(actualRoots.map(root => root.path))) !== JSON.stringify(expectedRoots)) {
334
+ throw new Error("Stock OMP explicit CLI resource roots differ from the selected native package roots");
335
+ }
336
+ for (const root of roots.filter(root => resourceRoots.includes(root.path))) {
337
+ const actualLevel = actualRoots[expectedRoots.indexOf(await realpath(root.path))]?.level;
338
+ if (actualLevel !== root.level) {
339
+ throw new Error(`Stock OMP explicit -e would change ${root.level} resource scope to ${actualLevel} scope: ${root.path}`);
340
+ }
341
+ }
342
+ console.log(`MANAGED_ULW_LAUNCH ${JSON.stringify({ extensionPaths: explicit, noExtensions: true })}`);
343
+ }
344
+ } finally { restore(); }
345
+ }
346
+
347
+ /** Serialized source preparation only. No Gateway, account adapter, or Host starts here. */
348
+ export async function updateManagedUlw(options: ManagedUlwOptions = {}): Promise<ManagedUlwStatus> {
349
+ const manifest = readUlwManifest(options.manifestPath);
350
+ const root = rootFor(options, manifest);
351
+ await mkdir(dirname(root), { recursive: true });
352
+ await initialize(root);
353
+ const lock = new Database(join(root, "update.sqlite"));
354
+ lock.exec("PRAGMA busy_timeout=0");
355
+ const deadline = Date.now() + manifest.commandTimeoutMs * 4;
356
+ try {
357
+ for (;;) {
358
+ try { lock.exec("BEGIN IMMEDIATE"); break; }
359
+ catch (error) {
360
+ if (!(error instanceof Error) || !/locked|busy/i.test(error.message) || Date.now() >= deadline) throw error;
361
+ await Bun.sleep(25);
362
+ }
363
+ }
364
+ let stage: string | undefined;
365
+ let upstreamRevision: string | null = null;
366
+ const checkedAt = new Date().toISOString();
367
+ try {
368
+ await atomicJson(join(root, "status.json"), { ...managedUlwStatus(options), checkedAt, updating: true, error: null });
369
+ const git = (args: string[], cwd = root) => run(["git", "-c", "core.hooksPath=/dev/null", ...args], cwd, manifest.commandTimeoutMs,
370
+ { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: root, USERPROFILE: root,
371
+ GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" });
372
+ const remote = await git(["ls-remote", "--symref", manifest.repository, "HEAD"]);
373
+ const branch = /^ref: (refs\/heads\/[^\s]+)\s+HEAD$/m.exec(remote)?.[1];
374
+ upstreamRevision = /^([0-9a-f]{40,64})\s+HEAD$/m.exec(remote)?.[1] ?? null;
375
+ if (!branch || !upstreamRevision) throw new Error("ULW upstream did not advertise an unambiguous default branch and HEAD commit");
376
+ const active = readActive(root);
377
+ let nextActive: ActiveRevision | undefined;
378
+ if (active && active.repository !== manifest.repository) throw new Error("Managed ULW source repository changed; explicit operator reconciliation required");
379
+ if (active?.revision === upstreamRevision && active.repository === manifest.repository) {
380
+ activeManagedUlw(options);
381
+ } else {
382
+ const revisionRoot = join(root, "revisions", upstreamRevision);
383
+ let prepared = false;
384
+ try {
385
+ const provenance = JSON.parse(await readFile(join(revisionRoot, "provenance.json"), "utf8")) as ActiveRevision;
386
+ if (provenance.revision !== upstreamRevision || provenance.repository !== manifest.repository)
387
+ throw new Error("Existing immutable ULW revision has different provenance");
388
+ validateManagedUlwPackage(join(revisionRoot, "package"));
389
+ prepared = true;
390
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
391
+ const provenance: ActiveRevision = { revision: upstreamRevision, repository: manifest.repository, branch, preparedAt: new Date().toISOString() };
392
+ if (!prepared) {
393
+ stage = await mkdtemp(join(root, ".stage-"));
394
+ const source = join(stage, "source");
395
+ const distribution = join(stage, "distribution");
396
+ const packagePath = join(distribution, "package");
397
+ await mkdir(packagePath, { recursive: true, mode: 0o700 });
398
+ await git(["clone", "--no-checkout", "--no-local", manifest.repository, source]);
399
+ await git(["fetch", "origin", upstreamRevision], source);
400
+ await git(["checkout", "--detach", upstreamRevision], source);
401
+ if (await git(["rev-parse", "HEAD"], source) !== upstreamRevision) throw new Error("ULW checkout revision changed while staging");
402
+ if (active) {
403
+ try { await git(["merge-base", "--is-ancestor", active.revision, upstreamRevision], source); }
404
+ catch { throw new Error("ULW upstream update is not a provable fast-forward; explicit operator reconciliation required"); }
405
+ }
406
+ await git(["submodule", "update", "--init", "--recursive", "--depth=1"], source);
407
+ await checkLinks(source);
408
+ // Export tracked runtime/resources, not .git, dev node_modules, or the
409
+ // user's checkout. Gitlinks are only build inputs for materialization.
410
+ const archive = join(stage, "source.tar");
411
+ await git(["archive", "--format=tar", `--output=${archive}`, "HEAD"], source);
412
+ await run(["tar", "-xf", archive, "-C", packagePath], stage, manifest.commandTimeoutMs);
413
+ if (manifest.materialize) {
414
+ const materialize = resolve(source, manifest.materialize);
415
+ if (!materialize.startsWith(source + sep)) throw new Error("ULW materializer leaves source checkout");
416
+ await run([process.execPath, materialize, "--target-root", join(packagePath, "skills/frontend")], source, manifest.commandTimeoutMs);
417
+ }
418
+ const pkgPath = join(packagePath, "package.json");
419
+ const pkg = JSON.parse(await readFile(pkgPath, "utf8")) as PackageManifest;
420
+ pkg.omp = { ...pkg.omp, skills: pkg.omp?.skills ?? ["./skills"] };
421
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
422
+ if (Object.keys(pkg.dependencies ?? {}).length || Object.keys(pkg.optionalDependencies ?? {}).length) {
423
+ await run([process.execPath, "install", "--production", "--ignore-scripts", "--frozen-lockfile"], packagePath, manifest.commandTimeoutMs);
424
+ }
425
+ validateManagedUlwPackage(packagePath);
426
+ await checkLinks(packagePath);
427
+ await probe(packagePath, stage, manifest);
428
+ await writeFile(join(distribution, "provenance.json"), JSON.stringify(provenance, null, 2) + "\n", { mode: 0o444 });
429
+ await immutableTree(packagePath);
430
+ await mkdir(join(root, "revisions"), { recursive: true, mode: 0o700 });
431
+ await rename(distribution, revisionRoot);
432
+ }
433
+ if (prepared) {
434
+ // A previously prepared revision may have been active before a remote
435
+ // rewind. Do not bypass ancestry merely because its files already exist.
436
+ stage = await mkdtemp(join(root, ".stage-"));
437
+ if (active) {
438
+ const source = join(stage, "ancestry");
439
+ await git(["clone", "--no-checkout", "--no-local", manifest.repository, source]);
440
+ await git(["fetch", "origin", upstreamRevision], source);
441
+ try { await git(["merge-base", "--is-ancestor", active.revision, upstreamRevision], source); }
442
+ catch { throw new Error("ULW upstream update is not a provable fast-forward; explicit operator reconciliation required"); }
443
+ }
444
+ await probe(join(revisionRoot, "package"), stage, manifest);
445
+ }
446
+ nextActive = provenance;
447
+ }
448
+ // Finish fallible staging cleanup/status publication before committing the
449
+ // active pointer, so a failed preparation never reports a rollback after
450
+ // it has already activated a new revision.
451
+ if (stage) { await rm(stage, { recursive: true, force: true }); stage = undefined; }
452
+ await atomicJson(join(root, "status.json"), { upstreamRevision, checkedAt, updating: false, error: null });
453
+ const selected = nextActive ?? active!;
454
+ const result: ManagedUlwStatus = { revision: selected.revision,
455
+ packagePath: join(root, "revisions", selected.revision, "package"), upstreamRevision, checkedAt, updating: false, error: null };
456
+ // The only activation write. Old immutable directories are never pruned:
457
+ // running Hosts and their native children may still import from them.
458
+ if (nextActive) await atomicJson(join(root, "active.json"), nextActive);
459
+ return result;
460
+ } catch (error) {
461
+ const message = error instanceof Error ? error.message : "Managed ULW update failed";
462
+ await atomicJson(join(root, "status.json"), { upstreamRevision, checkedAt, updating: false, error: message });
463
+ throw new Error(`Managed ULW update failed; previous active revision retained: ${message}`, { cause: error });
464
+ } finally {
465
+ // Never delete an immutable revision or any path outside this invocation's
466
+ // exclusively-created staging directory.
467
+ if (stage) await rm(stage, { recursive: true, force: true });
468
+ lock.exec("ROLLBACK");
469
+ }
470
+ } finally { lock.close(); }
471
+ }
@@ -0,0 +1,21 @@
1
+ import type { Platform } from "./contracts";
2
+
3
+ /** Platform message order only; event/edit IDs and local arrival times are not clocks. */
4
+ export function compareMessageIds(platform: Platform, left: string, right: string): -1 | 0 | 1 | null {
5
+ if (platform === "discord" || platform === "telegram") {
6
+ if (!/^\d+$/.test(left) || !/^\d+$/.test(right)) return null;
7
+ const a = BigInt(left);
8
+ const b = BigInt(right);
9
+ return a < b ? -1 : a > b ? 1 : 0;
10
+ }
11
+ if (platform !== "slack" || !/^\d+\.\d+$/.test(left) || !/^\d+\.\d+$/.test(right)) return null;
12
+ const [leftSeconds, leftFraction] = left.split(".") as [string, string];
13
+ const [rightSeconds, rightFraction] = right.split(".") as [string, string];
14
+ const a = BigInt(leftSeconds);
15
+ const b = BigInt(rightSeconds);
16
+ if (a !== b) return a < b ? -1 : 1;
17
+ const width = Math.max(leftFraction.length, rightFraction.length);
18
+ const fractionA = leftFraction.padEnd(width, "0");
19
+ const fractionB = rightFraction.padEnd(width, "0");
20
+ return fractionA < fractionB ? -1 : fractionA > fractionB ? 1 : 0;
21
+ }
@@ -0,0 +1,16 @@
1
+ /** Supported owner controls shared by each platform's command picker. */
2
+ export const MESSENGER_COMMANDS = [
3
+ { name: "help", description: "Show Superagent commands and their scope." },
4
+ { name: "status", description: "Inspect Superagent HEAD and this conversation's lane, including while busy." },
5
+ { name: "restart", description: "Restart Superagent Gateway and HEAD together when idle, preserving the session." },
6
+ { name: "context", description: "Inspect Superagent HEAD context without starting a model turn." },
7
+ { name: "usage", description: "Inspect Superagent HEAD usage without starting a model turn." },
8
+ { name: "resume", description: "Resume the Superagent lane bound to this conversation." },
9
+ { name: "resolve", description: "Close an already-uncertain Superagent HEAD input to unblock later HEAD work.", text: "The exact held uncertain input ID; required when more than one is held." },
10
+ { name: "main", description: "Select the main Superagent topic in this owner DM." },
11
+ { name: "model", description: "Inspect or change the Superagent HEAD model or named preset.", text: "Query, exact provider/model, or preset selection (including an optional --global)." },
12
+ { name: "effort", description: "Inspect or change the Superagent HEAD thinking effort.", text: "An exact advertised effort level; omit to inspect the current effort." },
13
+ { name: "compact", description: "Compact Superagent HEAD context when idle.", text: "Optional compaction instructions, including multiple lines." },
14
+ { name: "stop", description: "Stop Superagent HEAD work or pause a bound or explicitly named lane.", text: "head or an actual lane ID; omit to use this conversation's lane, otherwise HEAD." },
15
+ { name: "new", description: "Start a new Superagent topic in this owner DM, optionally with a request.", text: "An optional first request for the new topic." },
16
+ ] as const;
@@ -0,0 +1,143 @@
1
+ import type { Config } from "./config";
2
+ import { credentialEnvNames, requireMessengerCredentials, voiceApiKeyEnv } from "./config";
3
+ import type { Approval, Attachment, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, Inbound, MessageActivity, MessageReference, Messenger, OutputRecord, Platform, Route, StorePort, ThreadInfo, ThreadUpdate } from "./contracts";
4
+ import { physicalRouteKey } from "./contracts";
5
+ import { DeliveryError } from "./delivery";
6
+ import { DiscordMessenger } from "./discord";
7
+ import { SlackMessenger } from "./slack";
8
+ import { TelegramMessenger } from "./telegram";
9
+
10
+ /** One head; transports retain their own authenticated account and recovery state. */
11
+ export class MessengerHub implements Messenger {
12
+ private readonly active: Messenger[] = [];
13
+ private readonly activityQueues = new Map<string, Promise<void>>();
14
+ private readonly thinkingMessages = new Set<string>();
15
+ private started = false;
16
+
17
+ constructor(private readonly adapters: Partial<Record<Platform, Messenger>>) {
18
+ if (!Object.keys(adapters).length) throw new Error("At least one messenger is required");
19
+ }
20
+
21
+ private adapter(route: Route): Messenger {
22
+ const adapter = this.adapters[route.platform];
23
+ if (!adapter) throw new DeliveryError(`Messenger ${route.platform} is not configured`, "rejected");
24
+ return adapter;
25
+ }
26
+
27
+ async start(handlers: Parameters<Messenger["start"]>[0]): Promise<void> {
28
+ if (this.active.length) throw new Error("Messenger hub is already started");
29
+ try {
30
+ for (const [platform, adapter] of Object.entries(this.adapters) as [Platform, Messenger][]) {
31
+ this.active.push(adapter);
32
+ await adapter.start({
33
+ ready: handlers.ready,
34
+ message: async input => {
35
+ if (input.route.platform !== platform) throw new Error("Messenger intake crossed platform boundaries");
36
+ await handlers.message(input);
37
+ },
38
+ answer: async (approvalId, response, route) => {
39
+ if (route.platform !== platform) throw new Error("Messenger approval crossed platform boundaries");
40
+ await handlers.answer(approvalId, response, route);
41
+ },
42
+ reconnect: async () => {
43
+ if (this.started) await handlers.reconnect?.();
44
+ },
45
+ });
46
+ }
47
+ this.started = true;
48
+ } catch (error) {
49
+ await this.stop().catch(() => {});
50
+ throw error;
51
+ }
52
+ }
53
+
54
+ send(output: OutputRecord): Promise<string> {
55
+ return this.adapter(output.route).send(output);
56
+ }
57
+ async setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
58
+ const key = JSON.stringify([physicalRouteKey(message.route), message.messageId]);
59
+ const apply = async () => {
60
+ // An edit is fresh ingress, but Telegram's single reaction must stay thinking.
61
+ if (activity === "received" && this.thinkingMessages.has(key)) return;
62
+ if (activity === "thinking") this.thinkingMessages.add(key);
63
+ else if (activity === "idle") this.thinkingMessages.delete(key);
64
+ await this.adapter(message.route).setActivity?.(message, activity);
65
+ };
66
+ const previous = this.activityQueues.get(key);
67
+ // A later state is independent of an earlier failed cosmetic operation.
68
+ const operation = previous ? previous.then(apply, apply) : apply();
69
+ this.activityQueues.set(key, operation);
70
+ try { await operation; }
71
+ finally { if (this.activityQueues.get(key) === operation) this.activityQueues.delete(key); }
72
+ }
73
+ showApproval(approval: Approval): Promise<string> {
74
+ return this.adapter(approval.route).showApproval(approval);
75
+ }
76
+ dismissApproval(approval: Approval): Promise<void> {
77
+ return this.adapter(approval.route).dismissApproval(approval);
78
+ }
79
+ canCreateThread(route: Route, appliedTags?: readonly string[]): Promise<boolean> {
80
+ if (appliedTags !== undefined && route.platform !== "discord") throw new DeliveryError("Forum tags are only supported on Discord", "rejected");
81
+ return this.adapter(route).canCreateThread?.(route, appliedTags) ?? Promise.resolve(false);
82
+ }
83
+ createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route> {
84
+ if (appliedTags !== undefined && route.platform !== "discord") throw new DeliveryError("Forum tags are only supported on Discord", "rejected");
85
+ return this.adapter(route).createThread(route, title, sourceMessageId, appliedTags);
86
+ }
87
+ inspectThread(route: Route): Promise<ThreadInfo> {
88
+ const adapter = this.adapter(route);
89
+ if (!adapter.inspectThread) throw new DeliveryError("Thread inspection is unsupported on this transport", "rejected");
90
+ return adapter.inspectThread(route);
91
+ }
92
+ updateThread(route: Route, update: ThreadUpdate): Promise<ThreadInfo> {
93
+ const adapter = this.adapter(route);
94
+ if (!adapter.updateThread) throw new DeliveryError("Thread management is unsupported on this transport", "rejected");
95
+ return adapter.updateThread(route, update);
96
+ }
97
+ inspectDiscordContext(route: Route): Promise<DiscordContext> {
98
+ const adapter = this.adapter(route);
99
+ if (!adapter.inspectDiscordContext) throw new DeliveryError("Discord context inspection is unsupported", "rejected");
100
+ return adapter.inspectDiscordContext(route);
101
+ }
102
+ discordPurpose(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> {
103
+ const adapter = this.adapter(request.route);
104
+ if (!adapter.discordPurpose) throw new DeliveryError("Discord purpose notes are unsupported", "rejected");
105
+ return adapter.discordPurpose(request);
106
+ }
107
+ fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null> {
108
+ return this.adapter(route).fetchAfter(route, messageId);
109
+ }
110
+ openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
111
+ return this.adapter(route).openAttachment(route, attachment, signal);
112
+ }
113
+ async stop(): Promise<void> {
114
+ this.started = false;
115
+ await Promise.allSettled(this.activityQueues.values());
116
+ const stopped = await Promise.allSettled(this.active.splice(0).reverse().map(adapter => adapter.stop()));
117
+ const failed = stopped.filter((result): result is PromiseRejectedResult => result.status === "rejected");
118
+ if (failed.length) throw new AggregateError(failed.map(result => result.reason), "Messenger shutdown failed");
119
+ }
120
+ }
121
+
122
+ export function createMessenger(config: Config, store: Pick<StorePort, "getMeta" | "setMeta">, onError: (error: unknown) => void): MessengerHub {
123
+ requireMessengerCredentials(config);
124
+ const adapters: Partial<Record<Platform, Messenger>> = {};
125
+ if (config.discord) {
126
+ const keyName = voiceApiKeyEnv(config);
127
+ const key = keyName && process.env[keyName];
128
+ // Different variable names can still contain the same secret. Never use a
129
+ // configured transport token as a bearer credential on the OpenAI socket.
130
+ const shared = key && credentialEnvNames(config).some(name => name !== keyName && process.env[name] === key);
131
+ adapters.discord = new DiscordMessenger({
132
+ ...config.discord, token: process.env[config.discord.tokenEnv]!, voiceApiKey: shared ? undefined : key, store, onError,
133
+ });
134
+ }
135
+ if (config.telegram) adapters.telegram = new TelegramMessenger({
136
+ ...config.telegram, token: process.env[config.telegram.tokenEnv]!, store, onError,
137
+ });
138
+ if (config.slack) adapters.slack = new SlackMessenger({
139
+ ...config.slack, botToken: process.env[config.slack.botTokenEnv]!,
140
+ appToken: process.env[config.slack.appTokenEnv]!, onError,
141
+ });
142
+ return new MessengerHub(adapters);
143
+ }