omp-superagent 0.1.1 → 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 (60) hide show
  1. package/DESIGN.md +189 -48
  2. package/README.ko.md +30 -16
  3. package/README.md +39 -20
  4. package/THIRD_PARTY_NOTICES.md +81 -6
  5. package/docs/OPERATIONS.md +178 -30
  6. package/docs/discord-voice.md +96 -0
  7. package/docs/releases/0.1.2.md +53 -0
  8. package/package.json +13 -7
  9. package/scripts/ci.ts +10 -5
  10. package/scripts/release.ts +14 -6
  11. package/scripts/test-omp.sh +36 -0
  12. package/skills/head/SKILL.md +82 -241
  13. package/skills/head/references/model-selection.md +81 -261
  14. package/skills/head/references/routing.md +179 -354
  15. package/skills/head/references/supervision.md +120 -310
  16. package/skills/lane/SKILL.md +53 -175
  17. package/skills/lane/references/workflow.md +93 -347
  18. package/src/cli.ts +96 -10
  19. package/src/codex-live-bridge.py +73 -0
  20. package/src/codex-live.ts +244 -0
  21. package/src/codex-voice-requirements.txt +5 -0
  22. package/src/codex_live_auth.py +192 -0
  23. package/src/codex_live_media.py +219 -0
  24. package/src/codex_live_provider.py +192 -0
  25. package/src/config.ts +77 -2
  26. package/src/contracts.ts +70 -6
  27. package/src/decision-tool.ts +59 -0
  28. package/src/decisions.ts +143 -0
  29. package/src/delivery.ts +10 -0
  30. package/src/discord-context.ts +118 -0
  31. package/src/discord-voice-draft.ts +124 -0
  32. package/src/discord-voice-link.ts +270 -0
  33. package/src/discord-voice.ts +150 -0
  34. package/src/discord.ts +312 -45
  35. package/src/extension.ts +178 -21
  36. package/src/gateway-client.ts +11 -4
  37. package/src/gateway-server.ts +52 -4
  38. package/src/gateway-store.ts +16 -2
  39. package/src/gateway.ts +27 -11
  40. package/src/host-broker-services.ts +108 -0
  41. package/src/host-extension.ts +159 -47
  42. package/src/host-owner.ts +16 -0
  43. package/src/host-protocol.ts +9 -1
  44. package/src/host-services.ts +54 -0
  45. package/src/host.ts +3 -2
  46. package/src/installed-omp.ts +34 -26
  47. package/src/lane-extension.ts +5 -0
  48. package/src/lane-rows.ts +12 -0
  49. package/src/messengers.ts +38 -9
  50. package/src/native-presets.ts +91 -3
  51. package/src/native-settings.ts +3 -1
  52. package/src/openai-live.ts +377 -0
  53. package/src/pr-github-schema.ts +110 -0
  54. package/src/pr-github.ts +170 -0
  55. package/src/pr-watch.ts +200 -0
  56. package/src/runtime.ts +419 -54
  57. package/src/slack.ts +14 -11
  58. package/src/store.ts +86 -30
  59. package/src/telegram.ts +28 -12
  60. package/scripts/check-omp.ts +0 -4
@@ -1,15 +1,16 @@
1
1
  import * as fs from "node:fs/promises";
2
+ import { realpathSync } from "node:fs";
2
3
  import * as net from "node:net";
3
4
  import { isDeepStrictEqual } from "node:util";
4
5
  import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
5
- import { collectReports, collectScope, targetScope } from "@oh-my-pi/pi-coding-agent/cli/ps-data";
6
+ import type { UnitScope } from "@oh-my-pi/pi-coding-agent/daemon/protocol";
6
7
  import { cfgDefaultThinkingLevel } from "@oh-my-pi/pi-coding-agent/session/settings";
7
8
  import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
8
9
  import { lookup as lookupSetting } from "@oh-my-pi/pi-coding-agent/config/registry";
9
10
  import { pickDefaultAvailableModel, resolveModelRoleValue } from "@oh-my-pi/pi-coding-agent/config/model-resolver";
10
11
  import { resolveThinkingLevelForModel } from "@oh-my-pi/pi-tui/thinking";
11
12
  import { readSessionHeaderId } from "@oh-my-pi/pi-coding-agent/session/session-loader";
12
- import { HostChannel, serviceCompletionRecorded, type Frame } from "./host-protocol";
13
+ import { HostChannel, serviceCompletionRecorded, type Frame, type ServiceUnit } from "./host-protocol";
13
14
  import { parseSessionEntries } from "@oh-my-pi/pi-coding-agent/session/session-loader";
14
15
  import { USER_INTERRUPT_LABEL } from "@oh-my-pi/pi-coding-agent/session/messages";
15
16
  import { fitAbortAndRestoreQueueResponse } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-mode";
@@ -18,6 +19,35 @@ import { calculateTokensPerSecond } from "@oh-my-pi/pi-coding-agent/utils/token-
18
19
  import { toolWireSchema } from "@oh-my-pi/pi-ai/utils/schema";
19
20
  import type { LanePresetSnapshot } from "./contracts";
20
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
+
21
51
  /** Runs inside the installed native host. All native objects come from injected pi.pi. */
22
52
  export default function hostExtension(pi: ExtensionAPI): void {
23
53
  const socketPath = process.env.OMP_SUPERAGENT_NATIVE_SOCKET;
@@ -31,9 +61,13 @@ export default function hostExtension(pi: ExtensionAPI): void {
31
61
  let observationHeld = false;
32
62
  let runOrdinal = 0;
33
63
  let instanceKey: string | undefined;
34
- const serviceStarts = new Map<string, { name: string; cwd: string; owner: string }>();
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>();
35
70
  const interrupts = new Map<string, Promise<PromiseSettledResult<void>[]>>();
36
- const generationKey = (value: Frame) => JSON.stringify([value.owner, value.id, value.startedAt, value.restartCount]);
37
71
  const rootSession = () => {
38
72
  const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
39
73
  if (!(root instanceof pi.pi.AgentSession)) throw new Error("Native root session is unavailable");
@@ -46,6 +80,21 @@ export default function hostExtension(pi: ExtensionAPI): void {
46
80
  });
47
81
  root.sessionManager.flushSync();
48
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
+ };
49
98
  // Registry slots differ between the standalone executable and npm SDK.
50
99
  // Mirror native layers into this SDK before using any imported setting handle.
51
100
  const readOnly = (settings: Settings): Settings => {
@@ -68,13 +117,13 @@ export default function hostExtension(pi: ExtensionAPI): void {
68
117
  || typeof session.isCompacting !== "boolean" || typeof session.isDisposed !== "boolean"
69
118
  || !Number.isSafeInteger(session.queuedMessageCount) || session.queuedMessageCount < 0
70
119
  || typeof session.instanceKey !== "string" || !session.instanceKey
71
- || typeof session.hasPendingAsyncWork !== "function" || typeof session.getAsyncJobTree !== "function"
120
+ || typeof session.getAsyncJobTree !== "function"
72
121
  || typeof session.getAsyncJobSnapshot !== "function" || typeof session.beginDispose !== "function"
73
122
  || typeof session.abortCompaction !== "function" || typeof session.goalRuntime.pauseGoal !== "function"
74
123
  || typeof session.waitForIdle !== "function" || typeof session.yieldQueue?.has !== "function"
75
124
  || typeof session.sessionManager.ensureOnDisk !== "function" || typeof session.sessionManager.flushSync !== "function"
76
125
  || typeof session.settings.reloadFromDisk !== "function" || typeof session.settings.mirrorState !== "function"
77
- || typeof session.settings.getModelRoles !== "function" || typeof session.hasPendingAsyncWork() !== "boolean")
126
+ || typeof session.settings.getModelRoles !== "function")
78
127
  throw new Error("Installed OMP lacks required public native lifecycle capabilities");
79
128
  if (instanceKey !== undefined && session.instanceKey !== instanceKey)
80
129
  throw new Error("Native session instance changed within this managed Host");
@@ -119,7 +168,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
119
168
  agents.add(row.agentId!); changed = true;
120
169
  }
121
170
  }
122
- const owners = new Set<string>([identity.id, ...agents]);
171
+ const owners = new Set<string>([identity.id]);
123
172
  const ownerFiles = new Map<string, string>();
124
173
  if (identity.file) ownerFiles.set(identity.id, identity.file);
125
174
  for (const ref of refs) if (agents.has(ref.id) && ref.session)
@@ -142,17 +191,23 @@ export default function hostExtension(pi: ExtensionAPI): void {
142
191
  owners.add(id);
143
192
  ownerFiles.set(id, ref.sessionFile);
144
193
  }
145
- const reports = await collectReports(true, {});
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();
146
203
  const currentRefs = registry.list();
147
204
  if (exact().ref !== identity.ref || currentRefs.length !== refs.length
148
205
  || refs.some((ref, index) => currentRefs[index] !== ref))
149
206
  throw new Error("Native ownership tree changed during service observation");
150
- const services = reports.flatMap(report => report.daemons
151
- .filter(row => owners.has(row.snapshot.owner ?? ""))
152
- .map(row => ({ ...row, brokerPid: report.scope.brokerPid })));
153
- // An offline broker's persisted downgrade is not an authoritative live observation.
154
- const servicesUnknown = services.some(row => !row.supervised || !row.brokerPid || !row.snapshot.owner);
155
- const liveServices = services.some(row => !["exited", "failed"].includes(row.snapshot.state));
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));
156
211
  const deliveriesPending = (session: InstanceType<typeof pi.pi.AgentSession>) => {
157
212
  const delivery = session.getAsyncJobSnapshot({ recentLimit: 0 })?.delivery;
158
213
  return !!delivery && (delivery.delivering || delivery.queued > 0 || delivery.pendingJobIds.length > 0);
@@ -161,18 +216,22 @@ export default function hostExtension(pi: ExtensionAPI): void {
161
216
  && !(ref.session instanceof pi.pi.AgentSession));
162
217
  const descendantsBusy = () => refs.some(ref => agents.has(ref.id) && ref.id !== pi.pi.MAIN_AGENT_ID
163
218
  && (registry.isRunning(ref) || ref.session instanceof pi.pi.AgentSession
164
- && (ref.session.hasPendingAsyncWork() || ref.session.hasAdmittedSubmission || ref.session.hasPostPromptWork
219
+ && (pendingNativeWake(ref.session) || ref.session.hasAdmittedSubmission || ref.session.hasPostPromptWork
165
220
  || ref.session.isBusyForSnapshot || ref.session.yieldQueue.has() || deliveriesPending(ref.session))));
166
- const trackingKnown = journal.some(entry => entry.type === "custom" && entry.customType === "superagent_service_tracking"
167
- && (entry.data as Frame)?.rootSessionId === identity.id && (entry.data as Frame)?.known === true);
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);
168
224
  const generations = journal.flatMap(entry => entry.type === "custom" && entry.customType === "superagent_service_generation"
169
225
  && (entry.data as Frame)?.rootSessionId === identity.id ? [entry.data as Frame] : []);
170
226
  const serviceEntries = new Map<string, readonly unknown[]>();
171
- for (const owner of new Set(services.map(row => row.snapshot.owner!).concat(
227
+ for (const owner of new Set(services.map(unit => unit.owner!).concat(
172
228
  generations.map(row => (row.daemon as Frame | undefined)?.owner).filter((owner): owner is string => typeof owner === "string")))) {
173
229
  const file = ownerFiles.get(owner);
174
230
  if (!file) continue;
175
- const live = refs.find(ref => ref.session?.sessionManager.getSessionId() === owner)?.session;
231
+ const live = refs.find(ref => {
232
+ const id = ref.session?.sessionManager.getSessionId();
233
+ return id !== undefined && (id === owner || `${id}-advisor` === owner);
234
+ })?.session;
176
235
  if (!drain && live instanceof pi.pi.AgentSession) {
177
236
  serviceEntries.set(owner, live.sessionManager.getEntries());
178
237
  continue;
@@ -187,16 +246,16 @@ export default function hostExtension(pi: ExtensionAPI): void {
187
246
  const recorded = (daemon: Frame) => serviceCompletionRecorded(daemon, serviceEntries.get(String(daemon.owner)) ?? []);
188
247
  const tracked = generations.filter(row => row.daemon && typeof row.daemon === "object").map(row => row.daemon as Frame);
189
248
  const knownKeys = new Set(tracked.map(generationKey));
190
- const serviceDeliveryUnknown = generations.some(row => row.uncertain === true)
249
+ const serviceDeliveryUnknown = !trackingKnown || knownKeys.size !== tracked.length
250
+ || generations.some(row => row.uncertain === true)
191
251
  || generations.some(row => row.phase === "attempt" && !generations.some(result =>
192
- result.phase === "result" && result.toolCallId === row.toolCallId))
252
+ result.phase === "result" && result.owner === row.owner && result.toolCallId === row.toolCallId))
193
253
  || generations.some(row => Array.isArray(row.previous) && row.previous.some(value => {
194
254
  const previous = value as Frame;
195
255
  return owners.has(String(previous.owner)) && !knownKeys.has(generationKey(previous));
196
256
  }))
197
257
  || tracked.some(daemon => {
198
- if (services.some(row => generationKey(row.snapshot as unknown as Frame) === generationKey(daemon)
199
- && !["exited", "failed"].includes(row.snapshot.state))) return false;
258
+ if (services.some(unit => generationKey(unit) === generationKey(daemon) && !terminalService(unit.state))) return false;
200
259
  const entries = serviceEntries.get(String(daemon.owner)) ?? [];
201
260
  // A recorded terminal completion supplies the final snapshot even when
202
261
  // the broker now exposes a replacement generation under the same name.
@@ -208,12 +267,11 @@ export default function hostExtension(pi: ExtensionAPI): void {
208
267
  && serviceCompletionRecorded(value as Frame, entries));
209
268
  });
210
269
  })
211
- || services.some(row => !trackingKnown || !knownKeys.has(generationKey(row.snapshot as unknown as Frame))
212
- || ["exited", "failed"].includes(row.snapshot.state) && !recorded(row.snapshot as unknown as Frame));
270
+ || services.some(unit => !knownKeys.has(generationKey(unit))
271
+ || terminalService(unit.state) && !recorded({ ...unit }));
213
272
  if (drain) {
214
- const refreshed = (await collectReports(true, {})).flatMap(report => report.daemons
215
- .filter(row => owners.has(row.snapshot.owner ?? "")).map(row => row.snapshot));
216
- if (!isDeepStrictEqual(services.map(row => row.snapshot), refreshed))
273
+ const refreshed = await scopedServices();
274
+ if (!isDeepStrictEqual(services, refreshed))
217
275
  throw new Error("Native services changed while their durable completion evidence was drained");
218
276
  }
219
277
  if (!isDeepStrictEqual(refEpoch, registry.list().map(ref =>
@@ -227,7 +285,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
227
285
  const { session } = exact();
228
286
  return !mutationHeld && !observationHeld && !session.isDisposed && !session.isBusyForSnapshot && !session.isStreaming
229
287
  && !session.isCompacting && !session.hasAdmittedSubmission && !session.hasPostPromptWork
230
- && session.queuedMessageCount === 0 && !session.hasPendingAsyncWork()
288
+ && session.queuedMessageCount === 0 && !pendingNativeWake(session)
231
289
  && !session.yieldQueue.has()
232
290
  && !session.getGoalModeState()?.enabled;
233
291
  };
@@ -236,7 +294,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
236
294
  if (command.type === "get_state") {
237
295
  const { session } = exact();
238
296
  const queued = session.getQueuedMessages();
239
- // Adapted from oh-my-pi v18.20.2 rpc-mode.ts (MIT; THIRD_PARTY_NOTICES.md).
297
+ // Adapted from oh-my-pi v18.22.0 rpc-mode.ts (MIT; THIRD_PARTY_NOTICES.md).
240
298
  // Copyright (c) 2025 Mario Zechner; 2025-2026 Can Bölük; 2026 Stencil Labs, Inc.
241
299
  // This is a live observation while an owner command is pending, never an
242
300
  // idle receipt. Disposal still requires the stock RPC settlement check.
@@ -247,7 +305,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
247
305
  interruptMode: session.interruptMode, sessionFile: session.sessionFile,
248
306
  sessionId: session.sessionId, sessionName: session.sessionName,
249
307
  autoCompactionEnabled: session.autoCompactionEnabled,
250
- queuedMessageCount: session.queuedMessageCount, hasPendingAsyncWork: session.hasPendingAsyncWork(),
308
+ queuedMessageCount: session.queuedMessageCount, hasPendingAsyncWork: pendingNativeWake(session),
251
309
  isSettled: false,
252
310
  queuedMessages: { steering: [...queued.steering], followUp: [...queued.followUp], liveSteered: queued.liveSteered },
253
311
  todoPhases: session.getTodoPhases(), fastModeEnabled: session.isFastModeEnabled(),
@@ -372,24 +430,74 @@ export default function hostExtension(pi: ExtensionAPI): void {
372
430
  });
373
431
  pi.on("tool_call", async (event, ctx) => {
374
432
  const input = event.input as Frame;
375
- if (event.toolName !== "bash" || typeof input.name !== "string") return;
376
- const start = { name: input.name, cwd: ctx.cwd, owner: ctx.sessionManager.getSessionId() };
377
- serviceStarts.set(event.toolCallId, start);
378
- const report = await collectScope(await targetScope({ dir: ctx.cwd }));
379
- serviceObservation({ phase: "attempt", toolCallId: event.toolCallId, ...start,
380
- previous: report.daemons.filter(row => row.snapshot.name === start.name).map(row => row.snapshot) });
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);
381
482
  });
382
483
  pi.on("tool_result", async (event, ctx) => {
383
- const start = serviceStarts.get(event.toolCallId);
484
+ const owner = serviceOwner(ctx);
485
+ const key = JSON.stringify([owner, event.toolCallId]);
486
+ const start = serviceStarts.get(key);
384
487
  if (!start) return;
385
- serviceStarts.delete(event.toolCallId);
386
488
  const details = event.details as { service?: { name?: string; pid?: number } } | undefined;
387
- const report = await collectScope(await targetScope({ dir: start.cwd }));
388
- const row = report.daemons.find(row => row.snapshot.name === start.name && row.snapshot.owner === start.owner
389
- && row.snapshot.pid === details?.service?.pid);
390
- serviceObservation({ phase: "result", toolCallId: event.toolCallId, owner: ctx.sessionManager.getSessionId(),
391
- name: start.name, uncertain: event.isError || !row?.supervised || !report.scope.brokerPid || !details?.service,
392
- ...(row ? { daemon: row.snapshot } : {}) });
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); }
393
501
  });
394
502
  pi.on("session_start", async (_event, ctx) => {
395
503
  if (ctx.agent.kind !== "main") {
@@ -406,6 +514,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
406
514
  if (server) return;
407
515
  context = ctx;
408
516
  const identity = exact();
517
+ pendingNativeWake(identity.session);
409
518
  await ctx.sessionManager.ensureOnDisk();
410
519
  if (exact().ref !== identity.ref) throw new Error("Native session changed during materialization");
411
520
  identity.session.sessionManager.flushSync();
@@ -416,15 +525,18 @@ export default function hostExtension(pi: ExtensionAPI): void {
416
525
  entry.type === "custom_message" && entry.customType === "launch-completion"
417
526
  || entry.type === "message" && entry.message.role === "assistant" && Array.isArray(entry.message.content)
418
527
  && entry.message.content.some(part => part.type === "toolCall" && part.name === "bash"
419
- && typeof (part.arguments as Frame).name === "string")),
528
+ && serviceName((part.arguments as Frame).name) !== undefined)),
420
529
  });
421
530
  identity.session.sessionManager.flushSync();
422
531
  }
423
532
  server = net.createServer(socket => {
533
+ if (ownerChannel) { socket.destroy(); return; }
424
534
  const channel = new HostChannel(socket, socket, true);
535
+ ownerChannel = channel;
536
+ void channel.exited.then(() => { if (ownerChannel === channel) ownerChannel = undefined; });
425
537
  channel.encoder.setProtocolVersion(2);
426
538
  channel.on("frame", (command: Frame) => {
427
- if (typeof command.id !== "string") return;
539
+ if (command.type === "response" || typeof command.id !== "string") return;
428
540
  void handle(command).then(data => {
429
541
  channel.send(command.type === "interrupt_maintenance" && command.restoreQueue === true
430
542
  ? fitAbortAndRestoreQueueResponse(command.id as string, data as RpcAbortAndRestoreQueueResult, channel.encoder.maxResponseBytes)
package/src/host-owner.ts CHANGED
@@ -11,6 +11,7 @@ import { isDeepStrictEqual } from "node:util";
11
11
  const environment = { ...process.env };
12
12
  const manifest = JSON.parse(await fs.readFile(process.argv[2]!, "utf8")) as {
13
13
  options: Omit<HostOptions, "env">; args: string[]; configPath: string; nativeSocket: string;
14
+ processBackend: Awaited<ReturnType<typeof import("./installed-omp").inspectInstalledOmp>>["processBackend"];
14
15
  };
15
16
  const { options, args, configPath, nativeSocket } = manifest;
16
17
  // Select the same native profile before SDK imports initialize paths or stores.
@@ -118,9 +119,24 @@ requireSuccess(await native.request({ type: "negotiate_protocol", protocolVersio
118
119
  // Stock commands queue behind session_start; completion proves our native
119
120
  // extension finished materialization and opened its private control endpoint.
120
121
  requireSuccess(await native.request({ type: "get_state" }));
122
+ requireSuccess(await native.request({ type: "set_ask_dialog", enabled: true }));
121
123
  const socket = net.createConnection(nativeSocket);
122
124
  control = new HostChannel(socket, socket, true);
123
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
+ });
124
140
  await control.ready.promise;
125
141
  const identity = requireSuccess(await control.request({ type: "snapshot" }));
126
142
  if (identity.hostPid !== child.pid || identity.sessionFile !== options.sessionFile) throw new Error("Native launch identity mismatch");
@@ -3,6 +3,7 @@ import type { Readable, Writable } from "node:stream";
3
3
  import { StringDecoder } from "node:string_decoder";
4
4
  import { MAX_RPC_REASSEMBLED_BYTES, RpcFrameDecoder, RpcFrameEncoder } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-frame";
5
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";
6
7
  import type { LanePresetSnapshot } from "./contracts";
7
8
 
8
9
  /** Private adapter observations, not additions to the stock RPC protocol. */
@@ -16,6 +17,11 @@ export type HostState = RpcSessionState & {
16
17
  pendingUiRequests: Record<string, unknown>[];
17
18
  };
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
+ };
19
25
  export type Response = Frame & { success: boolean; data?: unknown; error?: string };
20
26
  export type HostResponse = RpcResponse | {
21
27
  type: "response"; id?: string; command: "shutdown_host" | "set_model_preset" | "get_host_admission"; success: true; data: Frame;
@@ -30,6 +36,7 @@ export class HostRequestTimeout extends Error {
30
36
  export function serviceCompletionRecorded(daemon: Frame, entries: readonly unknown[]): boolean {
31
37
  if (typeof daemon.owner !== "string" || typeof daemon.id !== "string" || typeof daemon.startedAt !== "number"
32
38
  || typeof daemon.restartCount !== "number" || typeof daemon.exitedAt !== "number"
39
+ || ("generation" in daemon && (typeof daemon.generation !== "string" || !daemon.generation))
33
40
  || !["exited", "failed"].includes(String(daemon.state))) return false;
34
41
  return entries.some(value => {
35
42
  if (!value || typeof value !== "object") return false;
@@ -39,7 +46,8 @@ export function serviceCompletionRecorded(daemon: Frame, entries: readonly unkno
39
46
  && Array.isArray(details?.daemons) && details.daemons.some(value => {
40
47
  if (!value || typeof value !== "object") return false;
41
48
  const observed = value as Frame;
42
- return ["owner", "id", "startedAt", "restartCount", "state", "exitedAt"]
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"]
43
51
  .every(field => daemon[field] === observed[field]);
44
52
  });
45
53
  });
@@ -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
+ }
package/src/host.ts CHANGED
@@ -296,7 +296,8 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
296
296
  throw new Error(`RPC socket already hosts session ${state.sessionId} at ${state.sessionFile}; explicit adoption required`);
297
297
  } finally { await connection.close(); }
298
298
  }
299
- await inspectInstalledOmp(options.command, [], options.env);
299
+ const { executable, processBackend } = await inspectInstalledOmp(options.command, [], options.env);
300
+ options = { ...options, command: [executable, ...options.command.slice(1)] };
300
301
 
301
302
  const launchDirectory = await fs.mkdtemp(path.join(path.dirname(options.socketPath), ".launch-"));
302
303
  const configPath = path.join(launchDirectory, "config.json");
@@ -334,7 +335,7 @@ async function launchHost(options: HostOptions): Promise<{ pid: number }> {
334
335
  launchArgs: [...options.command.slice(1), ...buildHostArgs(options, configPath)],
335
336
  env: options.env, bunCommand: [bun, "--no-env-file"] });
336
337
  const { env: _inheritedEnvironment, ...launchOptions } = options;
337
- await fs.writeFile(manifestPath, JSON.stringify({ options: launchOptions, args: buildHostArgs(options, configPath, composition), configPath,
338
+ await fs.writeFile(manifestPath, JSON.stringify({ options: launchOptions, args: buildHostArgs(options, configPath, composition), configPath, processBackend,
338
339
  nativeSocket: path.join(path.dirname(options.socketPath), `.n-${crypto.randomUUID().slice(0, 8)}.sock`) }),
339
340
  { flag: "wx", mode: 0o600 });
340
341
  child = spawn(bun, ["--no-env-file", fileURLToPath(new URL("./host-owner.ts", import.meta.url)), manifestPath], {
@@ -1,12 +1,8 @@
1
- import { readFileSync, realpathSync } from "node:fs";
1
+ import { realpathSync } from "node:fs";
2
2
  import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
5
  const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
6
- const minimumVersion: string = JSON.parse(readFileSync(join(root, "package.json"), "utf8"))
7
- .dependencies["@oh-my-pi/pi-coding-agent"];
8
- const minimum = minimumVersion.split(".").map(Number);
9
- export const supportedOmp = `>=${minimumVersion} <${minimum[0]! + 1}.0.0`;
10
6
 
11
7
  /** Resolve outside dependency shims, including PATH injected by bun run/install. */
12
8
  export function discoverInstalledOmp(path = process.env.PATH ?? ""): string {
@@ -18,46 +14,58 @@ export function discoverInstalledOmp(path = process.env.PATH ?? ""): string {
18
14
  if (executable.startsWith(join(root, "node_modules") + "/")) continue;
19
15
  return executable;
20
16
  }
21
- throw new Error(`An installed stock OMP ${supportedOmp} is required on PATH; setup does not download or build OMP`);
17
+ throw new Error("An installed stock OMP is required on PATH, or configure its executable directly");
22
18
  }
23
19
 
24
- /** Preserve native CLI arguments while keeping a bare omp independent of Bun's PATH. */
25
- export function resolveOmpCommand(command: string[], path = process.env.PATH ?? ""): string[] {
26
- if (command[0] === "omp") return [discoverInstalledOmp(path), ...command.slice(1)];
27
- if (command.some(arg => isAbsolute(arg) && resolve(arg).startsWith(join(root, "node_modules") + "/")))
20
+ /** Resolve path-like executables before any change to the launch working directory. */
21
+ export function resolveOmpCommand(command: string[], path = process.env.PATH ?? "", cwd = process.cwd()): string[] {
22
+ const [entry, ...args] = command;
23
+ if (!entry) throw new Error("Configure an installed OMP executable");
24
+ const executable = entry === "omp" ? discoverInstalledOmp(path) : entry.includes("/") ? resolve(cwd, entry) : entry;
25
+ if ([executable, ...args].some(arg => isAbsolute(arg) && resolve(arg).startsWith(join(root, "node_modules") + "/")))
28
26
  throw new Error("Configure a separately installed OMP executable, not this project's SDK dependency");
29
- return [...command];
27
+ return [executable, ...args];
30
28
  }
31
29
 
32
30
  /** Inspect CLI metadata only; never open an agent or provider session. */
33
31
  export async function inspectInstalledOmp(
34
- command: string[] = ["omp"], credentials: string[] = [], environment: NodeJS.ProcessEnv = process.env,
32
+ command: string[], credentials: string[] = [], environment: NodeJS.ProcessEnv = process.env,
35
33
  ) {
36
- const argv = resolveOmpCommand(command, environment.PATH ?? "");
34
+ const path = environment.PATH ?? "";
35
+ const [entry] = resolveOmpCommand(command, path);
36
+ const executable = entry && (isAbsolute(entry) ? entry : Bun.which(entry, { PATH: path }));
37
+ if (!executable) throw new Error(`Cannot find the configured OMP executable ${entry ?? ""} on PATH`);
37
38
  const env = { ...environment };
38
39
  for (const name of credentials) delete env[name];
39
- const probe = async (flag: string) => {
40
+ const probe = async (...args: string[]) => {
40
41
  // Require the CLI itself, not a runtime/script wrapper with an ambiguous
41
42
  // native argv boundary. Metadata inspection never loads launch extensions.
42
- const child = Bun.spawn([argv[0]!, flag], {
43
- env, stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: 10_000,
43
+ const child = Bun.spawn([executable, ...args], {
44
+ // Unlike --version, root help loads the CLI's bundled native addon.
45
+ // Its first extraction and load on macOS can take more than ten seconds.
46
+ env, stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: args[0] === "--version" ? 10_000 : 30_000,
44
47
  });
45
48
  const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
46
- if (code !== 0) throw new Error(`Installed OMP ${flag} failed (${code}); diagnostic output suppressed to protect credentials`);
49
+ if (code !== 0) throw new Error(`OMP executable ${executable}: ${args.join(" ")} failed (${code}); diagnostic output suppressed to protect credentials`);
47
50
  return stdout;
48
51
  };
49
- const version = (await probe("--version")).trim();
50
- const match = version.match(/^omp\/(\d+)\.(\d+)\.(\d+)$/);
51
- const actual = match?.slice(1).map(Number);
52
- if (!actual || actual[0] !== minimum[0] ||
53
- actual[1]! < minimum[1]! || actual[1] === minimum[1] && actual[2]! < minimum[2]!)
54
- throw new Error(`Install a supported stock OMP ${supportedOmp} and configure its executable directly, not a runtime/script wrapper; setup does not download or build OMP`);
52
+ const version = (await probe("--version")).trim().match(/^omp\/(\S+)$/)?.[1];
53
+ if (!version)
54
+ throw new Error(`${executable} did not identify as OMP; configure its executable directly, not a runtime/script wrapper`);
55
55
  const help = await probe("--help");
56
56
  const flags = ["--mode", "--resume", "--extension", "--model"];
57
- if (!flags.every(flag => new RegExp(`${flag}(?=[\\s,=])`).test(help)) || !/(?<![\w-])rpc(?![\w-])/.test(help))
58
- throw new Error("Installed OMP must support public stdio RPC, session resume, extensions, and model selection");
57
+ if (!flags.every(flag => new RegExp(`${flag}(?=[\\s,=])`).test(help)) || !/(?<![\w-])rpc-ui(?![\w-])/.test(help))
58
+ throw new Error(`OMP ${version} at ${executable} must support public stdio RPC (rpc-ui), session resume, extensions, and model selection`);
59
+ // Match the selected executable's process interface, not the package SDK or
60
+ // a failed/empty daemon observation. Both CLIs advertise these on ps only.
61
+ const processes = await probe("ps", "--help");
62
+ const broker = /--global(?=[\s,=])/.test(processes);
63
+ const daemon = /--signal(?=[\s,=])/.test(processes);
64
+ if (broker === daemon)
65
+ throw new Error(`OMP ${version} at ${executable} has an unrecognized process ownership interface (ps --help)`);
66
+ const processBackend = broker ? "broker" as const : "daemon" as const;
59
67
  return {
60
- version: actual.join("."), supported: supportedOmp, testedVersion: minimumVersion,
68
+ executable, version, processBackend,
61
69
  stdioRpc: true, sessions: true, extensions: true, modelSelection: true,
62
70
  };
63
71
  }