omp-superagent 0.1.5 → 0.1.6

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 (57) hide show
  1. package/DESIGN.md +62 -8
  2. package/README.ko.md +22 -14
  3. package/README.md +36 -22
  4. package/config.example.json +1 -0
  5. package/docs/OPERATIONS.md +180 -42
  6. package/docs/design/execution.md +20 -7
  7. package/docs/design/messaging.md +131 -11
  8. package/docs/releases/0.1.6.md +21 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +7 -2
  19. package/skills/head/references/model-selection.md +4 -4
  20. package/skills/head/references/routing.md +9 -4
  21. package/skills/head/references/supervision.md +4 -3
  22. package/skills/lane/SKILL.md +19 -13
  23. package/skills/lane/references/workflow.md +19 -11
  24. package/src/board.ts +7 -2
  25. package/src/cli.ts +22 -6
  26. package/src/config.ts +26 -3
  27. package/src/contracts.ts +20 -2
  28. package/src/decision-tool.ts +1 -1
  29. package/src/extension.ts +40 -2
  30. package/src/gateway-client.ts +22 -1
  31. package/src/gateway-config.ts +4 -4
  32. package/src/gateway-restart-env.ts +7 -2
  33. package/src/gateway-wire.ts +8 -0
  34. package/src/group-access.ts +222 -0
  35. package/src/group-policy.ts +117 -0
  36. package/src/group-runner-extension.ts +153 -0
  37. package/src/group-runner.ts +284 -0
  38. package/src/head-rotation.ts +88 -0
  39. package/src/host-extension.ts +52 -3
  40. package/src/host-protocol.ts +1 -0
  41. package/src/host-sdk-helper.ts +7 -0
  42. package/src/host-superkit.ts +26 -0
  43. package/src/host.ts +5 -1
  44. package/src/lane-extension.ts +6 -3
  45. package/src/managed-memory-helper.ts +22 -0
  46. package/src/managed-memory.ts +100 -0
  47. package/src/managed-ulw.ts +16 -20
  48. package/src/messenger-command-catalog.json +3 -2
  49. package/src/native-launch-profile.ts +16 -0
  50. package/src/native-settings.ts +9 -3
  51. package/src/result-attachment.ts +211 -0
  52. package/src/runtime.ts +1109 -157
  53. package/src/setup-memory.ts +15 -33
  54. package/src/setup.ts +24 -22
  55. package/src/store.ts +214 -13
  56. package/src/topic-history.ts +430 -0
  57. package/src/topic-request.ts +88 -0
@@ -0,0 +1,284 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { lstat, mkdir, mkdtemp, open, realpath, rm, symlink, writeFile } from "node:fs/promises";
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { GROUP_MODEL_SELECTOR } from "./group-policy";
8
+ import { restrictedWorkTools } from "./group-runner-extension";
9
+
10
+ type Input = {
11
+ readonly mode: "chat" | "work";
12
+ readonly text: string;
13
+ readonly id: string;
14
+ readonly stateDir: string;
15
+ readonly executable: string;
16
+ readonly model: string;
17
+ readonly repository?: string;
18
+ readonly signal?: AbortSignal;
19
+ };
20
+
21
+ type Result = { readonly ok: boolean; readonly text?: string; readonly worktree?: string };
22
+ type Command = {
23
+ readonly cwd: string;
24
+ readonly env: Readonly<Record<string, string>>;
25
+ readonly signal: AbortSignal;
26
+ readonly bytes: number;
27
+ readonly stdin?: string;
28
+ };
29
+
30
+ class RestrictedRunError extends Error {}
31
+ const safePath = "/usr/bin:/bin";
32
+ const extension = fileURLToPath(new URL("./group-runner-extension.ts", import.meta.url));
33
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
34
+ const checkoutBytes = 64 * 1024 * 1024;
35
+ const gitOid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
36
+ const modelApis = new Set(["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai"]);
37
+ const isolationFlags = ["--no-session", "--no-tools", "--no-extensions", "--no-context-files", "--no-rules",
38
+ "--no-skills", "--no-title", "--no-lsp", "--no-pty", "--no-prewalk", "--offline"] as const;
39
+
40
+ function command(argv: readonly [string, ...string[]], { cwd, env, signal, bytes, stdin }: Command): Promise<Buffer> {
41
+ signal.throwIfAborted();
42
+ return new Promise((done, fail) => {
43
+ const child = spawn(argv[0], argv.slice(1), { cwd, env, detached: true, stdio: ["pipe", "pipe", "ignore"] });
44
+ let failure: Error | undefined;
45
+ let size = 0;
46
+ const frames: Buffer[] = [];
47
+ const stop = (error: Error) => {
48
+ if (failure) return;
49
+ failure = error;
50
+ if (child.pid === undefined) return;
51
+ try { process.kill(-child.pid, "SIGKILL"); }
52
+ catch (e) { if (!(e instanceof Error && "code" in e && e.code === "ESRCH")) failure = new RestrictedRunError("Cannot stop restricted process"); }
53
+ };
54
+ const abort = () => stop(new RestrictedRunError("Restricted process cancelled or timed out"));
55
+ signal.addEventListener("abort", abort, { once: true });
56
+ child.on("error", stop);
57
+ child.stdin.on("error", stop);
58
+ child.stdout.on("error", stop);
59
+ child.stdout.on("data", (chunk: Buffer) => {
60
+ if (failure) return;
61
+ size += chunk.length;
62
+ if (size > bytes) stop(new RestrictedRunError("Restricted process exceeded output budget"));
63
+ else frames.push(chunk);
64
+ });
65
+ child.once("close", code => {
66
+ signal.removeEventListener("abort", abort);
67
+ if (failure || code !== 0) fail(failure ?? new RestrictedRunError("Restricted process failed"));
68
+ else done(Buffer.concat(frames, size));
69
+ });
70
+ if (signal.aborted) abort();
71
+ child.stdin.end(stdin);
72
+ });
73
+ }
74
+
75
+ function record(value: unknown): Record<string, unknown> {
76
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
77
+ return Object.fromEntries(Object.entries(value));
78
+ }
79
+
80
+ async function isolatedModel(state: string, selector: string): Promise<string> {
81
+ const match = GROUP_MODEL_SELECTOR.exec(selector);
82
+ if (!match) throw new RestrictedRunError("Configure an exact restricted provider/model");
83
+ const [, provider, model] = match;
84
+ const file = await open(join(state, "models.yml"), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
85
+ try {
86
+ const info = await file.stat();
87
+ const max = 32 * 1024;
88
+ if (!info.isFile() || info.nlink !== 1 || info.size > max || (info.mode & 0o077) !== 0 || info.uid !== process.getuid?.())
89
+ throw new RestrictedRunError("Restricted models.yml must be a small private regular file");
90
+ const buffer = Buffer.alloc(max + 1);
91
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
92
+ if (bytesRead > max) throw new RestrictedRunError("Restricted models.yml exceeds size budget");
93
+ const source = record(record(Bun.YAML.parse(utf8.decode(buffer.subarray(0, bytesRead)))).providers);
94
+ const { api, apiKey, baseUrl, models } = record(source[provider]);
95
+ if (typeof api !== "string" || !modelApis.has(api) || typeof apiKey !== "string" ||
96
+ !/^[!-~]{1,4096}$/.test(apiKey) || apiKey.startsWith("!") || typeof baseUrl !== "string" || !Array.isArray(models))
97
+ throw new RestrictedRunError("Restricted model requires a static API, base URL and literal key");
98
+ const url = new URL(baseUrl);
99
+ const loopback = url.hostname === "127.0.0.1" || url.hostname === "[::1]";
100
+ if ((url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) || url.username || url.password || url.search || url.hash)
101
+ throw new RestrictedRunError("Invalid restricted model base URL");
102
+ const selected = models.map(record).filter(row => row.id === model);
103
+ if (selected.length !== 1) throw new RestrictedRunError("Restricted model ID must match exactly one model");
104
+ const { name, reasoning, contextWindow, maxTokens, cost } = selected[0];
105
+ const rates = Object.fromEntries(["input", "output", "cacheRead", "cacheWrite"].map(key => {
106
+ const rate = record(cost)[key];
107
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0) throw new RestrictedRunError("Missing restricted model price");
108
+ return [key, rate];
109
+ }));
110
+ if (typeof name !== "string" || name.length < 1 || name.length > 150 || typeof contextWindow !== "number" ||
111
+ !Number.isSafeInteger(contextWindow) || contextWindow < 1024 || contextWindow > 2_000_000 ||
112
+ typeof maxTokens !== "number" || !Number.isSafeInteger(maxTokens) || maxTokens < 1 || maxTokens >= contextWindow)
113
+ throw new RestrictedRunError("Invalid restricted model limits");
114
+ return JSON.stringify({ providers: { [provider]: { api, apiKey, baseUrl: url.href, auth: "apiKey",
115
+ models: [{ id: model, name, reasoning: reasoning === true, input: ["text"], contextWindow,
116
+ maxTokens: Math.min(maxTokens, 8192), cost: rates }],
117
+ } } });
118
+ } finally { await file.close(); }
119
+ }
120
+
121
+ function isWithin(root: string, path: string): boolean {
122
+ const rel = relative(root, path);
123
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
124
+ }
125
+
126
+ async function checkout(input: Input, state: string, sandbox: string, signal: AbortSignal): Promise<string> {
127
+ if (!input.repository || !isAbsolute(input.repository)) throw new RestrictedRunError("Missing exact repository root");
128
+ const repo = await realpath(input.repository);
129
+ if (isWithin(repo, state)) throw new RestrictedRunError("Worktree state must be outside the source repository");
130
+ const gitOptions = {
131
+ cwd: repo, signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]), bytes: 8 * 1024 * 1024,
132
+ env: { PATH: safePath, HOME: sandbox, XDG_CONFIG_HOME: sandbox, GIT_CONFIG_NOSYSTEM: "1",
133
+ GIT_CONFIG_GLOBAL: "/dev/null", GIT_NO_LAZY_FETCH: "1", GIT_NO_REPLACE_OBJECTS: "1",
134
+ GIT_TERMINAL_PROMPT: "0", GIT_ALLOW_PROTOCOL: "" },
135
+ };
136
+ const git = (args: readonly string[], overrides: Partial<Command> = {}) => command(["/usr/bin/git",
137
+ "-c", `core.hooksPath=${sandbox}`, "-c", "core.fsmonitor=false", "-c", "core.protectHFS=true",
138
+ "-c", "core.protectNTFS=true", "-c", "core.sparseCheckout=false", "-c", "core.splitIndex=false", ...args,
139
+ ], { ...gitOptions, ...overrides });
140
+ const top = utf8.decode(await git(["rev-parse", "--show-toplevel"])).replace(/\n$/, "");
141
+ if (await realpath(top) !== repo) throw new RestrictedRunError("Configured directory is not a repository root");
142
+ const oid = utf8.decode(await git(["rev-parse", "--verify", "HEAD^{commit}"])).trim();
143
+ if (!gitOid.test(oid)) throw new RestrictedRunError("Invalid repository revision");
144
+ const tree = utf8.decode(await git(["ls-tree", "-r", "-z", "-l", oid])).split("\0");
145
+ if (tree.pop() !== "" || tree.length > 8192) throw new RestrictedRunError("Repository exceeds checkout entry budget");
146
+ let totalBytes = 0;
147
+ const files = tree.map(entry => {
148
+ const parts = /^(100644|100755|120000|160000) (?:blob|commit) ([a-f0-9]+) +(\d+|-)\t([^\0]+)$/.exec(entry);
149
+ if (!parts) throw new RestrictedRunError("Unsupported repository entry");
150
+ const [, mode, hash, size, path] = parts;
151
+ const length = mode === "160000" && size === "-" ? 0 : Number(size);
152
+ if (!gitOid.test(hash) || !Number.isSafeInteger(length) || length > 16 * 1024 * 1024 ||
153
+ path.split("/").some(part => !part || part === "." || part === ".." || part.toLowerCase() === ".git" ||
154
+ /[\\\x00-\x1f\x7f]/.test(part)))
155
+ throw new RestrictedRunError("Repository entry exceeds checkout safety bounds");
156
+ totalBytes += length;
157
+ if (totalBytes > checkoutBytes) throw new RestrictedRunError("Repository exceeds checkout byte budget");
158
+ return { mode, hash, path, length };
159
+ });
160
+ const blobs = files.filter(file => file.mode !== "160000");
161
+ const packed = await git(["cat-file", "--batch"], {
162
+ stdin: blobs.map(file => `${file.hash}\n`).join(""),
163
+ bytes: totalBytes + blobs.length * 100,
164
+ });
165
+ const claim = join(state, `work-${createHash("sha256").update(input.id).digest("hex")}`);
166
+ // The exclusive claim means an interrupted submission is never silently replayed over its checkout.
167
+ await mkdir(claim, { mode: 0o700 });
168
+ const worktree = join(claim, "checkout");
169
+ await git(["worktree", "add", "--detach", "--no-checkout", "--", worktree, oid]);
170
+ // Build only the index with Git. Never ask Git to write a file through checkout filters or hooks.
171
+ await git(["read-tree", oid], { cwd: worktree });
172
+ const directories = new Set([worktree]);
173
+ async function ensureDirectory(path: string): Promise<void> {
174
+ if (directories.has(path)) return;
175
+ await ensureDirectory(dirname(path));
176
+ // Never reuse an unexpected entry, including a symlink or a case-folded path alias.
177
+ await mkdir(path);
178
+ directories.add(path);
179
+ }
180
+ let cursor = 0;
181
+ for (const file of files) {
182
+ gitOptions.signal.throwIfAborted();
183
+ const path = join(worktree, file.path);
184
+ if (file.mode === "160000") { await ensureDirectory(path); continue; }
185
+ const prefix = `${file.hash} blob ${file.length}\n`;
186
+ const start = cursor + Buffer.byteLength(prefix);
187
+ const end = start + file.length;
188
+ if (packed.toString("ascii", cursor, start) !== prefix || packed[end] !== 10)
189
+ throw new RestrictedRunError("Git blob did not match its checked tree entry");
190
+ await ensureDirectory(dirname(path));
191
+ if (file.mode === "120000") await symlink(packed.subarray(start, end), path);
192
+ else await writeFile(path, packed.subarray(start, end), { flag: "wx", mode: file.mode === "100755" ? 0o755 : 0o644 });
193
+ cursor = end + 1;
194
+ }
195
+ return worktree;
196
+ }
197
+
198
+ function settledResult(output: Buffer, input: Input): { readonly text?: string } | undefined {
199
+ const permitted: readonly string[] = input.mode === "work" ? restrictedWorkTools : [];
200
+ let reply: string | undefined;
201
+ let terminalCount = 0;
202
+ let stopped = false;
203
+ for (const line of utf8.decode(output).split("\n")) {
204
+ if (!line) continue;
205
+ const event = record(JSON.parse(line));
206
+ if (event.type === "tool_execution_start" &&
207
+ (typeof event.toolName !== "string" || !permitted.includes(event.toolName))) return undefined;
208
+ if (event.type === "agent_end" && event.isTerminal !== false) terminalCount++;
209
+ if (event.type !== "message_end") continue;
210
+ const message = record(event.message);
211
+ if (message.role !== "assistant") continue;
212
+ if (`${message.provider}/${message.model}` !== input.model || terminalCount !== 0 || !Array.isArray(message.content))
213
+ return undefined;
214
+ stopped = message.stopReason === "stop";
215
+ const blocks = message.content.map(record);
216
+ if (input.mode === "chat") {
217
+ if (!stopped || blocks.some(block => block.type !== "text" && block.type !== "thinking")) return undefined;
218
+ reply = blocks.flatMap(block => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
219
+ }
220
+ }
221
+ if (terminalCount !== 1 || !stopped) return undefined;
222
+ if (input.mode === "work") return {};
223
+ return reply && Buffer.byteLength(reply) <= 16 * 1024 ? { text: reply } : undefined;
224
+ }
225
+
226
+ /** A one-shot stock OMP process. Neither mode joins an owner profile, session or repository cwd. */
227
+ export async function runRestrictedGroup(input: Input): Promise<Result> {
228
+ let sandbox: string | undefined;
229
+ let worktree: string | undefined;
230
+ try {
231
+ const deadline = AbortSignal.timeout(input.mode === "chat" ? 60_000 : 240_000);
232
+ const signal = input.signal ? AbortSignal.any([deadline, input.signal]) : deadline;
233
+ signal.throwIfAborted();
234
+ if (!isAbsolute(input.executable) || !isAbsolute(input.stateDir) || !input.id || input.id.length > 1024 ||
235
+ !input.text.trim() || Buffer.byteLength(input.text) > 16 * 1024) return { ok: false };
236
+ const configuredState = resolve(input.stateDir);
237
+ const stateInfo = await lstat(configuredState);
238
+ if (!stateInfo.isDirectory() || (stateInfo.mode & 0o077) !== 0 || stateInfo.uid !== process.getuid?.())
239
+ return { ok: false };
240
+ const state = await realpath(configuredState);
241
+ const model = await isolatedModel(state, input.model);
242
+ sandbox = await mkdtemp(join(await realpath("/tmp"), "omp-sa-group-"));
243
+ const home = join(sandbox, "home");
244
+ const agent = join(home, ".omp", "agent");
245
+ const cwd = join(home, "empty");
246
+ await mkdir(agent, { mode: 0o700, recursive: true });
247
+ await mkdir(cwd, { mode: 0o700 });
248
+ await writeFile(join(agent, "models.yml"), model, { mode: 0o600 });
249
+ await writeFile(join(agent, "config.yml"), JSON.stringify({
250
+ memory: { backend: "off" }, autolearn: { enabled: false }, mcp: { enableProjectConfig: false },
251
+ marketplace: { autoUpdate: false }, telemetry: { otlpExportEnabled: false },
252
+ }), { mode: 0o600 });
253
+ const env = { PATH: safePath, HOME: home, TMPDIR: sandbox, XDG_CONFIG_HOME: join(home, "config"),
254
+ XDG_DATA_HOME: join(home, "data"), XDG_STATE_HOME: join(home, "state"), XDG_CACHE_HOME: join(home, "cache"),
255
+ XDG_RUNTIME_DIR: sandbox, PI_CODING_AGENT_DIR: agent, GIT_CEILING_DIRECTORIES: sandbox };
256
+ const launch = { cwd, env, signal, bytes: 512 * 1024 };
257
+ const help = utf8.decode(await command([input.executable, "--help"], launch));
258
+ const required = [...isolationFlags, "--mode", "--model", "--thinking", "--max-time", "--max-cost", "--system-prompt",
259
+ ...(input.mode === "work" ? ["--extension", "--tools", "--approval-mode"] : [])];
260
+ if (!required.every(flag => new RegExp(`(?:^|\\s)${flag}(?=[=,\\s])`, "m").test(help)))
261
+ return { ok: false };
262
+ if (input.mode === "work") worktree = await checkout(input, state, sandbox, signal);
263
+ const flags = worktree
264
+ ? ["--extension", extension, "--tools", restrictedWorkTools.join(","), "--approval-mode", "yolo"] : [];
265
+ const output = await command([input.executable, "--mode", "json", ...isolationFlags,
266
+ "--model", input.model, "--thinking", "off", "--max-time", worktree ? "210s" : "45s", "--max-cost", worktree ? "0.25" : "0.05",
267
+ "--system-prompt", "The user message is a JSON string. Interpret its escapes literally. " + (worktree
268
+ ? "Work only with the three supplied repository tools. Your results stay local."
269
+ : "Answer the group message from this one interaction. You have no tools or prior conversation."),
270
+ ...flags,
271
+ ], { cwd, signal, env: worktree ? { ...env, OMP_SA_RESTRICTED_WORKTREE: worktree } : env,
272
+ // Stock print mode still auto-reads ASCII @path in piped prompts and expands ^model.
273
+ // JSON quoting also keeps user input out of slash and template command dispatch.
274
+ bytes: 8 * 1024 * 1024, stdin: JSON.stringify(input.text).replace(/[@^]/g, char => char === "@" ? "\\u0040" : "\\u005e") });
275
+ const result = settledResult(output, input);
276
+ if (worktree) return { ok: result !== undefined, worktree };
277
+ return result ? { ok: true, ...result } : { ok: false };
278
+ } catch (error) {
279
+ if (!(error instanceof Error)) throw error;
280
+ return worktree ? { ok: false, worktree } : { ok: false };
281
+ } finally {
282
+ if (sandbox) await rm(sandbox, { recursive: true, force: true });
283
+ }
284
+ }
@@ -0,0 +1,88 @@
1
+ import { basename, dirname, join } from "node:path";
2
+ import type { LanePresetSnapshot } from "./contracts";
3
+
4
+ export const HEAD_ROTATION_KEY = "gateway:head-rotation";
5
+ export const HEAD_SESSION_FILE_KEY = "main:sessionFile";
6
+ export const HEAD_ROTATION_PROBE = "superagent:head-rotation-probe";
7
+ export const HEAD_ROTATION_GUARD = "superagent:head-rotation-guard";
8
+ export const MIN_HEAD_IDLE_MS = 30 * 60 * 1000;
9
+
10
+ export interface RotationSelection {
11
+ readonly provider: string;
12
+ readonly modelId: string;
13
+ readonly reasoning: boolean;
14
+ readonly thinkingLevel: string | null;
15
+ readonly configuredThinkingLevel: string | null;
16
+ readonly modelSettings: LanePresetSnapshot;
17
+ }
18
+
19
+ export interface RotationNative {
20
+ readonly hostPid: number;
21
+ readonly sessionId: string;
22
+ readonly sessionFile: string;
23
+ readonly nativeRun: number;
24
+ readonly contextPercent: number;
25
+ readonly selection: RotationSelection;
26
+ }
27
+
28
+ export interface RotationResident {
29
+ readonly id: string;
30
+ readonly generation: number;
31
+ readonly pid: number;
32
+ readonly sessionId: string;
33
+ readonly inputId?: string;
34
+ readonly requestIds: readonly string[];
35
+ readonly result?: { readonly status: string; readonly agentInvoked: boolean; readonly goalResume?: true };
36
+ readonly ownedRuns: number;
37
+ readonly assistantOutcome?: { readonly status: "completed" | "error" | "aborted"; readonly run: number };
38
+ readonly entryId?: string;
39
+ }
40
+
41
+ export interface RotationAttestation {
42
+ readonly generation: number;
43
+ readonly nativeRun: number;
44
+ readonly idleMs: number;
45
+ readonly contextPercent: number;
46
+ readonly selection: RotationSelection;
47
+ readonly residents: readonly RotationResident[];
48
+ }
49
+
50
+ export interface HeadRotation {
51
+ readonly id: string;
52
+ readonly stage: "stopping" | "starting" | "launching" | "complete" | "refused";
53
+ readonly original: {
54
+ readonly pid: number;
55
+ readonly sessionId: string;
56
+ readonly sessionFile: string;
57
+ };
58
+ readonly sessionFile: string;
59
+ readonly stopBoundary: string | null;
60
+ readonly attestation: RotationAttestation;
61
+ readonly replacementSessionId: string | null;
62
+ }
63
+
64
+ export interface RotationProbeEvent {
65
+ readonly state: RotationNative;
66
+ readonly respond: (attestation: Promise<RotationAttestation | null>) => void;
67
+ }
68
+
69
+ export interface RotationGuardEvent {
70
+ readonly id: string;
71
+ readonly state: RotationNative;
72
+ readonly respond: (allowed: boolean) => void;
73
+ }
74
+
75
+ export function readHeadRotation(encoded: string | null): HeadRotation | null {
76
+ return encoded === null ? null : JSON.parse(encoded);
77
+ }
78
+
79
+ export function activeHeadSessionFile(stateDir: string, value: string | null): string {
80
+ const base = join(stateDir, "sessions", "main");
81
+ if (value === null) return join(base, "session.jsonl");
82
+ const id = basename(dirname(value));
83
+ if (!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(id)
84
+ || value !== join(base, "rotated", id, "session.jsonl")) {
85
+ throw new Error("Invalid managed HEAD session file");
86
+ }
87
+ return value;
88
+ }
@@ -12,11 +12,16 @@ import { resolveThinkingLevelForModel } from "@oh-my-pi/pi-tui/thinking";
12
12
  import { parseSessionEntries, readSessionHeaderId } from "@oh-my-pi/pi-coding-agent/session/session-loader";
13
13
  import { HostChannel, indexServiceCompletions, serviceGenerationKey, type Frame, type ServiceUnit } from "./host-protocol";
14
14
  import { USER_INTERRUPT_LABEL } from "@oh-my-pi/pi-coding-agent/session/messages";
15
+ import { MAX_RPC_REASSEMBLED_BYTES } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-frame";
15
16
  import { fitAbortAndRestoreQueueResponse } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-mode";
16
17
  import type { RpcAbortAndRestoreQueueResult, RpcSessionState } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
17
18
  import { calculateTokensPerSecond } from "@oh-my-pi/pi-coding-agent/utils/token-rate";
18
19
  import { toolWireSchema } from "@oh-my-pi/pi-ai/utils/schema";
19
20
  import type { LanePresetSnapshot } from "./contracts";
21
+ import { MANAGED_ULW_ENV } from "./managed-ulw";
22
+ import { verifyHostSuperkit } from "./host-superkit";
23
+ import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE, type RotationGuardEvent,
24
+ type RotationNative, type RotationProbeEvent } from "./head-rotation";
20
25
 
21
26
  const terminalService = (state: ServiceUnit["state"]) => state === "exited" || state === "failed";
22
27
  const serviceGeneration = ({ owner, id, generation, startedAt, restartCount }: ServiceUnit) =>
@@ -58,6 +63,8 @@ export default function hostExtension(pi: ExtensionAPI): void {
58
63
  let observationHeld = false;
59
64
  let runOrdinal = 0;
60
65
  let instanceKey: string | undefined;
66
+ const selectedSuperkit = process.env[MANAGED_ULW_ENV];
67
+ let loadedSuperkitPath: string | undefined;
61
68
  type ServiceStart = {
62
69
  readonly name: string; readonly scope: UnitScope; readonly owner: string;
63
70
  readonly sessionId: string; readonly toolCallId: string;
@@ -343,7 +350,32 @@ export default function hostExtension(pi: ExtensionAPI): void {
343
350
  && !session.yieldQueue.has()
344
351
  && !session.getGoalModeState()?.enabled;
345
352
  };
353
+ const rotationState = (): RotationNative | null => {
354
+ if (process.env.OMP_SUPERAGENT_ROLE !== "head" || !localIdle()) return null;
355
+ const { id, file, session } = exact();
356
+ const usage = session.getContextUsage();
357
+ const model = session.model;
358
+ if (!file || !usage || typeof usage.tokens !== "number" || !Number.isFinite(usage.tokens)
359
+ || typeof usage.percent !== "number" || !Number.isFinite(usage.percent) || usage.percent < 50
360
+ || !Number.isFinite(usage.contextWindow) || usage.contextWindow <= 0
361
+ || !model || typeof model.reasoning !== "boolean" || typeof session.configuredThinkingLevel !== "function") return null;
362
+ const { modelRoles, defaultThinkingLevel } = snapshot();
363
+ const roles = Object.fromEntries(Object.entries(modelRoles).filter((entry): entry is [string, string] =>
364
+ typeof entry[1] === "string"));
365
+ return { hostPid: process.pid, sessionId: id, sessionFile: file, nativeRun: runOrdinal,
366
+ contextPercent: usage.percent,
367
+ selection: { provider: model.provider, modelId: model.id, reasoning: model.reasoning,
368
+ thinkingLevel: session.thinkingLevel ?? null, configuredThinkingLevel: session.configuredThinkingLevel() ?? null,
369
+ modelSettings: { modelRoles: roles, ...(defaultThinkingLevel !== undefined ? { defaultThinkingLevel } : {}) } } };
370
+ };
346
371
  const handle = async (command: Frame): Promise<unknown> => {
372
+ if (command.type === "get_head_rotation") {
373
+ const state = rotationState();
374
+ if (!state) return null;
375
+ let attestation: Parameters<RotationProbeEvent["respond"]>[0] | undefined;
376
+ pi.events.emit(HEAD_ROTATION_PROBE, { state, respond: value => { attestation = value; } } satisfies RotationProbeEvent);
377
+ return attestation ?? null;
378
+ }
347
379
  if (command.type === "get_session_stats") return exact().session.getSessionStats();
348
380
  if (command.type === "get_state") {
349
381
  const { session } = exact();
@@ -354,6 +386,10 @@ export default function hostExtension(pi: ExtensionAPI): void {
354
386
  // idle receipt. Disposal still requires the stock RPC settlement check.
355
387
  return {
356
388
  model: session.model, thinkingLevel: session.thinkingLevel,
389
+ ...(command.thinkingLevels === true ? {
390
+ configuredThinkingLevel: session.configuredThinkingLevel() ?? null,
391
+ thinkingLevels: session.getAvailableEffortSelectors(),
392
+ } : {}),
357
393
  isStreaming: session.isStreaming, isCompacting: session.isCompacting,
358
394
  steeringMode: session.steeringMode, followUpMode: session.followUpMode,
359
395
  interruptMode: session.interruptMode, sessionFile: session.sessionFile,
@@ -417,12 +453,16 @@ export default function hostExtension(pi: ExtensionAPI): void {
417
453
  }
418
454
  if (command.type === "snapshot") {
419
455
  const ownership = await owned();
456
+ // The owner requires this first snapshot before opening its public socket.
457
+ loadedSuperkitPath ??= await verifyHostSuperkit(ownership.identity.session, selectedSuperkit);
420
458
  // Only an owner that implements the cursor command can advertise it to peers.
421
- return { ...ownerIdentity(ownership.identity), settingsScope: "session", modelSettings: snapshot(),
459
+ return { ...ownerIdentity(ownership.identity), loadedSuperkitPath, settingsScope: "session", modelSettings: snapshot(),
422
460
  journalCursorControlVersion: 1,
423
461
  hasOwnedRunningWork: ownership.unknown ? undefined : ownership.busy, mutationHeld, observationHeld,
424
462
  admitted: ownership.identity.session.hasAdmittedSubmission,
425
- postPromptWork: ownership.identity.session.hasPostPromptWork };
463
+ postPromptWork: ownership.identity.session.hasPostPromptWork,
464
+ ...(typeof ownership.identity.session.configuredThinkingLevel === "function"
465
+ ? { configuredThinkingLevel: ownership.identity.session.configuredThinkingLevel() ?? null } : {}) };
426
466
  }
427
467
  if (command.type === "set_model_preset") {
428
468
  if (!localIdle()) throw new Error("Native session is busy or has an unresolved mutation");
@@ -476,6 +516,14 @@ export default function hostExtension(pi: ExtensionAPI): void {
476
516
  const finalOwnership = await owned(true);
477
517
  if (exact().ref !== ownership.identity.ref || !localIdle() || ownership.unknown || finalOwnership.unknown
478
518
  || ownership.busy || finalOwnership.busy) throw new Error("session_busy");
519
+ if (typeof command.headRotation === "string") {
520
+ const state = rotationState();
521
+ if (!state) throw new Error("session_busy");
522
+ let allowed = false;
523
+ pi.events.emit(HEAD_ROTATION_GUARD, { id: command.headRotation, state,
524
+ respond: value => { allowed = value; } } satisfies RotationGuardEvent);
525
+ if (!allowed) throw new Error("session_busy");
526
+ }
479
527
  // The owner has fenced its inputs and revalidated stock state/UI. Nothing
480
528
  // awaits between this final native guard, disposal fence and shutdown.
481
529
  ownership.identity.session.sessionManager.flushSync();
@@ -601,8 +649,9 @@ export default function hostExtension(pi: ExtensionAPI): void {
601
649
  channel.on("frame", (command: Frame) => {
602
650
  if (command.type === "response" || typeof command.id !== "string") return;
603
651
  void handle(command).then(data => {
652
+ // This private channel always uses v2: fit the logical response, not an individual JSONL chunk.
604
653
  channel.send(command.type === "interrupt_maintenance" && command.restoreQueue === true
605
- ? fitAbortAndRestoreQueueResponse(command.id as string, data as RpcAbortAndRestoreQueueResult, channel.encoder.maxResponseBytes)
654
+ ? fitAbortAndRestoreQueueResponse(command.id as string, data as RpcAbortAndRestoreQueueResult, MAX_RPC_REASSEMBLED_BYTES)
606
655
  : { type: "response", command: command.type, id: command.id, success: true, data });
607
656
  }, error => {
608
657
  channel.send({ type: "response", command: command.type, id: command.id, success: false,
@@ -11,6 +11,7 @@ export type HostState = RpcSessionState & {
11
11
  hostPid: number;
12
12
  adapterOwnerPid: number;
13
13
  adapterProtocol: "owned-stock-stdio-v1";
14
+ readonly loadedSuperkitPath?: string;
14
15
  readonly journalCursorVersion?: 1;
15
16
  settingsScope: "session";
16
17
  modelSettings: LanePresetSnapshot;
@@ -5,11 +5,13 @@ import { rename, writeFile } from "node:fs/promises";
5
5
  import type { RpcAbortAndRestoreQueueResult } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
6
6
  import type { HostOptions } from "./host";
7
7
  import type { Frame } from "./host-protocol";
8
+ import type { RotationSelection } from "./head-rotation";
8
9
 
9
10
  type Manifest = {
10
11
  readonly options: Omit<HostOptions, "env">;
11
12
  readonly args: string[];
12
13
  readonly processBackend: "broker" | "daemon";
14
+ readonly headRotationSelection?: RotationSelection;
13
15
  };
14
16
  type Exit = {
15
17
  readonly pid: number; readonly ownerPid: number; readonly code: number | null; readonly signal: string | null;
@@ -71,6 +73,11 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
71
73
  const session = SessionManager.create(options.cwd, dirname(options.sessionFile));
72
74
  try {
73
75
  await session.setSessionFile(options.sessionFile);
76
+ const selection = manifest.headRotationSelection;
77
+ if (selection) {
78
+ session.appendModelChange(`${selection.provider}/${selection.modelId}`);
79
+ session.appendThinkingLevelChange(selection.thinkingLevel ?? undefined, selection.configuredThinkingLevel ?? undefined);
80
+ }
74
81
  await session.ensureOnDisk();
75
82
  session.flushSync();
76
83
  } finally { await session.close(); }
@@ -0,0 +1,26 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { sep } from "node:path";
3
+ import type { AgentSession } from "@oh-my-pi/pi-coding-agent";
4
+ import { readManagedUlwPackage } from "./managed-ulw";
5
+
6
+ /** Inspect this stock session's bound factories, not a second SDK loader or launch argv. */
7
+ export async function verifyHostSuperkit(session: AgentSession, selected: string | undefined): Promise<string> {
8
+ if (!selected) throw new Error("Managed omp-superkit launch path is missing");
9
+ const { packagePath, extensionFiles } = readManagedUlwPackage(selected);
10
+ const missingModule = () => {
11
+ const runner = session.extensionRunner;
12
+ if (!runner || typeof runner.getLoadedExtensions !== "function" || typeof runner.isExtensionActive !== "function")
13
+ throw new Error("Installed OMP cannot report its active extensions");
14
+ const active = new Set(runner.getLoadedExtensions()
15
+ .filter(ext => ext.resolvedPath.startsWith(packagePath + sep) && runner.isExtensionActive(ext.path))
16
+ .map(ext => realpathSync(ext.resolvedPath)));
17
+ return extensionFiles.find(file => !active.has(file));
18
+ };
19
+ let missing = missingModule();
20
+ if (missing && session.hasPendingDeferredExtensions) {
21
+ await session.loadDeferredExtensions();
22
+ missing = missingModule();
23
+ }
24
+ if (missing) throw new Error(`Managed omp-superkit extension is not active: ${missing}`);
25
+ return packagePath;
26
+ }
package/src/host.ts CHANGED
@@ -186,7 +186,11 @@ export class HostConnection {
186
186
  || state.adapterOwnerPid < 1) {
187
187
  throw new Error("Endpoint did not identify an owned stock-stdio adapter and persistent OMP session");
188
188
  }
189
- if (messageUpdates === "activity-v1") await connection.#enableActivityUpdates();
189
+ if (messageUpdates === "activity-v1") {
190
+ if (typeof state.loadedSuperkitPath !== "string" || !path.isAbsolute(state.loadedSuperkitPath))
191
+ throw new Error("Native Host has not verified its omp-superkit extension; stop and start the Host");
192
+ await connection.#enableActivityUpdates();
193
+ }
190
194
  return { connection, identity: { pid: state.hostPid, ownerPid: state.adapterOwnerPid,
191
195
  sessionId: state.sessionId, sessionFile: state.sessionFile, dev: after.dev, ino: after.ino } };
192
196
  } catch (error) {
@@ -5,6 +5,7 @@ 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
7
  import { type LaneEvidence, type LaneReportEvent, parseLaneReportResult } from "./lane-report";
8
+ import { registerResultAttach, RESULT_ATTACH_TOOL } from "./result-attachment";
8
9
  import { registerDecisionAsk } from "./decision-tool";
9
10
 
10
11
  const instructions = readFileSync(new URL("../skills/lane/SKILL.md", import.meta.url), "utf8");
@@ -29,7 +30,7 @@ const parameters = Type.Union([
29
30
  Type.Object({ status: Type.Literal("resolved"), summary, waiting, evidence: requiredEvidence },
30
31
  { additionalProperties: false }),
31
32
  ]);
32
- const coordinationTool = (name: string) => name === "lane_report" || name.startsWith("board_");
33
+ const coordinationTool = (name: string) => name === "lane_report" || name === RESULT_ATTACH_TOOL || name.startsWith("board_");
33
34
  const record = (value: unknown): value is Record<string, unknown> =>
34
35
  value !== null && typeof value === "object" && !Array.isArray(value);
35
36
  const text = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
@@ -122,6 +123,7 @@ function toolEvidence(id: string, records: ReturnType<typeof toolRecords>): Lane
122
123
  export default function laneExtension(pi: ExtensionAPI): void {
123
124
  if (process.env.OMP_SUPERAGENT_ROLE !== "lane") return;
124
125
  registerDecisionAsk(pi);
126
+ registerResultAttach(pi);
125
127
  let approvalSessionId: string | undefined;
126
128
  const pendingApprovals = new Set<string>();
127
129
  const approvals = (ctx: ExtensionContext) => {
@@ -137,7 +139,8 @@ export default function laneExtension(pi: ExtensionAPI): void {
137
139
  if (ctx.agent.kind !== "main") {
138
140
  // Subtract only our tool; never re-enable an operator-excluded native tool.
139
141
  const active = pi.getActiveTools();
140
- if (active.includes("lane_report")) await pi.setActiveTools(active.filter(name => name !== "lane_report"));
142
+ const scoped = active.filter(name => name !== "lane_report" && name !== RESULT_ATTACH_TOOL);
143
+ if (scoped.length !== active.length) await pi.setActiveTools(scoped);
141
144
  }
142
145
  });
143
146
  pi.on("tool_call", (event, ctx) => {
@@ -145,7 +148,7 @@ export default function laneExtension(pi: ExtensionAPI): void {
145
148
  return { block: true, reason: "Lane reporting is restricted to the root lane session" };
146
149
  }
147
150
  if (ctx.agent.kind === "main" && (event.toolName === "ask" || event.toolName === "write" && event.input.path === "xd://ask")) {
148
- return { block: true, reason: "Use decision_ask so HEAD can review the lane's choices before the owner is interrupted. Native execution approvals are unchanged." };
151
+ return { block: true, reason: "Use decision_ask for a structured owner choice or manager review. Native execution approvals are unchanged." };
149
152
  }
150
153
  });
151
154
  pi.on("tool_approval_requested", (event, ctx) => {
@@ -0,0 +1,22 @@
1
+ // Configuration only. Never import the SDK entry point, account storage, or a backend.
2
+ import { effectiveMnemopi, parseMemoryConsent, type MnemopiReport } from "./managed-memory";
3
+ import { parseNativeLaunch } from "./native-launch-profile";
4
+
5
+ const unavailable: MnemopiReport = { memory: { status: "unknown" }, updated: false };
6
+ async function check(): Promise<MnemopiReport> {
7
+ const cwd = process.cwd();
8
+ const [operation, ...args] = process.argv.slice(2);
9
+ if (operation !== "inspect" && operation !== "apply-consented") return unavailable;
10
+ const parsed = await parseNativeLaunch([...args, "--mode", "rpc-ui", "--cwd", cwd]);
11
+ if (parsed.mode !== "rpc-ui" || parsed.cwd !== cwd) return unavailable;
12
+ const { Settings } = await import("@oh-my-pi/pi-coding-agent/config/settings");
13
+ const settings = await Settings.loadReadOnly({ cwd, configFiles: parsed.config });
14
+ if (operation === "inspect") return { memory: await effectiveMnemopi(settings), updated: false };
15
+ const expected = parseMemoryConsent(await Bun.stdin.text());
16
+ const { saveMnemopiPreference } = await import("./setup-memory");
17
+ return saveMnemopiPreference(settings, expected);
18
+ }
19
+
20
+ // Native parse/read diagnostics may include private settings. Emit only known fields.
21
+ const report = await check().catch(() => unavailable);
22
+ process.stdout.write(`MANAGED_MEMORY ${JSON.stringify(report)}\n`);