omp-superagent 0.0.0-stage → 0.1.1

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 (76) hide show
  1. package/DESIGN.md +1361 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +184 -0
  4. package/README.md +205 -2
  5. package/THIRD_PARTY_NOTICES.md +313 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1030 -0
  12. package/docs/releases/0.1.0.md +222 -0
  13. package/docs/releases/0.1.1.md +60 -0
  14. package/package.json +59 -4
  15. package/scripts/check-omp.ts +4 -0
  16. package/scripts/ci.ts +28 -0
  17. package/scripts/prepare-ulw.ts +18 -0
  18. package/scripts/release.ts +50 -0
  19. package/scripts/setup.sh +25 -0
  20. package/skills/head/SKILL.md +259 -0
  21. package/skills/head/references/model-selection.md +263 -0
  22. package/skills/head/references/routing.md +356 -0
  23. package/skills/head/references/supervision.md +312 -0
  24. package/skills/lane/SKILL.md +188 -0
  25. package/skills/lane/references/workflow.md +349 -0
  26. package/src/autostart.ts +295 -0
  27. package/src/board-extension.ts +217 -0
  28. package/src/board.ts +396 -0
  29. package/src/cli.ts +167 -0
  30. package/src/config.ts +191 -0
  31. package/src/contracts.ts +317 -0
  32. package/src/credentials.ts +172 -0
  33. package/src/delivery.ts +7 -0
  34. package/src/dialog.ts +73 -0
  35. package/src/discord-command-registration.ts +201 -0
  36. package/src/discord-commands.ts +29 -0
  37. package/src/discord-markdown.ts +172 -0
  38. package/src/discord.ts +745 -0
  39. package/src/extension.ts +289 -0
  40. package/src/gateway-client.ts +222 -0
  41. package/src/gateway-protocol.ts +85 -0
  42. package/src/gateway-restart.ts +151 -0
  43. package/src/gateway-server.ts +392 -0
  44. package/src/gateway-store.ts +237 -0
  45. package/src/gateway.ts +638 -0
  46. package/src/head-recovery.ts +61 -0
  47. package/src/host-extension.ts +449 -0
  48. package/src/host-owner.ts +350 -0
  49. package/src/host-protocol.ts +136 -0
  50. package/src/host.ts +414 -0
  51. package/src/installed-omp.ts +63 -0
  52. package/src/lane-extension.ts +179 -0
  53. package/src/lane-models.ts +75 -0
  54. package/src/lane-report.ts +70 -0
  55. package/src/managed-ulw-probe.ts +172 -0
  56. package/src/managed-ulw.ts +471 -0
  57. package/src/message-order.ts +21 -0
  58. package/src/messenger-commands.ts +16 -0
  59. package/src/messengers.ts +114 -0
  60. package/src/native-presets.ts +282 -0
  61. package/src/native-sessions.ts +32 -0
  62. package/src/native-settings.ts +129 -0
  63. package/src/repository.ts +12 -0
  64. package/src/runtime.ts +3864 -0
  65. package/src/setup-judge.ts +34 -0
  66. package/src/setup-memory.ts +39 -0
  67. package/src/setup-profiles.ts +84 -0
  68. package/src/setup.ts +300 -0
  69. package/src/slack-command-registration.ts +217 -0
  70. package/src/slack-commands.ts +18 -0
  71. package/src/slack.ts +776 -0
  72. package/src/store.ts +806 -0
  73. package/src/telegram-command-registration.ts +155 -0
  74. package/src/telegram.ts +661 -0
  75. package/src/workflow.ts +94 -0
  76. package/upstream/ulw.json +9 -0
@@ -0,0 +1,61 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { HeadRecoveryAttempt } from "./contracts";
3
+
4
+ const object = (value: unknown): Record<string, unknown> =>
5
+ value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
6
+
7
+ /** Only journal identities and native outcome fields leave this evidence reader. */
8
+ export function headRecoveryEvidence(entries: unknown[], owner: Pick<HeadRecoveryAttempt,
9
+ "sessionId" | "sessionFile" | "requestId" | "cursor">, boundary?: string) {
10
+ const journal = entries.map(object);
11
+ const start = owner.cursor === null ? -1 : journal.findIndex(entry => entry.id === owner.cursor);
12
+ const end = boundary === undefined ? journal.length - 1 : journal.findIndex(entry => entry.id === boundary);
13
+ if (owner.cursor !== null && start < 0 || end <= start || typeof journal[end]?.id !== "string") return null;
14
+ const slice = journal.slice(start + 1, end + 1);
15
+ const matches = (entry: Record<string, unknown>, type: string) => entry.type === "custom" && entry.customType === type
16
+ && object(entry.data).sessionId === owner.sessionId && object(entry.data).sessionFile === owner.sessionFile;
17
+ const receipts = slice.filter(entry => matches(entry, "rpc_prompt_result"));
18
+ const receiptsForRequest = receipts.filter(entry => object(object(entry.data).frame).id === owner.requestId);
19
+ if (receiptsForRequest.length !== 1 || receipts.length !== 1) return null;
20
+ const receipt = receiptsForRequest[0]!;
21
+ const frame = object(object(receipt.data).frame);
22
+ const starts = slice.filter(entry => matches(entry, "rpc_agent_start"));
23
+ const latestStart = starts.at(-1);
24
+ const latestStartIndex = latestStart ? slice.indexOf(latestStart) : -1;
25
+ // Another submitted user message is an ownership boundary, even if its RPC
26
+ // receipt has not arrived. Do not borrow its assistant outcome.
27
+ const users = slice.filter(entry => entry.type === "message" && object(entry.message).role === "user");
28
+ const firstAssistantIndex = slice.findIndex(entry => entry.type === "message" && object(entry.message).role === "assistant");
29
+ if (users.length > 1 || users.some(entry => firstAssistantIndex >= 0 && slice.indexOf(entry) > firstAssistantIndex)) return null;
30
+ const assistants = slice.slice(latestStartIndex + 1).filter(entry => entry.type === "message"
31
+ && object(entry.message).role === "assistant");
32
+ const latestAssistant = assistants.at(-1);
33
+ const latestRunStatus = object(latestAssistant?.message).stopReason;
34
+ let outcome: "done" | "cancelled" | undefined;
35
+ const receiptData = object(receipt.data);
36
+ const startData = object(latestStart?.data);
37
+ const receiptAfterStart = typeof receiptData.runOrdinal === "number" && typeof startData.runOrdinal === "number"
38
+ && receiptData.hostPid === startData.hostPid
39
+ ? receiptData.runOrdinal >= startData.runOrdinal
40
+ : slice.indexOf(receipt) > latestStartIndex;
41
+ if (frame.status === "aborted" && (!latestStart || receiptAfterStart)) outcome = "cancelled";
42
+ if (frame.status === "completed") {
43
+ if (frame.agentInvoked === false && !latestStart) outcome = "done";
44
+ else if (latestStart && (latestRunStatus === "stop" || latestRunStatus === "length")) outcome = "done";
45
+ else if (latestStart && latestRunStatus === "aborted") outcome = "cancelled";
46
+ }
47
+ const selected = [receipt, ...starts, ...assistants];
48
+ if (selected.some(entry => typeof entry.id !== "string")) return null;
49
+ const entryIds = [...new Set(selected.map(entry => String(entry.id)))];
50
+ const proof = { entryIds, receiptStatus: String(frame.status), latestRunStatus: latestRunStatus ?? null,
51
+ outcome: outcome ?? null };
52
+ return { ...proof, boundary: String(journal[end]!.id),
53
+ fingerprint: createHash("sha256").update(JSON.stringify(slice.map(entry => [
54
+ entry.id, entry.type, entry.customType,
55
+ matches(entry, "rpc_prompt_result") ? object(entry.data).frame : null,
56
+ matches(entry, "rpc_prompt_result") || matches(entry, "rpc_agent_start")
57
+ ? [object(entry.data).hostPid ?? null, object(entry.data).instanceKey ?? null, object(entry.data).runOrdinal ?? null] : null,
58
+ entry.type === "message" ? object(entry.message).role : null,
59
+ entry.type === "message" ? object(entry.message).stopReason : null,
60
+ ]))).digest("hex") };
61
+ }
@@ -0,0 +1,449 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as net from "node:net";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
5
+ import { collectReports, collectScope, targetScope } from "@oh-my-pi/pi-coding-agent/cli/ps-data";
6
+ import { cfgDefaultThinkingLevel } from "@oh-my-pi/pi-coding-agent/session/settings";
7
+ import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
8
+ import { lookup as lookupSetting } from "@oh-my-pi/pi-coding-agent/config/registry";
9
+ import { pickDefaultAvailableModel, resolveModelRoleValue } from "@oh-my-pi/pi-coding-agent/config/model-resolver";
10
+ import { resolveThinkingLevelForModel } from "@oh-my-pi/pi-tui/thinking";
11
+ import { readSessionHeaderId } from "@oh-my-pi/pi-coding-agent/session/session-loader";
12
+ import { HostChannel, serviceCompletionRecorded, type Frame } from "./host-protocol";
13
+ import { parseSessionEntries } from "@oh-my-pi/pi-coding-agent/session/session-loader";
14
+ import { USER_INTERRUPT_LABEL } from "@oh-my-pi/pi-coding-agent/session/messages";
15
+ import { fitAbortAndRestoreQueueResponse } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-mode";
16
+ import type { RpcAbortAndRestoreQueueResult, RpcSessionState } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
17
+ import { calculateTokensPerSecond } from "@oh-my-pi/pi-coding-agent/utils/token-rate";
18
+ import { toolWireSchema } from "@oh-my-pi/pi-ai/utils/schema";
19
+ import type { LanePresetSnapshot } from "./contracts";
20
+
21
+ /** Runs inside the installed native host. All native objects come from injected pi.pi. */
22
+ export default function hostExtension(pi: ExtensionAPI): void {
23
+ const socketPath = process.env.OMP_SUPERAGENT_NATIVE_SOCKET;
24
+ const configPath = process.env.OMP_SUPERAGENT_HOST_CONFIG;
25
+ if (!socketPath || !configPath) return;
26
+ const goalEnabled = lookupSetting("goal.enabled");
27
+ if (!goalEnabled) throw new Error("Installed OMP lacks the public goal.enabled setting");
28
+ let context: ExtensionContext | undefined;
29
+ let server: net.Server | undefined;
30
+ let mutationHeld = false;
31
+ let observationHeld = false;
32
+ let runOrdinal = 0;
33
+ let instanceKey: string | undefined;
34
+ const serviceStarts = new Map<string, { name: string; cwd: string; owner: string }>();
35
+ const interrupts = new Map<string, Promise<PromiseSettledResult<void>[]>>();
36
+ const generationKey = (value: Frame) => JSON.stringify([value.owner, value.id, value.startedAt, value.restartCount]);
37
+ const rootSession = () => {
38
+ const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
39
+ if (!(root instanceof pi.pi.AgentSession)) throw new Error("Native root session is unavailable");
40
+ return root;
41
+ };
42
+ const serviceObservation = (data: Frame) => {
43
+ const root = rootSession();
44
+ root.sessionManager.appendCustomEntry("superagent_service_generation", {
45
+ rootSessionId: root.sessionManager.getSessionId(), ...data,
46
+ });
47
+ root.sessionManager.flushSync();
48
+ };
49
+ // Registry slots differ between the standalone executable and npm SDK.
50
+ // Mirror native layers into this SDK before using any imported setting handle.
51
+ const readOnly = (settings: Settings): Settings => {
52
+ const parent = settings.overlayParent();
53
+ return Settings.mirror({
54
+ write() { throw new Error("Native settings observation is read-only"); },
55
+ refresh() { throw new Error("Native settings observation is read-only"); },
56
+ cloneForCwd() { throw new Error("Native settings observation is read-only"); },
57
+ }, settings.mirrorState(), parent ? readOnly(parent) : undefined);
58
+ };
59
+ const exact = () => {
60
+ const ref = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID);
61
+ const session = ref?.session;
62
+ if (!ref || !context || !(session instanceof pi.pi.AgentSession)
63
+ || session.sessionManager.getSessionId() !== context.sessionManager.getSessionId()
64
+ || session.sessionManager.getSessionFile() !== context.sessionManager.getSessionFile())
65
+ throw new Error("Exact native session ownership is unavailable");
66
+ if (typeof session.hasAdmittedSubmission !== "boolean" || typeof session.hasPostPromptWork !== "boolean"
67
+ || typeof session.isBusyForSnapshot !== "boolean" || typeof session.isStreaming !== "boolean"
68
+ || typeof session.isCompacting !== "boolean" || typeof session.isDisposed !== "boolean"
69
+ || !Number.isSafeInteger(session.queuedMessageCount) || session.queuedMessageCount < 0
70
+ || typeof session.instanceKey !== "string" || !session.instanceKey
71
+ || typeof session.hasPendingAsyncWork !== "function" || typeof session.getAsyncJobTree !== "function"
72
+ || typeof session.getAsyncJobSnapshot !== "function" || typeof session.beginDispose !== "function"
73
+ || typeof session.abortCompaction !== "function" || typeof session.goalRuntime.pauseGoal !== "function"
74
+ || typeof session.waitForIdle !== "function" || typeof session.yieldQueue?.has !== "function"
75
+ || typeof session.sessionManager.ensureOnDisk !== "function" || typeof session.sessionManager.flushSync !== "function"
76
+ || typeof session.settings.reloadFromDisk !== "function" || typeof session.settings.mirrorState !== "function"
77
+ || typeof session.settings.getModelRoles !== "function" || typeof session.hasPendingAsyncWork() !== "boolean")
78
+ throw new Error("Installed OMP lacks required public native lifecycle capabilities");
79
+ if (instanceKey !== undefined && session.instanceKey !== instanceKey)
80
+ throw new Error("Native session instance changed within this managed Host");
81
+ instanceKey ??= session.instanceKey;
82
+ return { ref, session, id: session.sessionManager.getSessionId(), file: session.sessionManager.getSessionFile() };
83
+ };
84
+ const snapshot = () => {
85
+ const { session } = exact();
86
+ return { modelRoles: session.settings.getModelRoles(),
87
+ defaultThinkingLevel: cfgDefaultThinkingLevel.get(readOnly(session.settings)) };
88
+ };
89
+ const observation = (customType: string, data: Frame) => {
90
+ const { session, id, file } = exact();
91
+ try {
92
+ pi.appendEntry(customType, { ...data, sessionId: id, sessionFile: file, instanceKey: session.instanceKey });
93
+ session.sessionManager.flushSync();
94
+ const entry = session.sessionManager.getEntries().at(-1);
95
+ if (entry?.type !== "custom" || entry.customType !== customType)
96
+ throw new Error("Native observation entry identity is unavailable");
97
+ return entry.id;
98
+ } catch (error) { observationHeld = true; throw error; }
99
+ };
100
+ const owned = async (drain = false) => {
101
+ const identity = exact();
102
+ const registry = pi.pi.AgentRegistry.global();
103
+ const refs = registry.list();
104
+ const refEpoch = refs.map(ref => [ref.id, ref.generation, ref.parentId, ref.session?.instanceKey, ref.sessionFile]);
105
+ const journal = identity.session.sessionManager.getEntries();
106
+ const lineage = journal.flatMap(entry => {
107
+ if (entry.type !== "custom" || entry.customType !== "superagent_native_descendant") return [];
108
+ const data = entry.data as { rootSessionId?: string; agentId?: string; parentId?: string; sessionId?: string };
109
+ return data?.rootSessionId === identity.id && typeof data.agentId === "string"
110
+ && typeof data.parentId === "string" && typeof data.sessionId === "string" ? [data] : [];
111
+ });
112
+ const agents = new Set([pi.pi.MAIN_AGENT_ID]);
113
+ for (let changed = true; changed;) {
114
+ changed = false;
115
+ for (const ref of refs) if (ref.parentId && agents.has(ref.parentId) && !agents.has(ref.id)) {
116
+ agents.add(ref.id); changed = true;
117
+ }
118
+ for (const row of lineage) if (agents.has(row.parentId!) && !agents.has(row.agentId!)) {
119
+ agents.add(row.agentId!); changed = true;
120
+ }
121
+ }
122
+ const owners = new Set<string>([identity.id, ...agents]);
123
+ const ownerFiles = new Map<string, string>();
124
+ if (identity.file) ownerFiles.set(identity.id, identity.file);
125
+ for (const ref of refs) if (agents.has(ref.id) && ref.session)
126
+ {
127
+ const id = ref.session.sessionManager.getSessionId();
128
+ owners.add(id);
129
+ const file = ref.session.sessionManager.getSessionFile();
130
+ if (file) ownerFiles.set(id, file);
131
+ }
132
+ for (const row of lineage) if (agents.has(row.agentId!)) {
133
+ owners.add(row.sessionId!);
134
+ const file = (row as Frame).sessionFile;
135
+ if (typeof file === "string") ownerFiles.set(row.sessionId!, file);
136
+ }
137
+ for (const ref of refs) if (agents.has(ref.id) && !ref.session
138
+ && !lineage.some(row => row.agentId === ref.id)) {
139
+ if (!ref.sessionFile) throw new Error("Detached descendant service ownership cannot be established");
140
+ const id = await readSessionHeaderId(ref.sessionFile);
141
+ if (!id) throw new Error("Detached descendant session identity is unavailable");
142
+ owners.add(id);
143
+ ownerFiles.set(id, ref.sessionFile);
144
+ }
145
+ const reports = await collectReports(true, {});
146
+ const currentRefs = registry.list();
147
+ if (exact().ref !== identity.ref || currentRefs.length !== refs.length
148
+ || refs.some((ref, index) => currentRefs[index] !== ref))
149
+ throw new Error("Native ownership tree changed during service observation");
150
+ const services = reports.flatMap(report => report.daemons
151
+ .filter(row => owners.has(row.snapshot.owner ?? ""))
152
+ .map(row => ({ ...row, brokerPid: report.scope.brokerPid })));
153
+ // An offline broker's persisted downgrade is not an authoritative live observation.
154
+ const servicesUnknown = services.some(row => !row.supervised || !row.brokerPid || !row.snapshot.owner);
155
+ const liveServices = services.some(row => !["exited", "failed"].includes(row.snapshot.state));
156
+ const deliveriesPending = (session: InstanceType<typeof pi.pi.AgentSession>) => {
157
+ const delivery = session.getAsyncJobSnapshot({ recentLimit: 0 })?.delivery;
158
+ return !!delivery && (delivery.delivering || delivery.queued > 0 || delivery.pendingJobIds.length > 0);
159
+ };
160
+ const descendantsUnknown = () => refs.some(ref => agents.has(ref.id) && ref.session !== null
161
+ && !(ref.session instanceof pi.pi.AgentSession));
162
+ const descendantsBusy = () => refs.some(ref => agents.has(ref.id) && ref.id !== pi.pi.MAIN_AGENT_ID
163
+ && (registry.isRunning(ref) || ref.session instanceof pi.pi.AgentSession
164
+ && (ref.session.hasPendingAsyncWork() || ref.session.hasAdmittedSubmission || ref.session.hasPostPromptWork
165
+ || ref.session.isBusyForSnapshot || ref.session.yieldQueue.has() || deliveriesPending(ref.session))));
166
+ const trackingKnown = journal.some(entry => entry.type === "custom" && entry.customType === "superagent_service_tracking"
167
+ && (entry.data as Frame)?.rootSessionId === identity.id && (entry.data as Frame)?.known === true);
168
+ const generations = journal.flatMap(entry => entry.type === "custom" && entry.customType === "superagent_service_generation"
169
+ && (entry.data as Frame)?.rootSessionId === identity.id ? [entry.data as Frame] : []);
170
+ const serviceEntries = new Map<string, readonly unknown[]>();
171
+ for (const owner of new Set(services.map(row => row.snapshot.owner!).concat(
172
+ generations.map(row => (row.daemon as Frame | undefined)?.owner).filter((owner): owner is string => typeof owner === "string")))) {
173
+ const file = ownerFiles.get(owner);
174
+ if (!file) continue;
175
+ const live = refs.find(ref => ref.session?.sessionManager.getSessionId() === owner)?.session;
176
+ if (!drain && live instanceof pi.pi.AgentSession) {
177
+ serviceEntries.set(owner, live.sessionManager.getEntries());
178
+ continue;
179
+ }
180
+ if (drain && live instanceof pi.pi.AgentSession) {
181
+ await live.waitForIdle();
182
+ await live.sessionManager.ensureOnDisk();
183
+ live.sessionManager.flushSync();
184
+ }
185
+ serviceEntries.set(owner, parseSessionEntries(await fs.readFile(file, "utf8")));
186
+ }
187
+ const recorded = (daemon: Frame) => serviceCompletionRecorded(daemon, serviceEntries.get(String(daemon.owner)) ?? []);
188
+ const tracked = generations.filter(row => row.daemon && typeof row.daemon === "object").map(row => row.daemon as Frame);
189
+ const knownKeys = new Set(tracked.map(generationKey));
190
+ const serviceDeliveryUnknown = generations.some(row => row.uncertain === true)
191
+ || generations.some(row => row.phase === "attempt" && !generations.some(result =>
192
+ result.phase === "result" && result.toolCallId === row.toolCallId))
193
+ || generations.some(row => Array.isArray(row.previous) && row.previous.some(value => {
194
+ const previous = value as Frame;
195
+ return owners.has(String(previous.owner)) && !knownKeys.has(generationKey(previous));
196
+ }))
197
+ || tracked.some(daemon => {
198
+ if (services.some(row => generationKey(row.snapshot as unknown as Frame) === generationKey(daemon)
199
+ && !["exited", "failed"].includes(row.snapshot.state))) return false;
200
+ const entries = serviceEntries.get(String(daemon.owner)) ?? [];
201
+ // A recorded terminal completion supplies the final snapshot even when
202
+ // the broker now exposes a replacement generation under the same name.
203
+ return !entries.some(value => {
204
+ const entry = value as Frame;
205
+ const daemons = (entry.details as Frame | undefined)?.daemons;
206
+ return entry.type === "custom_message" && entry.customType === "launch-completion"
207
+ && Array.isArray(daemons) && daemons.some(value => generationKey(value as Frame) === generationKey(daemon)
208
+ && serviceCompletionRecorded(value as Frame, entries));
209
+ });
210
+ })
211
+ || services.some(row => !trackingKnown || !knownKeys.has(generationKey(row.snapshot as unknown as Frame))
212
+ || ["exited", "failed"].includes(row.snapshot.state) && !recorded(row.snapshot as unknown as Frame));
213
+ if (drain) {
214
+ const refreshed = (await collectReports(true, {})).flatMap(report => report.daemons
215
+ .filter(row => owners.has(row.snapshot.owner ?? "")).map(row => row.snapshot));
216
+ if (!isDeepStrictEqual(services.map(row => row.snapshot), refreshed))
217
+ throw new Error("Native services changed while their durable completion evidence was drained");
218
+ }
219
+ if (!isDeepStrictEqual(refEpoch, registry.list().map(ref =>
220
+ [ref.id, ref.generation, ref.parentId, ref.session?.instanceKey, ref.sessionFile])))
221
+ throw new Error("Native descendant identity changed during completion readback");
222
+ const tree = identity.session.getAsyncJobTree({ recentLimit: 0 });
223
+ return { identity, tree, unknown: servicesUnknown || serviceDeliveryUnknown || descendantsUnknown(),
224
+ busy: liveServices || descendantsBusy() || deliveriesPending(identity.session) || !!tree?.running.length };
225
+ };
226
+ const localIdle = () => {
227
+ const { session } = exact();
228
+ return !mutationHeld && !observationHeld && !session.isDisposed && !session.isBusyForSnapshot && !session.isStreaming
229
+ && !session.isCompacting && !session.hasAdmittedSubmission && !session.hasPostPromptWork
230
+ && session.queuedMessageCount === 0 && !session.hasPendingAsyncWork()
231
+ && !session.yieldQueue.has()
232
+ && !session.getGoalModeState()?.enabled;
233
+ };
234
+ const handle = async (command: Frame): Promise<unknown> => {
235
+ if (command.type === "get_session_stats") return exact().session.getSessionStats();
236
+ if (command.type === "get_state") {
237
+ const { session } = exact();
238
+ const queued = session.getQueuedMessages();
239
+ // Adapted from oh-my-pi v18.20.2 rpc-mode.ts (MIT; THIRD_PARTY_NOTICES.md).
240
+ // Copyright (c) 2025 Mario Zechner; 2025-2026 Can Bölük; 2026 Stencil Labs, Inc.
241
+ // This is a live observation while an owner command is pending, never an
242
+ // idle receipt. Disposal still requires the stock RPC settlement check.
243
+ return {
244
+ model: session.model, thinkingLevel: session.thinkingLevel,
245
+ isStreaming: session.isStreaming, isCompacting: session.isCompacting,
246
+ steeringMode: session.steeringMode, followUpMode: session.followUpMode,
247
+ interruptMode: session.interruptMode, sessionFile: session.sessionFile,
248
+ sessionId: session.sessionId, sessionName: session.sessionName,
249
+ autoCompactionEnabled: session.autoCompactionEnabled,
250
+ queuedMessageCount: session.queuedMessageCount, hasPendingAsyncWork: session.hasPendingAsyncWork(),
251
+ isSettled: false,
252
+ queuedMessages: { steering: [...queued.steering], followUp: [...queued.followUp], liveSteered: queued.liveSteered },
253
+ todoPhases: session.getTodoPhases(), fastModeEnabled: session.isFastModeEnabled(),
254
+ tokensPerSecond: calculateTokensPerSecond(session.messages, session.isStreaming),
255
+ fastModeActive: session.isFastModeActive(), slowModeSupported: session.isSlowModeSupported(),
256
+ slowModeEnabled: session.isSlowModeEnabled(), slowModeScope: session.getSlowModeScope(),
257
+ usageLimit: session.getUsageLimitState(), messageCount: session.messages.length,
258
+ systemPrompt: session.systemPrompt,
259
+ dumpTools: session.agent.state.tools.map(tool => ({
260
+ name: tool.name, description: tool.description, parameters: toolWireSchema(tool), examples: tool.examples,
261
+ })),
262
+ contextUsage: session.getContextUsage(), goal: session.getGoalModeState() ?? null,
263
+ } satisfies RpcSessionState;
264
+ }
265
+ if (command.type === "interrupt_maintenance") {
266
+ const { session } = exact();
267
+ const restored = command.restoreQueue === true ? session.clearQueue({ forInterrupt: true }) : undefined;
268
+ // abort() raises its barrier and withdraws marked internal context before
269
+ // its first await. Do not await its compaction cleanup until the owner has
270
+ // cancelled native UI; the pending compact may itself be awaiting that UI.
271
+ interrupts.set(String(command.id), Promise.allSettled([session.abort({ reason: USER_INTERRUPT_LABEL })]));
272
+ if (session.getGoalModeState()?.enabled) await session.goalRuntime.pauseGoal();
273
+ return restored ?? {};
274
+ }
275
+ if (command.type === "finish_interrupt") {
276
+ const token = String(command.token);
277
+ const pending = interrupts.get(token);
278
+ if (!pending) throw new Error("Native interrupt completion is unavailable");
279
+ try {
280
+ const [result] = await pending;
281
+ if (result!.status === "rejected") throw result!.reason;
282
+ } finally { interrupts.delete(token); }
283
+ return {};
284
+ }
285
+ if (command.type === "activate") {
286
+ const identity = exact();
287
+ // Native's default tool selection omits the goal tool. Add it only for
288
+ // that default, never widen an explicit --tools or --no-tools selection.
289
+ if (command.toolsExplicitlySelected === false && command.noTools === false
290
+ && goalEnabled.get(readOnly(identity.session.settings)) === true)
291
+ await pi.setActiveTools([...new Set([...pi.getActiveTools(), "goal"])]);
292
+ pi.events.emit("superagent:host-ready", { sessionId: identity.id, sessionFile: identity.file, pid: process.pid });
293
+ return {};
294
+ }
295
+ if (command.type === "observe") {
296
+ if (command.customType !== "rpc_prompt_result") throw new Error("Unsupported native observation");
297
+ return { entryId: observation("rpc_prompt_result", {
298
+ frame: command.frame, runOrdinal: command.runOrdinal, hostPid: command.hostPid,
299
+ }) };
300
+ }
301
+ if (command.type === "snapshot") {
302
+ const ownership = await owned();
303
+ return { hostPid: process.pid, sessionId: ownership.identity.id, sessionFile: ownership.identity.file,
304
+ generation: ownership.identity.ref.generation, instanceKey, settingsScope: "session", modelSettings: snapshot(),
305
+ hasOwnedRunningWork: ownership.unknown ? undefined : ownership.busy, mutationHeld, observationHeld,
306
+ admitted: ownership.identity.session.hasAdmittedSubmission,
307
+ postPromptWork: ownership.identity.session.hasPostPromptWork };
308
+ }
309
+ if (command.type === "set_model_preset") {
310
+ if (!localIdle()) throw new Error("Native session is busy or has an unresolved mutation");
311
+ const ownership = await owned(true);
312
+ if (ownership.unknown || ownership.busy || !localIdle()) throw new Error("Native owned work is not authoritatively drained");
313
+ const preset = command.preset as LanePresetSnapshot;
314
+ if (!preset || typeof preset.modelRoles !== "object"
315
+ || Object.values(preset.modelRoles).some(value => typeof value !== "string"))
316
+ throw new Error("A complete frozen model preset is required");
317
+ mutationHeld = true;
318
+ const settings = ownership.identity.session.settings;
319
+ await settings.reloadFromDisk();
320
+ const config = JSON.parse(await fs.readFile(configPath, "utf8"));
321
+ const previous = settings.getModelRoles();
322
+ const omitted = new Set([...Object.keys(previous), ...Object.keys(config.modelRoles ?? {})]);
323
+ config.modelRoles = { ...Object.fromEntries([...omitted].map(role => [role, null])), ...preset.modelRoles };
324
+ if (preset.defaultThinkingLevel !== undefined) config.defaultThinkingLevel = preset.defaultThinkingLevel;
325
+ const temporary = `${configPath}.${crypto.randomUUID()}`;
326
+ await fs.writeFile(temporary, JSON.stringify(config), { mode: 0o600, flag: "wx" });
327
+ await fs.rename(temporary, configPath);
328
+ await settings.reloadFromDisk();
329
+ if (exact().ref !== ownership.identity.ref || !isDeepStrictEqual(snapshot(), preset))
330
+ throw new Error("Native settings readback differs; mutation remains held");
331
+ const candidates = ownership.identity.session.getAvailableModels();
332
+ const selected = preset.modelRoles.default
333
+ ? resolveModelRoleValue(preset.modelRoles.default, candidates, { settings: readOnly(settings) })
334
+ : { model: pickDefaultAvailableModel(candidates.filter(model => context!.modelRegistry.hasConfiguredAuth(model)),
335
+ provider => context!.modelRegistry.hasConcreteAuth(provider)) };
336
+ const model = selected.model;
337
+ if (!model) throw new Error("Native model resolution failed; mutation remains held");
338
+ const expectedLevel = "thinkingLevel" in selected && selected.thinkingLevel !== undefined
339
+ ? selected.thinkingLevel : preset.defaultThinkingLevel;
340
+ const effectiveLevel = expectedLevel === "auto" ? "auto"
341
+ : expectedLevel === undefined ? undefined : resolveThinkingLevelForModel(model, expectedLevel);
342
+ if (!command.preserveActiveModel) {
343
+ await ownership.identity.session.setModelTemporary(model, expectedLevel);
344
+ }
345
+ if (exact().ref !== ownership.identity.ref || !isDeepStrictEqual(snapshot(), preset)
346
+ || !command.preserveActiveModel && (ownership.identity.session.model?.provider !== model.provider
347
+ || ownership.identity.session.model?.id !== model.id
348
+ || expectedLevel !== undefined && ownership.identity.session.configuredThinkingLevel() !== effectiveLevel))
349
+ throw new Error("Native model/effort readback differs; mutation remains held");
350
+ mutationHeld = false;
351
+ return { name: command.name, settingsScope: "session", preset: snapshot(), model: ownership.identity.session.model };
352
+ }
353
+ if (command.type === "shutdown_host") {
354
+ if (!localIdle()) throw new Error("session_busy");
355
+ const ownership = await owned(true);
356
+ await ownership.identity.session.waitForIdle();
357
+ await ownership.identity.session.sessionManager.ensureOnDisk();
358
+ const finalOwnership = await owned(true);
359
+ if (exact().ref !== ownership.identity.ref || !localIdle() || ownership.unknown || finalOwnership.unknown
360
+ || ownership.busy || finalOwnership.busy) throw new Error("session_busy");
361
+ // The owner has fenced its inputs and revalidated stock state/UI. Nothing
362
+ // awaits between this final native guard, disposal fence and shutdown.
363
+ ownership.identity.session.sessionManager.flushSync();
364
+ ownership.identity.session.beginDispose();
365
+ context!.shutdown();
366
+ return { shutdown: true, sessionId: ownership.identity.id, sessionFile: ownership.identity.file };
367
+ }
368
+ throw new Error("Unsupported private native control");
369
+ };
370
+ pi.on("agent_start", () => {
371
+ if (context?.agent.kind === "main") observation("rpc_agent_start", { runOrdinal: ++runOrdinal, hostPid: process.pid });
372
+ });
373
+ pi.on("tool_call", async (event, ctx) => {
374
+ const input = event.input as Frame;
375
+ if (event.toolName !== "bash" || typeof input.name !== "string") return;
376
+ const start = { name: input.name, cwd: ctx.cwd, owner: ctx.sessionManager.getSessionId() };
377
+ serviceStarts.set(event.toolCallId, start);
378
+ const report = await collectScope(await targetScope({ dir: ctx.cwd }));
379
+ serviceObservation({ phase: "attempt", toolCallId: event.toolCallId, ...start,
380
+ previous: report.daemons.filter(row => row.snapshot.name === start.name).map(row => row.snapshot) });
381
+ });
382
+ pi.on("tool_result", async (event, ctx) => {
383
+ const start = serviceStarts.get(event.toolCallId);
384
+ if (!start) return;
385
+ serviceStarts.delete(event.toolCallId);
386
+ const details = event.details as { service?: { name?: string; pid?: number } } | undefined;
387
+ const report = await collectScope(await targetScope({ dir: start.cwd }));
388
+ const row = report.daemons.find(row => row.snapshot.name === start.name && row.snapshot.owner === start.owner
389
+ && row.snapshot.pid === details?.service?.pid);
390
+ serviceObservation({ phase: "result", toolCallId: event.toolCallId, owner: ctx.sessionManager.getSessionId(),
391
+ name: start.name, uncertain: event.isError || !row?.supervised || !report.scope.brokerPid || !details?.service,
392
+ ...(row ? { daemon: row.snapshot } : {}) });
393
+ });
394
+ pi.on("session_start", async (_event, ctx) => {
395
+ if (ctx.agent.kind !== "main") {
396
+ const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
397
+ if (!(root instanceof pi.pi.AgentSession) || !ctx.agent.parentId)
398
+ throw new Error("Native descendant root ownership is unavailable");
399
+ root.sessionManager.appendCustomEntry("superagent_native_descendant", {
400
+ rootSessionId: root.sessionManager.getSessionId(), agentId: ctx.agent.id, parentId: ctx.agent.parentId,
401
+ sessionId: ctx.sessionManager.getSessionId(), sessionFile: ctx.sessionManager.getSessionFile(),
402
+ });
403
+ root.sessionManager.flushSync();
404
+ return;
405
+ }
406
+ if (server) return;
407
+ context = ctx;
408
+ const identity = exact();
409
+ await ctx.sessionManager.ensureOnDisk();
410
+ if (exact().ref !== identity.ref) throw new Error("Native session changed during materialization");
411
+ identity.session.sessionManager.flushSync();
412
+ const journal = identity.session.sessionManager.getEntries();
413
+ if (!journal.some(entry => entry.type === "custom" && entry.customType === "superagent_service_tracking")) {
414
+ identity.session.sessionManager.appendCustomEntry("superagent_service_tracking", {
415
+ rootSessionId: identity.id, known: !journal.some(entry =>
416
+ entry.type === "custom_message" && entry.customType === "launch-completion"
417
+ || entry.type === "message" && entry.message.role === "assistant" && Array.isArray(entry.message.content)
418
+ && entry.message.content.some(part => part.type === "toolCall" && part.name === "bash"
419
+ && typeof (part.arguments as Frame).name === "string")),
420
+ });
421
+ identity.session.sessionManager.flushSync();
422
+ }
423
+ server = net.createServer(socket => {
424
+ const channel = new HostChannel(socket, socket, true);
425
+ channel.encoder.setProtocolVersion(2);
426
+ channel.on("frame", (command: Frame) => {
427
+ if (typeof command.id !== "string") return;
428
+ void handle(command).then(data => {
429
+ channel.send(command.type === "interrupt_maintenance" && command.restoreQueue === true
430
+ ? fitAbortAndRestoreQueueResponse(command.id as string, data as RpcAbortAndRestoreQueueResult, channel.encoder.maxResponseBytes)
431
+ : { type: "response", command: command.type, id: command.id, success: true, data });
432
+ }, error => {
433
+ channel.send({ type: "response", command: command.type, id: command.id, success: false,
434
+ error: error instanceof Error ? error.message : String(error) });
435
+ });
436
+ });
437
+ channel.send({ type: "ready" });
438
+ });
439
+ await new Promise<void>((resolve, reject) => {
440
+ server!.once("error", reject);
441
+ server!.listen(socketPath, () => { void fs.chmod(socketPath, 0o600).then(resolve, reject); });
442
+ });
443
+ });
444
+ pi.on("session_shutdown", async () => {
445
+ if (!context || context.agent.kind !== "main") return;
446
+ server?.close();
447
+ await fs.unlink(socketPath).catch(error => { if (error.code !== "ENOENT") throw error; });
448
+ });
449
+ }