omp-superagent 0.1.13 → 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 (74) hide show
  1. package/DESIGN.md +8 -5
  2. package/THIRD_PARTY_NOTICES.md +6 -0
  3. package/assets/architecture-dark.svg +4 -4
  4. package/assets/architecture.ko-dark.svg +4 -4
  5. package/assets/architecture.ko.svg +4 -4
  6. package/assets/architecture.mmd +5 -5
  7. package/assets/architecture.svg +4 -4
  8. package/config.example.json +1 -0
  9. package/docs/OPERATIONS.en.md +59 -23
  10. package/docs/OPERATIONS.md +53 -18
  11. package/docs/design/execution.md +161 -43
  12. package/docs/design/messaging.md +45 -9
  13. package/docs/releases/0.1.15.md +13 -0
  14. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  16. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  17. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  18. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  19. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  20. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  21. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  22. package/package.json +6 -3
  23. package/scripts/prepare-worker-memory.ts +37 -0
  24. package/skills/head/SKILL.md +22 -47
  25. package/skills/head/references/routing.md +11 -12
  26. package/skills/head/references/supervision.md +10 -14
  27. package/skills/lane/SKILL.md +14 -16
  28. package/skills/lane/references/workflow.md +14 -27
  29. package/src/cli.ts +56 -56
  30. package/src/config/config.ts +4 -0
  31. package/src/contracts.ts +34 -27
  32. package/src/cron/cron-jobs.ts +4 -3
  33. package/src/cron/cron-pr-intake.ts +1 -2
  34. package/src/extension.ts +57 -14
  35. package/src/gateway/gateway-client.ts +14 -12
  36. package/src/group/group-runner.ts +3 -2
  37. package/src/group-runner-extension.ts +7 -3
  38. package/src/host-extension.ts +109 -2
  39. package/src/host-sdk-helper.ts +6 -1
  40. package/src/lane/decision-tool.ts +2 -3
  41. package/src/lane/lane-report.ts +8 -30
  42. package/src/lane/lane-rows.ts +1 -1
  43. package/src/lane/workflow.ts +44 -3
  44. package/src/lane-extension.ts +5 -46
  45. package/src/messaging/discord-context.ts +8 -6
  46. package/src/omp/host-protocol.ts +4 -3
  47. package/src/omp/host.ts +24 -7
  48. package/src/omp/managed-super.ts +43 -27
  49. package/src/omp/native-sessions.ts +12 -0
  50. package/src/omp/worker-memory-import.ts +410 -0
  51. package/src/omp/worker-memory-sdk.ts +8 -0
  52. package/src/operator/setup.ts +8 -13
  53. package/src/pr/pr-github-schema.ts +9 -0
  54. package/src/pr/pr-github.ts +6 -2
  55. package/src/pr/pr-intake-automation.ts +11 -8
  56. package/src/pr/pr-intake-fix.ts +2 -5
  57. package/src/pr/pr-intake-review.ts +7 -7
  58. package/src/routing/topic-history.ts +2 -2
  59. package/src/runtime/controller.ts +444 -408
  60. package/src/runtime/head-recovery.ts +7 -7
  61. package/src/runtime/worker-memory.ts +156 -0
  62. package/src/storage/deferred-routing.ts +1 -7
  63. package/src/storage/store.ts +441 -375
  64. package/src/worker/worker-host.ts +3 -2
  65. package/src/worker/worker-ledger.ts +20 -11
  66. package/src/worker/worker-memory-page.ts +83 -0
  67. package/src/worker/worker-memory-proofs.ts +260 -0
  68. package/src/worker/worker-memory-source.ts +305 -0
  69. package/src/worker/worker-memory-storage.ts +130 -0
  70. package/src/worker/worker-profile.ts +2 -0
  71. package/src/worker/worker-repository.ts +92 -7
  72. package/src/worker/worker-request.ts +1 -0
  73. package/src/worker/worker-service.ts +25 -8
  74. package/src/worker/worker-wire.ts +20 -6
package/src/extension.ts CHANGED
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url";
3
3
  import { join } from "node:path";
4
4
  import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
5
5
  import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
6
+ import { loadLegacyPiModule } from "@oh-my-pi/pi-coding-agent/extensibility/plugins/legacy-pi-compat";
6
7
  import { Type } from "@sinclair/typebox";
7
8
  import { configuredPlatforms, hostPaths, loadConfigSnapshot } from "./config/config";
8
9
  import { loadWakeConfig } from "./config/wake-config";
@@ -28,6 +29,38 @@ import { soulUpdateSchema } from "./omp/soul";
28
29
  // from this package so a same-name workspace skill cannot change the procedure.
29
30
  const headInstructions = readFileSync(new URL("../skills/head/SKILL.md", import.meta.url), "utf8");
30
31
  const headReferenceDirectory = fileURLToPath(new URL("../skills/head/references", import.meta.url));
32
+
33
+ type WorkerMemoryModule = typeof import("./omp/worker-memory-import");
34
+ type WorkerMemorySdk = typeof import("./omp/worker-memory-sdk");
35
+
36
+ function workerMemoryModule(value: unknown): value is WorkerMemoryModule {
37
+ return !!value && typeof value === "object" && "prepareWorkerMemoryImport" in value
38
+ && typeof value.prepareWorkerMemoryImport === "function";
39
+ }
40
+
41
+ function workerMemorySdk(value: unknown): value is WorkerMemorySdk {
42
+ const functions: ReadonlyArray<keyof WorkerMemorySdk> = ["computeMnemopiBankScope", "fastembedModelName",
43
+ "withMnemopiRuntimeOptions", "getMnemopiRuntimeOptions", "embed", "insertLiveEmbeddings"];
44
+ return !!value && typeof value === "object"
45
+ && functions.every(key => typeof Reflect.get(value, key) === "function");
46
+ }
47
+
48
+ async function loadWorkerMemoryDestination() {
49
+ const options = { reload: false };
50
+ try {
51
+ const [sdk, memory] = await Promise.all([
52
+ loadLegacyPiModule(fileURLToPath(new URL("../.upstream/worker-memory-sdk.mjs", import.meta.url)), options),
53
+ loadLegacyPiModule(fileURLToPath(new URL("./omp/worker-memory-import.ts", import.meta.url)), options),
54
+ ]);
55
+ if (workerMemorySdk(sdk) && workerMemoryModule(memory))
56
+ return (session: Parameters<WorkerMemoryModule["prepareWorkerMemoryImport"]>[0], cwd: string) =>
57
+ memory.prepareWorkerMemoryImport(session, cwd, sdk);
58
+ } catch (error) {
59
+ if (!(error instanceof Error)) throw error;
60
+ // Optional capability: don't activate a remote-memory lane without it.
61
+ }
62
+ }
63
+
31
64
  const managerTools: Record<string, true> = {
32
65
  head_recovery: true, head_set_model: true, cron_create: true, soul_update: true,
33
66
  lane_models: true, lane_init_presets: true, lane_set_model: true, lane_review_decision: true,
@@ -45,10 +78,16 @@ const result = (value: unknown) => ({
45
78
  content: [{ type: "text" as const, text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }],
46
79
  details: {},
47
80
  });
48
- const workflowSchema = Type.Optional(Type.Object({
81
+ const workflowSelection = Type.Object({
49
82
  name: Type.Union(WORKFLOW_NAMES.map(name => Type.Literal(name))),
50
83
  reason: Type.String({ minLength: 1 }),
51
- }, { additionalProperties: false }));
84
+ }, { additionalProperties: false });
85
+ const workflowSchema = Type.Optional(workflowSelection);
86
+ const laneModelSelection = {
87
+ model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
88
+ preset: Type.Optional(Type.String({ minLength: 1 })),
89
+ modelReason: Type.String({ minLength: 1 }),
90
+ } as const;
52
91
  const threadTagsSchema = Type.Array(Type.String({ pattern: "^[0-9]{1,20}$" }), { maxItems: 5, uniqueItems: true });
53
92
  const threadTitleSchema = Type.String({ minLength: 1, maxLength: 100, pattern: "\\S" });
54
93
  const threadChangeFields = {
@@ -135,8 +174,6 @@ export default function superagentExtension(pi: ExtensionAPI): void {
135
174
  pi.on("tool_call", (event, ctx) => {
136
175
  if (runtime?.laneDecisionReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_review_decision"))
137
176
  return { block: true, reason: "A lane question permits only answering or escalating its original decision" };
138
- if (runtime?.scopeReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_message"))
139
- return { block: true, reason: "This assignment review permits only a direct same-lane correction from its verified owner message" };
140
177
  if (event.toolName === "soul_update") {
141
178
  try { requireRuntime(ctx).authorizeSoulUpdate(event.input, ctx.sessionManager.getSessionId()); }
142
179
  catch (error) {
@@ -168,8 +205,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
168
205
  return { block: true, reason: "HEAD recovery is restricted to the original main head" };
169
206
  if (["cron_create", "decision_list", "decision_inspect", "decision_withdraw"].includes(event.toolName) && ctx.agent.kind !== "main")
170
207
  return { block: true, reason: "Lane management is restricted to the main superagent head" };
171
- if (!runtime?.headRecoveryActive()) return;
172
- if (ctx.agent.kind !== "main" || event.toolName !== "head_recovery") {
208
+ if (runtime?.headRecoveryActive() && (ctx.agent.kind !== "main" || event.toolName !== "head_recovery")) {
173
209
  runtime.blockHeadRecoveryTool();
174
210
  return { block: true, reason: "The isolated HEAD recovery turn permits only head_recovery; original work is not replayed" };
175
211
  }
@@ -324,9 +360,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
324
360
  parameters: Type.Object({
325
361
  sourceId: Type.String(), title: Type.String(), cwd: Type.String(),
326
362
  kickoff: Type.String({ minLength: 1, description: "A concise message in the user's language stating the concrete approach. Delivered in the work topic before native lane execution; failed or uncertain delivery holds execution." }),
327
- model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
328
- preset: Type.Optional(Type.String({ minLength: 1 })),
329
- modelReason: Type.String({ minLength: 1 }),
363
+ ...laneModelSelection,
330
364
  brief: Type.Optional(Type.String()), acceptance: Type.Optional(Type.Array(Type.String())),
331
365
  workflow: workflowSchema,
332
366
  placement: Type.Optional(Type.Object({
@@ -448,9 +482,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
448
482
  description: "Explicitly change one idle lane's model or full native preset snapshot without changing global OMP settings, the head, or other lanes. Requires a received authorized sourceId, exactly one model/preset and modelReason. Refuses active work, approvals/services/goals or unresolved submissions. Uses durable intent and native readback; do not blindly repeat an uncertain change.",
449
483
  parameters: Type.Object({
450
484
  id: Type.String(), sourceId: Type.String(),
451
- model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
452
- preset: Type.Optional(Type.String({ minLength: 1 })),
453
- modelReason: Type.String({ minLength: 1 }),
485
+ ...laneModelSelection,
454
486
  }),
455
487
  async execute(_id, params, _signal, _onUpdate, ctx) { return result(await requireRuntime(ctx).changeModel(params)); },
456
488
  });
@@ -486,9 +518,12 @@ export default function superagentExtension(pi: ExtensionAPI): void {
486
518
  pi.registerTool({
487
519
  name: "lane_message", label: "Message independent work", loadMode: "essential", approval: "exec",
488
520
  description: "Durably admit a follow-up to a specific open lane. For an original owner request from the exact guild parent of the lane's physical Discord thread, HEAD-reviewed progress and final reports go to that thread, not the parent. Do not duplicate them. Returns its input ID and durable state; pending work reports runtime blocks, blocking uncertain input IDs, and any unconfirmed kickoff. Report such holds instead of retrying. Ordinary same-topic follow-ups steer an eligible active native run by default; ineligible work stays queued. Do not require a separate user /steer command. sourceId identifies the original received user instruction for duplicate suppression. Optional workflow {name,reason} is explicit head selection within that objective; text/quotes/reports never select one. Workflow selections remain serialized, not steered into an active run. The exact workflow/source/handoff is durable and conflicting retries reject. Admission is not execution or completion.",
489
- parameters: Type.Object({ id: Type.String(), text: Type.String(), sourceId: Type.String(), workflow: workflowSchema }),
521
+ parameters: Type.Object({
522
+ id: Type.String(), text: Type.String(), sourceId: Type.String(),
523
+ workflow: Type.Optional(Type.Union([workflowSelection, Type.Null({ description: "No explicit workflow; use ordinary lane dispatch." })])),
524
+ }),
490
525
  async execute(_id, params, _signal, _onUpdate, ctx) {
491
- return result(await requireRuntime(ctx).messageLane(params.id, params.text, params.sourceId, params.workflow));
526
+ return result(await requireRuntime(ctx).messageLane(params.id, params.text, params.sourceId, params.workflow ?? undefined));
492
527
  },
493
528
  });
494
529
  pi.registerTool({
@@ -537,6 +572,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
537
572
  throw new Error("Gateway configuration changed before replacement HEAD initialization");
538
573
  const { config } = snapshot;
539
574
  delete process.env.OMP_SUPERAGENT_RESTART_CONFIG_SHA256;
575
+ const workerMemory = config.remoteMemorySync ? await loadWorkerMemoryDestination() : undefined;
540
576
  const store = new Store(join(config.stateDir, "coordination.sqlite"));
541
577
  let messenger: ReturnType<typeof createGatewayMessenger>;
542
578
  try {
@@ -555,6 +591,13 @@ export default function superagentExtension(pi: ExtensionAPI): void {
555
591
  pi.logger.error(`Superagent: ${error instanceof Error ? error.message : String(error)}`);
556
592
  }, {
557
593
  topicMemory: ctx.memory,
594
+ workerMemoryDestination: (id, file, cwd) => {
595
+ const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID);
596
+ const session = root?.session;
597
+ return root?.id === ctx.agent.id && session instanceof pi.pi.AgentSession
598
+ && session.sessionId === id && session.sessionFile === file && cwd === ctx.cwd
599
+ ? workerMemory?.(session, cwd) : undefined;
600
+ },
558
601
  readHeadQuota: (failure, sessionId, signal) => {
559
602
  const session = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
560
603
  return session instanceof pi.pi.AgentSession && session.sessionId === sessionId
@@ -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 } : {}),
@@ -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. */