@xzzpig/pi-subagents 0.16.0 → 0.18.0

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 (133) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. package/src/runs/shared/task-intent.ts +0 -244
@@ -20,9 +20,9 @@ import {
20
20
  import { readStatus, resolveWatchPath } from "../../shared/utils.ts";
21
21
  import { normalizeParallelGroups } from "./parallel-groups.ts";
22
22
  import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.ts";
23
- import { findNestedRouteForRootId, hasLiveNestedDescendants, updateAsyncJobNestedProjection } from "../shared/nested-events.ts";
23
+ import { findNestedRouteForRootId, hasLiveNestedDescendants, retainNestedLookupRoute, updateAsyncJobNestedProjection } from "../shared/nested-events.ts";
24
24
  import { listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
25
- import { EXTERNAL_JOB_BRIDGE_REQUEST_DIR, serviceExternalJobBridgeRequests } from "../shared/external-job-bridge.ts";
25
+ import { EXTERNAL_JOB_BRIDGE_REQUEST_DIR, externalJobBridgeEligibility, serviceExternalJobBridgeRequests } from "../shared/external-job-bridge.ts";
26
26
  import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.ts";
27
27
  import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.ts";
28
28
  import { validHostStepNodes } from "../shared/host-step-status.ts";
@@ -85,19 +85,6 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
85
85
  // Early native failure is visible before its publisher finishes. Retain only
86
86
  // that scoped observation, using the existing liveness sweep to renew delivery.
87
87
  const terminalPublications = new Map<string, { instanceId: string; pending: true } | { pending: false }>();
88
- const externalJobBridgeEligibility = (steps: AsyncJobState["steps"]): "required" | "not-required" | "unknown" => {
89
- if (!Array.isArray(steps)) return "unknown";
90
- for (const step of steps) {
91
- const runner = (step as { runner?: unknown } | null)?.runner;
92
- if (runner === undefined) continue;
93
- if (!runner || typeof runner !== "object" || Array.isArray(runner)) return "unknown";
94
- const runnerType = (runner as { type?: unknown }).type;
95
- if (typeof runnerType !== "string") return "unknown";
96
- if (runnerType === "external-job") return "required";
97
- if (runnerType !== "pi" && runnerType !== "external-cli") return "unknown";
98
- }
99
- return "not-required";
100
- };
101
88
  let rootWatcher: fs.FSWatcher | undefined;
102
89
  let nextLivenessAt = Date.now() + livenessIntervalMs;
103
90
  let nextWidgetAnimationAt = Date.now() + WIDGET_ANIMATION_INTERVAL_MS;
@@ -223,6 +210,8 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
223
210
  const timer = setTimeout(() => {
224
211
  state.cleanupTimers.delete(asyncId);
225
212
  closeJobWatcher(asyncId);
213
+ const job = state.asyncJobs.get(asyncId);
214
+ retainNestedLookupRoute(state, job?.nestedRoute, job?.sessionId);
226
215
  state.asyncJobs.delete(asyncId);
227
216
  rerenderLastWidget();
228
217
  }, completionRetentionMs);
@@ -262,24 +251,28 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
262
251
  if (!parsed || typeof parsed !== "object") return;
263
252
  if ((parsed as { type?: unknown }).type === "subagent.child-status") {
264
253
  const event = parsed as Partial<SubagentChildStatusEvent>;
265
- if (event.version !== 1 || typeof event.runId !== "string" || typeof event.childId !== "string" || (event.status !== "stopping" && event.status !== "stopped") || typeof event.ts !== "number") return;
266
- pi.events.emit(SUBAGENT_CHILD_STATUS_EVENT, {
267
- type: "subagent.child-status",
268
- version: 1,
269
- runId: event.runId,
270
- childId: event.childId,
271
- status: event.status,
272
- ts: event.ts,
273
- ...(typeof event.reason === "string" ? { reason: event.reason } : {}),
274
- source: event.source === "rpc" ? "rpc" : "async",
275
- asyncDir: job.asyncDir,
276
- ...(typeof event.stepIndex === "number" ? { stepIndex: event.stepIndex } : {}),
277
- ...(typeof event.agent === "string" ? { agent: event.agent } : {}),
278
- ...(typeof event.childRunId === "string" ? { childRunId: event.childRunId } : {}),
279
- ...(typeof event.workflowKey === "string" ? { workflowKey: event.workflowKey } : {}),
280
- ...(typeof event.phase === "string" ? { phase: event.phase } : {}),
281
- ...(typeof event.label === "string" ? { label: event.label } : {}),
282
- } satisfies SubagentChildStatusEvent);
254
+ if (event.version !== 1 || typeof event.runId !== "string" || typeof event.childId !== "string" || (event.status !== "started" && event.status !== "stopping" && event.status !== "stopped") || typeof event.ts !== "number") return;
255
+ try {
256
+ pi.events.emit(SUBAGENT_CHILD_STATUS_EVENT, {
257
+ type: "subagent.child-status",
258
+ version: 1,
259
+ runId: event.runId,
260
+ childId: event.childId,
261
+ status: event.status,
262
+ ts: event.ts,
263
+ ...(typeof event.reason === "string" ? { reason: event.reason } : {}),
264
+ source: event.source === "rpc" ? "rpc" : "async",
265
+ asyncDir: job.asyncDir,
266
+ ...(typeof event.stepIndex === "number" ? { stepIndex: event.stepIndex } : {}),
267
+ ...(typeof event.agent === "string" ? { agent: event.agent } : {}),
268
+ ...(typeof event.childRunId === "string" ? { childRunId: event.childRunId } : {}),
269
+ ...(typeof event.workflowKey === "string" ? { workflowKey: event.workflowKey } : {}),
270
+ ...(typeof event.phase === "string" ? { phase: event.phase } : {}),
271
+ ...(typeof event.label === "string" ? { label: event.label } : {}),
272
+ } satisfies SubagentChildStatusEvent);
273
+ } catch (error) {
274
+ console.error("Failed to emit async child status event:", error);
275
+ }
283
276
  return;
284
277
  }
285
278
  if ((parsed as { type?: unknown }).type === "subagent.steering.notice") {
@@ -694,7 +687,8 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
694
687
  const agents = firstGroupCount && firstGroupCount > 0
695
688
  ? rawAgents?.slice(0, firstGroupCount)
696
689
  : rawAgents;
697
- const sessionRoot = state.liveAsyncSessionRoots?.get(info.id);
690
+ const existingJob = state.asyncJobs.get(info.id);
691
+ const sessionRoot = state.liveAsyncSessionRoots?.get(info.id) ?? existingJob?.sessionRoot;
698
692
  state.liveAsyncSessionRoots?.delete(info.id);
699
693
  externalJobBridgeRuns.delete(info.id);
700
694
  terminalPublications.delete(info.id);
@@ -7,7 +7,7 @@ import { snapshotRequiredChildExtensions } from "../../shared/required-child-ext
7
7
  import { normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
8
8
  import { validateAcceptanceInput } from "../shared/acceptance.ts";
9
9
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
10
- import { intersectSubagentCapabilityCeilings, parseSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
10
+ import { intersectSubagentCapabilityCeilings, normalizeCapabilityCeilingAllowedAgents, parseSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
11
11
  import { validateRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
12
12
  import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
13
13
  import { resultFilePath, resultPayloadPathForIndexedRun } from "./result-files.ts";
@@ -83,6 +83,7 @@ interface AsyncResultFile {
83
83
  sandbox?: string;
84
84
  permissionProfile?: string;
85
85
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
86
+ admissionCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
86
87
  results?: Array<{ agent?: string; sessionName?: string; success?: boolean; sessionFile?: string; intercomTarget?: string; model?: string; thinking?: string; launchContractDigest?: string; sandbox?: string; permissionProfile?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling }>;
87
88
  }
88
89
 
@@ -154,6 +155,7 @@ function validateResultFile(value: unknown, resultPath: string): AsyncResultFile
154
155
  ...(data.sandbox === undefined ? {} : { sandbox: validateSandboxProfileName(data.sandbox, `async result file '${resultPath}' sandbox`) }),
155
156
  ...(data.permissionProfile === undefined ? {} : { permissionProfile: validatePermissionProfileName(data.permissionProfile, `async result file '${resultPath}' permissionProfile`) }),
156
157
  ...(data.capabilityCeiling === undefined ? {} : { capabilityCeiling: parseSubagentCapabilityCeiling(data.capabilityCeiling, `async result file '${resultPath}' capabilityCeiling`) }),
158
+ ...(data.admissionCapabilityCeiling === undefined ? {} : { admissionCapabilityCeiling: parseSubagentCapabilityCeiling(data.admissionCapabilityCeiling, `async result file '${resultPath}' admissionCapabilityCeiling`) }),
157
159
  ...(typeof success === "boolean" ? { success } : {}),
158
160
  ...(results ? { results } : {}),
159
161
  };
@@ -287,6 +289,7 @@ function validateStatusForResume(status: AsyncStatus | null, source: string): vo
287
289
  if (status.cwd !== undefined && typeof status.cwd !== "string") throw new Error(`Invalid async status '${source}': cwd must be a string.`);
288
290
  if (status.sessionFile !== undefined && typeof status.sessionFile !== "string") throw new Error(`Invalid async status '${source}': sessionFile must be a string.`);
289
291
  if (status.capabilityCeiling !== undefined) status.capabilityCeiling = parseSubagentCapabilityCeiling(status.capabilityCeiling, `async status '${source}' capabilityCeiling`);
292
+ if (status.admissionCapabilityCeiling !== undefined) status.admissionCapabilityCeiling = parseSubagentCapabilityCeiling(status.admissionCapabilityCeiling, `async status '${source}' admissionCapabilityCeiling`);
290
293
  if (status.steps !== undefined) {
291
294
  if (!Array.isArray(status.steps)) throw new Error(`Invalid async status '${source}': steps must be an array.`);
292
295
  status.steps.forEach((step, index) => {
@@ -312,9 +315,9 @@ function normalizeRecoveryAcceptance(value: unknown, descriptorPath: string): Ac
312
315
  return value as AcceptanceInput;
313
316
  }
314
317
 
315
- export function asyncReviveRequiresRecoveryDescriptor(target: Pick<AsyncResumeTarget, "recoveryDescriptor" | "mode" | "sessionFile">): boolean {
318
+ export function asyncReviveRequiresRecoveryDescriptor(target: Pick<AsyncResumeTarget, "recoveryDescriptor" | "mode" | "sessionFile" | "capabilityCeiling">): boolean {
316
319
  if (target.recoveryDescriptor) return false;
317
- return !(target.mode === "workflow" && Boolean(target.sessionFile));
320
+ return !(target.mode === "workflow" && target.sessionFile && target.capabilityCeiling);
318
321
  }
319
322
 
320
323
  function resumeTargetMode(status: AsyncStatus | null, result: AsyncResultFile | undefined): SubagentRunMode | undefined {
@@ -336,9 +339,9 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
336
339
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': expected an object.`);
337
340
  const parsed = value as Record<string, unknown>;
338
341
  const allowedFields = new Set([
339
- "modelResponseAliases", "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sandbox", "permissionProfile", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "modelOrigin", "fast", "thinking", "thinkingCeiling", "tools", "allowNestedSubagents", "extensions",
342
+ "modelResponseAliases", "version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sandbox", "permissionProfile", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "modelOrigin", "fast", "thinking", "thinkingCeiling", "tools", "allowNestedSubagents", "allowedAgents", "extensions",
340
343
  "subagentOnlyExtensions", "mcpDirectTools", "excludeTools", "mutationTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills",
341
- "skillPath", "agentFilePath", "completionGuard", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
344
+ "skillPath", "agentFilePath", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
342
345
  "artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
343
346
  "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef",
344
347
  "extensionBindings",
@@ -384,6 +387,10 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
384
387
  if (parsed.inheritGlobalContext === undefined) parsed.inheritGlobalContext = parsed.inheritProjectContext;
385
388
  else if (typeof parsed.inheritGlobalContext !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': inheritGlobalContext must be a boolean.`);
386
389
  if (parsed.allowNestedSubagents !== undefined && typeof parsed.allowNestedSubagents !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': allowNestedSubagents must be a boolean.`);
390
+ if (parsed.allowedAgents !== undefined) {
391
+ try { parsed.allowedAgents = normalizeCapabilityCeilingAllowedAgents(parsed.allowedAgents); }
392
+ catch (error) { throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${error instanceof Error ? error.message : String(error)}`); }
393
+ }
387
394
  if (!Number.isInteger(parsed.maxSubagentDepth) || (parsed.maxSubagentDepth as number) < 0) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': maxSubagentDepth must be a non-negative integer.`);
388
395
  for (const field of ["tools", "excludeTools", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "skills", "skillPath"] as const) {
389
396
  const item = parsed[field];
@@ -403,7 +410,6 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
403
410
  }
404
411
  if (parsed.sandbox !== undefined) parsed.sandbox = validateSandboxProfileName(parsed.sandbox, `async recovery descriptor '${descriptorPath}' sandbox`);
405
412
  if (parsed.permissionProfile !== undefined) parsed.permissionProfile = validatePermissionProfileName(parsed.permissionProfile, `async recovery descriptor '${descriptorPath}' permissionProfile`);
406
- if (parsed.completionGuard !== undefined && typeof parsed.completionGuard !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': completionGuard must be a boolean.`);
407
413
  if (parsed.structuredOutputSchema !== undefined && (!parsed.structuredOutputSchema || typeof parsed.structuredOutputSchema !== "object" || Array.isArray(parsed.structuredOutputSchema))) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': structuredOutputSchema must be an object.`);
408
414
  if (parsed.memory !== undefined) {
409
415
  if (!parsed.memory || typeof parsed.memory !== "object" || Array.isArray(parsed.memory)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': memory must be an object.`);
@@ -596,7 +602,9 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
596
602
  const stepModel = statusSteps[index]?.model ?? resultSteps[index]?.model ?? (stepCount === 1 ? result?.model : undefined);
597
603
  const stepThinking = statusSteps[index]?.thinking ?? resultSteps[index]?.thinking ?? (stepCount === 1 ? result?.thinking : undefined);
598
604
  const thinkingCeiling = statusSteps[index]?.thinkingCeiling ?? (stepCount === 1 ? recoveryDescriptor?.thinkingCeiling : undefined);
599
- const capabilityCeiling = intersectSubagentCapabilityCeilings(status?.capabilityCeiling, statusSteps[index]?.capabilityCeiling, result?.capabilityCeiling, resultSteps[index]?.capabilityCeiling);
605
+ const capabilityCeiling = mode === "workflow"
606
+ ? intersectSubagentCapabilityCeilings(status?.admissionCapabilityCeiling, result?.admissionCapabilityCeiling)
607
+ : intersectSubagentCapabilityCeilings(status?.capabilityCeiling, statusSteps[index]?.capabilityCeiling, result?.capabilityCeiling, resultSteps[index]?.capabilityCeiling);
600
608
  const managedWorktreeCwd = location.asyncDir
601
609
  ? resolveRetainedWorktreeCwd(parallelHandoffPath(location.asyncDir), runId, index)
602
610
  : undefined;
@@ -637,6 +645,7 @@ export function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descr
637
645
  tools: descriptor.tools ? [...descriptor.tools] : undefined,
638
646
  excludeTools: descriptor.excludeTools ? [...descriptor.excludeTools] : undefined,
639
647
  allowNestedSubagents: descriptor.allowNestedSubagents,
648
+ allowedAgents: descriptor.allowedAgents === undefined ? undefined : [...descriptor.allowedAgents],
640
649
  extensions: descriptor.extensions ? [...descriptor.extensions] : undefined,
641
650
  subagentOnlyExtensions: descriptor.subagentOnlyExtensions ? [...descriptor.subagentOnlyExtensions] : undefined,
642
651
  mcpDirectTools: descriptor.mcpDirectTools ? [...descriptor.mcpDirectTools] : undefined,
@@ -651,7 +660,6 @@ export function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descr
651
660
  skills: descriptor.skills ? [...descriptor.skills] : undefined,
652
661
  skillPath: descriptor.skillPath ? [...descriptor.skillPath] : undefined,
653
662
  filePath: descriptor.agentFilePath as string,
654
- completionGuard: descriptor.completionGuard,
655
663
  memory: descriptor.memory ? { ...descriptor.memory } : undefined,
656
664
  output: descriptor.outputPath,
657
665
  toolBudget: descriptor.initialToolBudget,
@@ -51,6 +51,7 @@ interface AsyncRunStepSummary {
51
51
  structured?: boolean;
52
52
  status: AsyncJobStep["status"];
53
53
  runner?: AsyncJobStep["runner"];
54
+ externalProcess?: AsyncJobStep["externalProcess"];
54
55
  activityState?: ActivityState;
55
56
  lastActivityAt?: number;
56
57
  currentTool?: string;
@@ -357,6 +358,7 @@ function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string
357
358
  ...(step.structured ? { structured: step.structured } : {}),
358
359
  status: step.status,
359
360
  ...(step.runner ? { runner: step.runner } : {}),
361
+ ...(step.externalProcess ? { externalProcess: step.externalProcess } : {}),
360
362
  ...(stepActivityState ? { activityState: stepActivityState } : {}),
361
363
  ...(stepLastActivityAt ? { lastActivityAt: stepLastActivityAt } : {}),
362
364
  ...(step.currentTool ? { currentTool: step.currentTool } : {}),
@@ -1,8 +1,16 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createJiti } from "jiti";
5
+ import * as piCore from "@earendil-works/pi-agent-core";
6
+ import * as piAi from "@earendil-works/pi-ai/compat";
7
+ import * as piTui from "@earendil-works/pi-tui";
3
8
  import * as sdk from "@earendil-works/pi-coding-agent";
9
+ import * as typebox from "typebox";
10
+ import * as typeboxCompile from "typebox/compile";
11
+ import * as typeboxValue from "typebox/value";
4
12
  import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.ts";
5
- import { runConfiguredSubagent, type SubagentRunConfig } from "./subagent-runner.ts";
13
+ import { runConfiguredSubagent, validateSubagentRunConfig } from "./subagent-runner-bootstrap.ts";
6
14
  import { getAgentDir } from "../../shared/utils.ts";
7
15
 
8
16
  /**
@@ -17,10 +25,9 @@ export default async function runBinaryBootstrap(): Promise<never> {
17
25
  delete process.env.PI_SUBAGENT_RUNNER_CONFIG;
18
26
  try {
19
27
  if (!configPath || !path.isAbsolute(configPath)) throw new Error("Missing absolute PI_SUBAGENT_RUNNER_CONFIG path");
20
- const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as SubagentRunConfig;
21
- if (!config || typeof config.id !== "string" || typeof config.asyncDir !== "string" || !Array.isArray(config.steps)) {
22
- throw new Error("Invalid binary runner configuration");
23
- }
28
+ const rawConfig: unknown = JSON.parse(fs.readFileSync(configPath, "utf8"));
29
+ validateSubagentRunConfig(rawConfig);
30
+ const config = rawConfig;
24
31
  try {
25
32
  fs.unlinkSync(configPath);
26
33
  } catch {
@@ -29,7 +36,28 @@ export default async function runBinaryBootstrap(): Promise<never> {
29
36
  // Pi applies httpIdleTimeoutMs to its dispatcher only after extension
30
37
  // factories return; this factory never does, so install the runner's own.
31
38
  installRunnerHttpDispatcher({ agentDir: getAgentDir(), cwd: process.cwd() });
32
- await runConfiguredSubagent(config, { loadPiCodingAgent: async () => sdk });
39
+ await runConfiguredSubagent(config, {
40
+ loadPiCodingAgent: async () => sdk,
41
+ loadExecutionModule: async () => {
42
+ // Native Bun imports bypass Pi's Jiti virtual peers in the compiled host.
43
+ const jiti = createJiti(import.meta.url, {
44
+ tryNative: false,
45
+ moduleCache: false,
46
+ virtualModules: {
47
+ "@earendil-works/pi-agent-core": piCore,
48
+ "@earendil-works/pi-ai": piAi,
49
+ "@earendil-works/pi-ai/compat": piAi,
50
+ "@earendil-works/pi-tui": piTui,
51
+ "@earendil-works/pi-coding-agent": sdk,
52
+ typebox,
53
+ "typebox/compile": typeboxCompile,
54
+ "typebox/value": typeboxValue,
55
+ },
56
+ });
57
+ const runner = `./subagent-runner${path.extname(fileURLToPath(import.meta.url))}`;
58
+ return jiti.import<typeof import("./subagent-runner.ts")>(runner);
59
+ },
60
+ });
33
61
  process.exit(0);
34
62
  } catch (error) {
35
63
  console.error("Subagent binary runner error:", error);
@@ -339,7 +339,16 @@ function formatDetachedForegroundFleetLines(runs: ForegroundRun[]): string[] {
339
339
  return lines;
340
340
  }
341
341
 
342
- function formatAsyncFleetLines(runs: AsyncRunSummary[]): string[] {
342
+ function externalCliStepFacts(step: AsyncRunSummary["steps"][number], now: number): string | undefined {
343
+ if (step.runner?.type !== "external-cli") return undefined;
344
+ const process = step.externalProcess;
345
+ const elapsed = process
346
+ ? process.durationMs ?? Math.max(0, (process.endedAt ?? now) - process.startedAt)
347
+ : undefined;
348
+ return `external-cli${elapsed !== undefined ? ` · ${formatDuration(elapsed)}` : ""}`;
349
+ }
350
+
351
+ function formatAsyncFleetLines(runs: AsyncRunSummary[], now = Date.now()): string[] {
343
352
  if (runs.length === 0) return [];
344
353
  const lines = ["Async runs:"];
345
354
  for (const run of runs) {
@@ -357,7 +366,7 @@ function formatAsyncFleetLines(runs: AsyncRunSummary[]): string[] {
357
366
  const phase = step.phase ? `[${step.phase}] ` : "";
358
367
  const stepActivity = formatActivityFacts(step);
359
368
  const modelThinking = formatModelThinking(step.model, step.thinking);
360
- const parts = [`${step.index}. ${phase}${display}${stepContext ? ` ${stepContext}` : ""}`, step.status, stepActivity, modelThinking].filter(Boolean);
369
+ const parts = [`${step.index}. ${phase}${display}${stepContext ? ` ${stepContext}` : ""}`, step.status, externalCliStepFacts(step, now), stepActivity, modelThinking].filter(Boolean);
361
370
  lines.push(` ${parts.join(" | ")}`);
362
371
  const output = path.join(run.asyncDir, `output-${step.index}.log`);
363
372
  if (fs.existsSync(output)) lines.push(` output: ${shortenPath(output)}`);
@@ -420,7 +429,7 @@ export function inspectSubagentFleet(_params: FleetViewParams, deps: FleetViewDe
420
429
  if (foregroundLines.length) lines.push(...foregroundLines, "");
421
430
  const detachedForegroundLines = formatDetachedForegroundFleetLines(detachedForegroundRuns);
422
431
  if (detachedForegroundLines.length) lines.push(...detachedForegroundLines, "");
423
- const asyncLines = formatAsyncFleetLines(asyncRuns);
432
+ const asyncLines = formatAsyncFleetLines(asyncRuns, deps.now?.() ?? Date.now());
424
433
  if (asyncLines.length) lines.push(...asyncLines, "");
425
434
  lines.push("Commands:");
426
435
  lines.push(" Refresh fleet: subagent({ action: \"status\", view: \"fleet\" })");
@@ -525,14 +534,39 @@ function appendTranscriptBody(lines: string[], sourceLabel: string, sourceLines:
525
534
  lines.push(...body.reverse());
526
535
  }
527
536
 
537
+ function resolveWorkflowTranscriptChild(status: AsyncStatus, asyncDir: string, options: TranscriptOptions): { status: AsyncStatus; asyncDir: string } | undefined {
538
+ if (status.mode !== "workflow" || options.index === undefined) return undefined;
539
+ const step = status.steps?.[options.index];
540
+ if (step?.async !== true || typeof step.runId !== "string" || !/^[A-Za-z0-9_-]+$/.test(step.runId) || step.runId === status.runId) return undefined;
541
+ try {
542
+ const asyncRoot = fs.realpathSync(path.dirname(asyncDir));
543
+ const childDir = path.join(asyncRoot, step.runId);
544
+ if (fs.realpathSync(childDir) !== childDir || fs.lstatSync(path.join(childDir, "status.json")).isSymbolicLink()) return undefined;
545
+ const childStatus = readStatus(childDir);
546
+ return childStatus?.runId === step.runId
547
+ && childStatus.parentWorkflowRunId === status.runId
548
+ && typeof step.workflowKey === "string" && step.workflowKey.length > 0
549
+ && childStatus.workflowKey === step.workflowKey
550
+ && typeof status.sessionId === "string" && status.sessionId.length > 0
551
+ && childStatus.sessionId === status.sessionId
552
+ ? { status: childStatus, asyncDir: childDir }
553
+ : undefined;
554
+ } catch (error) {
555
+ if (isNotFoundError(error)) return undefined;
556
+ throw error;
557
+ }
558
+ }
559
+
528
560
  export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string, options: TranscriptOptions = {}): string {
561
+ const workflowChild = resolveWorkflowTranscriptChild(status, asyncDir, options);
562
+ if (workflowChild) return formatAsyncRunTranscript(workflowChild.status, workflowChild.asyncDir, { ...options, index: undefined });
529
563
  const lineLimit = transcriptLineLimit(options.lines);
530
564
  const selected = selectTranscriptStep(status, options);
531
565
  const stepOutputPath = selected.index !== undefined ? path.join(asyncDir, `output-${selected.index}.log`) : undefined;
532
566
  const runOutputPath = resolveMaybeRelative(asyncDir, status.outputFile);
533
567
  const logPath = path.join(asyncDir, `subagent-log-${status.runId}.md`);
534
568
  const outputPaths = selected.index !== undefined
535
- ? uniqueStrings([stepOutputPath, runOutputPath && stepOutputPath && path.resolve(runOutputPath) === path.resolve(stepOutputPath) ? runOutputPath : undefined])
569
+ ? uniqueStrings([selected.step?.externalProcess?.finalOutputPath, stepOutputPath, runOutputPath && stepOutputPath && path.resolve(runOutputPath) === path.resolve(stepOutputPath) ? runOutputPath : undefined])
536
570
  : uniqueStrings([runOutputPath]);
537
571
  const sessionFile = selected.index !== undefined ? selected.step?.sessionFile : status.sessionFile;
538
572
  const eventsPath = path.join(asyncDir, "events.jsonl");
@@ -553,12 +587,22 @@ export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string,
553
587
  let transcriptLines: string[] = [];
554
588
  let transcriptSource = "Transcript tail";
555
589
  let truncated = false;
556
- for (const outputPath of outputPaths) {
590
+ const externalProcess = selected.step?.runner?.type === "external-cli" ? selected.step.externalProcess : undefined;
591
+ const externalLogPaths = externalProcess ? [
592
+ { path: externalProcess.stderrPath, label: "External stderr tail" },
593
+ { path: externalProcess.stdoutPath, label: "External stdout tail" },
594
+ ] : [];
595
+ const runningExternal = selected.step?.status === "running" && externalProcess;
596
+ const sources = runningExternal
597
+ ? [...externalLogPaths, ...outputPaths.map((outputPath) => ({ path: outputPath, label: "Transcript tail" }))]
598
+ : [...outputPaths.map((outputPath) => ({ path: outputPath, label: "Transcript tail" })), ...externalLogPaths];
599
+ for (const source of sources) {
600
+ const outputPath = source.path;
557
601
  const tail = readContainedTextTail(outputPath, lineLimit, [asyncDir], "output");
558
602
  if (tail.error) warnings.push(`Output read failed for ${tail.path}: ${tail.error}`);
559
- if (tail.lines.length === 0) continue;
603
+ if (!tail.lines.some((line) => line.trim().length > 0)) continue;
560
604
  transcriptLines = tail.lines;
561
- transcriptSource = `Transcript tail from ${tail.path}`;
605
+ transcriptSource = `${source.label} from ${tail.path}`;
562
606
  truncated = tail.truncated;
563
607
  break;
564
608
  }
@@ -141,6 +141,7 @@ export interface RegisterSubagentNotifyOptions {
141
141
  timers?: NotifyTimerApi;
142
142
  now?: () => number;
143
143
  ownership?: Pick<ResultDeliveryOwnership, "owns">;
144
+ sendRegistry?: CompletionSendRegistry;
144
145
  }
145
146
 
146
147
  export interface CompletionNotifier {
@@ -152,6 +153,8 @@ export interface CompletionNotifier {
152
153
  const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 4 * 1024;
153
154
  const CHILD_OUTPUT_PREVIEW_COUNT = 8;
154
155
  const PREVIEW_TRUNCATION_MARKER = "...[preview truncated]";
156
+ const COMPLETION_SEND_TTL_MS = 10 * 60 * 1000;
157
+ const COMPLETION_SEND_REGISTRY_CAP = 4_096;
155
158
  type CompletionChild = NonNullable<CompletionNotification["results"]>[number];
156
159
  interface RetainedPathError { path: string; code?: string; message: string }
157
160
  type RetainedPathProjection =
@@ -210,7 +213,7 @@ function formatRetainedPathError(label: string, error: RetainedPathError): strin
210
213
  function childStatus(child: CompletionChild, workflowState?: string): string {
211
214
  const knownStatus = child.status === "complete"
212
215
  ? "completed"
213
- : child.status === "completed" || child.status === "failed" || child.status === "paused" || child.status === "stopped" || child.status === "detached"
216
+ : child.status === "running" || child.status === "completed" || child.status === "failed" || child.status === "paused" || child.status === "stopped" || child.status === "detached"
214
217
  ? child.status
215
218
  : undefined;
216
219
  if (knownStatus) return knownStatus;
@@ -492,7 +495,7 @@ const notificationDebug = debuglog("pi-subagents-notify");
492
495
  type TraceIdentity = Pick<CompletionNotification, "id" | "runId" | "source">;
493
496
  type NotificationReason = "disposed" | "missing_session" | "foreground_session_mismatch" | "not_owned"
494
497
  | "intercom_delivered" | "deduped_ttl" | "deduped_pending" | "batch_deferred"
495
- | "emit_foreground_session_mismatch" | "emit_not_owned" | "send_accepted" | "send_failed" | "dispose_pending";
498
+ | "emit_foreground_session_mismatch" | "emit_not_owned" | "send_joined" | "send_accepted" | "send_failed" | "dispose_pending";
496
499
 
497
500
  // Slice before sanitizing: diagnostic work and each identity are bounded even for
498
501
  // malformed result metadata. Never include task/output, paths, or error bodies.
@@ -521,6 +524,72 @@ interface PendingCompletion {
521
524
  resolve(accepted: boolean): void;
522
525
  }
523
526
 
527
+ export interface CompletionSendClaim {
528
+ owned: boolean;
529
+ outcome: Promise<boolean>;
530
+ settle?(accepted: boolean): void;
531
+ }
532
+
533
+ export interface CompletionSendRegistry {
534
+ claim(key: string, now: number): CompletionSendClaim;
535
+ }
536
+
537
+ interface CompletionSendEntry {
538
+ outcome: Promise<boolean>;
539
+ resolve(accepted: boolean): void;
540
+ deliveredAt?: number;
541
+ }
542
+
543
+ /** A fresh registry is injectable so tests and separately scoped runtimes stay isolated. */
544
+ export function createCompletionSendRegistry(
545
+ ttlMs = COMPLETION_SEND_TTL_MS,
546
+ cap = COMPLETION_SEND_REGISTRY_CAP,
547
+ ): CompletionSendRegistry {
548
+ const entries = new Map<string, CompletionSendEntry>();
549
+ const prune = (now: number) => {
550
+ for (const [key, entry] of entries) {
551
+ if (entry.deliveredAt !== undefined && now - entry.deliveredAt > ttlMs) entries.delete(key);
552
+ }
553
+ if (entries.size <= cap) return;
554
+ for (const [key, entry] of entries) {
555
+ if (entries.size <= cap) break;
556
+ if (entry.deliveredAt !== undefined) entries.delete(key);
557
+ }
558
+ };
559
+ return {
560
+ claim(key, now) {
561
+ prune(now);
562
+ const existing = entries.get(key);
563
+ if (existing) return { owned: false, outcome: existing.outcome };
564
+ let resolve!: (accepted: boolean) => void;
565
+ const entry: CompletionSendEntry = {
566
+ outcome: new Promise<boolean>((settle) => { resolve = settle; }),
567
+ resolve: (accepted) => resolve(accepted),
568
+ };
569
+ entries.set(key, entry);
570
+ return {
571
+ owned: true,
572
+ outcome: entry.outcome,
573
+ settle(accepted) {
574
+ if (entries.get(key) !== entry) return;
575
+ if (accepted) {
576
+ entry.deliveredAt = now;
577
+ prune(now);
578
+ } else {
579
+ entries.delete(key);
580
+ }
581
+ entry.resolve(accepted);
582
+ },
583
+ };
584
+ },
585
+ };
586
+ }
587
+
588
+ const completionSendRegistrySymbol = Symbol.for("pi-subagents.completion-send-registry.v1");
589
+ const processGlobal = globalThis as typeof globalThis & { [completionSendRegistrySymbol]?: CompletionSendRegistry };
590
+ const processCompletionSendRegistry = processGlobal[completionSendRegistrySymbol]
591
+ ?? (processGlobal[completionSendRegistrySymbol] = createCompletionSendRegistry());
592
+
524
593
  function sendCompletion(pi: Pick<ExtensionAPI, "sendMessage">, items: PendingCompletion[]): boolean {
525
594
  if (items.length === 0) return true;
526
595
  const details = items.map((item) => item.details);
@@ -564,8 +633,11 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
564
633
  || summary.startsWith("Paused after interrupt.")
565
634
  );
566
635
  const status = stopped ? "stopped" : paused ? "paused" : result.success ? "completed" : "failed";
567
- const taskInfo =
568
- result.taskIndex !== undefined && result.totalTasks !== undefined
636
+ const runningChildren = (result.mode === "workflow" || agent === "workflow")
637
+ ? result.results?.filter((child) => childStatus(child) === "running").length ?? 0 : 0;
638
+ const taskInfo = runningChildren > 0
639
+ ? ` (${status === "completed" ? "dispatch complete; " : ""}${runningChildren} ${runningChildren === 1 ? "child" : "children"} running or uncollected)`
640
+ : result.taskIndex !== undefined && result.totalTasks !== undefined
569
641
  ? ` (${result.taskIndex + 1}/${result.totalTasks})`
570
642
  : undefined;
571
643
 
@@ -687,8 +759,9 @@ export default function registerSubagentNotify(
687
759
  ): CompletionNotifier {
688
760
  const seen = new Map<string, number>();
689
761
  const pending = new Map<string, Promise<boolean>>();
690
- const ttlMs = 10 * 60 * 1000;
762
+ const ttlMs = COMPLETION_SEND_TTL_MS;
691
763
  const now = options.now ?? Date.now;
764
+ const sendRegistry = options.sendRegistry ?? processCompletionSendRegistry;
692
765
  const batchConfig = resolveCompletionBatchConfig(options.batchConfig);
693
766
  const batchers = new Map<string, CompletionBatcher<PendingCompletion>>();
694
767
  let disposed = false;
@@ -716,8 +789,20 @@ export default function registerSubagentNotify(
716
789
  (owned ? accepted : rejected).push(item);
717
790
  }
718
791
  settle(rejected, false);
719
- const sent = sendCompletion(pi, accepted);
720
- settle(accepted, sent, sent ? "send_accepted" : "send_failed");
792
+ const claimed: Array<{ item: PendingCompletion; claim: CompletionSendClaim }> = [];
793
+ for (const item of accepted) {
794
+ const claim = sendRegistry.claim(item.key, now());
795
+ if (claim.owned) {
796
+ claimed.push({ item, claim });
797
+ continue;
798
+ }
799
+ traceNotification("send_joined", item.trace);
800
+ void claim.outcome.then((outcome) => settle([item], outcome, outcome ? undefined : "send_failed"));
801
+ }
802
+ const claimedItems = claimed.map(({ item }) => item);
803
+ const sent = sendCompletion(pi, claimedItems);
804
+ for (const { claim } of claimed) claim.settle?.(sent);
805
+ settle(claimedItems, sent, sent ? "send_accepted" : "send_failed");
721
806
  };
722
807
  const getBatcher = (result: CompletionNotification) => {
723
808
  const key = completionBatchKey(result);
@@ -793,6 +878,7 @@ export default function registerSubagentNotify(
793
878
  };
794
879
 
795
880
  const unsubscribeAsync = pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, (data) => {
881
+ if ((data as CompletionNotification).awaitedByWorkflow === true) return;
796
882
  void deliver(data as CompletionNotification);
797
883
  });
798
884
  const unsubscribeForeground = pi.events.on(SUBAGENT_FOREGROUND_COMPLETE_EVENT, (data) => {
@@ -0,0 +1,18 @@
1
+ import * as fs from "node:fs";
2
+
3
+ let resolved = false;
4
+ let cachedScope: string | undefined;
5
+
6
+ /** Linux PID namespace identity, cached because reconciliation is a polling path. */
7
+ export function currentPidNamespaceScope(): string | undefined {
8
+ if (resolved) return cachedScope;
9
+ resolved = true;
10
+ if (process.platform !== "linux") return undefined;
11
+ try {
12
+ const scope = fs.readlinkSync("/proc/self/ns/pid", "utf-8").trim();
13
+ cachedScope = scope || undefined;
14
+ } catch {
15
+ cachedScope = undefined;
16
+ }
17
+ return cachedScope;
18
+ }