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,366 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as fs from "node:fs/promises";
3
+ import * as net from "node:net";
4
+ import type { Frame, Response } from "./host-protocol";
5
+ import type { HostOptions } from "./host";
6
+ import type { RpcAbortAndRestoreQueueResult } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
7
+ import { dirname } from "node:path";
8
+ import { isDeepStrictEqual } from "node:util";
9
+
10
+ /** One ordinary pipe owner; reconnecting clients never become native stdin writers. */
11
+ const environment = { ...process.env };
12
+ const manifest = JSON.parse(await fs.readFile(process.argv[2]!, "utf8")) as {
13
+ options: Omit<HostOptions, "env">; args: string[]; configPath: string; nativeSocket: string;
14
+ processBackend: Awaited<ReturnType<typeof import("./installed-omp").inspectInstalledOmp>>["processBackend"];
15
+ };
16
+ const { options, args, configPath, nativeSocket } = manifest;
17
+ // Select the same native profile before SDK imports initialize paths or stores.
18
+ const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
19
+ const { setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
20
+ const bootstrap = extractProfileFlags([...options.command.slice(1), ...args]);
21
+ setProfile(bootstrap.profile ?? resolveProfileEnv(environment.OMP_PROFILE, environment.PI_PROFILE));
22
+ const { resolveCliArgv } = await import("@oh-my-pi/pi-coding-agent/cli-commands");
23
+ const { parseArgs } = await import("@oh-my-pi/pi-coding-agent/cli/args");
24
+ const resolvedArgv = resolveCliArgv(bootstrap.argv);
25
+ if ("error" in resolvedArgv) throw new Error(resolvedArgv.error);
26
+ const nativeArgs = parseArgs(resolvedArgv.argv.slice(1));
27
+ const { HostChannel, HostRequestTimeout } = await import("./host-protocol");
28
+ type HostChannel = import("./host-protocol").HostChannel;
29
+ const { SessionManager } = await import("@oh-my-pi/pi-coding-agent/session/session-manager");
30
+ const { MAX_RPC_FRAME_BYTES, MAX_RPC_REASSEMBLED_BYTES } = await import("@oh-my-pi/pi-coding-agent/modes/rpc/rpc-frame");
31
+ const { parseSessionEntries } = await import("@oh-my-pi/pi-coding-agent/session/session-loader");
32
+ const { fitAbortAndRestoreQueueResponse } = await import("@oh-my-pi/pi-coding-agent/modes/rpc/rpc-mode");
33
+ if (!await fs.stat(options.sessionFile).then(() => true, error => {
34
+ if (error.code === "ENOENT") return false;
35
+ throw error;
36
+ })) {
37
+ // The owner runs in the exact native environment/profile, including its
38
+ // breadcrumb store. Never manufacture a journal or hand --resume a missing path.
39
+ const session = SessionManager.create(options.cwd, dirname(options.sessionFile));
40
+ try {
41
+ await session.setSessionFile(options.sessionFile);
42
+ await session.ensureOnDisk();
43
+ session.flushSync();
44
+ } finally { await session.close(); }
45
+ }
46
+ const { publishNativeSession } = await import("./native-sessions");
47
+ await publishNativeSession(options.sessionFile, options.cwd);
48
+ const child = spawn(options.command[0]!, [...options.command.slice(1), ...args], {
49
+ cwd: options.cwd, env: { ...environment, OMP_SUPERAGENT_HOST_SOCKET: options.socketPath,
50
+ OMP_SUPERAGENT_NATIVE_SOCKET: nativeSocket, OMP_SUPERAGENT_HOST_CONFIG: configPath },
51
+ stdio: ["pipe", "pipe", "inherit"],
52
+ });
53
+ if (!child.stdin || !child.stdout) throw new Error("Native stdio pipes are unavailable");
54
+ const native = new HostChannel(child.stdout, child.stdin);
55
+ const peers = new Set<HostChannel>();
56
+ const ui = new Map<string, Frame>();
57
+ const requests = new Map<string, string>();
58
+ const responseRuns = new Map<string, number>();
59
+ const pendingGoalResumes = new Map<string, { id: string; generation: number }>();
60
+ let fencing = false;
61
+ let activeCommands = 0;
62
+ let serialCommands: Promise<void> = Promise.resolve();
63
+ let interruptCommands: Promise<void> = Promise.resolve();
64
+ let generation = 0;
65
+ let observations: Promise<void> = Promise.resolve();
66
+ let control: HostChannel;
67
+ let observationFailure: unknown;
68
+ let runOrdinal = 0;
69
+ const expectedObservations = new Map<string, Frame>();
70
+ const failedObservation = (error: unknown) => { observationFailure = error; fencing = true; };
71
+ const requireSuccess = (response: Response) => {
72
+ if (!response.success) throw new Error(response.error ?? "Native request failed");
73
+ return response.data as Frame;
74
+ };
75
+ const publish = (frame: Frame) => {
76
+ for (const peer of peers) {
77
+ try { peer.send(frame); } catch { peer.destroy(); }
78
+ }
79
+ };
80
+ const record = async (frame: Frame, observedRun = runOrdinal) => {
81
+ const result = requireSuccess(await control.request({ type: "observe", customType: "rpc_prompt_result", frame,
82
+ runOrdinal: observedRun, hostPid: child.pid }));
83
+ if (typeof result.entryId !== "string") throw new Error("Native durable observation identity was not confirmed");
84
+ expectedObservations.set(result.entryId, frame);
85
+ };
86
+ native.on("frame", (incoming: Frame) => {
87
+ if (incoming.type === "response") {
88
+ if (typeof incoming.id === "string" && requests.has(incoming.id)) {
89
+ responseRuns.set(incoming.id, runOrdinal);
90
+ if (!["prompt", "abort_and_prompt"].includes(String(incoming.command))) requests.delete(incoming.id);
91
+ }
92
+ return;
93
+ }
94
+ if (incoming.type === "ready") return;
95
+ const frame = { ...incoming };
96
+ if (frame.type === "extension_error" && String(frame.extensionPath).endsWith("/host-extension.ts"))
97
+ failedObservation(new Error("The native lifecycle extension reported an observation failure"));
98
+ if (frame.type === "agent_start") runOrdinal++;
99
+ if (typeof frame.id === "string" && requests.has(frame.id)) frame.id = requests.get(frame.id);
100
+ if (frame.type === "extension_ui_request" && typeof frame.id === "string") {
101
+ if (frame.method === "cancel") ui.delete(String(frame.targetId));
102
+ else if (["select", "confirm", "input", "editor", "ask"].includes(String(frame.method))) ui.set(frame.id, frame);
103
+ }
104
+ if (frame.type === "prompt_result") {
105
+ const resultRun = runOrdinal;
106
+ observations = observations.then(async () => {
107
+ if (observationFailure) return;
108
+ await record(frame, resultRun);
109
+ publish(frame);
110
+ })
111
+ .catch(failedObservation);
112
+ if (typeof incoming.id === "string") requests.delete(incoming.id);
113
+ } else observations = observations.then(() => {
114
+ if (!observationFailure) publish(frame);
115
+ }).catch(failedObservation);
116
+ });
117
+ await native.ready.promise;
118
+ requireSuccess(await native.request({ type: "negotiate_protocol", protocolVersion: 2 }));
119
+ // Stock commands queue behind session_start; completion proves our native
120
+ // extension finished materialization and opened its private control endpoint.
121
+ requireSuccess(await native.request({ type: "get_state" }));
122
+ requireSuccess(await native.request({ type: "set_ask_dialog", enabled: true }));
123
+ const socket = net.createConnection(nativeSocket);
124
+ control = new HostChannel(socket, socket, true);
125
+ control.encoder.setProtocolVersion(2);
126
+ // The standalone executable cannot load the npm daemon client's native addon in an
127
+ // extension. Serve its read-only inventory over the already-connected private channel.
128
+ const listServiceUnits = manifest.processBackend === "broker"
129
+ ? (await import("./host-broker-services")).brokerServiceInventory(options.cwd)
130
+ : (await import("./host-services")).listServiceUnits;
131
+ control.on("frame", (frame: Frame) => {
132
+ if (frame.type !== "list_service_units" || typeof frame.id !== "string") return;
133
+ const response = { type: "response", command: frame.type, id: frame.id };
134
+ void listServiceUnits(typeof frame.projectDir === "string" ? frame.projectDir : undefined,
135
+ typeof frame.serviceName === "string" ? frame.serviceName : undefined)
136
+ .then(units => control.send({ ...response, success: true, data: { units } }),
137
+ () => control.send({ ...response, success: false, error: "Native service ownership is unavailable" }))
138
+ .catch(() => control.destroy());
139
+ });
140
+ await control.ready.promise;
141
+ const identity = requireSuccess(await control.request({ type: "snapshot" }));
142
+ if (identity.hostPid !== child.pid || identity.sessionFile !== options.sessionFile) throw new Error("Native launch identity mismatch");
143
+ const initialPreset = options.modelPreset?.preset ?? options.modelSettings;
144
+ if (initialPreset) requireSuccess(await control.request({ type: "set_model_preset", name: options.modelPreset?.name,
145
+ preset: { ...initialPreset, defaultThinkingLevel: initialPreset.defaultThinkingLevel
146
+ ?? (identity.modelSettings as Frame).defaultThinkingLevel }, preserveActiveModel: !options.modelPreset }));
147
+ const state = async () => {
148
+ await observations;
149
+ if (observationFailure) throw new Error("A durable native observation failed; residency remains held");
150
+ const nativeState = requireSuccess(await (activeCommands
151
+ ? control.request({ type: "get_state" })
152
+ : native.request({ type: "get_state" })));
153
+ const owned = requireSuccess(await control.request({ type: "snapshot" }));
154
+ if (owned.sessionId !== nativeState.sessionId || owned.sessionFile !== nativeState.sessionFile
155
+ || owned.hostPid !== child.pid || owned.generation !== identity.generation || owned.instanceKey !== identity.instanceKey)
156
+ throw new Error("Native identity/generation changed");
157
+ if (typeof owned.hasOwnedRunningWork !== "boolean" || owned.observationHeld === true)
158
+ throw new Error("Native owned work or durable observations cannot be authoritatively established; residency remains held");
159
+ return { ...nativeState, ...owned, adapterOwnerPid: process.pid, adapterProtocol: "owned-stock-stdio-v1",
160
+ pendingUiRequests: [...ui.values()] };
161
+ };
162
+ const idle = (value: Frame) => value.isSettled === true && value.isStreaming === false
163
+ && value.isCompacting === false && value.hasPendingAsyncWork === false && value.queuedMessageCount === 0
164
+ && value.hasOwnedRunningWork === false && value.admitted === false && value.postPromptWork === false
165
+ && value.mutationHeld === false && !ui.size && !(value.goal as { enabled?: boolean } | null)?.enabled;
166
+ const handle = async (command: Frame, peer: HostChannel) => {
167
+ const originalId = typeof command.id === "string" ? command.id : crypto.randomUUID();
168
+ const respond = (response: Frame) => {
169
+ if (peers.has(peer)) peer.send({ ...response, type: "response", command: command.type, id: originalId });
170
+ };
171
+ if (command.type === "extension_ui_response") {
172
+ if (ui.has(originalId)) { native.send(command); ui.delete(originalId); }
173
+ return;
174
+ }
175
+ if (command.type === "negotiate_protocol") {
176
+ if (command.protocolVersion !== 2) { respond({ success: false, error: "Unsupported adapter protocol" }); return; }
177
+ peer.encoder.setProtocolVersion(2);
178
+ respond({ success: true, data: { protocolVersion: 2 } }); return;
179
+ }
180
+ if (command.type === "get_host_admission") {
181
+ respond({ success: true, data: { fenced: fencing, generation, pendingGoalResumes:
182
+ [...pendingGoalResumes.values()].map(resume => ({ ...resume, current: resume.generation === generation })) } });
183
+ return;
184
+ }
185
+ const stop = command.type === "abort" || command.type === "abort_and_restore_queue"
186
+ || command.type === "goal" && ["pause", "drop"].includes(String(command.op));
187
+ if (fencing && command.type !== "get_state" && command.type !== "shutdown_host" && !stop) {
188
+ respond({ success: false, error: "Host admission is fenced" }); return;
189
+ }
190
+ if (command.type === "abort" || command.type === "abort_and_restore_queue" || command.type === "abort_and_prompt"
191
+ || command.type === "goal" && ["pause", "drop"].includes(String(command.op))) {
192
+ generation++;
193
+ }
194
+ if (command.type === "shutdown_host" || command.type === "set_model_preset") {
195
+ fencing = true;
196
+ let effectStarted = false;
197
+ let held = false;
198
+ try {
199
+ if (activeCommands || requests.size || !idle(await state())) throw new Error("Host is busy (session_busy)");
200
+ const confirmed = await state();
201
+ if (activeCommands || requests.size || !idle(confirmed)) throw new Error("Host is busy (session_busy)");
202
+ effectStarted = true;
203
+ const result = await control.request(command);
204
+ if (!result.success) {
205
+ const snapshot = requireSuccess(await control.request({ type: "snapshot" }));
206
+ held = snapshot.mutationHeld === true;
207
+ respond(result);
208
+ return;
209
+ }
210
+ respond(result);
211
+ if (command.type === "shutdown_host") {
212
+ child.stdin!.end();
213
+ return;
214
+ }
215
+ } catch (error) {
216
+ if (effectStarted) {
217
+ held = true;
218
+ peer.destroy();
219
+ } else respond({ success: false, code: "session_busy", error: error instanceof Error ? error.message : String(error) });
220
+ } finally {
221
+ // A successful shutdown never reopens admission.
222
+ if (!held && (command.type !== "shutdown_host" || !child.stdin!.writableEnded)) fencing = false;
223
+ }
224
+ return;
225
+ }
226
+ // Native get_* commands are observations, not admitted execution. A
227
+ // reconnecting reader must not make an otherwise idle shutdown spuriously busy.
228
+ const readOnly = String(command.type).startsWith("get_");
229
+ if (!readOnly) activeCommands++;
230
+ let resumeToken: string | undefined;
231
+ let forwarded = false;
232
+ const admittedGeneration = generation;
233
+ const interrupt = command.type === "abort" || command.type === "abort_and_restore_queue"
234
+ || command.type === "abort_and_prompt";
235
+ const input = ["prompt", "steer", "follow_up", "abort_and_prompt", "steer_subagent", "dictation_start"]
236
+ .includes(String(command.type));
237
+ const background = command.type === "bash" || command.type === "predict_word";
238
+ const priorityQuery = command.type === "get_state" || command.type === "get_session_stats";
239
+ const predecessor = serialCommands;
240
+ const serialDone = interrupt || !input && !background && !priorityQuery ? Promise.withResolvers<void>() : undefined;
241
+ if (serialDone) serialCommands = predecessor.then(() => serialDone.promise);
242
+ const previousInterrupt = interruptCommands;
243
+ const interruptDone = interrupt ? Promise.withResolvers<void>() : undefined;
244
+ if (interruptDone) interruptCommands = previousInterrupt.then(() => interruptDone.promise);
245
+ if (command.type === "goal" && command.op === "resume") {
246
+ resumeToken = crypto.randomUUID();
247
+ pendingGoalResumes.set(resumeToken, { id: originalId, generation: admittedGeneration });
248
+ }
249
+ try {
250
+ // Keep unadmitted input on our side of a blocking native command. A control
251
+ // interrupt may release native compaction before stdin reads its abort frame.
252
+ if (interrupt) await previousInterrupt;
253
+ if (!interrupt && !background && !priorityQuery) await predecessor;
254
+ if ((input || resumeToken) && !interrupt && (generation !== admittedGeneration || fencing))
255
+ throw new Error(resumeToken ? "Goal resume cancelled before admission" : "Input cancelled before native admission");
256
+ if (command.type === "get_state") { respond({ success: true, data: await state() }); return; }
257
+ if (command.type === "get_session_stats") {
258
+ respond(await control.request(command));
259
+ return;
260
+ }
261
+ if (command.type === "get_entries") {
262
+ await observations;
263
+ if (observationFailure) throw new Error("Durable native observations are unavailable");
264
+ }
265
+ const nativeId = crypto.randomUUID();
266
+ let restored: RpcAbortAndRestoreQueueResult | undefined;
267
+ if (interrupt) {
268
+ // Establish the native abort barrier and withdraw already-admitted input
269
+ // before either UI cancellation or the serial RPC tail can release compact.
270
+ const started = requireSuccess(await control.request({
271
+ type: "interrupt_maintenance", restoreQueue: command.type === "abort_and_restore_queue",
272
+ }, nativeId));
273
+ if (command.type === "abort_and_restore_queue") restored = started as unknown as RpcAbortAndRestoreQueueResult;
274
+ for (const id of ui.keys()) native.send({ type: "extension_ui_response", id, cancelled: true });
275
+ ui.clear();
276
+ // Let the priority abort finish before the stock abort starts: overlapping
277
+ // abort() calls share a boolean barrier, and either finally can lower it.
278
+ requireSuccess(await control.request({ type: "finish_interrupt", token: nativeId }, undefined, 30_000));
279
+ }
280
+ if (!readOnly) requests.set(nativeId, originalId);
281
+ forwarded = true;
282
+ const completion = native.request({ ...command, id: undefined }, nativeId,
283
+ command.type === "compact" ? 0 : 30_000);
284
+ let result = await completion;
285
+ if (result.success && restored) {
286
+ // The original RPC still stops its builtin/goal controllers and supplies
287
+ // its receipt. Keep any input it withdrew too, in native queue order.
288
+ const remaining = result.data as RpcAbortAndRestoreQueueResult;
289
+ const flags = {
290
+ ...(restored.imagesDropped || remaining.imagesDropped ? { imagesDropped: true as const } : {}),
291
+ ...(restored.truncated || remaining.truncated ? { truncated: true as const } : {}),
292
+ };
293
+ result = fitAbortAndRestoreQueueResponse(originalId, {
294
+ ...restored, ...remaining,
295
+ steering: [...restored.steering, ...remaining.steering],
296
+ followUp: [...restored.followUp, ...remaining.followUp],
297
+ }, peer.encoder.maxResponseBytes - (Object.keys(flags).length ? Buffer.byteLength(JSON.stringify(flags)) : 0)) as Response;
298
+ Object.assign(result.data as RpcAbortAndRestoreQueueResult, flags);
299
+ }
300
+ if (command.type === "prompt" || command.type === "abort_and_prompt") {
301
+ if (result.success && (result.data as Frame | undefined)?.agentInvoked === false) {
302
+ await record({ type: "prompt_result", id: originalId, agentInvoked: false, status: "completed" }, responseRuns.get(nativeId));
303
+ requests.delete(nativeId);
304
+ } else if (!result.success) requests.delete(nativeId);
305
+ } else requests.delete(nativeId);
306
+ responseRuns.delete(nativeId);
307
+ respond(result);
308
+ } catch (error) {
309
+ if (error instanceof HostRequestTimeout && !forwarded && resumeToken) {
310
+ respond({ success: false, error: "Goal resume cancelled before admission" });
311
+ } else if (error instanceof HostRequestTimeout && !String(command.type).startsWith("get_")) {
312
+ fencing = true;
313
+ peer.destroy();
314
+ } else respond({ success: false, error: error instanceof Error ? error.message : String(error) });
315
+ } finally {
316
+ if (resumeToken) pendingGoalResumes.delete(resumeToken);
317
+ interruptDone?.resolve();
318
+ serialDone?.resolve();
319
+ if (!readOnly) activeCommands--;
320
+ }
321
+ };
322
+ const server = net.createServer(socket => {
323
+ const peer = new HostChannel(socket, socket, true);
324
+ peers.add(peer);
325
+ peer.on("frame", (frame: Frame) => { void handle(frame, peer).catch(() => peer.destroy()); });
326
+ void peer.exited.then(() => { peers.delete(peer); });
327
+ peer.send({ type: "ready", protocolVersion: 1, supportedProtocolVersions: [1, 2],
328
+ maxFrameBytes: MAX_RPC_FRAME_BYTES, maxReassembledFrameBytes: MAX_RPC_REASSEMBLED_BYTES });
329
+ });
330
+ await new Promise<void>((resolve, reject) => {
331
+ server.once("error", reject);
332
+ server.listen(options.socketPath, () => { void fs.chmod(options.socketPath, 0o600).then(resolve, reject); });
333
+ });
334
+ requireSuccess(await control.request({ type: "activate",
335
+ toolsExplicitlySelected: nativeArgs.tools !== undefined, noTools: nativeArgs.noTools === true }));
336
+ child.once("error", error => { console.error(error.message); process.exitCode = 1; native.destroy(); });
337
+ child.once("exit", (code, signal) => {
338
+ fencing = true;
339
+ void (async () => {
340
+ await observations;
341
+ // Only native exit and an actual readable journal complete persistence.
342
+ const journalText = await fs.readFile(options.sessionFile, "utf8");
343
+ for (const line of journalText.split("\n").filter(Boolean)) JSON.parse(line);
344
+ const journal = parseSessionEntries(journalText);
345
+ const persisted = journalText.endsWith("\n") && journal.some(entry => entry.type === "session" && entry.id === identity.sessionId);
346
+ const observationsFlushed = !observationFailure && [...expectedObservations].every(([id, frame]) =>
347
+ journal.some(entry => entry.id === id && entry.type === "custom" && entry.customType === "rpc_prompt_result"
348
+ && (entry.data as Frame)?.instanceKey === identity.instanceKey
349
+ && isDeepStrictEqual((entry.data as Frame)?.frame, frame)))
350
+ && Array.from({ length: runOrdinal }, (_, index) => index + 1).every(ordinal =>
351
+ journal.filter(entry => entry.type === "custom" && entry.customType === "rpc_agent_start"
352
+ && (entry.data as Frame)?.hostPid === child.pid && (entry.data as Frame)?.instanceKey === identity.instanceKey
353
+ && (entry.data as Frame)?.runOrdinal === ordinal).length === 1);
354
+ const receipt = `${options.socketPath}.exit.json`;
355
+ const temporary = `${receipt}.${crypto.randomUUID()}`;
356
+ await fs.writeFile(temporary, JSON.stringify({ pid: child.pid, ownerPid: process.pid,
357
+ sessionId: identity.sessionId, sessionFile: options.sessionFile, code, signal, persisted,
358
+ observationsFlushed }), { mode: 0o600, flag: "wx" });
359
+ await fs.rename(temporary, receipt);
360
+ if (!persisted || !observationsFlushed) throw new Error("Native exit persistence is unconfirmed; adapter remains fenced");
361
+ for (const peer of peers) peer.destroy();
362
+ control.destroy();
363
+ server.close();
364
+ process.exitCode = code === 0 && !signal ? 0 : 1;
365
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
366
+ });
@@ -0,0 +1,144 @@
1
+ import { EventEmitter } from "node:events";
2
+ import type { Readable, Writable } from "node:stream";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { MAX_RPC_REASSEMBLED_BYTES, RpcFrameDecoder, RpcFrameEncoder } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-frame";
5
+ import type { RpcResponse, RpcSessionState } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-types";
6
+ import type { UnitSnapshot } from "@oh-my-pi/pi-coding-agent/daemon/protocol";
7
+ import type { LanePresetSnapshot } from "./contracts";
8
+
9
+ /** Private adapter observations, not additions to the stock RPC protocol. */
10
+ export type HostState = RpcSessionState & {
11
+ hostPid: number;
12
+ adapterOwnerPid: number;
13
+ adapterProtocol: "owned-stock-stdio-v1";
14
+ settingsScope: "session";
15
+ modelSettings: LanePresetSnapshot;
16
+ hasOwnedRunningWork: boolean;
17
+ pendingUiRequests: Record<string, unknown>[];
18
+ };
19
+ export type Frame = Record<string, unknown>;
20
+ /** Only lifecycle evidence crosses the private socket, never command lines or service logs. */
21
+ export type ServiceUnit = Pick<UnitSnapshot, "id" | "key" | "owner" |
22
+ "startedAt" | "restartCount" | "state" | "exitedAt" | "pids" | "supervised"> & {
23
+ readonly generation?: UnitSnapshot["generation"];
24
+ };
25
+ export type Response = Frame & { success: boolean; data?: unknown; error?: string };
26
+ export type HostResponse = RpcResponse | {
27
+ type: "response"; id?: string; command: "shutdown_host" | "set_model_preset" | "get_host_admission"; success: true; data: Frame;
28
+ } | {
29
+ type: "response"; id?: string; command: string; success: false; error: string; code?: string;
30
+ };
31
+ export class HostRequestTimeout extends Error {
32
+ constructor() { super("Host request timed out; its outcome may be unknown"); }
33
+ }
34
+
35
+ /** Positive native journal evidence for this exact terminal service generation. */
36
+ export function serviceCompletionRecorded(daemon: Frame, entries: readonly unknown[]): boolean {
37
+ if (typeof daemon.owner !== "string" || typeof daemon.id !== "string" || typeof daemon.startedAt !== "number"
38
+ || typeof daemon.restartCount !== "number" || typeof daemon.exitedAt !== "number"
39
+ || ("generation" in daemon && (typeof daemon.generation !== "string" || !daemon.generation))
40
+ || !["exited", "failed"].includes(String(daemon.state))) return false;
41
+ return entries.some(value => {
42
+ if (!value || typeof value !== "object") return false;
43
+ const entry = value as Frame;
44
+ const details = entry.details as Frame | undefined;
45
+ return entry.type === "custom_message" && entry.customType === "launch-completion"
46
+ && Array.isArray(details?.daemons) && details.daemons.some(value => {
47
+ if (!value || typeof value !== "object") return false;
48
+ const observed = value as Frame;
49
+ // Legacy journal rows had no generation field; never match them to a new daemon generation.
50
+ return ["owner", "id", "generation", "startedAt", "restartCount", "state", "exitedAt"]
51
+ .every(field => daemon[field] === observed[field]);
52
+ });
53
+ });
54
+ }
55
+
56
+ /** Public native JSONL/v2 framing, with correlation owned by this adapter. */
57
+ export class HostChannel extends EventEmitter {
58
+ readonly pending = new Map<string, {
59
+ resolve(value: Response): void; reject(error: Error): void; timer?: ReturnType<typeof setTimeout>;
60
+ }>();
61
+ readonly exited: Promise<void>;
62
+ readonly ready = Promise.withResolvers<void>();
63
+ readonly encoder = new RpcFrameEncoder();
64
+ #closed = false;
65
+ constructor(readonly input: Readable, readonly output: Writable, readonly framed = false) {
66
+ super();
67
+ const closed = Promise.withResolvers<void>();
68
+ this.exited = closed.promise;
69
+ const decoder = new RpcFrameDecoder();
70
+ const text = new StringDecoder("utf8");
71
+ let buffer = "";
72
+ input.on("data", (chunk: string | Buffer) => {
73
+ try {
74
+ buffer += typeof chunk === "string" ? chunk : text.write(chunk);
75
+ if (Buffer.byteLength(buffer) > MAX_RPC_REASSEMBLED_BYTES) throw new Error("Host frame backlog exceeded its bound");
76
+ let end: number;
77
+ while ((end = buffer.indexOf("\n")) >= 0) {
78
+ const line = buffer.slice(0, end);
79
+ buffer = buffer.slice(end + 1);
80
+ if (!line) continue;
81
+ const decoded = decoder.push(JSON.parse(line));
82
+ if (!decoded) continue;
83
+ const frame = decoded as Frame;
84
+ if (frame.type === "ready") this.ready.resolve();
85
+ if (frame.type === "response" && typeof frame.id === "string") {
86
+ const request = this.pending.get(frame.id);
87
+ if (request) {
88
+ this.pending.delete(frame.id);
89
+ clearTimeout(request.timer);
90
+ request.resolve(frame as Response);
91
+ }
92
+ }
93
+ this.emit("frame", frame);
94
+ }
95
+ } catch (error) { this.destroy(error instanceof Error ? error : new Error(String(error))); }
96
+ });
97
+ const finish = () => {
98
+ if (this.#closed) return;
99
+ this.#closed = true;
100
+ const error = new Error("Host disconnected; request outcome may be unknown");
101
+ this.ready.reject(error);
102
+ for (const item of this.pending.values()) { clearTimeout(item.timer); item.reject(error); }
103
+ this.pending.clear();
104
+ closed.resolve();
105
+ };
106
+ void this.ready.promise.catch(() => {});
107
+ input.on("error", finish);
108
+ input.on("end", finish);
109
+ input.on("close", finish);
110
+ output.on("error", finish);
111
+ }
112
+ send(frame: Frame): void {
113
+ if (this.#closed || this.output.destroyed) throw new Error("Host is disconnected");
114
+ for (const data of this.framed ? this.encoder.encodeFrames(frame) : [`${JSON.stringify(frame)}\n`]) {
115
+ // Include protocol-v2 base64/chunk overhead within a bounded wire queue.
116
+ if (Buffer.byteLength(data) + this.output.writableLength > MAX_RPC_REASSEMBLED_BYTES * 2) {
117
+ this.destroy(new Error("Host write backlog exceeded its bound"));
118
+ throw new Error("Host write backlog exceeded its bound");
119
+ }
120
+ this.output.write(data);
121
+ }
122
+ }
123
+ request(frame: Frame, id: string = crypto.randomUUID(), timeoutMs = 10_000): Promise<Response> {
124
+ if (this.pending.has(id)) throw new Error(`Request ${id} is already outstanding`);
125
+ if (Buffer.byteLength(JSON.stringify(frame)) > 16 * 1024 * 1024) {
126
+ this.destroy();
127
+ return Promise.reject(new Error("Host write backlog exceeded its bound"));
128
+ }
129
+ const result = Promise.withResolvers<Response>();
130
+ const timer = timeoutMs > 0 ? setTimeout(() => {
131
+ this.pending.delete(id);
132
+ result.reject(new HostRequestTimeout());
133
+ }, timeoutMs) : undefined;
134
+ timer?.unref();
135
+ this.pending.set(id, { ...result, timer });
136
+ try { this.send({ ...frame, id }); }
137
+ catch (error) { this.pending.delete(id); clearTimeout(timer); result.reject(error); }
138
+ return result.promise;
139
+ }
140
+ destroy(error?: Error): void {
141
+ this.input.destroy(error);
142
+ this.output.destroy();
143
+ }
144
+ }
@@ -0,0 +1,54 @@
1
+ import { lstat } from "node:fs/promises";
2
+ import { once } from "node:events";
3
+ import { createConnection, isIPv4 } from "node:net";
4
+ import { FileLock } from "@oh-my-pi/pi-natives";
5
+ import { readOfflineUnits } from "@oh-my-pi/pi-coding-agent/cli/ps-data";
6
+ import { probeDaemon } from "@oh-my-pi/pi-coding-agent/daemon/client";
7
+ import { daemonEndpoint, daemonLockPath, daemonTcpAddress } from "@oh-my-pi/pi-coding-agent/daemon/paths";
8
+ import type { UnitSnapshot } from "@oh-my-pi/pi-coding-agent/daemon/protocol";
9
+ import type { ServiceUnit } from "./host-protocol";
10
+
11
+ /** An unreachable remote daemon cannot be inferred absent from this machine's store. */
12
+ async function confirmedOffline(): Promise<boolean> {
13
+ if (FileLock.isHeld(daemonLockPath())) return false;
14
+ const tcp = daemonTcpAddress();
15
+ if (!tcp) return lstat(daemonEndpoint()).then(() => false, error => {
16
+ if (error.code === "ENOENT") return true;
17
+ throw error;
18
+ });
19
+ if (tcp.host !== "localhost" && tcp.host !== "::1" && !(isIPv4(tcp.host) && tcp.host.startsWith("127."))) return false;
20
+ // probeDaemon also returns undefined on auth or protocol failures. Only a refused
21
+ // loopback connection (not an accepting listener or a timeout) proves absence.
22
+ const socket = createConnection({ ...tcp, signal: AbortSignal.timeout(1_000) });
23
+ try { await once(socket, "connect"); return false; }
24
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ECONNREFUSED"; }
25
+ finally { socket.destroy(); }
26
+ }
27
+
28
+ /** Called only by the Bun pipe owner, after profile bootstrap. Never spawns or upgrades the daemon. */
29
+ export async function listServiceUnits(projectDir?: string, key?: string): Promise<ServiceUnit[]> {
30
+ let units: UnitSnapshot[];
31
+ const deadline = performance.now() + 2_000;
32
+ for (;;) {
33
+ const client = await probeDaemon();
34
+ if (client) {
35
+ try {
36
+ units = (await client.request({ op: "list", kind: "proc",
37
+ ...(projectDir === undefined ? {} : { scope: { kind: "project", dir: projectDir } as const }) })).units;
38
+ break;
39
+ } catch {
40
+ // The daemon can exit between the handshake and list.
41
+ } finally { client.close(); }
42
+ }
43
+ if (await confirmedOffline()) { units = await readOfflineUnits(); break; }
44
+ // Stock takes its lifetime lock before it listens. Wait for that daemon,
45
+ // never launch it or retry a mutation. An unknown endpoint stays fenced.
46
+ if (!FileLock.isHeld(daemonLockPath()) || performance.now() >= deadline)
47
+ throw new Error("Cannot confirm native daemon service ownership");
48
+ await Bun.sleep(25);
49
+ }
50
+ return units.filter(unit => unit.kind === "proc" && (key === undefined || unit.key === key)
51
+ && (projectDir === undefined || unit.scope.kind === "project" && unit.scope.dir === projectDir))
52
+ .map(({ id, key, owner, generation, startedAt, restartCount, state, exitedAt, pids, supervised }) =>
53
+ ({ id, key, owner, generation, startedAt, restartCount, state, exitedAt, pids, supervised }));
54
+ }