omp-superagent 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/DESIGN.md +36 -20
  2. package/README.ko.md +140 -33
  3. package/README.md +165 -41
  4. package/THIRD_PARTY_NOTICES.md +9 -7
  5. package/config.example.json +3 -1
  6. package/docs/OPERATIONS.md +395 -157
  7. package/docs/design/execution.md +156 -22
  8. package/docs/design/messaging.md +258 -52
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.7.md +25 -0
  11. package/docs/releases/0.1.8.md +21 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  17. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  19. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  20. package/package.json +9 -9
  21. package/scripts/ci.ts +4 -4
  22. package/scripts/test-omp.sh +2 -1
  23. package/skills/head/SKILL.md +26 -5
  24. package/skills/head/references/routing.md +68 -33
  25. package/skills/head/references/supervision.md +20 -4
  26. package/skills/lane/references/workflow.md +16 -7
  27. package/src/board.ts +5 -3
  28. package/src/cli.ts +161 -19
  29. package/src/config.ts +21 -1
  30. package/src/contracts.ts +63 -8
  31. package/src/cron-jobs.ts +443 -19
  32. package/src/cron-pr-intake.ts +257 -0
  33. package/src/discord-markdown.ts +350 -123
  34. package/src/extension.ts +78 -13
  35. package/src/gateway-client.ts +8 -2
  36. package/src/head-quota.ts +80 -0
  37. package/src/head-recovery.ts +40 -1
  38. package/src/host-extension.ts +122 -4
  39. package/src/host-inventory-manifest.ts +2 -2
  40. package/src/host-protocol.ts +11 -0
  41. package/src/host-sdk-helper.ts +121 -12
  42. package/src/host.ts +175 -57
  43. package/src/installed-omp.ts +116 -4
  44. package/src/lane-rows.ts +44 -4
  45. package/src/lane-watch.ts +339 -0
  46. package/src/managed-memory-helper.ts +13 -10
  47. package/src/managed-memory.ts +62 -27
  48. package/src/managed-ulw-probe.ts +75 -20
  49. package/src/managed-ulw.ts +174 -21
  50. package/src/messenger-command-catalog.json +2 -2
  51. package/src/native-launch-profile.ts +4 -2
  52. package/src/native-presets.ts +32 -5
  53. package/src/native-sessions.ts +3 -1
  54. package/src/native-settings.ts +47 -9
  55. package/src/observation-request.ts +23 -0
  56. package/src/omp-usage.ts +254 -36
  57. package/src/pr-github-schema.ts +5 -1
  58. package/src/pr-github.ts +68 -19
  59. package/src/pr-intake-automation.ts +316 -0
  60. package/src/pr-intake-comment.ts +226 -0
  61. package/src/pr-intake-fix.ts +233 -0
  62. package/src/pr-intake-github.ts +480 -0
  63. package/src/pr-intake-material.ts +230 -0
  64. package/src/pr-intake-mode.ts +59 -0
  65. package/src/pr-intake-review.ts +397 -0
  66. package/src/pr-intake-tree.ts +69 -0
  67. package/src/pr-intake-work.ts +29 -0
  68. package/src/pr-watch.ts +91 -32
  69. package/src/runtime.ts +2702 -391
  70. package/src/setup-judge.ts +1 -1
  71. package/src/setup.ts +12 -16
  72. package/src/store.ts +429 -86
  73. package/src/topic-history.ts +243 -47
  74. package/src/worker-checkout.ts +106 -0
  75. package/src/worker-destination.ts +10 -0
  76. package/src/worker-doctor.ts +66 -0
  77. package/src/worker-enrollment.ts +165 -0
  78. package/src/worker-host.ts +180 -0
  79. package/src/worker-ledger.ts +188 -0
  80. package/src/worker-placement.ts +78 -0
  81. package/src/worker-profile.ts +274 -0
  82. package/src/worker-registration.ts +288 -0
  83. package/src/worker-repository.ts +233 -0
  84. package/src/worker-request.ts +74 -0
  85. package/src/worker-service.ts +230 -0
  86. package/src/worker-stdio.ts +61 -0
  87. package/src/worker-trust.ts +36 -0
  88. package/src/worker-wire.ts +204 -0
  89. package/src/workflow.ts +81 -32
  90. package/src/setup-memory.ts +0 -21
@@ -1,6 +1,6 @@
1
1
  import type { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
2
2
  import { Type, type Static } from "@sinclair/typebox";
3
- import { Value } from "@sinclair/typebox/value";
3
+ import { IsStandardObject as isRecord, Value } from "@sinclair/typebox/value";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { credentialEnvNames, type Config } from "./config";
6
6
 
@@ -9,59 +9,94 @@ const nativeScope = {
9
9
  Type.Literal("overlay"), Type.Literal("env"), Type.Literal("runtime")]),
10
10
  agentDir: Type.String(),
11
11
  };
12
- const enabledMemory = Type.Object({ ...nativeScope, status: Type.Literal("enabled"), backend: Type.Literal("mnemopi") });
13
- const missingMemory = Type.Object({
12
+ const enabledMemory = Type.Object({
14
13
  ...nativeScope,
15
- status: Type.Literal("missing"),
16
- backend: Type.Union([Type.Literal("off"), Type.Literal("local"), Type.Literal("hindsight"),
17
- Type.Literal("sharpshooter")]),
14
+ status: Type.Literal("enabled"),
15
+ backend: Type.Union([Type.Literal("local"), Type.Literal("hindsight"), Type.Literal("mnemopi"), Type.Literal("sharpshooter")]),
18
16
  });
17
+ const missingMemory = Type.Object({ ...nativeScope, status: Type.Literal("missing"), backend: Type.Literal("off") });
19
18
  const memoryStatus = Type.Union([enabledMemory, missingMemory, Type.Object({
20
- status: Type.Union([Type.Literal("legacy"), Type.Literal("unknown")]),
19
+ status: Type.Union([Type.Literal("legacy"), Type.Literal("unknown"), Type.Literal("unbound-profile")]),
21
20
  })]);
22
- const overlayUnset = Type.Object({ backend: Type.Null() });
23
21
  const memoryReport = Type.Object({ memory: memoryStatus, updated: Type.Boolean() });
24
- export type MnemopiStatus = Static<typeof memoryStatus>;
25
- export type MnemopiReport = Static<typeof memoryReport>;
22
+ export type ManagedMemoryStatus = Static<typeof memoryStatus>;
23
+ export type ManagedMemoryReport = Static<typeof memoryReport>;
26
24
  type GlobalMemoryCandidate = Static<typeof missingMemory> & { source: "default" | "global" };
27
25
 
28
- export async function effectiveMnemopi(settings: Settings): Promise<MnemopiStatus> {
26
+ export async function effectiveManagedMemory(settings: Settings, writeAgentDir: string | null): Promise<ManagedMemoryStatus> {
29
27
  const { cfgMemoryBackend } = await import("@oh-my-pi/pi-coding-agent/memory-backend/settings");
28
+ // The SDK reads an unrecognized selector as its default. It may belong to a newer CLI;
29
+ // never replace that explicit choice as if the operator had selected "off".
30
+ const configured = settings.rawValue(cfgMemoryBackend);
31
+ if (configured !== undefined && !cfgMemoryBackend.accepts(configured)) return { status: "unknown" };
30
32
  // The RPC soft pin uses this setting's own schema default when unconfigured.
31
33
  // Do not write a runtime override to the read-only snapshot used for consent.
32
34
  const backend = cfgMemoryBackend.get(settings);
33
35
  const agentDir = settings.getAgentDir();
34
36
  let source = cfgMemoryBackend.provenance(settings);
35
37
  if (source === "default") {
36
- // Stock provenance describes the value, not an explicit overlay tombstone.
37
- // An overlay unset must not make setup offer an ineffectual global edit.
38
- const { memory } = settings.mirrorState().configOverlay;
39
- if (memory === null || Value.Check(overlayUnset, memory)) {
40
- source = "overlay";
41
- } else {
38
+ // Native provenance reports the default for a masked selector as well as an
39
+ // absent one. Inspect the native layers before authorizing a global edit.
40
+ const { overrides, configOverlay, project, global } = settings.mirrorState();
41
+ for (const [owner, layer] of [
42
+ ["runtime", overrides], ["overlay", configOverlay], ["project", project], ["global", global],
43
+ ] as const) {
44
+ const section = layer.memory;
45
+ if (section === undefined) continue;
46
+ if (section !== null && !isRecord(section)) return { status: "unknown" };
47
+ if (owner !== "global" && (section === null || section.backend === null)) {
48
+ source = owner;
49
+ break;
50
+ }
51
+ }
52
+ if (source === "default") {
42
53
  const { hasUnresolvedNativeLegacy } = await import("./native-settings");
43
54
  if (await hasUnresolvedNativeLegacy(agentDir)) return { status: "legacy" };
44
55
  }
45
56
  }
46
- return backend === "mnemopi" ? { status: "enabled", backend, source, agentDir }
47
- : { status: "missing", backend, source, agentDir };
57
+ if (backend !== "off") return { status: "enabled", backend, source, agentDir };
58
+ if (source === "default" || source === "global") {
59
+ if (agentDir !== writeAgentDir) return { status: "unbound-profile" };
60
+ const { hasUnresolvedNativeProjectSettings } = await import("./native-settings");
61
+ if (await hasUnresolvedNativeProjectSettings(settings)) return { status: "unknown" };
62
+ }
63
+ return { status: "missing", backend, source, agentDir };
48
64
  }
49
65
 
50
- export function canEnableGlobalMemory(memory: MnemopiStatus): memory is GlobalMemoryCandidate {
66
+ export function canEnableGlobalMemory(memory: ManagedMemoryStatus): memory is GlobalMemoryCandidate {
51
67
  return memory.status === "missing" && (memory.source === "default" || memory.source === "global");
52
68
  }
53
69
 
54
- export function parseMemoryConsent(bytes: string): MnemopiStatus {
70
+ /** Setup binds the edit to the profile shown before final save; startup uses its launch profile. */
71
+ export async function ensureManagedMemory(settings: Settings, writeAgentDir: string | null, expected?: GlobalMemoryCandidate): Promise<ManagedMemoryReport> {
72
+ try {
73
+ const current = await effectiveManagedMemory(settings, writeAgentDir);
74
+ if (!canEnableGlobalMemory(current) || (expected && !Bun.deepEquals(current, expected))) {
75
+ return { memory: current, updated: false };
76
+ }
77
+ const { editNativeGlobalConfig, readNativeSettings } = await import("./native-settings");
78
+ const [updated] = await editNativeGlobalConfig(settings, [{ path: "memory.backend", value: "mnemopi" }],
79
+ async actual => Bun.deepEquals(await effectiveManagedMemory(actual, writeAgentDir), current));
80
+ // A concurrent edit may have selected another usable backend or disabled this workspace.
81
+ return { memory: await effectiveManagedMemory(await readNativeSettings(settings), writeAgentDir), updated: updated === true };
82
+ } catch {
83
+ // Native parse or lock errors can contain private settings.
84
+ return { memory: { status: "unknown" }, updated: false };
85
+ }
86
+ }
87
+
88
+ export function parseMemoryConsent(bytes: string): GlobalMemoryCandidate {
55
89
  const value: unknown = JSON.parse(bytes);
56
90
  if (!Value.Check(memoryStatus, value) || !canEnableGlobalMemory(value))
57
91
  throw new Error("Expected consent to repair the current global memory preference");
58
92
  return value;
59
93
  }
60
94
 
61
- export function memoryBlockReason(memory: MnemopiStatus): string {
62
- const requirement = "Managed sessions require effective native OMP Mnemopi (memory.backend=mnemopi).";
95
+ export function memoryBlockReason(memory: ManagedMemoryStatus): string {
96
+ const requirement = "Managed sessions require an enabled native OMP memory backend.";
63
97
  switch (memory.status) {
64
98
  case "enabled": return "";
99
+ case "unbound-profile": return `${requirement} Automatic configuration is limited to the operator's launch profile. Enable memory in the effective profile or select it explicitly at launch.`;
65
100
  case "unknown": return `${requirement} Native memory settings could not be verified; inspect the selected profile and launch overlays.`;
66
101
  case "legacy": return `${requirement} Unmigrated native settings could not be verified; migrate them with ordinary stock OMP in the selected profile first.`;
67
102
  case "missing": return `${requirement} Effective backend is ${memory.backend} (${memory.source} settings). ${
@@ -70,19 +105,19 @@ export function memoryBlockReason(memory: MnemopiStatus): string {
70
105
  }
71
106
  }
72
107
 
73
- export async function inspectManagedMnemopi(config: Config): Promise<MnemopiStatus> {
108
+ export async function inspectManagedMemory(config: Config): Promise<ManagedMemoryStatus> {
74
109
  return (await runMemoryHelper(config)).memory;
75
110
  }
76
111
 
77
- export function applyConsentedMnemopi(config: Config, consent: GlobalMemoryCandidate): Promise<MnemopiReport> {
112
+ export function applyConsentedMnemopi(config: Config, consent: GlobalMemoryCandidate): Promise<ManagedMemoryReport> {
78
113
  return runMemoryHelper(config, consent);
79
114
  }
80
115
 
81
- async function runMemoryHelper(config: Config, consent?: GlobalMemoryCandidate): Promise<MnemopiReport> {
116
+ async function runMemoryHelper(config: Config, consent?: GlobalMemoryCandidate): Promise<ManagedMemoryReport> {
82
117
  const env = { ...process.env };
83
118
  for (const name of credentialEnvNames(config)) delete env[name];
84
119
  const helper = fileURLToPath(new URL("./managed-memory-helper.ts", import.meta.url));
85
- const unavailable: MnemopiReport = { memory: { status: "unknown" }, updated: false };
120
+ const unavailable: ManagedMemoryReport = { memory: { status: "unknown" }, updated: false };
86
121
  try {
87
122
  const operation = consent ? "apply-consented" : "inspect";
88
123
  const child = Bun.spawn([process.execPath, "--no-env-file", "--no-install", helper, operation, ...config.command.slice(1)], {
@@ -6,20 +6,39 @@ import { getBundledModel, getBundledProviders } from "@oh-my-pi/pi-catalog";
6
6
  import { ModelRegistry, Settings, AuthStorage, SessionManager, createAgentSession } from "@oh-my-pi/pi-coding-agent";
7
7
  import { ExtensionRunner } from "@oh-my-pi/pi-coding-agent/extensibility/extensions/runner";
8
8
  import { listPackageExtensionModules, loadExtensions } from "@oh-my-pi/pi-coding-agent/extensibility/extensions/loader";
9
+ import { buildAvailableSlashCommands } from "@oh-my-pi/pi-coding-agent/slash-commands/available-commands";
9
10
  import { buildSystemPrompt } from "@oh-my-pi/pi-coding-agent/system-prompt";
11
+ import { WORKFLOW_NAMES } from "./contracts";
12
+ import { readManagedUlwPackage } from "./managed-ulw";
13
+ import { advertisedWorkflow } from "./workflow";
10
14
 
11
- const packagePath = process.argv[2];
12
- if (!packagePath) throw new Error("Managed ULW probe requires a package path");
15
+ const packageArg = process.argv[2];
16
+ if (!packageArg) throw new Error("Managed Superkit probe requires a package path");
17
+ const { packagePath, extensionFiles } = readManagedUlwPackage(packageArg);
13
18
  const home = process.env.HOME;
14
19
  const agentDir = process.env.PI_CODING_AGENT_DIR;
15
20
  assert(home && agentDir && resolve(dirname(agentDir)) === resolve(home) && resolve(process.cwd()) === resolve(home),
16
- "Managed ULW probe requires the updater's isolated HOME, agent directory and working directory");
21
+ "Managed Superkit probe requires the updater's isolated HOME, agent directory and working directory");
17
22
  let networkAttempts = 0;
18
- const refuseNetwork = () => { networkAttempts++; throw new Error("Managed ULW probe forbids network and provider calls"); };
23
+ const refuseNetwork = () => { networkAttempts++; throw new Error("Managed Superkit probe forbids network and provider calls"); };
19
24
  globalThis.fetch = Object.assign(async () => refuseNetwork(), { preconnect: refuseNetwork });
20
25
 
26
+ // Public command names changed; installed skill IDs (also legacy commands,
27
+ // except ultrawork) and the prompt/journal protocol did not.
28
+ const workflows = [
29
+ ["super-plan", "ulw-plan"],
30
+ ["super-run", "ulw-execute"],
31
+ ["super-loop", "ulw-loop"],
32
+ ["super-graph", "mass-ulw"],
33
+ ["super-research", "ulw-research"],
34
+ ] as const;
35
+ const skillPath = (id: string) => join(packagePath, "skills", id, "SKILL.md");
36
+ const directive = /<ultrawork-mode>([\s\S]*?)<\/ultrawork-mode>/.exec(await readFile(skillPath("ultrawork"), "utf8"))?.[1];
37
+ assert(directive?.trim(), "Managed Superkit must ship a directive in its installed ultrawork skill");
38
+
21
39
  const modules = await listPackageExtensionModules([packagePath], process.cwd(), { plugins: false });
22
- if (!modules.length) throw new Error("Managed ULW has no discoverable extension");
40
+ assert.deepEqual(await Promise.all(modules.map(module => realpath(module.path))), extensionFiles,
41
+ "Native OMP discovery must resolve exactly the advertised managed Superkit modules");
23
42
  // Use the same supported identity as the native composition fixture, but take
24
43
  // every model field from the declared published catalog rather than inventing a provider.
25
44
  const model = getBundledModel("xai", "grok-4.5");
@@ -36,8 +55,9 @@ const authStorage = await AuthStorage.create(":memory:");
36
55
  try {
37
56
  const sessionManager = SessionManager.inMemory(home);
38
57
  const loaded = await loadExtensions(modules.map(module => module.path), home);
39
- assert.deepEqual(loaded.errors, [], "Native OMP rejected managed ULW");
40
- assert.equal(loaded.extensions.length, modules.length, "Native OMP must load every advertised extension");
58
+ assert.deepEqual(loaded.errors, [], "Native OMP rejected managed Superkit");
59
+ assert.deepEqual(await Promise.all(loaded.extensions.map(extension => realpath(extension.resolvedPath))), extensionFiles,
60
+ "Native OMP must load every advertised managed Superkit extension");
41
61
  // Render the published SDK's bundled template in the isolated HOME without
42
62
  // tools, memory backend, SDK Agent, services, or provider/model execution.
43
63
  const { systemPrompt: nativeBase } = await buildSystemPrompt({
@@ -49,7 +69,7 @@ try {
49
69
  new ModelRegistry(authStorage, join(home, "models.yml"), { settings }), undefined, settings);
50
70
  const errors: unknown[] = [];
51
71
  const refuseEffect = (): never => {
52
- const error = new Error("Managed ULW prompt probe forbids agent, tool, service and session-control effects");
72
+ const error = new Error("Managed Superkit prompt probe forbids agent, tool, service and session-control effects");
53
73
  errors.push(error);
54
74
  throw error;
55
75
  };
@@ -88,22 +108,33 @@ try {
88
108
  assert.match(preset, /Grok 4\.5/, "Supported model-specific instructions must actually be selected");
89
109
  assert(!text.includes(nativeRole), "Model preset did not replace the native role");
90
110
  assert.equal(occurrences(text, "<omp-ulw-policy>"), workflow ? 1 : 0,
91
- workflow ? "Expected exactly one explicitly activated ULW policy" : "Model-profile loading must not activate ULW");
111
+ workflow ? "Expected exactly one explicitly activated SUPER policy" : "Ordinary or quoted text must not activate SUPER policy");
92
112
  assert.equal(occurrences(text, "</omp-ulw-policy>"), workflow ? 1 : 0);
93
113
  if (workflow) {
94
114
  const policy = /<omp-ulw-policy>\s*<ultrawork-mode>([\s\S]*?)<\/ultrawork-mode>\s*<\/omp-ulw-policy>/.exec(text)?.[1];
95
- assert(policy && policy.trim().length > 200, "Activated ULW policy must contain the workflow directive");
115
+ assert(policy && policy.trim().length > 200, "Activated SUPER policy must contain the workflow directive");
116
+ assert.equal(policy, directive, "Activated SUPER policy must use the installed ultrawork directive");
96
117
  assert(!nativeBase.join("\n\n").includes(policy), "Workflow policy must come from the candidate hook");
97
118
  }
98
- assert.deepEqual(errors, [], "Managed ULW native hooks failed");
119
+ assert.deepEqual(errors, [], "Managed Superkit native hooks failed");
99
120
  assert.equal(networkAttempts, 0);
100
121
  };
101
- const compose = async (prompt: string, base: string[], workflow: boolean) => {
122
+ const compose = async (prompt: string, base: string[], workflow: boolean, selected?: typeof workflows[number]) => {
102
123
  currentSystemPrompt = [...base];
103
124
  const result = await runner.emitBeforeAgentStart(prompt, undefined, [...base]);
104
125
  const blocks = result?.systemPrompt ?? base;
105
126
  currentSystemPrompt = blocks;
106
127
  check(blocks, workflow);
128
+ const pointers = (result?.messages ?? []).flatMap(message =>
129
+ typeof message === "object" && "customType" in message && message.customType === "omo-ultrawork:directive" ? [message] : []);
130
+ assert.equal(pointers.length, selected ? 1 : 0, "Only an explicitly selected specialized SUPER invocation may add a workflow directive");
131
+ if (selected) {
132
+ const [command, skill] = selected;
133
+ const content = pointers[0]?.content;
134
+ assert(typeof content === "string" && content.startsWith(`<omp-${skill}-pointer>`) && content.endsWith(`</omp-${skill}-pointer>`)
135
+ && content.includes(command) && content.includes(skillPath(skill)),
136
+ `SUPER command /${command} must point to its installed ${skill} skill`);
137
+ }
107
138
  return blocks;
108
139
  };
109
140
  // Fresh turns and recomposition must both retain exactly one preset. No
@@ -112,11 +143,21 @@ try {
112
143
  for (let turn = 0; turn < 2; turn++) {
113
144
  await compose(ordinary, await compose(ordinary, nativeBase, false), false);
114
145
  }
115
- assert.deepEqual(sessionManager.getBranch(), initialBranch, "Ordinary profile loading must not arm workflow state");
116
- const activated = `ulw ${ordinary}`;
146
+ await compose(`> /super-plan Do not run the quoted task.\n${ordinary}`, nativeBase, false);
147
+ assert.deepEqual(sessionManager.getBranch(), initialBranch, "Ordinary or quoted input must not arm workflow state");
148
+ // Graph selects its specialized workflow without arming plain SUPER.
149
+ await compose(`/super-graph ${ordinary}`, nativeBase, false, ["super-graph", "mass-ulw"]);
150
+ assert.deepEqual(sessionManager.getBranch(), initialBranch, "SUPER graph selection must not arm plain SUPER state");
117
151
  for (let turn = 0; turn < 2; turn++) {
152
+ const activated = `${turn === 0 ? "super" : "/super"} ${ordinary}`;
118
153
  await compose(activated, await compose(activated, nativeBase, true), true);
119
154
  }
155
+ assert.deepEqual(sessionManager.getBranch().slice(initialBranch.length).flatMap(entry =>
156
+ entry.type === "custom" && entry.customType === "omo-ultrawork:state" ? [entry.data] : []), [true],
157
+ "Plain SUPER must arm exactly once under the existing native journal type");
158
+ for (const selection of workflows) {
159
+ await compose(`${selection[0]} ${ordinary}`, nativeBase, true, selection);
160
+ }
120
161
  assert(sessionManager.getBranch().every(entry => entry.type !== "message"),
121
162
  "Workflow activation inspection must not create user/model messages");
122
163
  // An independent, unstarted SDK session proves native tools and skill://
@@ -132,16 +173,30 @@ try {
132
173
  });
133
174
  const resourceReads: string[] = [];
134
175
  try {
135
- assert.deepEqual(extensionsResult.errors, [], "Published SDK rejected managed ULW resources");
176
+ assert.deepEqual(extensionsResult.errors, [], "Published SDK rejected managed Superkit resources");
136
177
  assert.deepEqual(extensionsResult.extensions.filter(extension => !extension.path.startsWith("<inline-"))
137
178
  .map(extension => extension.resolvedPath), loaded.extensions.map(extension => extension.resolvedPath),
138
179
  "Resource inspection must load exactly the candidate modules, apart from SDK-owned inline factories");
180
+ // Use the same native catalog as get_available_commands. A matching file
181
+ // template or an extension with a mismatched descriptor is not routable.
182
+ const commands = await buildAvailableSlashCommands(resources);
183
+ for (const name of WORKFLOW_NAMES) {
184
+ if (name !== "jevify") assert(advertisedWorkflow({ commands }, name),
185
+ `Managed Superkit extension command /${name} is not advertised with its canonical descriptor`);
186
+ }
187
+ for (const name of ["ulw", ...workflows.map(([, skill]) => skill)]) {
188
+ assert(commands.some(command => command.name === name && command.source === "extension"),
189
+ `Managed Superkit legacy extension alias /${name} was not registered`);
190
+ }
139
191
  assert(resources.getEnabledToolNames().includes("read"), "Native read must remain available");
140
192
  assert(resources.getEnabledToolNames().includes("task"), "Native task must remain available");
141
- const root = await realpath(packagePath);
142
- const skills = resources.skills.filter(skill => skill.filePath.startsWith(root + "/"));
143
- assert(skills.length, "Managed ULW must expose its actual skills through native discovery");
144
- const read = resources.getToolByName("read")!;
193
+ const skills = resources.skills.filter(skill => skill.filePath.startsWith(packagePath + "/"));
194
+ for (const id of ["ultrawork", ...workflows.map(([, skill]) => skill)]) {
195
+ assert.equal(skills.find(skill => skill.name === id)?.filePath, skillPath(id),
196
+ `Native Superkit skill discovery must retain skill://${id} and its installed path`);
197
+ }
198
+ const read = resources.getToolByName("read");
199
+ assert(read, "Native read tool must be resolvable");
145
200
  for (const skill of skills) {
146
201
  const uri = `skill://${skill.name}:raw`;
147
202
  const output = await read.execute(`managed-ulw-resource-${resourceReads.length}`, { path: uri });
@@ -161,7 +216,7 @@ try {
161
216
  } finally {
162
217
  try {
163
218
  await runner.emit({ type: "session_shutdown" });
164
- assert.deepEqual(errors, [], "Managed ULW native hooks failed");
219
+ assert.deepEqual(errors, [], "Managed Superkit native hooks failed");
165
220
  assert.equal(networkAttempts, 0);
166
221
  } finally {
167
222
  runner.clearManagedTimers();
@@ -3,6 +3,7 @@ import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
3
  import { chmod, link, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { dirname, isAbsolute, join, resolve, sep } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import type { WorkerHostProfile } from "./worker-profile";
6
7
 
7
8
  const projectRoot = fileURLToPath(new URL("../", import.meta.url));
8
9
  const ownership = "omp-superagent-managed-ulw-v1";
@@ -188,33 +189,174 @@ async function probe(packagePath: string, stage: string, manifest: UlwManifest):
188
189
  home, manifest.probeTimeoutMs, env);
189
190
  }
190
191
 
191
- /** Snapshot native discovery in the exact environment the installed CLI will use. */
192
- export async function managedUlwLaunchExtensions(options: {
192
+ export type ManagedUlwLaunchInput = {
193
193
  cwd: string;
194
194
  managedUlwPath: string;
195
195
  extensionPaths: string[];
196
196
  configPath: string;
197
+ parentConfigPath?: string;
197
198
  /** Native argv prefix retained verbatim by the caller when it replaces the generated Host args. */
198
199
  commandArgs: string[];
199
200
  /** Exact native OMP argv, including the original command's flags and generated Host args; no executable prefix. */
200
201
  launchArgs: string[];
202
+ worker?: Pick<WorkerHostProfile, "extensionPaths">;
203
+ };
204
+ type ManagedUlwLaunchOptions = Omit<ManagedUlwLaunchInput, "managedUlwPath"> & {
205
+ managedUlwPath?: string;
201
206
  env: Record<string, string | undefined>;
202
207
  bunCommand: string[];
203
- }): Promise<{ extensionPaths: string[]; noExtensions: boolean }> {
204
- if (!options.bunCommand.length) throw new Error("Managed ULW discovery requires the launcher's Bun command");
205
- const { env, bunCommand, ...input } = options;
206
- const output = await run([...bunCommand, fileURLToPath(import.meta.url), "--launch-extensions", JSON.stringify(input)],
207
- options.cwd, 30_000, Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)));
208
- const result = output.split("\n").findLast(line => line.startsWith("MANAGED_ULW_LAUNCH "));
209
- if (!result) throw new Error("Stock OMP discovery did not return a launch composition");
210
- return JSON.parse(result.slice("MANAGED_ULW_LAUNCH ".length)) as { extensionPaths: string[]; noExtensions: boolean };
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;
211
241
  }
212
242
 
213
- if (import.meta.main && process.argv[2] === "--launch-extensions") {
214
- const input = JSON.parse(process.argv[3]!) as {
215
- cwd: string; managedUlwPath: string; extensionPaths: string[]; configPath: string;
216
- commandArgs: string[]; launchArgs: string[];
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 }> {
256
+ if (!options.bunCommand.length) throw new Error("Managed ULW discovery requires the launcher's Bun command");
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;
217
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
+ }
329
+ }
330
+
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> {
340
+ const { assertWorkerWorkspaceStartup } = await import("./worker-profile");
341
+ const { homedir } = await import("node:os");
342
+ assertWorkerWorkspaceStartup(input.cwd, homedir());
343
+ const { parseNativeLaunch } = await import("./native-launch-profile");
344
+ const parsed = await parseNativeLaunch(input.launchArgs);
345
+ if (!parsed.noExtensions || !parsed.noLsp)
346
+ throw new Error("Stock worker startup requires explicit extensions and disabled LSP discovery");
347
+ const { Settings } = await import("@oh-my-pi/pi-coding-agent/config/settings");
348
+ const settings = await Settings.loadReadOnly({ cwd: input.cwd, agentDir: parsed.launchAgentDir, configFiles: parsed.config });
349
+ const { effectiveManagedMemory, memoryBlockReason } = await import("./managed-memory");
350
+ const memory = await effectiveManagedMemory(settings, null);
351
+ if (memory.status !== "enabled") throw new Error(memoryBlockReason(memory));
352
+ // Do not enumerate ambient packages/hooks for a worker. The operator pins
353
+ // opt-in modules as files, while managed packages retain their own resources.
354
+ const managed = validateManagedUlwPackage(input.managedUlwPath);
355
+ const extensionPaths = [...new Set([...input.extensionPaths, managed, ...input.worker.extensionPaths])];
356
+ return { extensionPaths, noExtensions: true, memoryWriteDir: null };
357
+ }
358
+
359
+ async function launchComposition(input: ManagedUlwLaunchInput): Promise<ManagedUlwLaunchComposition> {
218
360
  const { parseNativeLaunch } = await import("./native-launch-profile");
219
361
  const parsed = await parseNativeLaunch(input.launchArgs);
220
362
  const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
@@ -240,11 +382,18 @@ if (import.meta.main && process.argv[2] === "--launch-extensions") {
240
382
  const { homedir } = await import("node:os");
241
383
  if (parsed.pluginDirs?.length) await injectPluginDirRoots(homedir(), parsed.pluginDirs, cwd);
242
384
  else await preloadPluginRoots(homedir(), cwd);
243
- const { effectiveMnemopi, memoryBlockReason } = await import("./managed-memory");
385
+ const { ensureManagedMemory, memoryBlockReason } = await import("./managed-memory");
244
386
  const settings = await Settings.loadReadOnly({ cwd, agentDir: getAgentDir(), configFiles: parsed.config })
245
387
  .catch(() => { throw new Error(memoryBlockReason({ status: "unknown" })); });
246
- const memory = await effectiveMnemopi(settings).catch(() => ({ status: "unknown" } as const));
247
- if (memory.status !== "enabled") throw new Error(memoryBlockReason(memory));
388
+ let memoryWriteDir: string | null = parsed.launchAgentDir;
389
+ if (input.parentConfigPath) {
390
+ // A lane inherits its head's post-dotenv environment. It cannot use that
391
+ // environment to enlarge the write authority recorded by the head's launcher.
392
+ const parent: unknown = await Bun.file(join(dirname(input.parentConfigPath), "owner.json")).json().catch(() => null);
393
+ if (!parent || typeof parent !== "object" || !("configPath" in parent) || parent.configPath !== input.parentConfigPath ||
394
+ !("memoryWriteDir" in parent) || parent.memoryWriteDir !== memoryWriteDir) memoryWriteDir = null;
395
+ }
396
+ let composition: { extensionPaths: string[]; noExtensions: boolean };
248
397
  const restore = initializeWithSettings(settings);
249
398
  try {
250
399
  const managed = validateManagedUlwPackage(input.managedUlwPath);
@@ -321,9 +470,7 @@ if (import.meta.main && process.argv[2] === "--launch-extensions") {
321
470
  if (!conflict) {
322
471
  // Ordinary native discovery preserves every native surface, including
323
472
  // TypeScript commands, when no other ULW copy needs exclusion.
324
- console.log(`MANAGED_ULW_LAUNCH ${JSON.stringify({
325
- extensionPaths: [...new Set([...input.extensionPaths, managed])], noExtensions: !!parsed.noExtensions,
326
- })}`);
473
+ composition = { extensionPaths: [...new Set([...input.extensionPaths, managed])], noExtensions: !!parsed.noExtensions };
327
474
  } else {
328
475
  const commands = parsed.noExtensions ? [] : (await discoverCustomCommands({ cwd, agentDir: getAgentDir() })).paths;
329
476
  if (commands.length) {
@@ -357,9 +504,15 @@ if (import.meta.main && process.argv[2] === "--launch-extensions") {
357
504
  throw new Error(`Stock OMP explicit -e would change ${root.level} resource scope to ${actualLevel} scope: ${root.path}`);
358
505
  }
359
506
  }
360
- console.log(`MANAGED_ULW_LAUNCH ${JSON.stringify({ extensionPaths: explicit, noExtensions: true })}`);
507
+ composition = { extensionPaths: explicit, noExtensions: true };
361
508
  }
362
509
  } finally { restore(); }
510
+ // Discovery can refuse an incompatible launch. Do not persist memory for it.
511
+ const { readNativeSettings } = await import("./native-settings");
512
+ const current = await readNativeSettings(settings).catch(() => { throw new Error(memoryBlockReason({ status: "unknown" })); });
513
+ const { memory } = await ensureManagedMemory(current, memoryWriteDir);
514
+ if (memory.status !== "enabled") throw new Error(memoryBlockReason(memory));
515
+ return { ...composition, memoryWriteDir };
363
516
  }
364
517
 
365
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." },
@@ -12,6 +12,6 @@
12
12
  { "name": "model", "description": "Choose a Superagent HEAD model, or inspect or apply a named preset.", "text": "Omit for the menu, or enter list, an exact provider/model, or a preset command." },
13
13
  { "name": "effort", "description": "Choose the Superagent HEAD thinking effort.", "text": "Omit for the menu, or enter an exact advertised effort level." },
14
14
  { "name": "compact", "description": "Compact Superagent HEAD context when idle.", "text": "Optional compaction instructions, including multiple lines." },
15
- { "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": "stop", "description": "Stop Superagent work in this conversation, the shared HEAD, or a named lane.", "text": "Omit for this conversation, or specify head or an exact lane ID." },
16
16
  { "name": "new", "description": "Start a Superagent work topic; use a sibling for a new request in an existing thread.", "text": "An optional first request for the new topic." }
17
17
  ]
@@ -1,9 +1,11 @@
1
1
  /** Stock OMP chooses its profile before settings or discovery import native dotenv. */
2
2
  export async function parseNativeLaunch(launchArgs: readonly string[]) {
3
3
  const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
4
- const { setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
4
+ const { getAgentDir, setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
5
5
  const bootstrap = extractProfileFlags(launchArgs);
6
6
  setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
7
+ // Capture the operator's destination before native launch imports load workspace dotenv.
8
+ const launchAgentDir = getAgentDir();
7
9
  if (bootstrap.aliasName !== undefined) throw new Error("Managed Hosts cannot install native aliases");
8
10
  const { isNativeShell } = await import("@oh-my-pi/pi-coding-agent/cli/native-shell");
9
11
  if (isNativeShell(bootstrap.argv[0])) throw new Error("Managed Hosts require native launch argv, not a shell command");
@@ -12,5 +14,5 @@ export async function parseNativeLaunch(launchArgs: readonly string[]) {
12
14
  if ("error" in resolved) throw new Error(resolved.error);
13
15
  if (resolved.argv[0] !== "launch") throw new Error("Managed Hosts require native OMP launch argv");
14
16
  const { parseArgs } = await import("@oh-my-pi/pi-coding-agent/cli/args");
15
- return parseArgs(resolved.argv.slice(1));
17
+ return { ...parseArgs(resolved.argv.slice(1)), launchAgentDir };
16
18
  }