omp-superagent 0.1.10 → 0.1.13

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 (154) hide show
  1. package/DESIGN.md +71 -15
  2. package/README.ko.md +10 -1
  3. package/README.md +10 -1
  4. package/THIRD_PARTY_NOTICES.md +35 -436
  5. package/assets/architecture-dark.svg +7 -12
  6. package/assets/architecture.ko-dark.svg +7 -12
  7. package/assets/architecture.ko.svg +7 -12
  8. package/assets/architecture.mmd +5 -13
  9. package/assets/architecture.svg +7 -12
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +282 -53
  12. package/docs/OPERATIONS.md +264 -45
  13. package/docs/design/execution.md +80 -52
  14. package/docs/design/messaging.md +113 -32
  15. package/docs/releases/0.1.11.md +20 -0
  16. package/docs/releases/0.1.13.md +13 -0
  17. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  18. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  19. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  21. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  23. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  25. package/package.json +13 -11
  26. package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
  27. package/scripts/upgrade-evidence-files.mjs +100 -0
  28. package/scripts/upgrade-evidence.mjs +192 -0
  29. package/scripts/upgrade-host-wire.mjs +162 -0
  30. package/skills/head/SKILL.md +12 -3
  31. package/skills/head/references/routing.md +1 -1
  32. package/skills/head/references/supervision.md +23 -26
  33. package/skills/lane/SKILL.md +28 -21
  34. package/skills/lane/references/workflow.md +15 -17
  35. package/src/cli.ts +33 -53
  36. package/src/{config.ts → config/config.ts} +7 -3
  37. package/src/config/wake-config.ts +36 -0
  38. package/src/contracts.ts +61 -12
  39. package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
  40. package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
  41. package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
  42. package/src/extension.ts +43 -25
  43. package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
  44. package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
  45. package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
  46. package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
  47. package/src/gateway-config.ts +1 -1
  48. package/src/gateway-restart-env.ts +3 -3
  49. package/src/{group-access.ts → group/group-access.ts} +8 -3
  50. package/src/{group-policy.ts → group/group-policy.ts} +2 -2
  51. package/src/{group-runner.ts → group/group-runner.ts} +11 -6
  52. package/src/host-extension.ts +164 -36
  53. package/src/host-sdk-helper.ts +66 -65
  54. package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
  55. package/src/{decisions.ts → lane/decisions.ts} +12 -10
  56. package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
  57. package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
  58. package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
  59. package/src/{workflow.ts → lane/workflow.ts} +1 -1
  60. package/src/lane-extension.ts +25 -7
  61. package/src/managed-memory-helper.ts +2 -2
  62. package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
  63. package/src/{delivery.ts → messaging/delivery.ts} +1 -1
  64. package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
  65. package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
  66. package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
  67. package/src/messaging/messenger-commands.ts +55 -0
  68. package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
  69. package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
  70. package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
  71. package/src/omp/head-resume.ts +123 -0
  72. package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
  73. package/src/{host-protocol.ts → omp/host-protocol.ts} +10 -2
  74. package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
  75. package/src/{host.ts → omp/host.ts} +26 -17
  76. package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
  77. package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
  78. package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
  79. package/src/omp/native-journal.ts +124 -0
  80. package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
  81. package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
  82. package/src/omp/native-sessions.ts +124 -0
  83. package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
  84. package/src/{soul.ts → omp/soul.ts} +2 -2
  85. package/src/omp/stock-head-launch.ts +31 -0
  86. package/src/{autostart.ts → operator/autostart.ts} +3 -3
  87. package/src/{operator.ts → operator/operator.ts} +2 -2
  88. package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
  89. package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
  90. package/src/{setup.ts → operator/setup.ts} +5 -5
  91. package/src/operator/stop-lane.ts +25 -0
  92. package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
  93. package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
  94. package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
  95. package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
  96. package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
  97. package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
  98. package/src/{message-order.ts → routing/message-order.ts} +1 -1
  99. package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
  100. package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
  101. package/src/{runtime.ts → runtime/controller.ts} +867 -1213
  102. package/src/runtime/deferred-routing.ts +106 -0
  103. package/src/runtime/dm-timeline.ts +194 -0
  104. package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
  105. package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
  106. package/src/runtime/model-journal.ts +119 -0
  107. package/src/runtime/native-frames.ts +131 -0
  108. package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
  109. package/src/runtime/preset-sync.ts +232 -0
  110. package/src/runtime/preset-watch-paths.ts +137 -0
  111. package/src/runtime/result-attachments.ts +146 -0
  112. package/src/storage/deferred-routing.ts +149 -0
  113. package/src/{store.ts → storage/store.ts} +75 -42
  114. package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
  115. package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
  116. package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
  117. package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
  118. package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
  119. package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
  120. package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
  121. package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
  122. package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
  123. package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
  124. package/src/worker-serve-prepare.ts +4 -4
  125. package/src/board-extension.ts +0 -217
  126. package/src/board.ts +0 -467
  127. package/src/gateway-host-helper.ts +0 -13
  128. package/src/messenger-commands.ts +0 -15
  129. package/src/native-sessions.ts +0 -34
  130. /package/src/{credentials.ts → config/credentials.ts} +0 -0
  131. /package/src/{lane-report.ts → lane/lane-report.ts} +0 -0
  132. /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
  133. /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
  134. /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
  135. /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
  136. /package/src/{host-reply-voice.ts → omp/host-reply-voice.ts} +0 -0
  137. /package/src/{host-services.ts → omp/host-services.ts} +0 -0
  138. /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
  139. /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
  140. /package/src/{repository.ts → operator/repository.ts} +0 -0
  141. /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
  142. /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
  143. /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
  144. /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
  145. /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
  146. /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
  147. /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
  148. /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
  149. /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
  150. /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
  151. /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
  152. /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
  153. /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
  154. /package/upstream/{ulw.json → super.json} +0 -0
@@ -1,12 +1,13 @@
1
1
  // Short-lived SDK operations. The Rust owner, not this process, owns native stdin and the reconnectable socket.
2
2
  import { dirname } from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
- import { chmod, rename, writeFile } from "node:fs/promises";
4
+ import { chmod, lstat, rename, writeFile } from "node:fs/promises";
5
5
  import type { RpcAbortAndRestoreQueueResult } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
6
- import type { HostOptions } from "./host";
7
- import type { Frame } from "./host-protocol";
8
- import type { RotationSelection } from "./head-rotation";
9
- import type { ManagedUlwLaunchInput } from "./managed-ulw";
6
+ import type { HostOptions } from "./omp/host";
7
+ import type { RotationSelection } from "./runtime/head-rotation";
8
+ import type { ManagedUlwLaunchComposition, ManagedUlwLaunchInput } from "./omp/managed-super";
9
+ import type { NativeProfile, NativeProfileBinding } from "./omp/native-sessions";
10
+ import { launchArgvHash, stockReplayRefusal } from "./omp/stock-head-launch";
10
11
 
11
12
  type Manifest = {
12
13
  readonly options: Omit<HostOptions, "env">;
@@ -14,57 +15,19 @@ type Manifest = {
14
15
  readonly configPath: string;
15
16
  readonly processBackend: "broker" | "daemon";
16
17
  readonly headRotationSelection?: RotationSelection;
18
+ readonly headHibernationSessionId?: string;
19
+ readonly expectedNativeProfile?: NativeProfile;
17
20
  };
18
- type Exit = {
19
- readonly pid: number; readonly ownerPid: number; readonly code: number | null; readonly signal: string | null;
20
- readonly sessionId: string; readonly instanceKey?: string | null; readonly runOrdinal: number;
21
- readonly workerAttempt?: string | null;
22
- readonly observationFailure: boolean; readonly expectedObservations: readonly [string, Frame][];
23
- };
24
-
25
- async function verifyExit({ options }: Manifest, exit: Exit) {
26
- const { visitEntriesFromFileStream } = await import("@oh-my-pi/pi-coding-agent/session/session-loader");
27
- const expected = new Map(exit.expectedObservations);
28
- const starts = new Set<number>();
29
- let duplicate = false;
30
- let malformed = false;
31
- let header = false;
32
- await visitEntriesFromFileStream(options.sessionFile, entry => {
33
- if (entry.type === "session") { header ||= entry.id === exit.sessionId; return; }
34
- if (entry.type !== "custom" || !entry.data || typeof entry.data !== "object") return;
35
- const data = entry.data as Frame;
36
- if (data.instanceKey !== (exit.instanceKey ?? undefined)) return;
37
- if (entry.customType === "rpc_prompt_result" && expected.has(entry.id) &&
38
- isDeepStrictEqual(data.frame, expected.get(entry.id))) expected.delete(entry.id);
39
- if (entry.customType === "rpc_agent_start" && data.hostPid === exit.pid && typeof data.runOrdinal === "number" &&
40
- Number.isSafeInteger(data.runOrdinal) && data.runOrdinal >= 1 && data.runOrdinal <= exit.runOrdinal) {
41
- duplicate ||= starts.has(data.runOrdinal);
42
- starts.add(data.runOrdinal);
43
- }
44
- }, { throwIfMissing: true, onMalformedRecord: () => { malformed = true; } });
45
- const journal = Bun.file(options.sessionFile);
46
- const size = journal.size;
47
- const persisted = header && !malformed && size > 0 && (await journal.slice(size - 1, size).text()) === "\n";
48
- const observationsFlushed = !exit.observationFailure && !expected.size && !duplicate && starts.size === exit.runOrdinal;
49
- const { pid, ownerPid, sessionId, code, signal } = exit;
50
- const receipt = `${options.socketPath}.exit.json`;
51
- const temporary = `${receipt}.${crypto.randomUUID()}`;
52
- await writeFile(temporary, JSON.stringify({ pid, ownerPid, sessionId, sessionFile: options.sessionFile, code,
53
- ...(exit.workerAttempt ? { workerAttempt: exit.workerAttempt } : {}),
54
- signal, persisted, observationsFlushed }), { mode: 0o600, flag: "wx" });
55
- await rename(temporary, receipt);
56
- if (!persisted || !observationsFlushed) throw new Error("Native exit persistence is unconfirmed");
57
- return { persisted, observationsFlushed };
58
- }
59
21
 
60
- async function run(operation: string | undefined, manifest: Manifest, input: unknown, profileResolved = false) {
22
+ async function run(operation: string | undefined, manifest: Manifest, input: unknown, nativeProfile?: NativeProfile) {
61
23
  const { options } = manifest;
62
24
  const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
63
- const bootstrap = extractProfileFlags([...options.command.slice(1), ...manifest.args]);
25
+ const launchArgs = [...options.command.slice(1), ...manifest.args];
26
+ const bootstrap = extractProfileFlags(launchArgs);
64
27
  // Native discovery already selected the profile and applied dotenv.
65
28
  // Rebootstrapping now would re-select from the mutated environment or
66
29
  // clear its effective agent directory before publishing the session.
67
- if (!profileResolved) {
30
+ if (!nativeProfile) {
68
31
  const { setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
69
32
  setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
70
33
  }
@@ -75,8 +38,19 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
75
38
  const argv = resolveCliArgv(bootstrap.argv);
76
39
  if ("error" in argv) throw new Error(argv.error);
77
40
  const parsed = parseArgs(argv.argv.slice(1));
41
+ const emptyToolSelection = parsed.tools?.length === 0;
42
+ const parkedSession = manifest.headHibernationSessionId;
43
+ const { matchesNativeProfile, publishNativeSession, sdkNativeProfilePaths } = await import("./omp/native-sessions");
44
+ const requireNativeProfile = () => {
45
+ const expected = manifest.expectedNativeProfile;
46
+ if ((nativeProfile && !matchesNativeProfile(sdkNativeProfilePaths(), nativeProfile))
47
+ || (expected !== undefined && !isDeepStrictEqual(nativeProfile, expected))
48
+ || (parkedSession !== undefined && expected === undefined))
49
+ throw new Error("Native profile changed before journal preparation or publication");
50
+ };
51
+ requireNativeProfile();
78
52
  if (options.prReviewOnly) {
79
- if (parsed.noTools !== true || parsed.tools !== undefined || !parsed.noExtensions ||
53
+ if (parsed.noTools === true || !emptyToolSelection || !parsed.noExtensions ||
80
54
  !parsed.noSkills || !parsed.noRules || !parsed.noContextFiles || !parsed.noLsp ||
81
55
  !parsed.noTitle || !parsed.noPrewalk || !parsed.offline ||
82
56
  parsed.trustedExtensions?.length !== 1 || parsed.config?.length !== 1 || parsed.config[0] !== manifest.configPath)
@@ -86,7 +60,7 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
86
60
  const { cfgDisabledProviders } = await import("@oh-my-pi/pi-coding-agent/config/model-settings");
87
61
  const { getAllCapabilitiesInfo } = await import("@oh-my-pi/pi-coding-agent/discovery");
88
62
  const { getAllPluginToolPaths } = await import("@oh-my-pi/pi-coding-agent/extensibility/plugins/loader");
89
- const { PR_REVIEW_GITHUB_ENV } = await import("./host-protocol");
63
+ const { PR_REVIEW_GITHUB_ENV } = await import("./omp/host-protocol");
90
64
  if (PR_REVIEW_GITHUB_ENV.some(name => process.env[name]))
91
65
  throw new Error("Static PR review cannot load GitHub credentials from the native profile");
92
66
  const native = await Settings.loadReadOnly({ cwd: options.cwd, agentDir: getAgentDir() });
@@ -105,9 +79,15 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
105
79
  await writeFile(staging, JSON.stringify({ ...overlay, disabledProviders: [...disabled] }), { mode: 0o600, flag: "wx" });
106
80
  await rename(staging, manifest.configPath);
107
81
  }
108
- const { lstat, stat } = await import("node:fs/promises");
82
+ const { stat } = await import("node:fs/promises");
109
83
  const expectedWorkerSession = process.env.OMP_SUPERAGENT_WORKER_EXPECTED_SESSION;
110
- const missing = await (expectedWorkerSession === undefined && !options.prReviewOnly ? stat : lstat)(options.sessionFile).then(async info => {
84
+ const inspect = expectedWorkerSession !== undefined || parkedSession !== undefined || options.prReviewOnly ? lstat : stat;
85
+ const missing = await inspect(options.sessionFile).then(async info => {
86
+ if (parkedSession !== undefined) {
87
+ const { readNativeSessionId } = await import("./omp/native-journal");
88
+ if (!info.isFile() || !parkedSession || await readNativeSessionId(options.sessionFile, info) !== parkedSession)
89
+ throw new Error("HEAD journal no longer matches the hibernated session");
90
+ }
111
91
  if (expectedWorkerSession !== undefined) {
112
92
  const { readSessionHeaderId } = await import("@oh-my-pi/pi-coding-agent/session/session-loader");
113
93
  if (!info.isFile() || !expectedWorkerSession || await readSessionHeaderId(options.sessionFile) !== expectedWorkerSession)
@@ -127,10 +107,12 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
127
107
  return false;
128
108
  }, error => {
129
109
  if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
110
+ if (parkedSession !== undefined) throw new Error("Cannot recreate a missing hibernated HEAD session");
130
111
  if (expectedWorkerSession) throw new Error("Worker cannot recreate a missing reserved session");
131
112
  return true;
132
113
  });
133
114
  if (missing) {
115
+ requireNativeProfile();
134
116
  const { SessionManager } = await import("@oh-my-pi/pi-coding-agent/session/session-manager");
135
117
  const session = SessionManager.create(options.cwd, dirname(options.sessionFile));
136
118
  try {
@@ -139,7 +121,7 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
139
121
  session.appendCustomEntry("superagent_pr_review_policy", { version: 1, cwd: options.cwd });
140
122
  const selection = manifest.headRotationSelection;
141
123
  if (selection) {
142
- session.appendModelChange(`${selection.provider}/${selection.modelId}`);
124
+ session.appendModelChange(selection.modelIdentity ?? `${selection.provider}/${selection.modelId}`);
143
125
  session.appendThinkingLevelChange(selection.thinkingLevel ?? undefined, selection.configuredThinkingLevel ?? undefined);
144
126
  }
145
127
  await session.ensureOnDisk();
@@ -147,19 +129,28 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
147
129
  } finally { await session.close(); }
148
130
  if (options.prReviewOnly) await chmod(options.sessionFile, 0o600);
149
131
  }
132
+ let nativeProfileBinding: NativeProfileBinding | undefined;
150
133
  if (!options.prReviewOnly) {
151
- const { publishNativeSession } = await import("./native-sessions");
152
- await publishNativeSession(options.sessionFile, options.cwd);
134
+ requireNativeProfile();
135
+ const discoveryEntry = await publishNativeSession(options.sessionFile, options.cwd, parkedSession, nativeProfile);
136
+ if (nativeProfile) {
137
+ if (!discoveryEntry) throw new Error("Prepared native session could not be found in discovery");
138
+ nativeProfileBinding = { profile: nativeProfile, discoveryEntry };
139
+ }
153
140
  }
154
- const { hostInventoryManifest } = await import("./host-inventory-manifest");
141
+ const { hostInventoryManifest } = await import("./omp/host-inventory-manifest");
155
142
  return { toolsExplicitlySelected: parsed.tools !== undefined, noTools: parsed.noTools === true,
143
+ nativeProfileBinding,
144
+ replayableArgvHash: argv.argv[0] === "launch" && !stockReplayRefusal(parsed, options.sessionFile)
145
+ ? launchArgvHash(launchArgs) : undefined,
146
+ ...(options.prReviewOnly ? { emptyToolSelection } : {}),
156
147
  inventory: await hostInventoryManifest(manifest.processBackend, options.cwd) };
157
148
  }
158
149
  case "inventory": {
159
150
  const { projectDir, serviceName } = input as { projectDir?: string; serviceName?: string };
160
151
  const list = manifest.processBackend === "broker"
161
- ? (await import("./host-broker-services")).brokerServiceInventory(options.cwd)
162
- : (await import("./host-services")).listServiceUnits;
152
+ ? (await import("./omp/host-broker-services")).brokerServiceInventory(options.cwd)
153
+ : (await import("./omp/host-services")).listServiceUnits;
163
154
  return { units: await list(projectDir ?? undefined, serviceName ?? undefined) };
164
155
  }
165
156
  case "fit": {
@@ -174,7 +165,6 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
174
165
  if (!result.success || result.command !== "abort_and_restore_queue") throw new Error("Cannot fit restored queue");
175
166
  return { ...result, data: { ...result.data, ...flags } };
176
167
  }
177
- case "exit": return verifyExit(manifest, input as Exit);
178
168
  default: throw new Error("Unknown Host SDK operation");
179
169
  }
180
170
  }
@@ -196,11 +186,11 @@ async function launch() {
196
186
  const newline = buffered.indexOf("\n");
197
187
  const input: ManagedUlwLaunchInput | null = JSON.parse(buffered.slice(0, newline));
198
188
  let rest = buffered.slice(newline + 1);
199
- let composition;
189
+ let composition: ManagedUlwLaunchComposition;
200
190
  if (input === null) {
201
191
  composition = { extensionPaths: [], noExtensions: true, memoryWriteDir: null };
202
192
  } else {
203
- const { managedUlwLaunchComposition } = await import("./managed-ulw");
193
+ const { managedUlwLaunchComposition } = await import("./omp/managed-super");
204
194
  try { composition = await managedUlwLaunchComposition(input); }
205
195
  catch (error) {
206
196
  // Discovery refusals name the launch argument or package the operator must change.
@@ -214,17 +204,28 @@ async function launch() {
214
204
  rest += decoder.decode();
215
205
  if (!rest) return;
216
206
  const manifest: Manifest = JSON.parse(rest);
217
- process.stdout.write(JSON.stringify(await run("prepare", manifest, manifest, input !== null && !input.worker)));
207
+ if (input?.expectedNativeProfile && !isDeepStrictEqual(composition.nativeProfile, input.expectedNativeProfile))
208
+ throw new Error("Native HEAD profile differs from the sleeping checkpoint");
209
+ process.stdout.write(JSON.stringify(await run("prepare", manifest, manifest, composition.nativeProfile)));
218
210
  }
219
211
 
220
212
  const [, , operation, path] = process.argv;
221
213
  try {
222
214
  if (operation === "launch") await launch();
215
+ else if (operation === "head-resume-command") {
216
+ const { headResumeCommand } = await import("./omp/head-resume");
217
+ const result = await headResumeCommand(await Bun.stdin.json());
218
+ process.stdout.write(`\nMANAGED_HEAD_RESUME ${JSON.stringify(result)}\n`);
219
+ }
223
220
  else if (operation === "prepare") throw new Error("Session preparation follows launch discovery");
224
- else {
221
+ else if (operation === "inventory" || operation === "fit") {
222
+ if (!path) throw new Error("Host manifest is required");
225
223
  const input = await Bun.stdin.json();
226
- const manifest: Manifest = await Bun.file(path!).json();
224
+ const manifest: Manifest = await Bun.file(path).json();
227
225
  process.stdout.write(JSON.stringify(await run(operation, manifest, input)));
226
+ } else {
227
+ console.error("Unsupported Host SDK operation");
228
+ process.exitCode = 1;
228
229
  }
229
230
  } catch {
230
231
  // SDK errors may contain native frames, authorization data or prompt content.
@@ -1,7 +1,7 @@
1
1
  import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
2
2
  import { Type } from "@sinclair/typebox";
3
3
  import { decisionId } from "./decisions";
4
- import { parseDialog } from "./dialog";
4
+ import { parseDialog } from "../messaging/dialog";
5
5
 
6
6
  /** Structured owner questions use the native host's UI, never a second messenger path. */
7
7
  export function registerDecisionAsk(pi: ExtensionAPI): void {
@@ -22,10 +22,15 @@ export function registerDecisionAsk(pi: ExtensionAPI): void {
22
22
  pi.registerTool({
23
23
  name: "decision_ask", label: "Request a tracked decision", approval: "read", loadMode: "essential",
24
24
  description: (role === "lane"
25
- ? "In topic reply mode, ask only when the owner must decide. In manager handoff mode, HEAD can select routine options within the original assignment; important or unresolved choices go to the owner. A submitted answer does not grant execution approval or expand scope. "
25
+ ? "Use to: \"head\" for an in-scope coordination choice that needs HEAD's answer, even from a work topic. " +
26
+ "Omit to for the normal recipient (topic: owner; manager handoff: HEAD). " +
27
+ "HEAD may select an original option or escalate the same question to the owner. " +
28
+ "On corrective assignments, to: \"head\" is cancelled privately, not sent to the owner. " +
29
+ "An answer never grants execution approval or changes scope. "
26
30
  : "Ask the owner structured questions on this managed session's native UI. ") +
27
- "Returns a stable decision id and the actual submitted answers or cancellation, timeout, or chat state. Recommendations, timeouts and chat are not acceptance. No default answers, timeout, messenger routing, or automatic work resume.",
31
+ "Returns a stable decision id and the actual submitted answers or cancellation, timeout, or chat state. Recommendations, timeouts and chat are not acceptance. No default answers, route override, or automatic work resume.",
28
32
  parameters: Type.Object({
33
+ ...(role === "lane" ? { to: Type.Optional(Type.Literal("head")) } : {}),
29
34
  questions: Type.Array(Type.Object({
30
35
  question: Type.String(),
31
36
  header: Type.Optional(Type.String()),
@@ -40,9 +45,12 @@ export function registerDecisionAsk(pi: ExtensionAPI): void {
40
45
  }, { additionalProperties: false }),
41
46
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
42
47
  if (ctx.agent.kind !== "main") throw new Error(restricted);
48
+ if (params.to !== undefined && (role !== "lane" || params.to !== "head"))
49
+ throw new Error("Only a managed lane can direct a coordination question to HEAD");
43
50
  const id = decisionId(ctx.sessionManager.getSessionId(), toolCallId);
51
+ const prefix = role === "lane" && params.to === "head" ? `${id}:head` : id;
44
52
  const dialog = parseDialog({ method: "ask", questions: Array.isArray(params.questions)
45
- ? params.questions.map((question, index) => ({ ...question, id: `${id}:${index}` })) : params.questions });
53
+ ? params.questions.map((question, index) => ({ ...question, id: `${prefix}:${index}` })) : params.questions });
46
54
  if (dialog.method !== "ask") throw new Error("Expected structured decision questions");
47
55
  if (!ctx.ui.askDialog) throw new Error("Native structured decision UI is unavailable on this host");
48
56
  if (asking) throw new Error("An owner decision dialog is already pending in this native session");
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import type { Approval, ApprovalResolution, DialogResponse, StorePort } from "./contracts";
3
- import { parseDialog, type Question } from "./dialog";
4
- import { DeliveryError } from "./delivery";
2
+ import type { Approval, ApprovalResolution, DialogResponse, StorePort } from "../contracts";
3
+ import { parseDialog, type Question } from "../messaging/dialog";
4
+ import { DeliveryError } from "../messaging/delivery";
5
5
 
6
6
  interface Receipt {
7
7
  approvalId: string;
@@ -36,15 +36,17 @@ export function decisionId(sessionId: string, toolCallId: string): string {
36
36
  }
37
37
 
38
38
  /** Only the managed decision tool's structured questions enter this ledger. */
39
- export function decisionRequestId(request: Record<string, unknown>): string | null {
39
+ export function decisionRequest(request: Record<string, unknown>): { id: string; toHead: boolean } | null {
40
40
  if (request.method !== "ask" || request.secret === true || !Array.isArray(request.questions)) return null;
41
41
  const first = request.questions[0] as { id?: unknown } | undefined;
42
- const id = typeof first?.id === "string" ? /^(d-[a-f0-9]{24}):0$/.exec(first.id)?.[1] : undefined;
43
- if (!id) return null;
42
+ const match = typeof first?.id === "string" ? /^(d-[a-f0-9]{24})(:head)?:0$/.exec(first.id) : null;
43
+ if (!match?.[1]) return null;
44
+ const id = match[1];
45
+ const prefix = id + (match[2] ?? "");
44
46
  const dialog = parseDialog(request);
45
- if (dialog.method !== "ask" || dialog.questions.some((question, index) => question.id !== `${id}:${index}`))
47
+ if (dialog.method !== "ask" || dialog.questions.some((question, index) => question.id !== `${prefix}:${index}`))
46
48
  throw new Error("Decision question identity changed");
47
- return id;
49
+ return { id, toHead: !!match[2] };
48
50
  }
49
51
 
50
52
  const metadataKey = "decisions:v1";
@@ -54,7 +56,7 @@ const receipts = (store: StorePort): Record<string, Receipt> => JSON.parse(store
54
56
  export function captureDecision(store: StorePort, approval: Approval): void {
55
57
  if (!approval.decision) return;
56
58
  const { id } = approval.decision;
57
- if (decisionRequestId(approval.request) !== id) throw new Error("Decision does not match its native questions");
59
+ if (decisionRequest(approval.request)?.id !== id) throw new Error("Decision does not match its native questions");
58
60
  const records = receipts(store);
59
61
  if (records[id]) throw new Error("Decision already has a native request; do not ask it again");
60
62
  records[id] = { approvalId: approval.id, createdAt: Date.now() };
@@ -121,7 +123,7 @@ export function acknowledgeDecision(store: StorePort, approval: Approval, sessio
121
123
  export function decisionViews(store: StorePort): DecisionView[] {
122
124
  return Object.entries(receipts(store)).map(([id, receipt]) => {
123
125
  const approval = store.approval(receipt.approvalId);
124
- if (!approval?.decision || approval.decision.id !== id || decisionRequestId(approval.request) !== id)
126
+ if (!approval?.decision || approval.decision.id !== id || decisionRequest(approval.request)?.id !== id)
125
127
  throw new Error("Decision ledger is not bound to its original native question");
126
128
  const dialog = parseDialog(approval.request);
127
129
  if (dialog.method !== "ask") throw new Error("Decision question is unavailable");
@@ -1,4 +1,4 @@
1
- import type { LaneModel, LaneModelChoice, ModelPreset, LanePresetSnapshot, ResolvedLanePreset } from "./contracts";
1
+ import type { LaneModel, LaneModelChoice, ModelPreset, LanePresetSnapshot, ResolvedLanePreset } from "../contracts";
2
2
 
3
3
  export interface LaneModelCandidate extends LaneModel {
4
4
  name?: string;
@@ -2,8 +2,8 @@ import type { Database } from "bun:sqlite";
2
2
  import { isAbsolute, normalize } from "node:path";
3
3
  import { Type } from "@sinclair/typebox";
4
4
  import { Value } from "@sinclair/typebox/value";
5
- import type { Lane } from "./contracts";
6
- import type { RemotePlacement } from "./worker-wire";
5
+ import type { Lane } from "../contracts";
6
+ import type { RemotePlacement } from "../worker/worker-wire";
7
7
 
8
8
  export interface LaneRow {
9
9
  readonly data: string;
@@ -2,8 +2,8 @@
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { Type, type Static } from "@sinclair/typebox/type";
4
4
  import { Value } from "@sinclair/typebox/value";
5
- import { authorizeRoute, type Config } from "./config";
6
- import { routeKey, type InputRecord, type Lane, type OutputRecord, type Route, type StorePort } from "./contracts";
5
+ import { authorizeRoute, type Config } from "../config/config";
6
+ import { routeKey, type InputRecord, type Lane, type OutputRecord, type Route, type StorePort } from "../contracts";
7
7
 
8
8
  const stateKey = "lane-watch:v1";
9
9
  const noticePrefix = "lane-watch-notice:";
@@ -171,6 +171,10 @@ export class LaneWatcher {
171
171
  }
172
172
  }
173
173
 
174
+ hasScheduledWork(): boolean {
175
+ return this.state().watches.some(watch => this.held(watch) === null);
176
+ }
177
+
174
178
  /** Cross-platform accounts must be authenticated before the durable cursor advances. */
175
179
  async pollCrossPlatform(now: number, proof: CrossPlatformProof): Promise<boolean> {
176
180
  let notified = false;
@@ -1,4 +1,4 @@
1
- import { WORKFLOW_NAMES, type InputRecord, type WorkflowActivation, type WorkflowChoice, type WorkflowName } from "./contracts";
1
+ import { WORKFLOW_NAMES, type InputRecord, type WorkflowActivation, type WorkflowChoice, type WorkflowName } from "../contracts";
2
2
 
3
3
  // Public commands and leading delimiters match omp-superkit ulw.ts at c11a6e4.
4
4
  // Skill paths and persisted native keys are deliberately not public selectors.
@@ -4,9 +4,9 @@ import { resolve } from "node:path";
4
4
  import type { ToolCall, ToolResultMessage } from "@oh-my-pi/pi-ai";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
6
6
  import { type Static, Type } from "@sinclair/typebox";
7
- import { type LaneEvidence, type LaneReportEvent, type ScopeReviewReceipt, parseLaneReportResult } from "./lane-report";
8
- import { registerResultAttach, RESULT_ATTACH_TOOL } from "./result-attachment";
9
- import { registerDecisionAsk } from "./decision-tool";
7
+ import { type LaneEvidence, type LaneReportEvent, type ScopeReviewReceipt, parseLaneReportResult } from "./lane/lane-report";
8
+ import { registerResultAttach, RESULT_ATTACH_TOOL } from "./messaging/result-attachment";
9
+ import { registerDecisionAsk } from "./lane/decision-tool";
10
10
 
11
11
  const instructions = readFileSync(new URL("../skills/lane/SKILL.md", import.meta.url), "utf8");
12
12
  const nonempty = Type.String({ minLength: 1, pattern: "\\S" });
@@ -31,7 +31,9 @@ const parameters = Type.Union([
31
31
  { additionalProperties: false }),
32
32
  Type.Object({ status: Type.Literal("scope_review"), sourceId: nonempty }, { additionalProperties: false }),
33
33
  ]);
34
- const coordinationTool = (name: string) => name === "lane_report" || name === RESULT_ATTACH_TOOL || name.startsWith("board_");
34
+ // Resumed native journals can still contain retired board tools. They were never work evidence.
35
+ const coordinationTool = (name: string) =>
36
+ name === "lane_report" || name === RESULT_ATTACH_TOOL || name === "decision_ask" || name.startsWith("board_");
35
37
  const record = (value: unknown): value is Record<string, unknown> =>
36
38
  value !== null && typeof value === "object" && !Array.isArray(value);
37
39
  const text = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
@@ -117,14 +119,28 @@ function toolEvidence(id: string, records: ReturnType<typeof toolRecords>): Lane
117
119
  if (!call || !result || result.toolName !== call.name || result.isError !== false ||
118
120
  coordinationTool(call.name) || (typeof call.arguments.path === "string" &&
119
121
  /^xd:\/\/(?:lane_report|board_[a-z_]+)(?:[/?#]|$)/.test(call.arguments.path)) ||
120
- parseLaneReportResult(result) || (record(result.details) && result.details.type === "superagent-scope-review")) {
121
- throw new Error("Lane tool evidence requires a completed successful native tool call, not report/board chatter");
122
+ parseLaneReportResult(result) || (record(result.details) && result.details.type === "superagent-scope-review") ||
123
+ transportedCoordination(call, result)) {
124
+ throw new Error("Lane tool evidence requires a completed successful native tool call, not a coordination receipt");
122
125
  }
123
126
  // Native identity/time envelopes are not evidence of changed work.
124
127
  const resultRecord = { toolName: result.toolName, content: result.content, details: result.details, isError: result.isError };
125
128
  return { kind: "tool", ref: id, fingerprint: createHash("sha256").update(JSON.stringify(resultRecord)).digest("hex") };
126
129
  }
127
130
 
131
+ function transportedCoordination(call: ToolCall, result: ToolResultMessage): boolean {
132
+ const details = result.details;
133
+ if (!record(details)) return false;
134
+ const device = details.xdev;
135
+ if (call.name === "write" && record(device) && device.mode === "execute" &&
136
+ typeof device.tool === "string" && call.arguments.path === `xd://${device.tool}` && coordinationTool(device.tool))
137
+ return true;
138
+ // The shell's dispatch records, not command text or stdout, identify tools that ran.
139
+ return call.name === "bash" && Array.isArray(details.toolCommands) &&
140
+ details.toolCommands.some((dispatch: unknown) => record(dispatch) && dispatch.mode === "execute" &&
141
+ typeof dispatch.exitCode === "number" && typeof dispatch.tool === "string" && coordinationTool(dispatch.tool));
142
+ }
143
+
128
144
  /** A worker role entrypoint, never the head's manager or messenger client. */
129
145
  export default function laneExtension(pi: ExtensionAPI): void {
130
146
  if (process.env.OMP_SUPERAGENT_ROLE !== "lane") return;
@@ -190,11 +206,13 @@ export default function laneExtension(pi: ExtensionAPI): void {
190
206
  name: "lane_report", label: "Report lane observations", approval: "read", loadMode: "essential",
191
207
  description: "Record an evidence-backed progress, waiting, or resolved observation in this lane's native tool journal. " +
192
208
  "Progress/resolved require selected real file paths or completed successful native toolCallIds; hashes are computed here. " +
209
+ "Decision receipts and other coordination activity are not evidence of work. " +
193
210
  "Waiting/resolved name the exact tool/approval/job ID or a dependency label. Native tool/approval/job waiting IDs must be observable now. " +
211
+ "Topic observations do not notify HEAD. For manager handoffs, changed evidence or wait transitions are queued for HEAD. " +
194
212
  "For a standalone original owner message in the active bound topic that appears to supersede the existing assignment, " +
195
213
  "call lane_report directly with status scope_review and its Original source ID, never via eval, bash, or write. " +
196
214
  "This only requests HEAD review; it does not grant permission. " +
197
- "Reports do not send messages, prove acceptance, dispatch, resume, or change execution authority. Board/report chatter is not evidence.",
215
+ "Reports do not themselves send messenger messages, prove acceptance, dispatch, resume, or change execution authority.",
198
216
  parameters,
199
217
  async execute(id, params, signal, _onUpdate, ctx) {
200
218
  if (ctx.agent.kind !== "main") throw new Error("Lane reporting is restricted to the root lane session");
@@ -1,6 +1,6 @@
1
1
  // Configuration only. Never import the SDK entry point, account storage, or a backend.
2
- import { canEnableGlobalMemory, effectiveManagedMemory, ensureManagedMemory, parseMemoryConsent, type ManagedMemoryReport } from "./managed-memory";
3
- import { parseNativeLaunch } from "./native-launch-profile";
2
+ import { canEnableGlobalMemory, effectiveManagedMemory, ensureManagedMemory, parseMemoryConsent, type ManagedMemoryReport } from "./omp/managed-memory";
3
+ import { parseNativeLaunch } from "./omp/native-launch-profile";
4
4
 
5
5
  const unavailable: ManagedMemoryReport = { memory: { status: "unknown" }, updated: false };
6
6
  const [operation, ...args] = process.argv.slice(2);
@@ -9,9 +9,9 @@ import { listPackageExtensionModules, loadExtensions } from "@oh-my-pi/pi-coding
9
9
  import { buildAvailableSlashCommands } from "@oh-my-pi/pi-coding-agent/slash-commands/available-commands";
10
10
  import { buildSystemPrompt } from "@oh-my-pi/pi-coding-agent/system-prompt";
11
11
  import { WORKFLOW_NAMES } from "./contracts";
12
- import { readManagedUlwPackage } from "./managed-ulw";
13
- import { canonicalSuperkitSkills, hasCanonicalSuperkitSkills, legacySuperkitSkills, superkitWorkflows as workflows } from "./superkit-skills";
14
- import { advertisedWorkflow } from "./workflow";
12
+ import { readManagedUlwPackage } from "./omp/managed-super";
13
+ import { canonicalSuperkitSkills, hasCanonicalSuperkitSkills, legacySuperkitSkills, superkitWorkflows as workflows } from "./omp/superkit-skills";
14
+ import { advertisedWorkflow } from "./lane/workflow";
15
15
 
16
16
  const packageArg = process.argv[2];
17
17
  if (!packageArg) throw new Error("Managed Superkit probe requires a package path");
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { routeKey, type Approval } from "./contracts";
2
+ import { routeKey, type Approval } from "../contracts";
3
3
 
4
4
  /** Existing cards and persisted dialog progress must keep this exact identity. */
5
5
  export function approvalCardToken(approval: Approval): string {
@@ -1,5 +1,5 @@
1
- import type { Config } from "./config";
2
- import { operatorBotToken, runOperator, type OperatorRun } from "./operator";
1
+ import type { Config } from "../config/config";
2
+ import { operatorBotToken, runOperator, type OperatorRun } from "../operator/operator";
3
3
 
4
4
  export interface DiscordCommandRegistrationOptions {
5
5
  readonly apply?: boolean;
@@ -26,6 +26,7 @@ export interface DiscordCommandRegistrationReport {
26
26
  readonly applicationId: string;
27
27
  readonly botId: string;
28
28
  readonly plannedGlobal: readonly DiscordDefinition[];
29
+ readonly preApplyTextOptionDrift: readonly string[];
29
30
  readonly currentGlobal: readonly RegistrationSummary[];
30
31
  readonly obsoleteGlobal: readonly RegistrationSummary[];
31
32
  readonly guilds: readonly {
@@ -1,7 +1,7 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import { Type } from "@sinclair/typebox/type";
3
3
  import { Value } from "@sinclair/typebox/value";
4
- import { physicalRoute, physicalRouteKey, type DiscordPurposeNote, type DiscordPurposeRequest, type Route, type StorePort } from "./contracts";
4
+ import { physicalRoute, physicalRouteKey, type DiscordPurposeNote, type DiscordPurposeRequest, type Route, type StorePort } from "../contracts";
5
5
  import { DeliveryError } from "./delivery";
6
6
 
7
7
  const PURPOSES = "discord:purposes";
@@ -13,6 +13,7 @@
13
13
  { "name": "model", "description": "Choose a Superagent HEAD model or preset, or use --lane for the bound lane.", "text": "Omit for the menu, or enter list, provider/model, --lane provider/model, or a preset command.",
14
14
  "discord": { "description": "Choose a model for the Superagent HEAD or the current lane.", "text": true } },
15
15
  { "name": "effort", "description": "Choose the Superagent HEAD thinking effort.", "text": "Omit for the menu, or enter an exact advertised effort level." },
16
+ { "name": "fast", "description": "Choose and confirm the Superagent HEAD fast service tier." },
16
17
  { "name": "compact", "description": "Compact Superagent HEAD context when idle.", "text": "Optional compaction instructions, including multiple lines." },
17
18
  { "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." },
18
19
  { "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." },
@@ -0,0 +1,55 @@
1
+ import catalog from "./messenger-command-catalog.json" with { type: "json" };
2
+ import type { Inbound } from "../contracts";
3
+
4
+ /** Owner controls and platform-specific registration metadata shared with the native Gateway. */
5
+ export const MESSENGER_COMMAND_CATALOG: readonly {
6
+ readonly name: string;
7
+ readonly description: string;
8
+ readonly text?: string;
9
+ readonly discordOnly?: boolean;
10
+ readonly discord?: {
11
+ readonly description: string;
12
+ readonly text: boolean;
13
+ };
14
+ }[] = catalog;
15
+
16
+ export const MESSENGER_COMMANDS = MESSENGER_COMMAND_CATALOG.filter(command => !command.discordOnly);
17
+
18
+ /** Never promote a slash token exposed by Telegram's routing-only redaction. */
19
+ export function telegramCommandBlocked(input: Inbound): boolean {
20
+ if (input.route.platform !== "telegram" || input.pickerSelection) return false;
21
+ if (input.telegramProtectedCommand !== undefined) return input.telegramProtectedCommand;
22
+ if (input.routingText === undefined) return false;
23
+ // Legacy receipts have no explicit verdict. The old redaction can veto
24
+ // command authority but cannot give it to a different token in the view.
25
+ const written = /^\s*(\/\S+)/u.exec(input.text);
26
+ if (!written) return input.routingText.trimStart().startsWith("/");
27
+ return !input.routingText.startsWith(written[0])
28
+ || !/^(?:\s|$)/u.test(input.routingText.slice(written[0].length));
29
+ }
30
+
31
+ /** Ordinary Slack messages use mrkdwn entities; slash payloads and picker values do not. */
32
+ export function messengerCommandText(input: Inbound): string {
33
+ const { text } = input;
34
+ if (input.route.platform !== "slack" || input.messageId === null || !text.includes("&")) return text;
35
+ const name = /^\s*\/([a-z-]+)\s/u.exec(text)?.[1];
36
+ if (!name || !MESSENGER_COMMANDS.some(command => command.name === name)) return text;
37
+ // Decode exactly once. The stored text remains the identity used for replay.
38
+ return text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
39
+ }
40
+
41
+ /** Discord may strip this bot's addresses from the edges, but not change the owner's command. */
42
+ export function matchesWrittenCommand(input: Inbound): boolean {
43
+ if (input.discordOriginalText === undefined) return true;
44
+ let written = input.discordOriginalText.trim();
45
+ const text = input.text.trim();
46
+ const addresses = [`<@${input.route.accountId}>`, `<@!${input.route.accountId}>`];
47
+ while (written !== text) {
48
+ const leading = addresses.find(tag => written.startsWith(tag));
49
+ if (leading) { written = written.slice(leading.length).trimStart(); continue; }
50
+ const trailing = addresses.find(tag => written.endsWith(tag));
51
+ if (!trailing) return false;
52
+ written = written.slice(0, -trailing.length).trimEnd();
53
+ }
54
+ return true;
55
+ }
@@ -2,7 +2,7 @@ import { isAbsolute } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
4
4
  import { Type } from "@sinclair/typebox";
5
- import type { Inbound } from "./contracts";
5
+ import type { Inbound } from "../contracts";
6
6
 
7
7
  const MAX_RESULT_ATTACHMENT_BYTES = 8 * 1024 * 1024;
8
8
  export const RESULT_ATTACH_TOOL = "result_attach";
@@ -65,7 +65,7 @@ export function isOriginalAttachmentMessage({ id, messageId, route }: Inbound):
65
65
  : `${route.platform}:${route.accountId}:${route.channelId}:${messageId}:original`);
66
66
  }
67
67
 
68
- const binary = fileURLToPath(new URL(`../gateway/bin/omp-gateway-${process.platform}-${process.arch}`, import.meta.url));
68
+ const binary = fileURLToPath(new URL(`../../gateway/bin/omp-gateway-${process.platform}-${process.arch}`, import.meta.url));
69
69
 
70
70
  type StageCommand =
71
71
  | { readonly action: "stage"; readonly stateDir: string; readonly cwd: string; readonly path: string; readonly privatePaths: readonly string[] }
@@ -94,7 +94,7 @@ export function isResultAttachmentSnapshot(value: unknown): value is ResultAttac
94
94
  const snapshot = asRecord(value);
95
95
  return snapshot !== null && Object.keys(snapshot).length === 5 &&
96
96
  typeof snapshot.name === "string" && validPath(snapshot.name) && Buffer.byteLength(snapshot.name) <= 180 &&
97
- /^[\p{L}\p{N}\p{M}_. -]+$/u.test(snapshot.name) &&
97
+ /^[\p{L}\p{N}\p{M}_. &-]+$/u.test(snapshot.name) &&
98
98
  typeof snapshot.size === "number" && Number.isSafeInteger(snapshot.size) &&
99
99
  snapshot.size > 0 && snapshot.size <= MAX_RESULT_ATTACHMENT_BYTES &&
100
100
  typeof snapshot.sha256 === "string" && /^[a-f0-9]{64}$/.test(snapshot.sha256) &&
@@ -1,6 +1,6 @@
1
- import type { Config } from "./config";
2
- import { readCredentialFile, validateCredential } from "./credentials";
3
- import { runOperator, type OperatorRun } from "./operator";
1
+ import type { Config } from "../config/config";
2
+ import { readCredentialFile, validateCredential } from "../config/credentials";
3
+ import { runOperator, type OperatorRun } from "../operator/operator";
4
4
 
5
5
  export interface SlackCommandRegistrationOptions {
6
6
  readonly apply?: boolean;