omp-superagent 0.0.0-stage → 0.1.2

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 (97) hide show
  1. package/DESIGN.md +1502 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +198 -0
  4. package/README.md +224 -2
  5. package/THIRD_PARTY_NOTICES.md +388 -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 +1178 -0
  12. package/docs/discord-voice.md +96 -0
  13. package/docs/releases/0.1.0.md +222 -0
  14. package/docs/releases/0.1.1.md +60 -0
  15. package/docs/releases/0.1.2.md +53 -0
  16. package/package.json +65 -4
  17. package/scripts/ci.ts +33 -0
  18. package/scripts/prepare-ulw.ts +18 -0
  19. package/scripts/release.ts +58 -0
  20. package/scripts/setup.sh +25 -0
  21. package/scripts/test-omp.sh +36 -0
  22. package/skills/head/SKILL.md +100 -0
  23. package/skills/head/references/model-selection.md +83 -0
  24. package/skills/head/references/routing.md +181 -0
  25. package/skills/head/references/supervision.md +122 -0
  26. package/skills/lane/SKILL.md +66 -0
  27. package/skills/lane/references/workflow.md +95 -0
  28. package/src/autostart.ts +295 -0
  29. package/src/board-extension.ts +217 -0
  30. package/src/board.ts +396 -0
  31. package/src/cli.ts +253 -0
  32. package/src/codex-live-bridge.py +73 -0
  33. package/src/codex-live.ts +244 -0
  34. package/src/codex-voice-requirements.txt +5 -0
  35. package/src/codex_live_auth.py +192 -0
  36. package/src/codex_live_media.py +219 -0
  37. package/src/codex_live_provider.py +192 -0
  38. package/src/config.ts +266 -0
  39. package/src/contracts.ts +381 -0
  40. package/src/credentials.ts +172 -0
  41. package/src/decision-tool.ts +59 -0
  42. package/src/decisions.ts +143 -0
  43. package/src/delivery.ts +17 -0
  44. package/src/dialog.ts +73 -0
  45. package/src/discord-command-registration.ts +201 -0
  46. package/src/discord-commands.ts +29 -0
  47. package/src/discord-context.ts +118 -0
  48. package/src/discord-markdown.ts +172 -0
  49. package/src/discord-voice-draft.ts +124 -0
  50. package/src/discord-voice-link.ts +270 -0
  51. package/src/discord-voice.ts +150 -0
  52. package/src/discord.ts +1012 -0
  53. package/src/extension.ts +446 -0
  54. package/src/gateway-client.ts +229 -0
  55. package/src/gateway-protocol.ts +85 -0
  56. package/src/gateway-restart.ts +151 -0
  57. package/src/gateway-server.ts +440 -0
  58. package/src/gateway-store.ts +251 -0
  59. package/src/gateway.ts +654 -0
  60. package/src/head-recovery.ts +61 -0
  61. package/src/host-broker-services.ts +108 -0
  62. package/src/host-extension.ts +561 -0
  63. package/src/host-owner.ts +366 -0
  64. package/src/host-protocol.ts +144 -0
  65. package/src/host-services.ts +54 -0
  66. package/src/host.ts +415 -0
  67. package/src/installed-omp.ts +71 -0
  68. package/src/lane-extension.ts +184 -0
  69. package/src/lane-models.ts +75 -0
  70. package/src/lane-report.ts +70 -0
  71. package/src/lane-rows.ts +12 -0
  72. package/src/managed-ulw-probe.ts +172 -0
  73. package/src/managed-ulw.ts +471 -0
  74. package/src/message-order.ts +21 -0
  75. package/src/messenger-commands.ts +16 -0
  76. package/src/messengers.ts +143 -0
  77. package/src/native-presets.ts +370 -0
  78. package/src/native-sessions.ts +32 -0
  79. package/src/native-settings.ts +131 -0
  80. package/src/openai-live.ts +377 -0
  81. package/src/pr-github-schema.ts +110 -0
  82. package/src/pr-github.ts +170 -0
  83. package/src/pr-watch.ts +200 -0
  84. package/src/repository.ts +12 -0
  85. package/src/runtime.ts +4229 -0
  86. package/src/setup-judge.ts +34 -0
  87. package/src/setup-memory.ts +39 -0
  88. package/src/setup-profiles.ts +84 -0
  89. package/src/setup.ts +300 -0
  90. package/src/slack-command-registration.ts +217 -0
  91. package/src/slack-commands.ts +18 -0
  92. package/src/slack.ts +779 -0
  93. package/src/store.ts +862 -0
  94. package/src/telegram-command-registration.ts +155 -0
  95. package/src/telegram.ts +677 -0
  96. package/src/workflow.ts +94 -0
  97. package/upstream/ulw.json +9 -0
@@ -0,0 +1,561 @@
1
+ import * as fs from "node:fs/promises";
2
+ import { realpathSync } from "node:fs";
3
+ import * as net from "node:net";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
6
+ import type { UnitScope } from "@oh-my-pi/pi-coding-agent/daemon/protocol";
7
+ import { cfgDefaultThinkingLevel } from "@oh-my-pi/pi-coding-agent/session/settings";
8
+ import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
9
+ import { lookup as lookupSetting } from "@oh-my-pi/pi-coding-agent/config/registry";
10
+ import { pickDefaultAvailableModel, resolveModelRoleValue } from "@oh-my-pi/pi-coding-agent/config/model-resolver";
11
+ import { resolveThinkingLevelForModel } from "@oh-my-pi/pi-tui/thinking";
12
+ import { readSessionHeaderId } from "@oh-my-pi/pi-coding-agent/session/session-loader";
13
+ import { HostChannel, serviceCompletionRecorded, type Frame, type ServiceUnit } from "./host-protocol";
14
+ import { parseSessionEntries } from "@oh-my-pi/pi-coding-agent/session/session-loader";
15
+ import { USER_INTERRUPT_LABEL } from "@oh-my-pi/pi-coding-agent/session/messages";
16
+ import { fitAbortAndRestoreQueueResponse } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-mode";
17
+ import type { RpcAbortAndRestoreQueueResult, RpcSessionState } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
18
+ import { calculateTokensPerSecond } from "@oh-my-pi/pi-coding-agent/utils/token-rate";
19
+ import { toolWireSchema } from "@oh-my-pi/pi-ai/utils/schema";
20
+ import type { LanePresetSnapshot } from "./contracts";
21
+
22
+ const terminalService = (state: ServiceUnit["state"]) => state === "exited" || state === "failed";
23
+ const generationKey = (value: Frame | ServiceUnit) =>
24
+ JSON.stringify([value.owner, value.id, value.generation, value.startedAt, value.restartCount]);
25
+ const serviceGeneration = ({ owner, id, generation, startedAt, restartCount }: ServiceUnit) =>
26
+ ({ owner, id, generation, startedAt, restartCount });
27
+ const serviceName = (value: unknown) => typeof value === "string" ? value.trim() || undefined : undefined;
28
+ const serviceOwner = ({ agent, sessionManager }: ExtensionContext) => {
29
+ const id = sessionManager.getSessionId();
30
+ return agent.kind === "sub" && agent.id === "advisor" ? `${id}-advisor` : id;
31
+ };
32
+
33
+ /** Match the running CLI's own RPC settlement predicate (old and new SDK surface). */
34
+ function pendingNativeWake(session: { readonly wakeSources?: unknown; readonly hasPendingAsyncWork?: () => boolean }): boolean {
35
+ if ("wakeSources" in session) return session.wakeSources !== undefined;
36
+ if (typeof session.hasPendingAsyncWork === "function") return session.hasPendingAsyncWork();
37
+ throw new Error("Installed OMP cannot observe pending native async work");
38
+ }
39
+
40
+ // Root and subagent extension factories in one native process share this pipe owner.
41
+ let ownerChannel: HostChannel | undefined;
42
+ const serviceReservations = new Set<string>();
43
+ async function observeServices(scope?: UnitScope, name?: string): Promise<ServiceUnit[]> {
44
+ if (!ownerChannel || scope && scope.kind !== "project") throw new Error("No native service observation channel");
45
+ const response = await ownerChannel.request({ type: "list_service_units", projectDir: scope?.dir, serviceName: name });
46
+ const data = response.data as { units?: ServiceUnit[] } | undefined;
47
+ if (!response.success || !Array.isArray(data?.units)) throw new Error("Native service ownership is unavailable");
48
+ return data.units;
49
+ }
50
+
51
+ /** Runs inside the installed native host. All native objects come from injected pi.pi. */
52
+ export default function hostExtension(pi: ExtensionAPI): void {
53
+ const socketPath = process.env.OMP_SUPERAGENT_NATIVE_SOCKET;
54
+ const configPath = process.env.OMP_SUPERAGENT_HOST_CONFIG;
55
+ if (!socketPath || !configPath) return;
56
+ const goalEnabled = lookupSetting("goal.enabled");
57
+ if (!goalEnabled) throw new Error("Installed OMP lacks the public goal.enabled setting");
58
+ let context: ExtensionContext | undefined;
59
+ let server: net.Server | undefined;
60
+ let mutationHeld = false;
61
+ let observationHeld = false;
62
+ let runOrdinal = 0;
63
+ let instanceKey: string | undefined;
64
+ type ServiceStart = {
65
+ readonly name: string; readonly scope: UnitScope; readonly owner: string;
66
+ readonly sessionId: string; readonly toolCallId: string;
67
+ readonly previousIds: ReadonlySet<string>; readonly reservation: string;
68
+ };
69
+ const serviceStarts = new Map<string, ServiceStart>();
70
+ const interrupts = new Map<string, Promise<PromiseSettledResult<void>[]>>();
71
+ const rootSession = () => {
72
+ const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
73
+ if (!(root instanceof pi.pi.AgentSession)) throw new Error("Native root session is unavailable");
74
+ return root;
75
+ };
76
+ const serviceObservation = (data: Frame) => {
77
+ const root = rootSession();
78
+ root.sessionManager.appendCustomEntry("superagent_service_generation", {
79
+ rootSessionId: root.sessionManager.getSessionId(), ...data,
80
+ });
81
+ root.sessionManager.flushSync();
82
+ };
83
+ const releaseServiceStart = (key: string, start: ServiceStart) => {
84
+ if (serviceStarts.get(key) !== start) return;
85
+ serviceStarts.delete(key);
86
+ serviceReservations.delete(start.reservation);
87
+ };
88
+ const finishWithoutServiceResult = (key: string, noLaunch?: "approval_denied" | "not_dispatched") => {
89
+ const start = serviceStarts.get(key);
90
+ if (!start) return;
91
+ try {
92
+ // An unclassified terminal result ends the in-process reservation but
93
+ // remains durably unknown, never "not launched".
94
+ serviceObservation({ phase: "result", toolCallId: start.toolCallId, owner: start.owner, name: start.name,
95
+ ...(noLaunch ? { notLaunched: noLaunch } : { uncertain: true }) });
96
+ } finally { releaseServiceStart(key, start); }
97
+ };
98
+ // Registry slots differ between the standalone executable and npm SDK.
99
+ // Mirror native layers into this SDK before using any imported setting handle.
100
+ const readOnly = (settings: Settings): Settings => {
101
+ const parent = settings.overlayParent();
102
+ return Settings.mirror({
103
+ write() { throw new Error("Native settings observation is read-only"); },
104
+ refresh() { throw new Error("Native settings observation is read-only"); },
105
+ cloneForCwd() { throw new Error("Native settings observation is read-only"); },
106
+ }, settings.mirrorState(), parent ? readOnly(parent) : undefined);
107
+ };
108
+ const exact = () => {
109
+ const ref = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID);
110
+ const session = ref?.session;
111
+ if (!ref || !context || !(session instanceof pi.pi.AgentSession)
112
+ || session.sessionManager.getSessionId() !== context.sessionManager.getSessionId()
113
+ || session.sessionManager.getSessionFile() !== context.sessionManager.getSessionFile())
114
+ throw new Error("Exact native session ownership is unavailable");
115
+ if (typeof session.hasAdmittedSubmission !== "boolean" || typeof session.hasPostPromptWork !== "boolean"
116
+ || typeof session.isBusyForSnapshot !== "boolean" || typeof session.isStreaming !== "boolean"
117
+ || typeof session.isCompacting !== "boolean" || typeof session.isDisposed !== "boolean"
118
+ || !Number.isSafeInteger(session.queuedMessageCount) || session.queuedMessageCount < 0
119
+ || typeof session.instanceKey !== "string" || !session.instanceKey
120
+ || typeof session.getAsyncJobTree !== "function"
121
+ || typeof session.getAsyncJobSnapshot !== "function" || typeof session.beginDispose !== "function"
122
+ || typeof session.abortCompaction !== "function" || typeof session.goalRuntime.pauseGoal !== "function"
123
+ || typeof session.waitForIdle !== "function" || typeof session.yieldQueue?.has !== "function"
124
+ || typeof session.sessionManager.ensureOnDisk !== "function" || typeof session.sessionManager.flushSync !== "function"
125
+ || typeof session.settings.reloadFromDisk !== "function" || typeof session.settings.mirrorState !== "function"
126
+ || typeof session.settings.getModelRoles !== "function")
127
+ throw new Error("Installed OMP lacks required public native lifecycle capabilities");
128
+ if (instanceKey !== undefined && session.instanceKey !== instanceKey)
129
+ throw new Error("Native session instance changed within this managed Host");
130
+ instanceKey ??= session.instanceKey;
131
+ return { ref, session, id: session.sessionManager.getSessionId(), file: session.sessionManager.getSessionFile() };
132
+ };
133
+ const snapshot = () => {
134
+ const { session } = exact();
135
+ return { modelRoles: session.settings.getModelRoles(),
136
+ defaultThinkingLevel: cfgDefaultThinkingLevel.get(readOnly(session.settings)) };
137
+ };
138
+ const observation = (customType: string, data: Frame) => {
139
+ const { session, id, file } = exact();
140
+ try {
141
+ pi.appendEntry(customType, { ...data, sessionId: id, sessionFile: file, instanceKey: session.instanceKey });
142
+ session.sessionManager.flushSync();
143
+ const entry = session.sessionManager.getEntries().at(-1);
144
+ if (entry?.type !== "custom" || entry.customType !== customType)
145
+ throw new Error("Native observation entry identity is unavailable");
146
+ return entry.id;
147
+ } catch (error) { observationHeld = true; throw error; }
148
+ };
149
+ const owned = async (drain = false) => {
150
+ const identity = exact();
151
+ const registry = pi.pi.AgentRegistry.global();
152
+ const refs = registry.list();
153
+ const refEpoch = refs.map(ref => [ref.id, ref.generation, ref.parentId, ref.session?.instanceKey, ref.sessionFile]);
154
+ const journal = identity.session.sessionManager.getEntries();
155
+ const lineage = journal.flatMap(entry => {
156
+ if (entry.type !== "custom" || entry.customType !== "superagent_native_descendant") return [];
157
+ const data = entry.data as { rootSessionId?: string; agentId?: string; parentId?: string; sessionId?: string };
158
+ return data?.rootSessionId === identity.id && typeof data.agentId === "string"
159
+ && typeof data.parentId === "string" && typeof data.sessionId === "string" ? [data] : [];
160
+ });
161
+ const agents = new Set([pi.pi.MAIN_AGENT_ID]);
162
+ for (let changed = true; changed;) {
163
+ changed = false;
164
+ for (const ref of refs) if (ref.parentId && agents.has(ref.parentId) && !agents.has(ref.id)) {
165
+ agents.add(ref.id); changed = true;
166
+ }
167
+ for (const row of lineage) if (agents.has(row.parentId!) && !agents.has(row.agentId!)) {
168
+ agents.add(row.agentId!); changed = true;
169
+ }
170
+ }
171
+ const owners = new Set<string>([identity.id]);
172
+ const ownerFiles = new Map<string, string>();
173
+ if (identity.file) ownerFiles.set(identity.id, identity.file);
174
+ for (const ref of refs) if (agents.has(ref.id) && ref.session)
175
+ {
176
+ const id = ref.session.sessionManager.getSessionId();
177
+ owners.add(id);
178
+ const file = ref.session.sessionManager.getSessionFile();
179
+ if (file) ownerFiles.set(id, file);
180
+ }
181
+ for (const row of lineage) if (agents.has(row.agentId!)) {
182
+ owners.add(row.sessionId!);
183
+ const file = (row as Frame).sessionFile;
184
+ if (typeof file === "string") ownerFiles.set(row.sessionId!, file);
185
+ }
186
+ for (const ref of refs) if (agents.has(ref.id) && !ref.session
187
+ && !lineage.some(row => row.agentId === ref.id)) {
188
+ if (!ref.sessionFile) throw new Error("Detached descendant service ownership cannot be established");
189
+ const id = await readSessionHeaderId(ref.sessionFile);
190
+ if (!id) throw new Error("Detached descendant session identity is unavailable");
191
+ owners.add(id);
192
+ ownerFiles.set(id, ref.sessionFile);
193
+ }
194
+ // Native advisor tools use the same transcript but an owner derived from its session ID.
195
+ for (const id of [...owners]) {
196
+ const advisor = `${id}-advisor`;
197
+ owners.add(advisor);
198
+ const file = ownerFiles.get(id);
199
+ if (file) ownerFiles.set(advisor, file);
200
+ }
201
+ const scopedServices = async () => (await observeServices()).filter(unit => unit.owner && owners.has(unit.owner));
202
+ const services = await scopedServices();
203
+ const currentRefs = registry.list();
204
+ if (exact().ref !== identity.ref || currentRefs.length !== refs.length
205
+ || refs.some((ref, index) => currentRefs[index] !== ref))
206
+ throw new Error("Native ownership tree changed during service observation");
207
+ // Offline/unsupervised live rows are not authoritative; terminal rows still
208
+ // need their exact durable completion, which an offline downgrade cannot supply.
209
+ const servicesUnknown = services.some(unit => !unit.supervised && !terminalService(unit.state));
210
+ const liveServices = services.some(unit => !terminalService(unit.state));
211
+ const deliveriesPending = (session: InstanceType<typeof pi.pi.AgentSession>) => {
212
+ const delivery = session.getAsyncJobSnapshot({ recentLimit: 0 })?.delivery;
213
+ return !!delivery && (delivery.delivering || delivery.queued > 0 || delivery.pendingJobIds.length > 0);
214
+ };
215
+ const descendantsUnknown = () => refs.some(ref => agents.has(ref.id) && ref.session !== null
216
+ && !(ref.session instanceof pi.pi.AgentSession));
217
+ const descendantsBusy = () => refs.some(ref => agents.has(ref.id) && ref.id !== pi.pi.MAIN_AGENT_ID
218
+ && (registry.isRunning(ref) || ref.session instanceof pi.pi.AgentSession
219
+ && (pendingNativeWake(ref.session) || ref.session.hasAdmittedSubmission || ref.session.hasPostPromptWork
220
+ || ref.session.isBusyForSnapshot || ref.session.yieldQueue.has() || deliveriesPending(ref.session))));
221
+ const tracking = journal.flatMap(entry => entry.type === "custom" && entry.customType === "superagent_service_tracking"
222
+ && (entry.data as Frame)?.rootSessionId === identity.id ? [(entry.data as Frame).known] : []);
223
+ const trackingKnown = tracking.length > 0 && tracking.every(known => known === true);
224
+ const generations = journal.flatMap(entry => entry.type === "custom" && entry.customType === "superagent_service_generation"
225
+ && (entry.data as Frame)?.rootSessionId === identity.id ? [entry.data as Frame] : []);
226
+ const serviceEntries = new Map<string, readonly unknown[]>();
227
+ for (const owner of new Set(services.map(unit => unit.owner!).concat(
228
+ generations.map(row => (row.daemon as Frame | undefined)?.owner).filter((owner): owner is string => typeof owner === "string")))) {
229
+ const file = ownerFiles.get(owner);
230
+ if (!file) continue;
231
+ const live = refs.find(ref => {
232
+ const id = ref.session?.sessionManager.getSessionId();
233
+ return id !== undefined && (id === owner || `${id}-advisor` === owner);
234
+ })?.session;
235
+ if (!drain && live instanceof pi.pi.AgentSession) {
236
+ serviceEntries.set(owner, live.sessionManager.getEntries());
237
+ continue;
238
+ }
239
+ if (drain && live instanceof pi.pi.AgentSession) {
240
+ await live.waitForIdle();
241
+ await live.sessionManager.ensureOnDisk();
242
+ live.sessionManager.flushSync();
243
+ }
244
+ serviceEntries.set(owner, parseSessionEntries(await fs.readFile(file, "utf8")));
245
+ }
246
+ const recorded = (daemon: Frame) => serviceCompletionRecorded(daemon, serviceEntries.get(String(daemon.owner)) ?? []);
247
+ const tracked = generations.filter(row => row.daemon && typeof row.daemon === "object").map(row => row.daemon as Frame);
248
+ const knownKeys = new Set(tracked.map(generationKey));
249
+ const serviceDeliveryUnknown = !trackingKnown || knownKeys.size !== tracked.length
250
+ || generations.some(row => row.uncertain === true)
251
+ || generations.some(row => row.phase === "attempt" && !generations.some(result =>
252
+ result.phase === "result" && result.owner === row.owner && result.toolCallId === row.toolCallId))
253
+ || generations.some(row => Array.isArray(row.previous) && row.previous.some(value => {
254
+ const previous = value as Frame;
255
+ return owners.has(String(previous.owner)) && !knownKeys.has(generationKey(previous));
256
+ }))
257
+ || tracked.some(daemon => {
258
+ if (services.some(unit => generationKey(unit) === generationKey(daemon) && !terminalService(unit.state))) return false;
259
+ const entries = serviceEntries.get(String(daemon.owner)) ?? [];
260
+ // A recorded terminal completion supplies the final snapshot even when
261
+ // the broker now exposes a replacement generation under the same name.
262
+ return !entries.some(value => {
263
+ const entry = value as Frame;
264
+ const daemons = (entry.details as Frame | undefined)?.daemons;
265
+ return entry.type === "custom_message" && entry.customType === "launch-completion"
266
+ && Array.isArray(daemons) && daemons.some(value => generationKey(value as Frame) === generationKey(daemon)
267
+ && serviceCompletionRecorded(value as Frame, entries));
268
+ });
269
+ })
270
+ || services.some(unit => !knownKeys.has(generationKey(unit))
271
+ || terminalService(unit.state) && !recorded({ ...unit }));
272
+ if (drain) {
273
+ const refreshed = await scopedServices();
274
+ if (!isDeepStrictEqual(services, refreshed))
275
+ throw new Error("Native services changed while their durable completion evidence was drained");
276
+ }
277
+ if (!isDeepStrictEqual(refEpoch, registry.list().map(ref =>
278
+ [ref.id, ref.generation, ref.parentId, ref.session?.instanceKey, ref.sessionFile])))
279
+ throw new Error("Native descendant identity changed during completion readback");
280
+ const tree = identity.session.getAsyncJobTree({ recentLimit: 0 });
281
+ return { identity, tree, unknown: servicesUnknown || serviceDeliveryUnknown || descendantsUnknown(),
282
+ busy: liveServices || descendantsBusy() || deliveriesPending(identity.session) || !!tree?.running.length };
283
+ };
284
+ const localIdle = () => {
285
+ const { session } = exact();
286
+ return !mutationHeld && !observationHeld && !session.isDisposed && !session.isBusyForSnapshot && !session.isStreaming
287
+ && !session.isCompacting && !session.hasAdmittedSubmission && !session.hasPostPromptWork
288
+ && session.queuedMessageCount === 0 && !pendingNativeWake(session)
289
+ && !session.yieldQueue.has()
290
+ && !session.getGoalModeState()?.enabled;
291
+ };
292
+ const handle = async (command: Frame): Promise<unknown> => {
293
+ if (command.type === "get_session_stats") return exact().session.getSessionStats();
294
+ if (command.type === "get_state") {
295
+ const { session } = exact();
296
+ const queued = session.getQueuedMessages();
297
+ // Adapted from oh-my-pi v18.22.0 rpc-mode.ts (MIT; THIRD_PARTY_NOTICES.md).
298
+ // Copyright (c) 2025 Mario Zechner; 2025-2026 Can Bölük; 2026 Stencil Labs, Inc.
299
+ // This is a live observation while an owner command is pending, never an
300
+ // idle receipt. Disposal still requires the stock RPC settlement check.
301
+ return {
302
+ model: session.model, thinkingLevel: session.thinkingLevel,
303
+ isStreaming: session.isStreaming, isCompacting: session.isCompacting,
304
+ steeringMode: session.steeringMode, followUpMode: session.followUpMode,
305
+ interruptMode: session.interruptMode, sessionFile: session.sessionFile,
306
+ sessionId: session.sessionId, sessionName: session.sessionName,
307
+ autoCompactionEnabled: session.autoCompactionEnabled,
308
+ queuedMessageCount: session.queuedMessageCount, hasPendingAsyncWork: pendingNativeWake(session),
309
+ isSettled: false,
310
+ queuedMessages: { steering: [...queued.steering], followUp: [...queued.followUp], liveSteered: queued.liveSteered },
311
+ todoPhases: session.getTodoPhases(), fastModeEnabled: session.isFastModeEnabled(),
312
+ tokensPerSecond: calculateTokensPerSecond(session.messages, session.isStreaming),
313
+ fastModeActive: session.isFastModeActive(), slowModeSupported: session.isSlowModeSupported(),
314
+ slowModeEnabled: session.isSlowModeEnabled(), slowModeScope: session.getSlowModeScope(),
315
+ usageLimit: session.getUsageLimitState(), messageCount: session.messages.length,
316
+ systemPrompt: session.systemPrompt,
317
+ dumpTools: session.agent.state.tools.map(tool => ({
318
+ name: tool.name, description: tool.description, parameters: toolWireSchema(tool), examples: tool.examples,
319
+ })),
320
+ contextUsage: session.getContextUsage(), goal: session.getGoalModeState() ?? null,
321
+ } satisfies RpcSessionState;
322
+ }
323
+ if (command.type === "interrupt_maintenance") {
324
+ const { session } = exact();
325
+ const restored = command.restoreQueue === true ? session.clearQueue({ forInterrupt: true }) : undefined;
326
+ // abort() raises its barrier and withdraws marked internal context before
327
+ // its first await. Do not await its compaction cleanup until the owner has
328
+ // cancelled native UI; the pending compact may itself be awaiting that UI.
329
+ interrupts.set(String(command.id), Promise.allSettled([session.abort({ reason: USER_INTERRUPT_LABEL })]));
330
+ if (session.getGoalModeState()?.enabled) await session.goalRuntime.pauseGoal();
331
+ return restored ?? {};
332
+ }
333
+ if (command.type === "finish_interrupt") {
334
+ const token = String(command.token);
335
+ const pending = interrupts.get(token);
336
+ if (!pending) throw new Error("Native interrupt completion is unavailable");
337
+ try {
338
+ const [result] = await pending;
339
+ if (result!.status === "rejected") throw result!.reason;
340
+ } finally { interrupts.delete(token); }
341
+ return {};
342
+ }
343
+ if (command.type === "activate") {
344
+ const identity = exact();
345
+ // Native's default tool selection omits the goal tool. Add it only for
346
+ // that default, never widen an explicit --tools or --no-tools selection.
347
+ if (command.toolsExplicitlySelected === false && command.noTools === false
348
+ && goalEnabled.get(readOnly(identity.session.settings)) === true)
349
+ await pi.setActiveTools([...new Set([...pi.getActiveTools(), "goal"])]);
350
+ pi.events.emit("superagent:host-ready", { sessionId: identity.id, sessionFile: identity.file, pid: process.pid });
351
+ return {};
352
+ }
353
+ if (command.type === "observe") {
354
+ if (command.customType !== "rpc_prompt_result") throw new Error("Unsupported native observation");
355
+ return { entryId: observation("rpc_prompt_result", {
356
+ frame: command.frame, runOrdinal: command.runOrdinal, hostPid: command.hostPid,
357
+ }) };
358
+ }
359
+ if (command.type === "snapshot") {
360
+ const ownership = await owned();
361
+ return { hostPid: process.pid, sessionId: ownership.identity.id, sessionFile: ownership.identity.file,
362
+ generation: ownership.identity.ref.generation, instanceKey, settingsScope: "session", modelSettings: snapshot(),
363
+ hasOwnedRunningWork: ownership.unknown ? undefined : ownership.busy, mutationHeld, observationHeld,
364
+ admitted: ownership.identity.session.hasAdmittedSubmission,
365
+ postPromptWork: ownership.identity.session.hasPostPromptWork };
366
+ }
367
+ if (command.type === "set_model_preset") {
368
+ if (!localIdle()) throw new Error("Native session is busy or has an unresolved mutation");
369
+ const ownership = await owned(true);
370
+ if (ownership.unknown || ownership.busy || !localIdle()) throw new Error("Native owned work is not authoritatively drained");
371
+ const preset = command.preset as LanePresetSnapshot;
372
+ if (!preset || typeof preset.modelRoles !== "object"
373
+ || Object.values(preset.modelRoles).some(value => typeof value !== "string"))
374
+ throw new Error("A complete frozen model preset is required");
375
+ mutationHeld = true;
376
+ const settings = ownership.identity.session.settings;
377
+ await settings.reloadFromDisk();
378
+ const config = JSON.parse(await fs.readFile(configPath, "utf8"));
379
+ const previous = settings.getModelRoles();
380
+ const omitted = new Set([...Object.keys(previous), ...Object.keys(config.modelRoles ?? {})]);
381
+ config.modelRoles = { ...Object.fromEntries([...omitted].map(role => [role, null])), ...preset.modelRoles };
382
+ if (preset.defaultThinkingLevel !== undefined) config.defaultThinkingLevel = preset.defaultThinkingLevel;
383
+ const temporary = `${configPath}.${crypto.randomUUID()}`;
384
+ await fs.writeFile(temporary, JSON.stringify(config), { mode: 0o600, flag: "wx" });
385
+ await fs.rename(temporary, configPath);
386
+ await settings.reloadFromDisk();
387
+ if (exact().ref !== ownership.identity.ref || !isDeepStrictEqual(snapshot(), preset))
388
+ throw new Error("Native settings readback differs; mutation remains held");
389
+ const candidates = ownership.identity.session.getAvailableModels();
390
+ const selected = preset.modelRoles.default
391
+ ? resolveModelRoleValue(preset.modelRoles.default, candidates, { settings: readOnly(settings) })
392
+ : { model: pickDefaultAvailableModel(candidates.filter(model => context!.modelRegistry.hasConfiguredAuth(model)),
393
+ provider => context!.modelRegistry.hasConcreteAuth(provider)) };
394
+ const model = selected.model;
395
+ if (!model) throw new Error("Native model resolution failed; mutation remains held");
396
+ const expectedLevel = "thinkingLevel" in selected && selected.thinkingLevel !== undefined
397
+ ? selected.thinkingLevel : preset.defaultThinkingLevel;
398
+ const effectiveLevel = expectedLevel === "auto" ? "auto"
399
+ : expectedLevel === undefined ? undefined : resolveThinkingLevelForModel(model, expectedLevel);
400
+ if (!command.preserveActiveModel) {
401
+ await ownership.identity.session.setModelTemporary(model, expectedLevel);
402
+ }
403
+ if (exact().ref !== ownership.identity.ref || !isDeepStrictEqual(snapshot(), preset)
404
+ || !command.preserveActiveModel && (ownership.identity.session.model?.provider !== model.provider
405
+ || ownership.identity.session.model?.id !== model.id
406
+ || expectedLevel !== undefined && ownership.identity.session.configuredThinkingLevel() !== effectiveLevel))
407
+ throw new Error("Native model/effort readback differs; mutation remains held");
408
+ mutationHeld = false;
409
+ return { name: command.name, settingsScope: "session", preset: snapshot(), model: ownership.identity.session.model };
410
+ }
411
+ if (command.type === "shutdown_host") {
412
+ if (!localIdle()) throw new Error("session_busy");
413
+ const ownership = await owned(true);
414
+ await ownership.identity.session.waitForIdle();
415
+ await ownership.identity.session.sessionManager.ensureOnDisk();
416
+ const finalOwnership = await owned(true);
417
+ if (exact().ref !== ownership.identity.ref || !localIdle() || ownership.unknown || finalOwnership.unknown
418
+ || ownership.busy || finalOwnership.busy) throw new Error("session_busy");
419
+ // The owner has fenced its inputs and revalidated stock state/UI. Nothing
420
+ // awaits between this final native guard, disposal fence and shutdown.
421
+ ownership.identity.session.sessionManager.flushSync();
422
+ ownership.identity.session.beginDispose();
423
+ context!.shutdown();
424
+ return { shutdown: true, sessionId: ownership.identity.id, sessionFile: ownership.identity.file };
425
+ }
426
+ throw new Error("Unsupported private native control");
427
+ };
428
+ pi.on("agent_start", () => {
429
+ if (context?.agent.kind === "main") observation("rpc_agent_start", { runOrdinal: ++runOrdinal, hostPid: process.pid });
430
+ });
431
+ pi.on("tool_call", async (event, ctx) => {
432
+ const input = event.input as Frame;
433
+ if (event.toolName !== "bash") return;
434
+ const name = serviceName(input.name);
435
+ if (!name) return;
436
+ const owner = serviceOwner(ctx);
437
+ let dir: string;
438
+ try { dir = realpathSync(ctx.cwd); }
439
+ catch { return { block: true, reason: "The named service's project scope could not be established" }; }
440
+ const scope = { kind: "project", dir } as const;
441
+ const reservation = JSON.stringify([socketPath, dir, name]);
442
+ const key = JSON.stringify([owner, event.toolCallId]);
443
+ if (serviceReservations.has(reservation) || serviceStarts.has(key))
444
+ return { block: true, reason: "A named service launch for this project and name is already in progress" };
445
+ serviceReservations.add(reservation);
446
+ let admitted = false;
447
+ try {
448
+ const previous = await observeServices(scope, name);
449
+ if (previous.some(unit => !unit.supervised && (!terminalService(unit.state) || unit.exitedAt === undefined)))
450
+ return { block: true, reason: "The existing named service's live state could not be established" };
451
+ if (previous.some(unit => !terminalService(unit.state) && unit.owner !== owner))
452
+ return { block: true, reason: "A live named service in this project belongs to another session" };
453
+ serviceObservation({ phase: "attempt", toolCallId: event.toolCallId, name, cwd: dir, owner,
454
+ previous: previous.map(serviceGeneration) });
455
+ serviceStarts.set(key, { name, scope, owner, reservation, sessionId: ctx.sessionManager.getSessionId(),
456
+ toolCallId: event.toolCallId, previousIds: new Set(previous.map(unit => unit.id)) });
457
+ admitted = true;
458
+ } catch {
459
+ return { block: true, reason: "Named service ownership could not be established before launch" };
460
+ } finally {
461
+ if (!admitted) serviceReservations.delete(reservation);
462
+ }
463
+ });
464
+ pi.on("tool_approval_resolved", (event, ctx) => {
465
+ if (event.toolName !== "bash" || event.approved !== false) return;
466
+ const sessionId = ctx.sessionManager.getSessionId();
467
+ if (event.sessionId && event.sessionId !== sessionId) return;
468
+ // Advisor calls share the primary runner for approval, which does not
469
+ // carry the advisor identity on this event. Require one exact session/call.
470
+ const starts = [...serviceStarts].filter(([, start]) =>
471
+ start.sessionId === sessionId && start.toolCallId === event.toolCallId);
472
+ const [matched] = starts;
473
+ if (starts.length === 1 && matched) finishWithoutServiceResult(matched[0], "approval_denied");
474
+ });
475
+ pi.on("message_end", (event, ctx) => {
476
+ const message = event.message;
477
+ if (message.role !== "toolResult" || message.toolName !== "bash") return;
478
+ const details = message.details as Frame | undefined;
479
+ const notDispatched = message.isError && details?.__synthetic === true && details.executed === false;
480
+ finishWithoutServiceResult(JSON.stringify([serviceOwner(ctx), message.toolCallId]),
481
+ notDispatched ? "not_dispatched" : undefined);
482
+ });
483
+ pi.on("tool_result", async (event, ctx) => {
484
+ const owner = serviceOwner(ctx);
485
+ const key = JSON.stringify([owner, event.toolCallId]);
486
+ const start = serviceStarts.get(key);
487
+ if (!start) return;
488
+ const details = event.details as { service?: { name?: string; pid?: number } } | undefined;
489
+ // An exited proc has no PID on the new board. A fresh unit can be tracked
490
+ // without that PID, but still needs its exact durable launch completion.
491
+ try {
492
+ const unit = details?.service?.name === start.name
493
+ ? (await observeServices(start.scope, start.name)).find(unit => unit.supervised && unit.key === start.name
494
+ && unit.owner === start.owner && unit.restartCount === 0 && !start.previousIds.has(unit.id)
495
+ && (terminalService(unit.state) || unit.pids[0] !== undefined && unit.pids[0] === details.service?.pid))
496
+ : undefined;
497
+ if (serviceStarts.get(key) !== start) return;
498
+ serviceObservation({ phase: "result", toolCallId: event.toolCallId, owner,
499
+ name: start.name, uncertain: event.isError || !unit, ...(unit ? { daemon: serviceGeneration(unit) } : {}) });
500
+ } finally { releaseServiceStart(key, start); }
501
+ });
502
+ pi.on("session_start", async (_event, ctx) => {
503
+ if (ctx.agent.kind !== "main") {
504
+ const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
505
+ if (!(root instanceof pi.pi.AgentSession) || !ctx.agent.parentId)
506
+ throw new Error("Native descendant root ownership is unavailable");
507
+ root.sessionManager.appendCustomEntry("superagent_native_descendant", {
508
+ rootSessionId: root.sessionManager.getSessionId(), agentId: ctx.agent.id, parentId: ctx.agent.parentId,
509
+ sessionId: ctx.sessionManager.getSessionId(), sessionFile: ctx.sessionManager.getSessionFile(),
510
+ });
511
+ root.sessionManager.flushSync();
512
+ return;
513
+ }
514
+ if (server) return;
515
+ context = ctx;
516
+ const identity = exact();
517
+ pendingNativeWake(identity.session);
518
+ await ctx.sessionManager.ensureOnDisk();
519
+ if (exact().ref !== identity.ref) throw new Error("Native session changed during materialization");
520
+ identity.session.sessionManager.flushSync();
521
+ const journal = identity.session.sessionManager.getEntries();
522
+ if (!journal.some(entry => entry.type === "custom" && entry.customType === "superagent_service_tracking")) {
523
+ identity.session.sessionManager.appendCustomEntry("superagent_service_tracking", {
524
+ rootSessionId: identity.id, known: !journal.some(entry =>
525
+ entry.type === "custom_message" && entry.customType === "launch-completion"
526
+ || entry.type === "message" && entry.message.role === "assistant" && Array.isArray(entry.message.content)
527
+ && entry.message.content.some(part => part.type === "toolCall" && part.name === "bash"
528
+ && serviceName((part.arguments as Frame).name) !== undefined)),
529
+ });
530
+ identity.session.sessionManager.flushSync();
531
+ }
532
+ server = net.createServer(socket => {
533
+ if (ownerChannel) { socket.destroy(); return; }
534
+ const channel = new HostChannel(socket, socket, true);
535
+ ownerChannel = channel;
536
+ void channel.exited.then(() => { if (ownerChannel === channel) ownerChannel = undefined; });
537
+ channel.encoder.setProtocolVersion(2);
538
+ channel.on("frame", (command: Frame) => {
539
+ if (command.type === "response" || typeof command.id !== "string") return;
540
+ void handle(command).then(data => {
541
+ channel.send(command.type === "interrupt_maintenance" && command.restoreQueue === true
542
+ ? fitAbortAndRestoreQueueResponse(command.id as string, data as RpcAbortAndRestoreQueueResult, channel.encoder.maxResponseBytes)
543
+ : { type: "response", command: command.type, id: command.id, success: true, data });
544
+ }, error => {
545
+ channel.send({ type: "response", command: command.type, id: command.id, success: false,
546
+ error: error instanceof Error ? error.message : String(error) });
547
+ });
548
+ });
549
+ channel.send({ type: "ready" });
550
+ });
551
+ await new Promise<void>((resolve, reject) => {
552
+ server!.once("error", reject);
553
+ server!.listen(socketPath, () => { void fs.chmod(socketPath, 0o600).then(resolve, reject); });
554
+ });
555
+ });
556
+ pi.on("session_shutdown", async () => {
557
+ if (!context || context.agent.kind !== "main") return;
558
+ server?.close();
559
+ await fs.unlink(socketPath).catch(error => { if (error.code !== "ENOENT") throw error; });
560
+ });
561
+ }