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