omp-superagent 0.1.11 → 0.1.15

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 (82) hide show
  1. package/DESIGN.md +21 -5
  2. package/README.ko.md +3 -1
  3. package/README.md +3 -1
  4. package/THIRD_PARTY_NOTICES.md +6 -0
  5. package/assets/architecture-dark.svg +4 -4
  6. package/assets/architecture.ko-dark.svg +4 -4
  7. package/assets/architecture.ko.svg +4 -4
  8. package/assets/architecture.mmd +5 -5
  9. package/assets/architecture.svg +4 -4
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +242 -31
  12. package/docs/OPERATIONS.md +225 -25
  13. package/docs/design/execution.md +161 -43
  14. package/docs/design/messaging.md +45 -9
  15. package/docs/releases/0.1.11.md +4 -2
  16. package/docs/releases/0.1.13.md +13 -0
  17. package/docs/releases/0.1.15.md +13 -0
  18. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  19. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  21. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  23. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  25. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  26. package/package.json +9 -3
  27. package/scripts/prepare-worker-memory.ts +37 -0
  28. package/scripts/upgrade-evidence-files.mjs +100 -0
  29. package/scripts/upgrade-evidence.mjs +192 -0
  30. package/scripts/upgrade-host-wire.mjs +162 -0
  31. package/skills/head/SKILL.md +22 -47
  32. package/skills/head/references/routing.md +11 -12
  33. package/skills/head/references/supervision.md +10 -14
  34. package/skills/lane/SKILL.md +14 -16
  35. package/skills/lane/references/workflow.md +14 -27
  36. package/src/cli.ts +59 -79
  37. package/src/config/config.ts +4 -0
  38. package/src/contracts.ts +34 -27
  39. package/src/cron/cron-jobs.ts +4 -3
  40. package/src/cron/cron-pr-intake.ts +1 -2
  41. package/src/extension.ts +57 -14
  42. package/src/gateway/gateway-client.ts +14 -12
  43. package/src/group/group-runner.ts +3 -2
  44. package/src/group-runner-extension.ts +7 -3
  45. package/src/host-extension.ts +109 -2
  46. package/src/host-sdk-helper.ts +12 -3
  47. package/src/lane/decision-tool.ts +2 -3
  48. package/src/lane/lane-report.ts +8 -30
  49. package/src/lane/lane-rows.ts +1 -1
  50. package/src/lane/workflow.ts +44 -3
  51. package/src/lane-extension.ts +5 -46
  52. package/src/messaging/discord-context.ts +8 -6
  53. package/src/omp/host-protocol.ts +4 -3
  54. package/src/omp/host.ts +24 -7
  55. package/src/omp/managed-super.ts +43 -27
  56. package/src/omp/native-sessions.ts +12 -0
  57. package/src/omp/worker-memory-import.ts +410 -0
  58. package/src/omp/worker-memory-sdk.ts +8 -0
  59. package/src/operator/setup.ts +8 -13
  60. package/src/operator/stop-lane.ts +25 -0
  61. package/src/pr/pr-github-schema.ts +9 -0
  62. package/src/pr/pr-github.ts +6 -2
  63. package/src/pr/pr-intake-automation.ts +11 -8
  64. package/src/pr/pr-intake-fix.ts +2 -5
  65. package/src/pr/pr-intake-review.ts +7 -7
  66. package/src/routing/topic-history.ts +2 -2
  67. package/src/runtime/controller.ts +444 -408
  68. package/src/runtime/head-recovery.ts +7 -7
  69. package/src/runtime/worker-memory.ts +156 -0
  70. package/src/storage/deferred-routing.ts +1 -7
  71. package/src/storage/store.ts +441 -375
  72. package/src/worker/worker-host.ts +3 -2
  73. package/src/worker/worker-ledger.ts +20 -11
  74. package/src/worker/worker-memory-page.ts +83 -0
  75. package/src/worker/worker-memory-proofs.ts +260 -0
  76. package/src/worker/worker-memory-source.ts +305 -0
  77. package/src/worker/worker-memory-storage.ts +130 -0
  78. package/src/worker/worker-profile.ts +2 -0
  79. package/src/worker/worker-repository.ts +92 -7
  80. package/src/worker/worker-request.ts +1 -0
  81. package/src/worker/worker-service.ts +25 -8
  82. package/src/worker/worker-wire.ts +20 -6
@@ -13,7 +13,7 @@ import type { GroupReply } from "../group/group-policy";
13
13
  import type { DiscordPresenceStatus, MessengerPresenceRequest } from "../contracts";
14
14
 
15
15
  export interface GatewayHeadMessenger extends Messenger {
16
- assertRoute(route: Route, purpose?: "history"): Promise<void>;
16
+ assertRoute(route: Route, purpose?: "history" | "bound-work"): Promise<void>;
17
17
  requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord>;
18
18
  }
19
19
 
@@ -28,6 +28,11 @@ function retryableReconnect(error: unknown): boolean {
28
28
  return retryableHandshake(error) || (error instanceof DeliveryError && error.certainty === "uncertain");
29
29
  }
30
30
 
31
+ function stableEffectId(parts: readonly string[]): string {
32
+ const hash = createHash("sha256").update(JSON.stringify(parts)).digest("hex");
33
+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
34
+ }
35
+
31
36
  /** Transport-only head adapter. Detaching never logs out the actual accounts. */
32
37
  class GatewayMessenger implements GatewayHeadMessenger {
33
38
  readonly managesStartupHistory = true;
@@ -192,31 +197,28 @@ class GatewayMessenger implements GatewayHeadMessenger {
192
197
  }
193
198
  }
194
199
 
195
- private effect<T>(operation: string, args: unknown[]): Promise<T> {
196
- return this.call<T>("/effect", { id: crypto.randomUUID(), operation, args });
200
+ private effect<T>(operation: string, args: unknown[], id: string = crypto.randomUUID()): Promise<T> {
201
+ return this.call<T>("/effect", { id, operation, args });
197
202
  }
198
203
  sendGroup(reply: GroupReply): Promise<string> {
199
- const hash = createHash("sha256").update(JSON.stringify(["group-reply", reply.sourceId, reply.outcome])).digest("hex");
200
- const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
201
- return this.call<string>("/effect", { id, operation: "sendGroup", args: [reply] });
204
+ return this.effect("sendGroup", [reply], stableEffectId(["group-reply", reply.sourceId, reply.outcome]));
202
205
  }
203
206
  requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord> { return this.call("/restart", request); }
204
207
  send(output: OutputRecord): Promise<string> {
205
208
  const { resultAttachment } = output;
206
209
  if (!resultAttachment) return this.effect("send", [output]);
207
210
  // Stable across client reattachment; the Gateway journals the one attempt.
208
- const hash = createHash("sha256").update(JSON.stringify(["result-attachment", output.id])).digest("hex");
209
- const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
211
+ const id = stableEffectId(["result-attachment", output.id]);
210
212
  // Transfer only a receipt; the old persisted payload is read by the Gateway
211
213
  // itself so its original attempt fingerprint can still be reconciled.
212
214
  const { payload } = resultAttachment;
213
- return this.call<string>("/effect", { id, operation: "send", args: [{
215
+ return this.effect("send", [{
214
216
  id: output.id, route: output.route, text: output.text, replyTo: output.replyTo,
215
217
  resultAttachment: "data" in payload ? { name: payload.name, legacy: true } : payload,
216
- }] });
218
+ }], id);
217
219
  }
218
- assertRoute(route: Route, purpose?: "history"): Promise<void> {
219
- return this.call(purpose === "history" ? "/history/route" : "/route", { route }, AbortSignal.timeout(1000));
220
+ assertRoute(route: Route, purpose?: "history" | "bound-work"): Promise<void> {
221
+ return this.call(purpose === "history" || purpose === "bound-work" ? "/history/route" : "/route", { route }, AbortSignal.timeout(1000));
220
222
  }
221
223
  setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
222
224
  return this.effect("setActivity", [{ route: message.route, messageId: message.messageId }, activity]);
@@ -102,8 +102,9 @@ async function isolatedModel(state: string, selector: string): Promise<string> {
102
102
  const selected = models.map(record).filter(row => row.id === model);
103
103
  if (selected.length !== 1) throw new RestrictedRunError("Restricted model ID must match exactly one model");
104
104
  const { name, reasoning, contextWindow, maxTokens, cost } = selected[0];
105
+ const prices = record(cost);
105
106
  const rates = Object.fromEntries(["input", "output", "cacheRead", "cacheWrite"].map(key => {
106
- const rate = record(cost)[key];
107
+ const rate = prices[key];
107
108
  if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0) throw new RestrictedRunError("Missing restricted model price");
108
109
  return [key, rate];
109
110
  }));
@@ -212,8 +213,8 @@ function settledResult(output: Buffer, input: Input): { readonly text?: string }
212
213
  if (`${message.provider}/${message.model}` !== input.model || terminalCount !== 0 || !Array.isArray(message.content))
213
214
  return undefined;
214
215
  stopped = message.stopReason === "stop";
215
- const blocks = message.content.map(record);
216
216
  if (input.mode === "chat") {
217
+ const blocks = message.content.map(record);
217
218
  if (!stopped || blocks.some(block => block.type !== "text" && block.type !== "thinking")) return undefined;
218
219
  reply = blocks.flatMap(block => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
219
220
  }
@@ -24,14 +24,18 @@ function sameFile(first: Stats, second: Stats): boolean {
24
24
  return first.dev === second.dev && first.ino === second.ino;
25
25
  }
26
26
 
27
+ function eligibleFile(info: Stats): boolean {
28
+ return info.isFile() && info.nlink === 1 && info.size <= maxBytes;
29
+ }
30
+
27
31
  function existingText(path: string): { readonly text: string; readonly mode: number } {
28
32
  const expected = lstatSync(path);
29
- if (!expected.isFile() || expected.nlink !== 1 || expected.size > maxBytes || realpathSync.native(path) !== path)
33
+ if (!eligibleFile(expected) || realpathSync.native(path) !== path)
30
34
  throw new RestrictedPathError("Not an eligible regular text file");
31
35
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
32
36
  try {
33
37
  const actual = fstatSync(fd);
34
- if (!sameFile(expected, actual) || !actual.isFile() || actual.nlink !== 1 || actual.size > maxBytes)
38
+ if (!sameFile(expected, actual) || !eligibleFile(actual))
35
39
  throw new RestrictedPathError("File changed or is not an eligible regular file");
36
40
  const buffer = Buffer.alloc(maxBytes + 1);
37
41
  let size = 0;
@@ -111,7 +115,7 @@ export default function groupWorktree(pi: ExtensionAPI): void {
111
115
  if (!isVisibleSegment(entry.name)) continue;
112
116
  const info = lstatSync(join(directory, entry.name));
113
117
  if (info.isDirectory()) names.push(`${entry.name}/`);
114
- else if (info.isFile() && info.nlink === 1 && info.size <= maxBytes) names.push(entry.name);
118
+ else if (eligibleFile(info)) names.push(entry.name);
115
119
  }
116
120
  } finally { handle.closeSync(); }
117
121
  return names.sort().join("\n");
@@ -15,7 +15,7 @@ import { buildServiceTierByFamily } from "@oh-my-pi/pi-coding-agent/config/servi
15
15
  import { getRestorableSessionModels } from "@oh-my-pi/pi-coding-agent/session/session-context";
16
16
  import { clampThinkingLevelForModel } from "@oh-my-pi/pi-catalog/model-thinking";
17
17
  import { parseSessionEntries, readSessionHeaderId } from "@oh-my-pi/pi-coding-agent/session/session-loader";
18
- import { HostChannel, LANE_MODEL_PROMOTION_RECEIPT, PR_REVIEW_GITHUB_ENV, PR_REVIEW_SYSTEM_PROMPT, indexServiceCompletions, serviceGenerationKey, type FastModeState, type Frame, type ServiceUnit } from "./omp/host-protocol";
18
+ import { HostChannel, LANE_MODEL_PROMOTION_RECEIPT, PR_REVIEW_GITHUB_ENV, PR_REVIEW_SYSTEM_PROMPT, indexServiceCompletions, serviceGenerationKey, terminalService, type FastModeState, type Frame, type ServiceUnit } from "./omp/host-protocol";
19
19
  import { USER_INTERRUPT_LABEL } from "@oh-my-pi/pi-coding-agent/session/messages";
20
20
  import { MAX_RPC_REASSEMBLED_BYTES } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-frame";
21
21
  import { fitAbortAndRestoreQueueResponse } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-mode";
@@ -32,8 +32,11 @@ import { installReplyVoice } from "./omp/host-reply-voice";
32
32
  import { matchesPreparedLaunch } from "./omp/stock-head-launch";
33
33
  import { NATIVE_PROFILE_ENV, bindNativeProfile, matchesNativeProfile, type HostReadyEvent,
34
34
  type NativeProfileBinding, type NativeProfilePaths } from "./omp/native-sessions";
35
+ import { isWorkerMemoryCursor, isWorkerMemoryStamp } from "./worker/worker-memory-page";
36
+ import { canBeginWorkerFact, isWorkerFactRoot, type WorkerFactCarrier } from "./worker/worker-memory-proofs";
37
+ import { bindWorkerMemorySource } from "./worker/worker-memory-source";
38
+ import { WORKER_MEMORY_ENV, WORKER_MEMORY_PROFILE_ENV } from "./worker/worker-memory-storage";
35
39
 
36
- const terminalService = (state: ServiceUnit["state"]) => state === "exited" || state === "failed";
37
40
  const serviceGeneration = ({ owner, id, generation, startedAt, restartCount }: ServiceUnit) =>
38
41
  ({ owner, id, generation, startedAt, restartCount });
39
42
  const serviceName = (value: unknown) => typeof value === "string" ? value.trim() || undefined : undefined;
@@ -90,6 +93,12 @@ export default function hostExtension(pi: ExtensionAPI): void {
90
93
  let instanceKey: string | undefined;
91
94
  const selectedSuperkit = process.env[MANAGED_ULW_ENV];
92
95
  const workerAttempt = process.env.OMP_SUPERAGENT_WORKER_ATTEMPT;
96
+ const memoryLaunch = workerAttempt && process.env.OMP_SUPERAGENT_ROLE === "lane" ? process.env[WORKER_MEMORY_ENV] : undefined;
97
+ const workerMemoryProfileBinding: NativeProfileBinding | null = memoryLaunch
98
+ ? JSON.parse(process.env[WORKER_MEMORY_PROFILE_ENV] ?? "null") : null;
99
+ let workerMemoryProfile: { readonly root: ReturnType<typeof exact>; readonly paths: NativeProfilePaths } | undefined;
100
+ let workerMemoryProfileAttempted = false;
101
+ let workerMemory: ReturnType<typeof bindWorkerMemorySource> | undefined;
93
102
  const reviewCwd = process.env.OMP_SUPERAGENT_PR_REVIEW_CWD;
94
103
  let replyVoice: ReturnType<typeof installReplyVoice>;
95
104
  if (reviewCwd && PR_REVIEW_GITHUB_ENV.some(name => process.env[name]))
@@ -202,6 +211,24 @@ export default function hostExtension(pi: ExtensionAPI): void {
202
211
  if (!(error instanceof Error)) throw error;
203
212
  }
204
213
  };
214
+ const workerMemoryProfileCurrent = ({ session, ref, id, file }: ReturnType<typeof exact>): boolean => {
215
+ if (!workerMemoryProfileBinding || !workerMemoryProfile || !file) return false;
216
+ const { root, paths } = workerMemoryProfile;
217
+ if (root.session !== session || root.ref !== ref || root.id !== id || root.file !== file) return false;
218
+ const { profile, discoveryEntry } = workerMemoryProfileBinding;
219
+ return matchesNativeProfile(paths, profile) && realpathSync(dirname(discoveryEntry)) === dirname(discoveryEntry)
220
+ && realpathSync(discoveryEntry) === file;
221
+ };
222
+ const currentWorkerMemory = (identity: ReturnType<typeof exact>) => {
223
+ const { session, file } = identity;
224
+ if (!memoryLaunch || !workerAttempt || !file || !workerMemoryProfileCurrent(identity)) return;
225
+ // Background native initialization must not delay Host startup or tools.
226
+ // Keep the attested root/profile even if there is not yet a live source.
227
+ if (!workerMemory && session.getMnemopiSessionState?.()) {
228
+ workerMemory = bindWorkerMemorySource(session, { encoded: memoryLaunch, file, attempt: workerAttempt });
229
+ }
230
+ return workerMemory;
231
+ };
205
232
  const snapshot = () => {
206
233
  const { session } = exact();
207
234
  return { modelRoles: session.settings.getModelRoles(),
@@ -682,12 +709,61 @@ export default function hostExtension(pi: ExtensionAPI): void {
682
709
  if (observationHeld) throw new Error("Durable native observations are unavailable");
683
710
  return { ...ownerIdentity(identity), leafId: identity.session.sessionManager.getLeafId() };
684
711
  }
712
+ if (command.type === "get_worker_memory") {
713
+ const { after, unchanged } = command;
714
+ if (!workerMemoryProfile || !isWorkerMemoryCursor(after) || (unchanged !== undefined && (after !== 0 || !isWorkerMemoryStamp(unchanged))))
715
+ throw new Error("Worker memory is unavailable");
716
+ const identity = exact();
717
+ const { session } = identity;
718
+ const run = runOrdinal;
719
+ const assertIdle = () => {
720
+ assertSameRoot(identity);
721
+ if (runOrdinal !== run || !localIdle() || session.isSessionTransitioning !== false
722
+ || session.isRunActive !== false || session.getPlanModeState()?.enabled || session.getPrewalkState?.())
723
+ throw new Error("session_busy");
724
+ if (!workerMemoryProfileCurrent(identity)) throw new Error("Worker memory profile changed");
725
+ };
726
+ assertIdle();
727
+ const source = currentWorkerMemory(identity);
728
+ if (!source) throw new Error("Worker memory is unavailable");
729
+ await source.verifyCheckout();
730
+ assertIdle();
731
+ const observed = source.page({ after, ...(unchanged !== undefined && { unchanged }) }, run > 0);
732
+ // The earlier worker probe alone cannot cover later Git changes while
733
+ // attached. Check again before releasing any native contents.
734
+ await source.verifyCheckout();
735
+ assertIdle();
736
+ observed.assertCurrent();
737
+ return { ...ownerIdentity(identity), page: observed.page };
738
+ }
685
739
  if (command.type === "snapshot") {
686
740
  const ownership = await owned();
687
741
  // The owner requires this first snapshot before opening its public socket.
688
742
  const prReviewPolicy = reviewCwd ? reviewPolicy(ownership.identity.session, reviewCwd) : undefined;
689
743
  if (!reviewCwd) loadedSuperkitPath ??= await verifyHostSuperkit(ownership.identity.session, selectedSuperkit);
690
744
  const { session, ref } = ownership.identity;
745
+ let workerMemoryControlVersion: 1 | undefined;
746
+ if (memoryLaunch && workerAttempt && workerMemoryProfileBinding && ownership.identity.file) {
747
+ try {
748
+ if (!workerMemoryProfileAttempted) {
749
+ workerMemoryProfileAttempted = true;
750
+ const { id, file } = ownership.identity;
751
+ const paths = await bindNativeProfile(pi.pi, {
752
+ agentDir: session.settings.getAgentDir(), id, file,
753
+ }, workerMemoryProfileBinding);
754
+ assertSameRoot(ownership.identity);
755
+ workerMemoryProfile = { root: ownership.identity, paths };
756
+ } else assertSameRoot(ownership.identity);
757
+ const source = currentWorkerMemory(ownership.identity);
758
+ if (source) {
759
+ source.validate();
760
+ workerMemoryControlVersion = 1;
761
+ }
762
+ } catch (error) {
763
+ // An unavailable bank does not make ordinary observations unavailable.
764
+ if (!(error instanceof Error)) throw error;
765
+ }
766
+ }
691
767
  const wakes = session.wakeSources;
692
768
  const running = process.env.OMP_SUPERAGENT_ROLE === "head" && ownership.tree
693
769
  ? ownership.tree.running.filter(job => job.ownerId === ref.id) : undefined;
@@ -708,6 +784,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
708
784
  ? session.effectiveServiceTier(session.model) ?? "none" : undefined,
709
785
  } : {}),
710
786
  journalCursorControlVersion: 1,
787
+ ...(workerMemoryControlVersion && { workerMemoryControlVersion }),
711
788
  ...(replyVoice?.available() ? { replyVoiceControlVersion: 2 } : {}),
712
789
  ...(running ? { headJobs: { running: running.map(job => job.id), awaitingOnly } } : {}),
713
790
  fastMode: headFastMode(ownership.identity.session),
@@ -870,6 +947,33 @@ export default function hostExtension(pi: ExtensionAPI): void {
870
947
  pi.on("agent_start", () => {
871
948
  if (context?.agent.kind === "main") observation("rpc_agent_start", { runOrdinal: ++runOrdinal, hostPid: process.pid });
872
949
  });
950
+ const observeWorkerFact = (tool: string, ctx: ExtensionContext, observe: (source: NonNullable<typeof workerMemory>,
951
+ name: WorkerFactCarrier) => void, input?: unknown) => {
952
+ if (!workerMemoryProfile || (tool !== "retain" && tool !== "learn" && tool !== "bash")
953
+ || ctx.agent.kind !== "main" || ctx.agent.id !== pi.pi.MAIN_AGENT_ID
954
+ || (!workerMemory && !canBeginWorkerFact(tool, input))) return;
955
+ try {
956
+ const identity = exact();
957
+ if (!isWorkerFactRoot(ctx, pi.pi.MAIN_AGENT_ID, identity.session.sessionManager)
958
+ || !identity.session.getAllToolInfos().some(info =>
959
+ info.name === tool && info.sourceInfo.source === "builtin" && info.sourceInfo.path === `<builtin:${tool}>`)) return;
960
+ const source = currentWorkerMemory(identity);
961
+ if (source) observe(source, tool);
962
+ } catch (error) {
963
+ // Attestation is optional and cannot change the native tool's outcome.
964
+ if (!(error instanceof Error)) throw error;
965
+ workerMemory?.clearFactStarts();
966
+ }
967
+ };
968
+ pi.on("tool_execution_start", (event, ctx) => {
969
+ observeWorkerFact(event.toolName, ctx, (source, tool) => source.startFact(tool, event.toolCallId, event.args), event.args);
970
+ });
971
+ pi.on("tool_execution_end", (event, ctx) => {
972
+ observeWorkerFact(event.toolName, ctx, (source, tool) => source.finishFact(tool, event.toolCallId, !event.isError, event.result));
973
+ });
974
+ pi.on("agent_end", (_event, ctx) => {
975
+ if (ctx.agent.kind === "main" && ctx.agent.id === pi.pi.MAIN_AGENT_ID) workerMemory?.clearFactStarts();
976
+ });
873
977
  pi.on("tool_call", async (event, ctx) => {
874
978
  if (reviewCwd) return { block: true, reason: "Static PR review does not execute tools" };
875
979
  const input = event.input as Frame;
@@ -927,6 +1031,8 @@ export default function hostExtension(pi: ExtensionAPI): void {
927
1031
  notDispatched ? "not_dispatched" : undefined);
928
1032
  });
929
1033
  pi.on("tool_result", async (event, ctx) => {
1034
+ if (!event.isError && event.parentToolCallId === undefined)
1035
+ observeWorkerFact(event.toolName, ctx, (source, toolName) => source.returnFact({ ...event, toolName }), event.input);
930
1036
  const owner = serviceOwner(ctx);
931
1037
  const key = JSON.stringify([owner, event.toolCallId]);
932
1038
  const start = serviceStarts.get(key);
@@ -1028,6 +1134,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
1028
1134
  });
1029
1135
  pi.on("session_shutdown", async () => {
1030
1136
  if (!context || context.agent.kind !== "main") return;
1137
+ workerMemory?.close();
1031
1138
  server?.close();
1032
1139
  await fs.unlink(socketPath).catch(error => { if (error.code !== "ENOENT") throw error; });
1033
1140
  });
@@ -17,6 +17,7 @@ type Manifest = {
17
17
  readonly headRotationSelection?: RotationSelection;
18
18
  readonly headHibernationSessionId?: string;
19
19
  readonly expectedNativeProfile?: NativeProfile;
20
+ readonly workerMemoryProfile?: NativeProfile;
20
21
  };
21
22
 
22
23
  async function run(operation: string | undefined, manifest: Manifest, input: unknown, nativeProfile?: NativeProfile) {
@@ -130,6 +131,7 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
130
131
  if (options.prReviewOnly) await chmod(options.sessionFile, 0o600);
131
132
  }
132
133
  let nativeProfileBinding: NativeProfileBinding | undefined;
134
+ let workerMemoryProfileBinding: NativeProfileBinding | undefined;
133
135
  if (!options.prReviewOnly) {
134
136
  requireNativeProfile();
135
137
  const discoveryEntry = await publishNativeSession(options.sessionFile, options.cwd, parkedSession, nativeProfile);
@@ -137,10 +139,13 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
137
139
  if (!discoveryEntry) throw new Error("Prepared native session could not be found in discovery");
138
140
  nativeProfileBinding = { profile: nativeProfile, discoveryEntry };
139
141
  }
142
+ if (manifest.workerMemoryProfile && discoveryEntry
143
+ && matchesNativeProfile(sdkNativeProfilePaths(), manifest.workerMemoryProfile))
144
+ workerMemoryProfileBinding = { profile: manifest.workerMemoryProfile, discoveryEntry };
140
145
  }
141
146
  const { hostInventoryManifest } = await import("./omp/host-inventory-manifest");
142
147
  return { toolsExplicitlySelected: parsed.tools !== undefined, noTools: parsed.noTools === true,
143
- nativeProfileBinding,
148
+ nativeProfileBinding, workerMemoryProfileBinding,
144
149
  replayableArgvHash: argv.argv[0] === "launch" && !stockReplayRefusal(parsed, options.sessionFile)
145
150
  ? launchArgvHash(launchArgs) : undefined,
146
151
  ...(options.prReviewOnly ? { emptyToolSelection } : {}),
@@ -219,10 +224,14 @@ try {
219
224
  }
220
225
  else if (operation === "prepare") throw new Error("Session preparation follows launch discovery");
221
226
  else if (operation === "inventory" || operation === "fit") {
227
+ if (!path) throw new Error("Host manifest is required");
222
228
  const input = await Bun.stdin.json();
223
- const manifest: Manifest = await Bun.file(path!).json();
229
+ const manifest: Manifest = await Bun.file(path).json();
224
230
  process.stdout.write(JSON.stringify(await run(operation, manifest, input)));
225
- } else throw new Error("Unknown Host SDK operation");
231
+ } else {
232
+ console.error("Unsupported Host SDK operation");
233
+ process.exitCode = 1;
234
+ }
226
235
  } catch {
227
236
  // SDK errors may contain native frames, authorization data or prompt content.
228
237
  console.error("Host SDK operation failed");
@@ -22,11 +22,10 @@ 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
- ? "Use to: \"head\" for an in-scope coordination choice that needs HEAD's answer, even from a work topic. " +
25
+ ? "Use to: \"head\" for a coordination choice that needs HEAD's answer, even from a work topic. " +
26
26
  "Omit to for the normal recipient (topic: owner; manager handoff: HEAD). " +
27
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. "
28
+ "An answer never grants execution approval or authority to change the assignment. "
30
29
  : "Ask the owner structured questions on this managed session's native UI. ") +
31
30
  "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.",
32
31
  parameters: Type.Object({
@@ -1,5 +1,4 @@
1
1
  import { isAbsolute, normalize } from "node:path";
2
- import { isDeepStrictEqual } from "node:util";
3
2
 
4
3
  export type LaneWaitTarget =
5
4
  | { kind: "tool" | "approval" | "job"; id: string; target: string }
@@ -25,27 +24,6 @@ export interface LaneReportEvent {
25
24
  report: LaneReport;
26
25
  }
27
26
 
28
- /** Evidence of a tool execution only; it does not authorize a scope change. */
29
- export type ScopeReviewReceipt = {
30
- readonly type: "superagent-scope-review";
31
- readonly sourceId: string;
32
- readonly sessionId: string;
33
- readonly sessionFile: string;
34
- readonly toolCallId: string;
35
- };
36
-
37
- /** Stock OMP select wire for this tool. A positive answer describes this call
38
- * only; the native Host, not the controller, handles any session-wide choice. */
39
- export function scopeReviewApproval(request: Record<string, unknown>, response?: { value?: string }): boolean {
40
- if (request.method !== "select" || request.secret === true) return false;
41
- const options = request.options;
42
- const session = "Approve lane_report for this session";
43
- if (!isDeepStrictEqual(options, ["Approve", "Deny"]) && !isDeepStrictEqual(options, ["Approve", session, "Deny"])) return false;
44
- if (!response) return true;
45
- return isDeepStrictEqual(response, { value: "Approve" })
46
- || Array.isArray(options) && options.includes(session) && isDeepStrictEqual(response, { value: session });
47
- }
48
-
49
27
  export function laneWaitKey(waiting: LaneWaitTarget): string {
50
28
  return JSON.stringify([waiting.kind, waiting.kind === "dependency" ? waiting.target : waiting.id]);
51
29
  }
@@ -56,6 +34,13 @@ const text = (value: unknown): value is string => typeof value === "string" && v
56
34
  const keys = (value: Record<string, unknown>, names: string[]) =>
57
35
  Object.keys(value).every(key => names.includes(key));
58
36
 
37
+ export function isLaneWaitTarget(value: unknown): value is LaneWaitTarget {
38
+ return record(value) && text(value.target) && (value.kind === "dependency"
39
+ ? keys(value, ["kind", "target"])
40
+ : ["tool", "approval", "job"].includes(value.kind as string) &&
41
+ keys(value, ["kind", "id", "target"]) && text(value.id));
42
+ }
43
+
59
44
  /** Parse only the structured native result, never receipt text or a claimed event in content. */
60
45
  export function parseLaneReportResult(result: unknown): LaneReportEvent | null {
61
46
  try {
@@ -76,14 +61,7 @@ export function parseLaneReportResult(result: unknown): LaneReportEvent | null {
76
61
  if (report.status !== "waiting" && report.evidence.length === 0) return null;
77
62
  if (report.status === "progress") {
78
63
  if (Object.hasOwn(report, "waiting")) return null;
79
- } else {
80
- const waiting = report.waiting;
81
- if (!record(waiting) || !text(waiting.target)) return null;
82
- if (waiting.kind === "dependency") {
83
- if (!keys(waiting, ["kind", "target"])) return null;
84
- } else if (!["tool", "approval", "job"].includes(waiting.kind as string) ||
85
- !text(waiting.id) || !keys(waiting, ["kind", "id", "target"])) return null;
86
- }
64
+ } else if (!isLaneWaitTarget(report.waiting)) return null;
87
65
  return event as unknown as LaneReportEvent;
88
66
  } catch {
89
67
  // Malformed native details must not escape into the head's event loop.
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
  import { isAbsolute, normalize } from "node:path";
3
- import { Type } from "@sinclair/typebox";
3
+ import { Type } from "@sinclair/typebox/type";
4
4
  import { Value } from "@sinclair/typebox/value";
5
5
  import type { Lane } from "../contracts";
6
6
  import type { RemotePlacement } from "../worker/worker-wire";
@@ -1,4 +1,4 @@
1
- import { WORKFLOW_NAMES, type InputRecord, type WorkflowActivation, type WorkflowChoice, type WorkflowName } from "../contracts";
1
+ import { WORKFLOW_NAMES, type Inbound, 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.
@@ -47,11 +47,52 @@ function invocation(text: string): { name: WorkflowName; length: number; legacy?
47
47
  return { name: "super", length: prefix + plain[0].length, legacy: true };
48
48
  }
49
49
 
50
- export function leadingWorkflow(text: string): WorkflowName | null {
50
+ function leadingInvocation(text: string) {
51
51
  const match = invocation(text);
52
52
  // Upstream masks URLs before reading its SUPER/ULW selectors. Do not
53
53
  // accidentally admit one just because a real command may use a colon.
54
- return match && (match.name === "jevify" || !leadingUri.test(text)) ? match.name : null;
54
+ return match && (match.name === "jevify" || !leadingUri.test(text)) ? match : null;
55
+ }
56
+
57
+ export function leadingWorkflow(text: string): WorkflowName | null {
58
+ return leadingInvocation(text)?.name ?? null;
59
+ }
60
+
61
+ /** Telegram's entity view can corroborate a written selector, but cannot supply one. */
62
+ export function ownerWorkflowRequest(input: Inbound, task: string): {
63
+ readonly name: WorkflowName | null;
64
+ readonly projection?: { readonly text: string; readonly selectorChanged: boolean };
65
+ } {
66
+ if (input.route.platform !== "telegram" || input.pickerSelection || input.routingText === input.text)
67
+ return { name: leadingWorkflow(task) };
68
+
69
+ // Remove only the wrapper parsed from the genuine request. Parsing a new
70
+ // /head, /new or cwd header exposed by redaction could also expose a selector.
71
+ const written = leadingInvocation(task);
72
+ const prefix = input.text.slice(0, input.text.length - task.length);
73
+ const view = input.routingText ?? "";
74
+ const aligned = view.startsWith(prefix);
75
+ const body = aligned ? view.slice(prefix.length) : view;
76
+ const visible = leadingInvocation(body);
77
+ const selector = task.slice(0, written?.length ?? 0);
78
+ const exact = aligned && written && visible && visible.name === written.name
79
+ && body.slice(0, visible.length) === selector;
80
+ if (exact) {
81
+ // The adapter attests the first slash token, but prose (or a selector
82
+ // after a wrapper) can be ambiguous if redaction exposed a repeated word.
83
+ // CR/LF survive redaction, so only the rest of the same line can stand in for it.
84
+ const directSlash = !prefix && input.telegramProtectedCommand === false && /^\/\S+$/u.test(selector.trimStart());
85
+ const finalWord = /\S+$/u.exec(selector)?.[0];
86
+ const sameLine = /^[^\r\n]*/u.exec(task.slice(selector.length))?.[0];
87
+ if (directSlash || !finalWord || !sameLine?.includes(finalWord)) {
88
+ return { name: written.name, projection: { text: body, selectorChanged: false } };
89
+ }
90
+ }
91
+ return {
92
+ name: null,
93
+ // In particular, a revealed jevify must not reach the native prose matcher.
94
+ projection: { text: visible ? body.slice(visible.length) : body, selectorChanged: Boolean(written || visible) },
95
+ };
55
96
  }
56
97
 
57
98
  /** Read old coordination identities without making aliases valid manager inputs. */
@@ -4,7 +4,7 @@ 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/lane-report";
7
+ import { isLaneWaitTarget, type LaneEvidence, type LaneReportEvent, parseLaneReportResult } from "./lane/lane-report";
8
8
  import { registerResultAttach, RESULT_ATTACH_TOOL } from "./messaging/result-attachment";
9
9
  import { registerDecisionAsk } from "./lane/decision-tool";
10
10
 
@@ -29,7 +29,6 @@ const parameters = Type.Union([
29
29
  { additionalProperties: false }),
30
30
  Type.Object({ status: Type.Literal("resolved"), summary, waiting, evidence: requiredEvidence },
31
31
  { additionalProperties: false }),
32
- Type.Object({ status: Type.Literal("scope_review"), sourceId: nonempty }, { additionalProperties: false }),
33
32
  ]);
34
33
  // Resumed native journals can still contain retired board tools. They were never work evidence.
35
34
  const coordinationTool = (name: string) =>
@@ -43,10 +42,6 @@ const keys = (value: Record<string, unknown>, names: string[]) =>
43
42
  // Direct native/custom-tool dispatch can bypass model argument validation.
44
43
  function validInput(input: unknown): input is Static<typeof parameters> {
45
44
  if (!record(input)) return false;
46
- if (input.status === "scope_review") {
47
- return Object.hasOwn(input, "status") && Object.hasOwn(input, "sourceId") &&
48
- keys(input, ["status", "sourceId"]) && text(input.sourceId);
49
- }
50
45
  if (!keys(input, ["status", "summary", "waiting", "evidence"]) ||
51
46
  !text(input.summary) || input.summary.length > 4000 ||
52
47
  !["progress", "waiting", "resolved"].includes(input.status as string)) return false;
@@ -56,11 +51,7 @@ function validInput(input: unknown): input is Static<typeof parameters> {
56
51
  : item.kind !== "tool" || !keys(item, ["kind", "toolCallId"]) || !text(item.toolCallId))))) return false;
57
52
  if (input.status !== "waiting" && (!Array.isArray(input.evidence) || input.evidence.length === 0)) return false;
58
53
  if (input.status === "progress") return !Object.hasOwn(input, "waiting");
59
- const target = input.waiting;
60
- return record(target) && text(target.target) && (target.kind === "dependency"
61
- ? keys(target, ["kind", "target"])
62
- : ["tool", "approval", "job"].includes(target.kind as string) &&
63
- keys(target, ["kind", "id", "target"]) && text(target.id));
54
+ return isLaneWaitTarget(input.waiting);
64
55
  }
65
56
 
66
57
  function fileEvidence(path: string, cwd: string): LaneEvidence {
@@ -119,8 +110,7 @@ function toolEvidence(id: string, records: ReturnType<typeof toolRecords>): Lane
119
110
  if (!call || !result || result.toolName !== call.name || result.isError !== false ||
120
111
  coordinationTool(call.name) || (typeof call.arguments.path === "string" &&
121
112
  /^xd:\/\/(?:lane_report|board_[a-z_]+)(?:[/?#]|$)/.test(call.arguments.path)) ||
122
- parseLaneReportResult(result) || (record(result.details) && result.details.type === "superagent-scope-review") ||
123
- transportedCoordination(call, result)) {
113
+ parseLaneReportResult(result) || transportedCoordination(call, result)) {
124
114
  throw new Error("Lane tool evidence requires a completed successful native tool call, not a coordination receipt");
125
115
  }
126
116
  // Native identity/time envelopes are not evidence of changed work.
@@ -148,12 +138,10 @@ export default function laneExtension(pi: ExtensionAPI): void {
148
138
  registerResultAttach(pi);
149
139
  let approvalSessionId: string | undefined;
150
140
  const pendingApprovals = new Set<string>();
151
- const scopeApprovals = new Map<string, "requested" | "approved" | "unverified">();
152
141
  const approvals = (ctx: ExtensionContext) => {
153
142
  const sessionId = ctx.sessionManager.getSessionId();
154
143
  if (approvalSessionId !== sessionId) {
155
144
  pendingApprovals.clear();
156
- scopeApprovals.clear();
157
145
  approvalSessionId = sessionId;
158
146
  }
159
147
  return pendingApprovals;
@@ -178,22 +166,13 @@ export default function laneExtension(pi: ExtensionAPI): void {
178
166
  pi.on("tool_approval_requested", (event, ctx) => {
179
167
  if (ctx.agent.kind === "main" && event.sessionId === ctx.sessionManager.getSessionId()) {
180
168
  approvals(ctx).add(event.toolCallId);
181
- if (event.toolName === "lane_report")
182
- scopeApprovals.set(event.toolCallId, scopeApprovals.has(event.toolCallId) ? "unverified" : "requested");
183
169
  }
184
170
  });
185
171
  pi.on("tool_approval_resolved", (event, ctx) => {
186
172
  if (event.sessionId !== ctx.sessionManager.getSessionId()) return;
187
173
  approvals(ctx).delete(event.toolCallId);
188
- if (ctx.agent.kind === "main" && event.toolName === "lane_report")
189
- scopeApprovals.set(event.toolCallId,
190
- event.approved && scopeApprovals.get(event.toolCallId) === "requested" ? "approved" : "unverified");
191
- });
192
- pi.on("agent_end", (_event, ctx) => { if (ctx.agent.kind === "main") scopeApprovals.clear(); });
193
- pi.on("session_shutdown", () => {
194
- pendingApprovals.clear();
195
- scopeApprovals.clear();
196
174
  });
175
+ pi.on("session_shutdown", () => { pendingApprovals.clear(); });
197
176
  pi.on("before_agent_start", async (event, ctx) => {
198
177
  if (ctx.agent.kind !== "main") return;
199
178
  return { systemPrompt: [
@@ -209,31 +188,11 @@ export default function laneExtension(pi: ExtensionAPI): void {
209
188
  "Decision receipts and other coordination activity are not evidence of work. " +
210
189
  "Waiting/resolved name the exact tool/approval/job ID or a dependency label. Native tool/approval/job waiting IDs must be observable now. " +
211
190
  "Topic observations do not notify HEAD. For manager handoffs, changed evidence or wait transitions are queued for HEAD. " +
212
- "For a standalone original owner message in the active bound topic that appears to supersede the existing assignment, " +
213
- "call lane_report directly with status scope_review and its Original source ID, never via eval, bash, or write. " +
214
- "This only requests HEAD review; it does not grant permission. " +
215
191
  "Reports do not themselves send messenger messages, prove acceptance, dispatch, resume, or change execution authority.",
216
192
  parameters,
217
- async execute(id, params, signal, _onUpdate, ctx) {
193
+ async execute(id, params, _signal, _onUpdate, ctx) {
218
194
  if (ctx.agent.kind !== "main") throw new Error("Lane reporting is restricted to the root lane session");
219
195
  if (!validInput(params)) throw new Error("Invalid lane report parameters");
220
- approvals(ctx);
221
- const nativeApproval = scopeApprovals.get(id);
222
- scopeApprovals.delete(id);
223
- if (params.status === "scope_review") {
224
- signal?.throwIfAborted();
225
- const sessionFile = ctx.sessionManager.getSessionFile();
226
- if (!sessionFile) throw new Error("Lane scope review requires a native session file");
227
- const receipt: ScopeReviewReceipt = {
228
- type: "superagent-scope-review", sourceId: params.sourceId,
229
- sessionId: ctx.sessionManager.getSessionId(), sessionFile, toolCallId: id,
230
- };
231
- // Only a matched direct native start/end can request review. Do not append a custom entry.
232
- return {
233
- content: [{ type: "text", text: "Emitted a scope-review signal. HEAD admission depends on controller verification and successful settlement; the assignment has not changed." }],
234
- details: nativeApproval === undefined ? receipt : { ...receipt, nativeApproval },
235
- };
236
- }
237
196
  const target = params.status === "waiting" ? params.waiting : undefined;
238
197
  if (target?.kind === "approval" && !approvals(ctx).has(target.id)) {
239
198
  throw new Error("Lane approval wait requires an observed pending native tool approval");