@vicary/pi-subagents 0.88.0 → 0.88.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 (44) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/bundle/child-tool-plan.js +2 -2
  3. package/bundle/{chunk-AOSILI5R.js → chunk-2HKPEANZ.js} +75 -40
  4. package/bundle/{chunk-SVIXQDIV.js → chunk-4ZQBZDF3.js} +2 -2
  5. package/bundle/{chunk-YZPVALSQ.js → chunk-5EMPFFO4.js} +3 -3
  6. package/bundle/{chunk-CKLZ5FGU.js → chunk-6CG2VAG4.js} +1 -1
  7. package/bundle/{chunk-6EUQPQY7.js → chunk-7OX6O7DQ.js} +3 -3
  8. package/bundle/{chunk-TDJKY2NE.js → chunk-AZPP3G4N.js} +3 -3
  9. package/bundle/{chunk-BW5JLKIU.js → chunk-BKISQ5CJ.js} +21 -16
  10. package/bundle/{chunk-XZXYPZUT.js → chunk-CGWNA6EJ.js} +46 -28
  11. package/bundle/{chunk-3DT5X2QC.js → chunk-CPSUJHZE.js} +11 -8
  12. package/bundle/{chunk-3MFYKBKI.js → chunk-D32H53HM.js} +3 -3
  13. package/bundle/{chunk-PJSOS2Q4.js → chunk-DSHQWGHO.js} +1 -1
  14. package/bundle/{chunk-JYHTDTOZ.js → chunk-IYT7X46U.js} +2 -2
  15. package/bundle/{chunk-NVGQE2H2.js → chunk-JQTHG2ID.js} +7 -7
  16. package/bundle/{chunk-RHYVKQQL.js → chunk-LV3CPYXJ.js} +2 -2
  17. package/bundle/{chunk-IZEKQEY4.js → chunk-PYKBTBY6.js} +23 -6
  18. package/bundle/{chunk-6PR44R7E.js → chunk-RMZAAXIR.js} +1 -1
  19. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  20. package/bundle/index.js +1 -1
  21. package/bundle/preflight.js +4 -4
  22. package/bundle/required-child-extensions.js +1 -1
  23. package/docs/agents.md +4 -2
  24. package/docs/workflows.md +3 -1
  25. package/package.json +2 -2
  26. package/src/extension/index.d.ts +1 -1
  27. package/src/extension/index.js +43 -20
  28. package/src/extension/subagent-launch-tool.d.ts +6 -2
  29. package/src/extension/subagent-launch-tool.js +13 -9
  30. package/src/runs/background/stale-run-reconciler.js +17 -8
  31. package/src/runs/foreground/subagent-executor.js +11 -6
  32. package/src/runs/shared/child-launch.js +6 -3
  33. package/src/runs/shared/child-session.d.ts +1 -1
  34. package/src/runs/shared/child-session.js +3 -27
  35. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -3
  36. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -4
  37. package/src/shared/compaction-interruption.d.ts +9 -0
  38. package/src/shared/compaction-interruption.js +47 -0
  39. package/src/shared/parent-wake.d.ts +3 -2
  40. package/src/shared/parent-wake.js +14 -3
  41. package/src/shared/required-child-extensions.d.ts +2 -0
  42. package/src/shared/required-child-extensions.js +27 -0
  43. package/src/tui/fleet.d.ts +7 -2
  44. package/src/tui/fleet.js +22 -0
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
+ import { AgentSession } from "@earendil-works/pi-coding-agent";
5
6
  import { Box, Container, Spacer, Text } from "@earendil-works/pi-tui";
6
7
  import { clearAgentDiscoveryCache, discoverAgentSnapshot, discoverAgents, discoverAgentsAll } from "../agents/agents.js";
7
8
  import { resolveGlobalNpmRoot } from "../agents/global-npm-root.js";
@@ -13,6 +14,7 @@ import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "..
13
14
  import { resolveCurrentSessionId } from "../shared/session-identity.js";
14
15
  import { recordSessionReplacement, recordSessionStart } from "../shared/session-succession.js";
15
16
  import { createSessionSwitchGuard } from "./session-switch.js";
17
+ import { compactionInProgress, compactionInterruptedRun, installCompactionInterruptionCapture, takeCompactionAbort } from "../shared/compaction-interruption.js";
16
18
  import { reportSessionWarning } from "../shared/session-warnings.js";
17
19
  import { getAgentDir } from "../shared/utils.js";
18
20
  import { isStaleExtensionContextError, MODEL_ONLY_TOOL, withCachedUiContext } from "../shared/extension-context.js";
@@ -215,6 +217,7 @@ export default function registerSubagentExtension(pi) {
215
217
  if (process.env[SUBAGENT_CHILD_ENV] === "1") {
216
218
  return;
217
219
  }
220
+ installCompactionInterruptionCapture(AgentSession);
218
221
  const runtimeRegistry = getRuntimeRegistry();
219
222
  setMainThinkingLevelSource(() => readMainThinkingLevel(() => pi.getThinkingLevel()));
220
223
  DIRS.results = ensureAccessibleDir(DIRS.results);
@@ -747,7 +750,7 @@ export default function registerSubagentExtension(pi) {
747
750
  try {
748
751
  // The run is still active here, so its signal tells a user stop (Esc) apart from a finished or failed run.
749
752
  // Pi skips agent_before_settle after an abort. Background runs keep going, but they must not restart the parent.
750
- if (ctx.hasUI && ctx.signal?.aborted) {
753
+ if (ctx.hasUI && ctx.signal?.aborted && !takeCompactionAbort(ctx.sessionManager)) {
751
754
  parentWake.userAborted();
752
755
  const active = activeAsyncJobCount();
753
756
  if (active > 0)
@@ -1110,7 +1113,12 @@ export default function registerSubagentExtension(pi) {
1110
1113
  }
1111
1114
  };
1112
1115
  let compactionResumeTimer;
1113
- const cancelCompactionResume = () => { clearTimeout(compactionResumeTimer); compactionResumeTimer = undefined; };
1116
+ let compactionInterruptedParent = false;
1117
+ const cancelCompactionResume = () => {
1118
+ clearTimeout(compactionResumeTimer);
1119
+ compactionResumeTimer = undefined;
1120
+ compactionInterruptedParent = false;
1121
+ };
1114
1122
  pi.on("agent_start", () => {
1115
1123
  cancelCompactionResume();
1116
1124
  parentWake.agentStarted();
@@ -1132,38 +1140,53 @@ export default function registerSubagentExtension(pi) {
1132
1140
  if (event.reason !== "manual")
1133
1141
  suspendWidgetsForCompaction();
1134
1142
  });
1135
- // Pi emits session_compact before it clears its compaction state. sendMessage's run path has no
1136
- // compaction guard (only prompt() refuses), so wait for the parent to go idle before the resume notice
1137
- // starts a run. A run that starts first cancels the pending resume.
1138
- pi.on("session_compact", (event) => {
1143
+ // parentWake only appends wakes during a manual compaction. Once every overlapping compaction has ended, wake
1144
+ // the parent once if a wake was deferred, or if a successful compaction cut off a working parent with
1145
+ // background work (Pi never continues that run). Pi emits session_compact before it clears its compaction
1146
+ // state, so wait until the session is idle and compact() has returned. A run that starts first cancels it.
1147
+ const wakeAfterCompaction = (completed) => (event, ctx) => {
1139
1148
  if (event.reason !== "manual")
1140
1149
  return;
1141
- if (activeAsyncJobCount() === 0 || !withLastUiContext(() => true))
1150
+ const sessionManager = ctx.sessionManager;
1151
+ if (completed && compactionInterruptedRun(sessionManager))
1152
+ compactionInterruptedParent = true;
1153
+ if (compactionResumeTimer)
1142
1154
  return;
1143
- cancelCompactionResume();
1144
1155
  const sessionId = state.currentSessionId;
1145
1156
  const deadline = Date.now() + COMPACTION_RESUME_DEADLINE_MS;
1146
- const resumeWhenIdle = () => {
1147
- if (state.currentSessionId !== sessionId || activeAsyncJobCount() === 0)
1157
+ const wakeWhenIdle = () => {
1158
+ compactionResumeTimer = undefined;
1159
+ if (state.currentSessionId !== sessionId)
1148
1160
  return;
1149
- const idle = withLastUiContext((ctx) => ctx.isIdle());
1150
- if (idle === undefined)
1151
- return;
1152
- if (!idle) {
1161
+ let idle;
1162
+ try {
1163
+ idle = ctx.isIdle();
1164
+ }
1165
+ catch {
1166
+ return; // Replaced or reloaded: the new session's runtime owns its notices.
1167
+ }
1168
+ // Past the deadline the next compaction event polls again.
1169
+ if (!idle || compactionInProgress(sessionManager)) {
1153
1170
  if (Date.now() < deadline)
1154
- compactionResumeTimer = setTimeout(resumeWhenIdle, COMPACTION_RESUME_POLL_MS);
1171
+ compactionResumeTimer = setTimeout(wakeWhenIdle, COMPACTION_RESUME_POLL_MS);
1155
1172
  return;
1156
1173
  }
1157
- // Pi's compact() aborts a live run first, which set the user-abort hold; this resume is deliberate.
1158
- parentWake.releaseHold();
1174
+ const interrupted = compactionInterruptedParent && activeAsyncJobCount() > 0 && withLastUiContext(() => true) === true;
1175
+ compactionInterruptedParent = false;
1176
+ if (!parentWake.takeDeferredWake() && !interrupted)
1177
+ return;
1159
1178
  parentWake.sendMessage({
1160
1179
  customType: "subagent-compaction-resume",
1161
- content: "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready.",
1180
+ content: interrupted
1181
+ ? "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready."
1182
+ : "Compaction is complete. Act on the background subagent notices above.",
1162
1183
  display: false,
1163
1184
  }, { triggerTurn: true });
1164
1185
  };
1165
- compactionResumeTimer = setTimeout(resumeWhenIdle, COMPACTION_RESUME_POLL_MS);
1166
- });
1186
+ compactionResumeTimer = setTimeout(wakeWhenIdle, COMPACTION_RESUME_POLL_MS);
1187
+ };
1188
+ pi.on("session_compact", wakeAfterCompaction(true));
1189
+ pi.on("session_compact_failed", wakeAfterCompaction(false));
1167
1190
  pi.on("session_start", (event, ctx) => {
1168
1191
  parentWake.bindSession(ctx);
1169
1192
  completionNotifier.bindSession(ctx.sessionManager);
@@ -20,6 +20,10 @@ declare const parameters: Type.TObject<{
20
20
  export type SubagentLaunchArgs = Static<typeof parameters>;
21
21
  /** Not declared to the model, so the system prompt and tool list stay unchanged. */
22
22
  export declare function registerSubagentLaunchTool(pi: ExtensionAPI): void;
23
- /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
24
- export declare function approveWorkflowChildLaunch(ctx: ExtensionContext, describe: () => SubagentLaunchArgs, signal: AbortSignal): Promise<string | undefined>;
23
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, or the task the handlers left. */
24
+ export declare function approveWorkflowChildLaunch(ctx: ExtensionContext, describe: () => SubagentLaunchArgs, signal: AbortSignal): Promise<{
25
+ refusal: string;
26
+ } | {
27
+ task?: string;
28
+ }>;
25
29
  export {};
@@ -22,27 +22,31 @@ export function registerSubagentLaunchTool(pi) {
22
22
  pi.registerTool({
23
23
  name: SUBAGENT_LAUNCH_TOOL,
24
24
  label: "Subagent launch",
25
- description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
25
+ description: "A workflow is about to start this subagent. Blocking this call stops that child from starting; changing its task changes what the child is told.",
26
26
  parameters,
27
27
  exposure: "deferred",
28
- async execute() {
29
- return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
28
+ // Pi hands execute the input after every tool_call handler ran, so a handler's change to task arrives here.
29
+ async execute(_toolCallId, params) {
30
+ return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: { task: params.task } };
30
31
  },
31
32
  });
32
33
  }
33
- /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
34
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, or the task the handlers left. */
34
35
  export async function approveWorkflowChildLaunch(ctx, describe, signal) {
35
36
  // Starts with no tool call behind them (schedule ticks, auto-resume, RPC) have no executeTool, and a tool
36
37
  // allowlist that leaves the tool out unregisters it: no handler could see the call in either case.
37
38
  if (!("executeTool" in ctx))
38
- return undefined;
39
+ return {};
39
40
  const toolCtx = ctx;
40
41
  if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL))
41
- return undefined;
42
+ return {};
42
43
  const args = describe();
43
44
  const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
44
- if (!outcome.isError)
45
- return undefined;
45
+ if (!outcome.isError) {
46
+ // Pi doesn't validate the input again after a handler changes it.
47
+ const task = outcome.result.details?.task;
48
+ return { task: typeof task === "string" ? task : undefined };
49
+ }
46
50
  const reason = outcome.result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
47
- return `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}`;
51
+ return { refusal: `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}` };
48
52
  }
@@ -450,8 +450,23 @@ export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
450
450
  const existingResultPath = effectiveStatus.sessionId
451
451
  ? resultPayloadPathForSessionRun(resultsDir, effectiveStatus.sessionId, runId) ?? (regularFileExists(resultPath) ? resultPath : undefined)
452
452
  : regularFileExists(resultPath) ? resultPath : undefined;
453
+ const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
454
+ const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
455
+ const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
456
+ const runnerLiveness = (pid) => checkRecordedPidLiveness({ pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
457
+ kill: options.kill,
458
+ observedScope,
459
+ observedBootId: options.bootId ? options.bootId() : currentBootId(),
460
+ });
453
461
  if (existingResultPath) {
454
- const terminalStatus = effectiveStatus.state === "running" || effectiveStatus.state === "queued"
462
+ // A live runner writes its result before its final status; repairing in that window would replace
463
+ // its pending exit proof with a placeholder. Only a confirmed-alive pid defers: a result is better
464
+ // evidence than an unprobeable pid, and a pid from another pid namespace can be alive here as an unrelated
465
+ // process. A workflow's pid is its host Pi process, which outlives the workflow.
466
+ const runnerStillFinishing = effectiveStatus.state === "running" && effectiveStatus.mode !== "workflow" && typeof effectiveStatus.pid === "number"
467
+ && effectiveStatus.pidNamespaceScope === observedScope
468
+ && now - lastUpdate <= staleAfterMs && runnerLiveness(effectiveStatus.pid) === "alive";
469
+ const terminalStatus = (effectiveStatus.state === "running" || effectiveStatus.state === "queued") && !runnerStillFinishing
455
470
  ? terminalStatusFromResult(effectiveStatus, existingResultPath, now)
456
471
  : undefined;
457
472
  if (terminalStatus) {
@@ -491,14 +506,8 @@ export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
491
506
  return { status: null, repaired: false, resultPath };
492
507
  }
493
508
  }
494
- const liveness = checkRecordedPidLiveness({ pid: effectiveStatus.pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
495
- kill: options.kill,
496
- observedScope: options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope(),
497
- observedBootId: options.bootId ? options.bootId() : currentBootId(),
498
- });
509
+ const liveness = runnerLiveness(effectiveStatus.pid);
499
510
  if (liveness !== "dead") {
500
- const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
501
- const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
502
511
  if (now - lastUpdate <= staleAfterMs)
503
512
  return { status: status ?? null, repaired: false, resultPath };
504
513
  const probe = liveness === "alive" ? "is still live" : "cannot be probed from this process";
@@ -5951,9 +5951,12 @@ export function createSubagentExecutor(deps) {
5951
5951
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
5952
5952
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
5953
5953
  preparedChildParams = childRequest;
5954
- const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5955
- if (launchRefusal)
5956
- return buildRequestedModeError(childRequest, launchRefusal);
5954
+ const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5955
+ if ("refusal" in approval)
5956
+ return buildRequestedModeError(childRequest, approval.refusal);
5957
+ // Assigned in place: the WeakMaps below are keyed on this object. A resume's task is its message, which stays as sent.
5958
+ if (approval.task !== undefined && childRequest.action !== "resume")
5959
+ childRequest.task = approval.task;
5957
5960
  if (workflowUsageBudget.budget)
5958
5961
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5959
5962
  if (workflowRequiredExtensions)
@@ -6282,9 +6285,11 @@ export function createSubagentExecutor(deps) {
6282
6285
  const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
6283
6286
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
6284
6287
  preparedChildParams = childRequest;
6285
- const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6286
- if (launchRefusal)
6287
- return buildRequestedModeError(childRequest, launchRefusal);
6288
+ const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6289
+ if ("refusal" in approval)
6290
+ return buildRequestedModeError(childRequest, approval.refusal);
6291
+ if (approval.task !== undefined && childRequest.action !== "resume")
6292
+ childRequest.task = approval.task;
6288
6293
  if (workflowUsageBudget.budget)
6289
6294
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6290
6295
  if (workflowRequiredExtensions)
@@ -13,7 +13,7 @@ import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV } from "./e
13
13
  import { intersectSubagentCapabilityCeilings } from "./capability-ceiling.js";
14
14
  import { isSubagentRuntimeExtensionPath, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, supervisorChannelDir, } from "./child-tool-plan.js";
15
15
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.js";
16
- import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
16
+ import { createRequiredChildExtensionIdentity, resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
17
17
  import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
18
18
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
19
19
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
@@ -57,6 +57,8 @@ function childProcessEnv(input, toolPlan) {
57
57
  else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
58
58
  env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
59
59
  }
60
+ else if (input.tools === undefined && !toolPlan.capabilityCeiling)
61
+ env[MCP_DIRECT_TOOLS_ENV] = undefined;
60
62
  else
61
63
  env[MCP_DIRECT_TOOLS_ENV] = "__none__";
62
64
  return env;
@@ -106,10 +108,11 @@ export function buildInProcessChildLaunch(input) {
106
108
  permissionRules: input.permissionRules,
107
109
  runtimeSnapshotHost: input.runtimeSnapshotHost,
108
110
  });
109
- // Foreground children load no ambient extensions, so an extension's registerMcpServer() never runs in them.
111
+ // Foreground children load no ambient extensions, so only their required extensions' registerMcpServer() runs in them.
110
112
  if (input.host === "parent" && input.runtimeSnapshotHost && toolPlan.builtinMcpTools?.length) {
113
+ const requiredExtensionIdentity = createRequiredChildExtensionIdentity(toolPlan.requiredExtensions.map(({ path }) => path));
111
114
  // Pi treats a session without a trust decision as trusted.
112
- const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false);
115
+ const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false, (extensionPath) => requiredExtensionIdentity(extensionPath) !== undefined);
113
116
  if (servers.length)
114
117
  throw new Error(`Agent '${input.childAgentName}' selects MCP tools from servers that extensions registered (${servers.join(", ")}). Only background children (async: true) load those extensions; run the agent in the background or add the server to the global mcp.json or a trusted project's .pi/mcp.json.`);
115
118
  }
@@ -1,7 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
4
- import type { RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
4
+ import { type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
5
5
  import type { PlacementMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
6
6
  export interface ChildSessionEvent {
7
7
  type: string;
@@ -26,6 +26,7 @@ import { parseAcceptanceReport } from "./acceptance.js";
26
26
  import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.js";
27
27
  import { resolvePackageSubpath } from "../background/runner-aliases.js";
28
28
  import { PI_CODING_AGENT_PACKAGE, resolveHostPiPackageRoot } from "./pi-spawn.js";
29
+ import { createRequiredChildExtensionIdentity } from "../../shared/required-child-extensions.js";
29
30
  /** Mirror pi's JSON event projection: `message_update` drops the partial message. */
30
31
  export function projectChildSessionEventForJson(event) {
31
32
  if (event.type !== "message_update")
@@ -80,32 +81,6 @@ const CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime
80
81
  const CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
81
82
  /** Same class as UNICODE_SPACES in pi-coding-agent dist/utils/paths.js, which resolvePath(..., { normalizeUnicodeSpaces: true }) replaces with a space. */
82
83
  const PI_UNICODE_SPACES = new RegExp("[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]", "g");
83
- function childExtensionFileIdentity(extensionPath) {
84
- if (!path.isAbsolute(extensionPath))
85
- return undefined;
86
- try {
87
- const stat = fs.statSync(extensionPath, { bigint: true });
88
- return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;
89
- }
90
- catch {
91
- return undefined;
92
- }
93
- }
94
- function createRequiredChildExtensionIdentity(requiredPaths) {
95
- const aliases = new Map([...requiredPaths].map((extensionPath) => [extensionPath, childExtensionFileIdentity(extensionPath) ?? extensionPath]));
96
- const identities = new Set(aliases.values());
97
- return (extensionPath) => {
98
- const known = aliases.get(extensionPath);
99
- if (known !== undefined)
100
- return known;
101
- const identity = childExtensionFileIdentity(extensionPath);
102
- if (identity === undefined || !identities.has(identity))
103
- return undefined;
104
- // Retain the alias even if the extension removes its file before reporting a failure.
105
- aliases.set(extensionPath, identity);
106
- return identity;
107
- };
108
- }
109
84
  /** The prompt runtime filters parent-only context before ambient extensions inspect
110
85
  * the child prompt, and the boundary hook appends the child boundary after every
111
86
  * extension has added its prompt sections. Every other extension keeps its order. */
@@ -591,7 +566,8 @@ export function createDefaultChildSessionFactory(options = {}) {
591
566
  await session.bindExtensions({
592
567
  mode: "print",
593
568
  onError: (error) => {
594
- if (binding && isRequiredSource(error.extensionPath))
569
+ // Pi's unconnected-MCP-server report means the server's tools are outside this child's tool contract, which the child can run without.
570
+ if (binding && error.event !== "register_mcp_server" && isRequiredSource(error.extensionPath))
595
571
  requiredStartupErrors.push(`${error.extensionPath} (${error.event}): ${error.error}`);
596
572
  launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error });
597
573
  },
@@ -53,6 +53,7 @@ export interface McpRuntimeSnapshotHost {
53
53
  /** Pi 0.99: servers extensions added with `pi.registerMcpServer()`. */
54
54
  getMcpServers?(): readonly {
55
55
  name: string;
56
+ extensionPath: string;
56
57
  }[];
57
58
  }
58
59
  /** A `pi.getAllTools()` entry; `exposure` and `namespace` exist only from Pi 0.99. */
@@ -76,8 +77,9 @@ export declare function resolveMcpDirectToolResolution(mcpDirectTools: string[]
76
77
  export declare function formatUnresolvedBuiltinMcpSelectors(agentName: string | undefined, selectors: readonly string[]): string;
77
78
  /**
78
79
  * Selected servers that only an extension registered, which a child without ambient extensions
79
- * never has. A server of the same name in an `mcp.json` the child reads takes precedence; like Pi,
80
- * the project file is read only when the project is trusted.
80
+ * never has unless the registering extension is one the child loads (`loadedByChild`). A server of
81
+ * the same name in an `mcp.json` the child reads takes precedence; like Pi, the project file is read
82
+ * only when the project is trusted.
81
83
  */
82
- export declare function extensionOnlyMcpServers(selections: readonly ResolvedMcpDirectToolSelection[], host: McpRuntimeSnapshotHost, cwd: string, projectTrusted: boolean): string[];
84
+ export declare function extensionOnlyMcpServers(selections: readonly ResolvedMcpDirectToolSelection[], host: McpRuntimeSnapshotHost, cwd: string, projectTrusted: boolean, loadedByChild: (extensionPath: string) => boolean): string[];
83
85
  export declare function computeMcpServerHash(definition: ServerEntry): string;
@@ -118,11 +118,12 @@ export function formatUnresolvedBuiltinMcpSelectors(agentName, selectors) {
118
118
  }
119
119
  /**
120
120
  * Selected servers that only an extension registered, which a child without ambient extensions
121
- * never has. A server of the same name in an `mcp.json` the child reads takes precedence; like Pi,
122
- * the project file is read only when the project is trusted.
121
+ * never has unless the registering extension is one the child loads (`loadedByChild`). A server of
122
+ * the same name in an `mcp.json` the child reads takes precedence; like Pi, the project file is read
123
+ * only when the project is trusted.
123
124
  */
124
- export function extensionOnlyMcpServers(selections, host, cwd, projectTrusted) {
125
- const registered = new Set(host.getMcpServers?.().map(({ name }) => name));
125
+ export function extensionOnlyMcpServers(selections, host, cwd, projectTrusted, loadedByChild) {
126
+ const registered = new Set(host.getMcpServers?.().filter(({ extensionPath }) => !loadedByChild(extensionPath)).map(({ name }) => name));
126
127
  const servers = [...new Set(selections.map(({ selector }) => selector.split("/")[0]))].filter((server) => registered.has(server));
127
128
  if (servers.length === 0)
128
129
  return [];
@@ -0,0 +1,9 @@
1
+ export declare function installCompactionInterruptionCapture(sessionClass: {
2
+ prototype: object;
3
+ }): void;
4
+ /** A manual compaction of this session is in progress, until compact() returns. */
5
+ export declare function compactionInProgress(sessionManager: object): boolean;
6
+ /** A manual compaction of this session that aborted an active run is in progress. */
7
+ export declare function compactionInterruptedRun(sessionManager: object): boolean;
8
+ /** True once, for the aborted end of the run the compaction interrupted; a later run's abort is the user's. */
9
+ export declare function takeCompactionAbort(sessionManager: object): boolean;
@@ -0,0 +1,47 @@
1
+ // Pi's manual compaction (/compact, RPC, ctx.compact()) aborts the active run before any hook runs, and its
2
+ // events do not say whether it interrupted one. Record that in AgentSession.compact, their shared entry point.
3
+ const stateSymbol = Symbol.for("pi-subagents.compaction-interruption.v1");
4
+ const wrappedSymbol = Symbol.for("pi-subagents.compaction-interruption.v1.wrapped");
5
+ // Shared with the wrapper an earlier extension instance installed before a reload.
6
+ const globalStore = globalThis;
7
+ const compactions = globalStore[stateSymbol] ??= new WeakMap();
8
+ export function installCompactionInterruptionCapture(sessionClass) {
9
+ const prototype = sessionClass.prototype;
10
+ const original = prototype.compact;
11
+ if (original[wrappedSymbol])
12
+ return;
13
+ const compact = async function (...args) {
14
+ const manager = this.sessionManager;
15
+ const compaction = compactions.get(manager) ?? { calls: 0, interrupted: false, abortPending: false };
16
+ compactions.set(manager, compaction);
17
+ compaction.calls += 1;
18
+ // Overlapping calls share the record: a later idle call must not erase an earlier interruption.
19
+ if (this.isStreaming)
20
+ compaction.interrupted = compaction.abortPending = true;
21
+ try {
22
+ return await original.apply(this, args);
23
+ }
24
+ finally {
25
+ if (--compaction.calls === 0)
26
+ compactions.delete(manager);
27
+ }
28
+ };
29
+ compact[wrappedSymbol] = true;
30
+ prototype.compact = compact;
31
+ }
32
+ /** A manual compaction of this session is in progress, until compact() returns. */
33
+ export function compactionInProgress(sessionManager) {
34
+ return compactions.has(sessionManager);
35
+ }
36
+ /** A manual compaction of this session that aborted an active run is in progress. */
37
+ export function compactionInterruptedRun(sessionManager) {
38
+ return compactions.get(sessionManager)?.interrupted === true;
39
+ }
40
+ /** True once, for the aborted end of the run the compaction interrupted; a later run's abort is the user's. */
41
+ export function takeCompactionAbort(sessionManager) {
42
+ const compaction = compactions.get(sessionManager);
43
+ if (!compaction?.abortPending)
44
+ return false;
45
+ compaction.abortPending = false;
46
+ return true;
47
+ }
@@ -10,6 +10,7 @@ export interface ParentWake {
10
10
  * Returns true when the message was only appended (held, or another wake is already starting
11
11
  * the run): Pi emits no extension message_start for it.
12
12
  * After userAborted() and until the next run starts, a turn-triggering message is only appended.
13
+ * So it is during a manual compaction, which Pi does not guard against a new run; takeDeferredWake() reports it.
13
14
  */
14
15
  sendMessage(...args: Parameters<ExtensionAPI["sendMessage"]>): boolean;
15
16
  /** True from an idle wake until its run starts or the session shuts down. Past the deadline it holds only while the parent is busy, which may still be the wake's preflight (for example compacting). */
@@ -18,9 +19,9 @@ export interface ParentWake {
18
19
  agentStarted(): void;
19
20
  /** The user stopped the parent run: hold wakes until the next run starts. */
20
21
  userAborted(): void;
21
- /** A deliberate resume (manual compaction) drops the hold without touching the shared wake reservation. */
22
- releaseHold(): void;
23
22
  isHeld(): boolean;
23
+ /** True once if a wake was only appended because a manual compaction was in progress. */
24
+ takeDeferredWake(): boolean;
24
25
  sessionShutdown(reason: string | undefined): void;
25
26
  }
26
27
  export declare function createParentWake(pi: Pick<ExtensionAPI, "sendMessage">, now?: () => number): ParentWake;
@@ -1,3 +1,4 @@
1
+ import { compactionInProgress } from "./compaction-interruption.js";
1
2
  /** Ends a waking notice that reports results. */
2
3
  export const COMPLETION_ACTION = "Read the saved results above and resume the already-authorized parent task, or report completion. If approval is required, explicitly ask the user. Do not silently yield, rerun completed work, or infer new authorization.";
3
4
  /** Ends a waking notice that reports a problem or a run state rather than results. */
@@ -14,6 +15,7 @@ export function createParentWake(pi, now = Date.now) {
14
15
  // Captured at bind: Pi's ctx throws once stale, which it can be by session_shutdown.
15
16
  let session;
16
17
  let held = false;
18
+ let deferred = false;
17
19
  // Look the reservation up on every access: another extension may have created this session's entry.
18
20
  const reservation = () => {
19
21
  // Pi can shut an extension down before session_start binds it; an unbound wake reserved nothing.
@@ -42,6 +44,11 @@ export function createParentWake(pi, now = Date.now) {
42
44
  pi.sendMessage(message, { triggerTurn: false });
43
45
  return true;
44
46
  }
47
+ if (session && compactionInProgress(session.manager)) {
48
+ deferred = true;
49
+ pi.sendMessage(message, { triggerTurn: false });
50
+ return true;
51
+ }
45
52
  if (ctx.isIdle())
46
53
  reservation().sentAt = now();
47
54
  pi.sendMessage(message, options);
@@ -51,15 +58,19 @@ export function createParentWake(pi, now = Date.now) {
51
58
  bindSession(context) {
52
59
  ctx = context;
53
60
  session = { manager: context.sessionManager, id: context.sessionManager.getSessionId() };
54
- held = false;
61
+ held = deferred = false;
55
62
  },
56
63
  agentStarted() {
57
64
  reservation().sentAt = undefined;
58
- held = false;
65
+ held = deferred = false;
59
66
  },
60
67
  userAborted: () => { held = true; },
61
- releaseHold: () => { held = false; },
62
68
  isHeld: () => held,
69
+ takeDeferredWake() {
70
+ const wasDeferred = deferred;
71
+ deferred = false;
72
+ return wasDeferred;
73
+ },
63
74
  sessionShutdown(reason) {
64
75
  if (reason !== "reload")
65
76
  reservation().sentAt = undefined;
@@ -28,6 +28,8 @@ export declare function assertRequiredChildExtensionsAdmitted(snapshots: Readonl
28
28
  runnerType?: string;
29
29
  machine?: string;
30
30
  }): void;
31
+ /** Maps a path to the identity of the required extension file it names, or undefined. A required path that can't be stat'ed matches only its own spelling. */
32
+ export declare function createRequiredChildExtensionIdentity(requiredPaths: Iterable<string>): (extensionPath: string) => string | undefined;
31
33
  export declare function hasMandatoryRequiredChildExtensions(snapshot: RequiredChildExtensionSnapshot | undefined): snapshot is RequiredChildExtensionSnapshot;
32
34
  /** Persist a run's mandatory snapshot so append-step admits against it; writes nothing without a mandatory entry. */
33
35
  export declare function writeRetainedRequiredChildExtensions(asyncDir: string, snapshot: RequiredChildExtensionSnapshot): void;
@@ -87,6 +87,33 @@ export function assertRequiredChildExtensionsAdmitted(snapshots, launch) {
87
87
  if (route)
88
88
  throw new Error(`Agent '${launch.agent}' cannot run on ${route}: the host requires child extensions (${ids.join(", ")}) for every runner, and only local native Pi children load them.`);
89
89
  }
90
+ function childExtensionFileIdentity(extensionPath) {
91
+ if (!path.isAbsolute(extensionPath))
92
+ return undefined;
93
+ try {
94
+ const stat = fs.statSync(extensionPath, { bigint: true });
95
+ return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;
96
+ }
97
+ catch {
98
+ return undefined;
99
+ }
100
+ }
101
+ /** Maps a path to the identity of the required extension file it names, or undefined. A required path that can't be stat'ed matches only its own spelling. */
102
+ export function createRequiredChildExtensionIdentity(requiredPaths) {
103
+ const aliases = new Map([...requiredPaths].map((extensionPath) => [extensionPath, childExtensionFileIdentity(extensionPath) ?? extensionPath]));
104
+ const identities = new Set(aliases.values());
105
+ return (extensionPath) => {
106
+ const known = aliases.get(extensionPath);
107
+ if (known !== undefined)
108
+ return known;
109
+ const identity = childExtensionFileIdentity(extensionPath);
110
+ if (identity === undefined || !identities.has(identity))
111
+ return undefined;
112
+ // Retain the alias even if the extension removes its file before reporting a failure.
113
+ aliases.set(extensionPath, identity);
114
+ return identity;
115
+ };
116
+ }
90
117
  export function hasMandatoryRequiredChildExtensions(snapshot) {
91
118
  return snapshot?.some((entry) => entry.requireForAllRunners) === true;
92
119
  }
@@ -1,5 +1,5 @@
1
1
  import { type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { type Component, type MarkdownTheme, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
2
+ import { type Component, type Focusable, type MarkdownTheme, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
3
3
  import { type ExternalRun } from "../api/external-runs.ts";
4
4
  import { type FleetKeybindingAction, type FleetKeybindingsConfig, type ForegroundChildControl, type ForegroundResumeChild, type ForegroundResumeRun, type ForegroundRunControl, type SubagentState } from "../shared/types.ts";
5
5
  import { type AsyncRunSummary } from "../runs/background/async-status.ts";
@@ -14,6 +14,7 @@ type FleetTui = {
14
14
  rows: number;
15
15
  };
16
16
  requestRender(): void;
17
+ getFocusedComponent?(): Component | null;
17
18
  };
18
19
  type AsyncStep = AsyncRunSummary["steps"][number];
19
20
  export type FleetItem = ({
@@ -108,7 +109,7 @@ export declare function collectFleetSnapshot(state: SubagentState, options?: {
108
109
  resultsDir?: string;
109
110
  limit?: number;
110
111
  }): FleetSnapshot;
111
- export declare class SubagentFleetComponent implements Component {
112
+ export declare class SubagentFleetComponent implements Component, Focusable {
112
113
  private snapshot;
113
114
  private selected;
114
115
  private selectedKey;
@@ -125,6 +126,8 @@ export declare class SubagentFleetComponent implements Component {
125
126
  private actionBusy;
126
127
  private transcriptCache;
127
128
  private disposed;
129
+ private hasFocus;
130
+ private readonly openedOver;
128
131
  private refreshTimer;
129
132
  private readonly refreshMs;
130
133
  private readonly tui;
@@ -154,6 +157,8 @@ export declare class SubagentFleetComponent implements Component {
154
157
  private setActionNotice;
155
158
  private runAction;
156
159
  private scrollDetail;
160
+ get focused(): boolean;
161
+ set focused(value: boolean);
157
162
  handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined;
158
163
  handleInput(data: string): void;
159
164
  private rosterLines;