@xzzpig/pi-subagents 0.2.0 → 0.4.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 (103) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +2 -0
  3. package/agents/oracle.md +7 -5
  4. package/agents/researcher.md +1 -1
  5. package/agents/reviewer.md +2 -2
  6. package/agents/scout.md +1 -1
  7. package/agents/worker.md +1 -1
  8. package/docs/agents.md +3 -0
  9. package/docs/configuration.md +121 -10
  10. package/docs/extension-api.md +36 -0
  11. package/docs/missions.md +5 -3
  12. package/docs/observability.md +43 -3
  13. package/docs/tool-reference.md +20 -3
  14. package/docs/workflows.md +2 -2
  15. package/package.json +4 -4
  16. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  17. package/skills/pi-subagents/references/execution-controls.md +5 -4
  18. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  19. package/skills/pi-subagents/references/prompting-and-roles.md +31 -15
  20. package/src/agents/agent-serializer.ts +2 -0
  21. package/src/agents/agents.ts +46 -15
  22. package/src/api/external-runs.ts +174 -84
  23. package/src/api/preflight.ts +13 -7
  24. package/src/extension/config.ts +59 -0
  25. package/src/extension/doctor.ts +40 -0
  26. package/src/extension/index.ts +83 -9
  27. package/src/extension/public-execution.ts +37 -4
  28. package/src/extension/rpc.ts +8 -10
  29. package/src/extension/schemas.ts +12 -10
  30. package/src/extension/tool-description.ts +13 -9
  31. package/src/inspectors/herdr/actions.ts +13 -8
  32. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  33. package/src/inspectors/herdr/project-panes.ts +2 -6
  34. package/src/inspectors/herdr/shell-command.ts +16 -0
  35. package/src/intercom/intercom-bridge.ts +9 -5
  36. package/src/intercom/native-supervisor-channel.ts +19 -42
  37. package/src/missions/goal-driver.ts +3 -1
  38. package/src/missions/lifecycle.ts +4 -7
  39. package/src/missions/store.ts +12 -7
  40. package/src/missions/workflow-state.ts +6 -2
  41. package/src/runs/background/active-async-capacity.ts +431 -0
  42. package/src/runs/background/active-run-index.ts +77 -3
  43. package/src/runs/background/async-execution.ts +190 -72
  44. package/src/runs/background/async-job-tracker.ts +5 -0
  45. package/src/runs/background/async-resume.ts +21 -7
  46. package/src/runs/background/async-status-snapshot.ts +277 -0
  47. package/src/runs/background/async-status.ts +17 -6
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/chain-root-attachment.ts +2 -2
  50. package/src/runs/background/completion-replay.ts +11 -1
  51. package/src/runs/background/fleet-view.ts +21 -6
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-files.ts +437 -0
  55. package/src/runs/background/result-watcher.ts +188 -41
  56. package/src/runs/background/resume-guidance.ts +27 -7
  57. package/src/runs/background/retained-children.ts +75 -18
  58. package/src/runs/background/run-id-resolver.ts +30 -24
  59. package/src/runs/background/run-status.ts +106 -5
  60. package/src/runs/background/scheduled-runs.ts +54 -28
  61. package/src/runs/background/stale-run-reconciler.ts +30 -16
  62. package/src/runs/background/subagent-runner.ts +352 -62
  63. package/src/runs/background/subagent-wait.ts +2 -0
  64. package/src/runs/background/wait-completions.ts +5 -2
  65. package/src/runs/foreground/async-dismiss-action.ts +2 -1
  66. package/src/runs/foreground/chain-execution.ts +53 -2
  67. package/src/runs/foreground/execution.ts +309 -34
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/prompt-audit.ts +172 -0
  70. package/src/runs/foreground/subagent-executor.ts +936 -224
  71. package/src/runs/shared/acceptance.ts +13 -4
  72. package/src/runs/shared/completion-guard.ts +107 -1
  73. package/src/runs/shared/external-cli-runner.ts +4 -0
  74. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  75. package/src/runs/shared/model-fallback.ts +16 -2
  76. package/src/runs/shared/nested-events.ts +66 -62
  77. package/src/runs/shared/orca-progress-tabs.ts +375 -0
  78. package/src/runs/shared/parallel-utils.ts +4 -0
  79. package/src/runs/shared/pi-args.ts +44 -1
  80. package/src/runs/shared/run-fanout-budget.ts +280 -0
  81. package/src/runs/shared/single-output.ts +4 -2
  82. package/src/runs/shared/subagent-control.ts +15 -0
  83. package/src/runs/shared/subagent-prompt-runtime.ts +1 -9
  84. package/src/runs/shared/subagent-startup-retry.ts +12 -0
  85. package/src/runs/shared/task-intent.ts +19 -3
  86. package/src/runs/shared/tool-timeout.ts +93 -0
  87. package/src/runs/shared/worktree.ts +17 -5
  88. package/src/shared/agent-stream-options.ts +5 -0
  89. package/src/shared/artifacts.ts +2 -6
  90. package/src/shared/display-text.ts +50 -0
  91. package/src/shared/node-executable.ts +21 -0
  92. package/src/shared/types.ts +143 -5
  93. package/src/shared/utils.ts +3 -1
  94. package/src/slash/slash-commands.ts +34 -25
  95. package/src/slash/slash-live-state.ts +3 -0
  96. package/src/tui/fleet-status.ts +164 -47
  97. package/src/tui/fleet-transcript.ts +1 -48
  98. package/src/tui/fleet.ts +352 -27
  99. package/src/tui/render.ts +122 -44
  100. package/src/watchdog/permission-arbiter.ts +2 -1
  101. package/src/watchdog/review.ts +4 -3
  102. package/src/workflows/chat-progress.ts +10 -2
  103. package/src/workflows/scripted-workflow.ts +292 -79
@@ -98,3 +98,53 @@ export function previewDisplayText(value: string, maxLength: number): string {
98
98
  if (maxLength <= 3) return truncateDisplayText(normalized, maxLength);
99
99
  return `${truncateDisplayText(normalized, maxLength - 3)}...`;
100
100
  }
101
+
102
+ const BINARY_CONTENT_PLACEHOLDER = "[binary content omitted for safe display]";
103
+
104
+ function isUnsafeTerminalCodePoint(codePoint: number): boolean {
105
+ const terminalControl = (codePoint <= 0x1f && codePoint !== 0x09 && codePoint !== 0x0a)
106
+ || (codePoint >= 0x7f && codePoint <= 0x9f);
107
+ const bidiControl = codePoint === 0x061c
108
+ || codePoint === 0x200e
109
+ || codePoint === 0x200f
110
+ || (codePoint >= 0x202a && codePoint <= 0x202e)
111
+ || (codePoint >= 0x2066 && codePoint <= 0x2069);
112
+ const privateUse = (codePoint >= 0xe000 && codePoint <= 0xf8ff)
113
+ || (codePoint >= 0xf0000 && codePoint <= 0xffffd)
114
+ || (codePoint >= 0x100000 && codePoint <= 0x10fffd);
115
+ const invalidScalar = codePoint >= 0xd800 && codePoint <= 0xdfff;
116
+ const nonCharacter = (codePoint >= 0xfdd0 && codePoint <= 0xfdef)
117
+ || (codePoint & 0xffff) === 0xfffe
118
+ || (codePoint & 0xffff) === 0xffff;
119
+ return terminalControl || bidiControl || privateUse || invalidScalar || nonCharacter;
120
+ }
121
+
122
+ function looksLikeBinaryContent(text: string): boolean {
123
+ if (text.includes("\0")) return true;
124
+ let suspiciousControls = 0;
125
+ let replacementCharacters = 0;
126
+ let codePoints = 0;
127
+ for (const character of text) {
128
+ codePoints++;
129
+ const codePoint = character.codePointAt(0) ?? 0;
130
+ if ((codePoint <= 0x08) || (codePoint >= 0x0e && codePoint <= 0x1f)) suspiciousControls++;
131
+ if (codePoint === 0xfffd) replacementCharacters++;
132
+ }
133
+ if (codePoints === 0) return false;
134
+ return (suspiciousControls >= 4 && suspiciousControls / codePoints >= 0.1)
135
+ || (replacementCharacters >= 3 && replacementCharacters / codePoints >= 0.1);
136
+ }
137
+
138
+ /** Escapes untrusted text before rendering it in a terminal while preserving safe newlines and tabs. */
139
+ export function safeTerminalText(value: string): string {
140
+ const normalized = value.replace(/\r\n/g, "\n");
141
+ if (looksLikeBinaryContent(normalized)) return BINARY_CONTENT_PLACEHOLDER;
142
+ let safe = "";
143
+ for (const character of normalized) {
144
+ const codePoint = character.codePointAt(0) ?? 0;
145
+ safe += isUnsafeTerminalCodePoint(codePoint)
146
+ ? `[U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}]`
147
+ : character;
148
+ }
149
+ return safe;
150
+ }
@@ -0,0 +1,21 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+
4
+ function isNodeExecutableName(execPath: string): boolean {
5
+ const basename = path.basename(execPath).toLowerCase();
6
+ return basename === "node" || basename === "node.exe" || basename === "nodejs" || basename === "nodejs.exe";
7
+ }
8
+
9
+ function canUseNodeExecutable(execPath: string): boolean {
10
+ try {
11
+ fs.accessSync(execPath, process.platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ export function resolveNodeExecutable(execPath = process.execPath): string {
19
+ if (isNodeExecutableName(execPath) && canUseNodeExecutable(execPath)) return execPath;
20
+ return process.platform === "win32" ? "node.exe" : "node";
21
+ }
@@ -215,7 +215,7 @@ export interface ControlEvent {
215
215
  nestedRunId?: string;
216
216
  nestingPath?: NestedRunAddress["path"];
217
217
  message: string;
218
- reason?: "idle" | "completion_guard" | "active_long_running" | "tool_failures" | "supervisor_request" | "time_threshold" | "turn_threshold" | "token_threshold";
218
+ reason?: "idle" | "completion_guard" | "active_long_running" | "tool_failures" | "supervisor_request" | "time_threshold" | "turn_threshold" | "token_threshold" | "tool_open_threshold";
219
219
  turns?: number;
220
220
  tokens?: number;
221
221
  toolCount?: number;
@@ -328,6 +328,7 @@ export interface FileMutationEffect {
328
328
  expected: boolean;
329
329
  attempted: boolean;
330
330
  message?: string;
331
+ resolvedBy?: "llm-intent-arbiter";
331
332
  }
332
333
 
333
334
  export interface EffectsProjection {
@@ -343,6 +344,7 @@ export type ProcessTerminalReason =
343
344
  | "runner-candidate-missing"
344
345
  | "runner-instance-mismatch"
345
346
  | "writer-close-unverified"
347
+ | "process-tree-unverified"
346
348
  | "canonical-session-unavailable"
347
349
  | "canonical-session-lease-active"
348
350
  | "canonical-session-release-unverified"
@@ -357,6 +359,19 @@ export interface RunnerProcessInstanceExitV1 {
357
359
  signal: string | null;
358
360
  }
359
361
 
362
+ export type ProcessTreeTerminalV1 =
363
+ | {
364
+ state: "observed";
365
+ mechanism: "posix-process-group";
366
+ processGroupId: number;
367
+ verifiedAt: number;
368
+ }
369
+ | {
370
+ state: "unknown";
371
+ reason: "unsupported-platform" | "signal-failed" | "verification-failed";
372
+ diagnostic?: string;
373
+ };
374
+
360
375
  export interface PiWriterProcessInstanceExitV1 {
361
376
  processInstanceId: string;
362
377
  kind: "pi-writer";
@@ -364,6 +379,7 @@ export interface PiWriterProcessInstanceExitV1 {
364
379
  closeObservedAt: number;
365
380
  exitCode: number | null;
366
381
  signal: string | null;
382
+ processTree: ProcessTreeTerminalV1;
367
383
  }
368
384
 
369
385
  export type ProcessInstanceExitV1 = RunnerProcessInstanceExitV1 | PiWriterProcessInstanceExitV1;
@@ -462,9 +478,30 @@ export interface SteeringNotice {
462
478
  currentSessionId?: string;
463
479
  }
464
480
 
481
+ export interface RunFanoutBudgetDescriptor {
482
+ version: 1;
483
+ rootRunId: string;
484
+ directory: string;
485
+ limit: number;
486
+ parentPath?: string;
487
+ }
488
+
489
+ export interface RunFanoutBudgetSnapshot {
490
+ used: number;
491
+ limit: number;
492
+ remaining: number;
493
+ }
494
+
495
+ export interface RunFanoutRejection extends RunFanoutBudgetSnapshot {
496
+ code: "RUN_FANOUT_LIMIT";
497
+ path: string;
498
+ requested: number;
499
+ }
500
+
465
501
  export interface SteeringRecoveryDescriptor {
466
502
  version: 1;
467
503
  launchContractDigest?: string;
504
+ runFanoutBudget: RunFanoutBudgetDescriptor;
468
505
  sourceRunId: string;
469
506
  agentContract?: AgentContract;
470
507
  agent: string;
@@ -491,6 +528,8 @@ export interface SteeringRecoveryDescriptor {
491
528
  structuredOutputSchema?: JsonSchemaObject;
492
529
  acceptance?: AcceptanceInput;
493
530
  controlConfig?: ResolvedControlConfig;
531
+ /** Raw per-run bridge override. Omitted descriptors continue to use global config. */
532
+ intercomBridge?: IntercomBridgeConfig;
494
533
  absoluteDeadlineAt?: number;
495
534
  initialTurnBudget?: ResolvedTurnBudget;
496
535
  initialToolBudget?: ResolvedToolBudget;
@@ -992,6 +1031,7 @@ export interface Details {
992
1031
  controlEvents?: ControlEvent[];
993
1032
  steering?: SteerActionResult;
994
1033
  asyncId?: string;
1034
+ background?: boolean;
995
1035
  asyncDir?: string;
996
1036
  timeoutMs?: number;
997
1037
  deadlineAt?: number;
@@ -1024,6 +1064,9 @@ export interface Details {
1024
1064
  // Aggregated cost across all agents in the run
1025
1065
  totalCost?: CostSummary;
1026
1066
  spawnBudget?: SpawnBudgetSnapshot;
1067
+ runFanoutBudget?: RunFanoutBudgetSnapshot;
1068
+ runFanoutRejection?: RunFanoutRejection;
1069
+ activeAsyncCapacity?: ActiveAsyncCapacitySnapshot;
1027
1070
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1028
1071
  capabilityAudit?: SubagentCapabilityAudit;
1029
1072
  parallelHandoff?: ParallelHandoffReference;
@@ -1046,7 +1089,7 @@ export interface Details {
1046
1089
  trace: Array<{
1047
1090
  operation: "run" | "status";
1048
1091
  key: string;
1049
- state: "started" | "completed" | "failed" | "reused";
1092
+ state: "started" | "completed" | "failed" | "detached" | "stopped" | "reused";
1050
1093
  agent?: string;
1051
1094
  runId?: string;
1052
1095
  phase?: string;
@@ -1219,6 +1262,8 @@ export interface AsyncStartedEvent {
1219
1262
  asyncDir?: string;
1220
1263
  /** Parent-resolved launch directory, used as a trusted artifact root while this session is live. */
1221
1264
  cwd?: string;
1265
+ /** Parent-resolved child session root, used only while this session owns the live run. */
1266
+ sessionRoot?: string;
1222
1267
  pid?: number;
1223
1268
  sessionId?: string;
1224
1269
  mode?: SubagentRunMode;
@@ -1323,6 +1368,8 @@ export interface AsyncStatus {
1323
1368
  workflowGraph?: WorkflowGraphSnapshot;
1324
1369
  checkpoint?: ChainCheckpointState;
1325
1370
  processTerminal?: ProcessTerminalV1;
1371
+ runFanoutBudget?: RunFanoutBudgetSnapshot;
1372
+ runFanoutBudgetDescriptor?: RunFanoutBudgetDescriptor;
1326
1373
  launchContractDigest?: string;
1327
1374
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
1328
1375
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
@@ -1342,6 +1389,10 @@ export interface AsyncStatus {
1342
1389
  phase?: string;
1343
1390
  label?: string;
1344
1391
  workflowKey?: string;
1392
+ /** Child run identity for workflow capacity reconciliation. */
1393
+ runId?: string;
1394
+ /** True only when this workflow child owns a detached async runner. */
1395
+ async?: boolean;
1345
1396
  parentWorkflowRunId?: string;
1346
1397
  outputName?: string;
1347
1398
  structured?: boolean;
@@ -1414,8 +1465,12 @@ export type AsyncJobStep = NonNullable<AsyncStatus["steps"]>[number] & {
1414
1465
  export interface AsyncJobState {
1415
1466
  asyncId: string;
1416
1467
  asyncDir: string;
1468
+ /** Host tool-call id retained when it differs from the internal run id. */
1469
+ toolCallId?: string;
1417
1470
  /** Parent-resolved launch directory retained for trusted live artifact lookup. */
1418
1471
  cwd?: string;
1472
+ /** Parent-resolved child session root retained for trusted live transcript lookup. */
1473
+ sessionRoot?: string;
1419
1474
  status: "queued" | "running" | "complete" | "failed" | "paused" | "stopped" | "rejected";
1420
1475
  /** Short caller-facing task/goal shown in fleet surfaces when available. */
1421
1476
  description?: string;
@@ -1574,6 +1629,12 @@ export interface ForegroundRunControl {
1574
1629
  toolCount?: number;
1575
1630
  /** Independently tracked children for foreground parallel work and fleet inspection. */
1576
1631
  activeChildren?: Map<number, ForegroundChildControl>;
1632
+ /** Live Prompt Audit redo callback. It is current-session memory only. */
1633
+ promptAuditRedo?: (index: number, guidance: string) => Promise<{ text: string; isError?: boolean }>;
1634
+ /** Memory-only source run for Prompt Audit redo. */
1635
+ sourceRunId?: string;
1636
+ /** Memory-only replacement run started by Prompt Audit redo. */
1637
+ supersededByRunId?: string;
1577
1638
  /** Scheduling owners that may still launch another child. Removal is safe only at zero. */
1578
1639
  schedulingOwners?: number;
1579
1640
  nestedRoute?: NestedRouteInfo;
@@ -1593,6 +1654,12 @@ export interface WaitSubscriptionRecord {
1593
1654
  expiresAt: number;
1594
1655
  }
1595
1656
 
1657
+ export interface ActiveAsyncCapacitySnapshot {
1658
+ used: number;
1659
+ /** Zero means the opt-in cap is disabled. */
1660
+ limit: number;
1661
+ }
1662
+
1596
1663
  export interface SubagentState {
1597
1664
  baseCwd: string;
1598
1665
  currentSessionId: string | null;
@@ -1603,6 +1670,10 @@ export interface SubagentState {
1603
1670
  /** Runtime mission-store snapshot used by optional inspector context. */
1604
1671
  missionStoreConfig?: MissionStoreConfig;
1605
1672
  parentSessionFile?: string | null;
1673
+ /** Extension-owned roots trusted for child session transcript reads. */
1674
+ trustedSessionRoots?: string[];
1675
+ /** Live async session roots created by this parent executor, keyed by run id. */
1676
+ liveAsyncSessionRoots?: Map<string, string>;
1606
1677
  /** Last valid parent session model observed for this session; used when continuation contexts omit ctx.model. */
1607
1678
  lastParentModel?: { provider: string; id: string };
1608
1679
  subagentInProgress?: boolean;
@@ -1613,6 +1684,8 @@ export interface SubagentState {
1613
1684
  granted?: number;
1614
1685
  grantHistory?: SpawnBudgetGrant[];
1615
1686
  };
1687
+ /** Current-session top-level async capacity projection. */
1688
+ activeAsyncCapacity?: ActiveAsyncCapacitySnapshot;
1616
1689
  asyncJobs: Map<string, AsyncJobState>;
1617
1690
  /** Current-session active and recent async runs for the native fleet inspector. */
1618
1691
  fleetJobs?: Map<string, AsyncJobState>;
@@ -1697,6 +1770,10 @@ export interface RunSyncOptions {
1697
1770
  interruptSignal?: AbortSignal;
1698
1771
  timeoutMs?: number;
1699
1772
  deadlineAt?: number;
1773
+ /** Per-call per-tool timeout (ms), resolved with the agent/config/environment ladder at execution. */
1774
+ toolTimeoutMs?: number;
1775
+ /** Raw global config.toolTimeoutMs, used by the per-child resolver. */
1776
+ configToolTimeoutMs?: number;
1700
1777
  turnBudget?: ResolvedTurnBudget;
1701
1778
  usageBudget?: UsageBudgetConfig;
1702
1779
  /** Enforce maxTurns + graceTurns as a hard model-turn boundary. */
@@ -1730,9 +1807,12 @@ export interface RunSyncOptions {
1730
1807
  /** Effective parent wait-tool setting propagated to the child runtime. */
1731
1808
  waitToolEnabled?: boolean;
1732
1809
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1810
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
1733
1811
  nestedRoute?: NestedRouteInfo;
1734
1812
  /** Override the agent's default model (format: "provider/id" or just "id") */
1735
1813
  modelOverride?: string;
1814
+ /** LLM intent arbiter for the completion mutation guard (rescues read-only review runs). */
1815
+ llmIntentArbiter?: import("../runs/shared/llm-intent-arbiter.ts").TaskMutationArbiter;
1736
1816
  /** Override the agent's default thinking level for this run */
1737
1817
  thinkingOverride?: AgentConfig["thinking"];
1738
1818
  /** Registry models available for heuristic bare-model resolution */
@@ -1756,6 +1836,10 @@ export interface RunSyncOptions {
1756
1836
  dynamic?: boolean;
1757
1837
  dynamicGroup?: boolean;
1758
1838
  };
1839
+ /** Private live callback for the exact child prompt after runtime acceptance injection. */
1840
+ onEffectivePrompt?: (prompt: string) => void;
1841
+ /** Internal lifecycle hook for the observer shared across retries of one logical child. */
1842
+ onOrcaProgressTabCreated?: (tab: import("../runs/shared/orca-progress-tabs.ts").OrcaProgressTab) => void;
1759
1843
  }
1760
1844
 
1761
1845
  export type IntercomBridgeMode = "off" | "fork-only" | "always";
@@ -1817,8 +1901,22 @@ export const FLEET_KEYBINDING_ACTIONS = [
1817
1901
  export type FleetKeybindingAction = typeof FLEET_KEYBINDING_ACTIONS[number];
1818
1902
  export type FleetKeybindingsConfig = Partial<Record<FleetKeybindingAction, string[]>>;
1819
1903
 
1904
+ export interface OrcaProgressTabsConfig {
1905
+ /** Create one Orca terminal tab per running subagent. Experimental and opt-in. */
1906
+ enabled?: boolean;
1907
+ }
1908
+
1909
+ export interface MainWindowRendererConfig {
1910
+ /** Unit of horizontal space in main chat subagent call/result rows. Omit to preserve current spacing. Set 0 for no extra padding. */
1911
+ horizontalSpacing?: number;
1912
+ /** Maximum collapsed rich-result rows. Expanded output is not capped. */
1913
+ compactResultMaxLines?: number;
1914
+ }
1915
+
1820
1916
  export interface ExtensionConfig {
1821
1917
  asyncByDefault?: boolean;
1918
+ /** Optional shortcut that detaches the active foreground single-subagent run. */
1919
+ foregroundDetachShortcut?: string;
1822
1920
  /** Show the Claude Code-style navigable fleet. Defaults to true. */
1823
1921
  fleetView?: boolean;
1824
1922
  /** Place the persistent FleetView above or below the editor. Defaults to belowEditor. */
@@ -1833,6 +1931,10 @@ export interface ExtensionConfig {
1833
1931
  legacyChainControls?: boolean;
1834
1932
  /** Inline chat rendering for the subagent tool. Defaults to rich. */
1835
1933
  inlineToolDisplay?: InlineToolDisplay;
1934
+ /** Density controls for the main chat subagent call/result renderer. */
1935
+ mainWindowRenderer?: MainWindowRendererConfig;
1936
+ /** Experimental observer: mirror each native subagent's progress into a new Orca tab. */
1937
+ orcaProgressTabs?: OrcaProgressTabsConfig;
1836
1938
  forceTopLevelAsync?: boolean;
1837
1939
  waitTool?: WaitToolConfig;
1838
1940
  defaultSessionDir?: string;
@@ -1840,8 +1942,31 @@ export interface ExtensionConfig {
1840
1942
  maxSubagentDepth?: number;
1841
1943
  /** Optional cumulative session cap. Unset or 0 means unlimited. */
1842
1944
  maxSubagentSpawnsPerSession?: number;
1945
+ /** Cumulative logical-child cap for one top-level run tree. Defaults to 64. */
1946
+ maxSubagentSpawnsPerRun?: number;
1947
+ /** Optional active top-level async run cap per parent session. Unset or 0 means unlimited. */
1948
+ maxActiveAsyncRunsPerSession?: number;
1843
1949
  /** Global cap on simultaneously-running subagent tasks within a single run. Defaults to 20. */
1844
1950
  globalConcurrencyLimit?: number;
1951
+ /**
1952
+ * Global default runtime deadline in milliseconds. It replaces the built-in
1953
+ * 30-minute backstop for single, parallel, and chain launches (foreground, plus
1954
+ * plain single-agent async runs) when neither the call (`timeoutMs`/`maxRuntimeMs`)
1955
+ * nor the selected agent provides a timeout. Explicit call values and agent
1956
+ * frontmatter defaults still win. Composite async runs (chain/parallel/workflow)
1957
+ * stay unbounded at the top level by design — their children are bounded individually.
1958
+ * Must be a positive integer; invalid values are ignored.
1959
+ */
1960
+ timeoutMs?: number;
1961
+ /**
1962
+ * Optional hard per-tool-call timeout in milliseconds. Bounds a single
1963
+ * subagent tool call inside the child; the run-level timeout remains
1964
+ * authoritative. Known-fast built-in tools have a five-minute default when
1965
+ * this is undefined. Precedence: call param > agent frontmatter > this config >
1966
+ * PI_SUBAGENT_TOOL_TIMEOUT_MS. Must be a positive integer; invalid values
1967
+ * are rejected with an error.
1968
+ */
1969
+ toolTimeoutMs?: number;
1845
1970
  control?: ControlConfig;
1846
1971
  completionBatch?: CompletionBatchConfig;
1847
1972
  turnBudget?: TurnBudgetConfig;
@@ -1854,7 +1979,7 @@ export interface ExtensionConfig {
1854
1979
  worktreeSetupHook?: string;
1855
1980
  worktreeSetupHookTimeoutMs?: number;
1856
1981
  worktreeBaseDir?: string;
1857
- /** Where to store subagent artifact files. Defaults to "project" (cwd/.pi/subagents). Set to "session" for pi session dir, or "temp" for OS temp. */
1982
+ /** Where to store subagent artifact files. Defaults to "session" (the pi session directory, or OS temp when unavailable). Set to "project" for cwd/.pi/subagents. */
1858
1983
  artifactDir?: ArtifactDirPreference;
1859
1984
  /** Artifact cleanup retention. Set cleanupDays to 0 to disable cleanup. */
1860
1985
  artifactConfig?: Pick<ArtifactConfig, "cleanupDays">;
@@ -1878,7 +2003,7 @@ export const DEFAULT_MAX_OUTPUT: Required<MaxOutputConfig> = {
1878
2003
 
1879
2004
  export const DEFAULT_ARTIFACT_CONFIG: ArtifactConfig = {
1880
2005
  enabled: true,
1881
- dir: "project",
2006
+ dir: "session",
1882
2007
  includeInput: true,
1883
2008
  includeOutput: true,
1884
2009
  includeJsonl: false,
@@ -1965,7 +2090,7 @@ export const SLASH_SUBAGENT_CANCEL_EVENT = "subagent:slash:cancel";
1965
2090
  export const POLL_INTERVAL_MS = 250;
1966
2091
  export const MAX_WIDGET_JOBS = 4;
1967
2092
  export const DEFAULT_SUBAGENT_MAX_DEPTH = 2;
1968
- export const SUBAGENT_ACTIONS = ["list", "get", "models", "children.list", "guide", "create", "update", "delete", "eject", "disable", "enable", "reset", "mission.create", "mission.list", "mission.show", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "worktree.discard", "refine", "refine.show", "refine.rollback", "inspector.open", "inspector.status", "inspector.close", "project.open", "project.status", "project.close", "status", "grant-spawn-budget", "interrupt", "resume", "steer", "stop", "dismiss", "append-step", "approve-checkpoint", "reject-checkpoint", "doctor", "watchdog.status", "watchdog.check", "watchdog.configure", "watchdog.recommend-model", "schedule.create", "schedule.list", "schedule.show", "schedule.history", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"] as const;
2093
+ export const SUBAGENT_ACTIONS = ["list", "get", "models", "children.list", "guide", "create", "update", "delete", "eject", "disable", "enable", "reset", "mission.create", "mission.list", "mission.show", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "worktree.discard", "refine", "refine.show", "refine.rollback", "inspector.open", "inspector.status", "inspector.close", "project.open", "project.status", "project.close", "status", "debug.run", "grant-spawn-budget", "interrupt", "resume", "steer", "stop", "dismiss", "append-step", "approve-checkpoint", "reject-checkpoint", "doctor", "watchdog.status", "watchdog.check", "watchdog.configure", "watchdog.recommend-model", "schedule.create", "schedule.list", "schedule.show", "schedule.history", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"] as const;
1969
2094
 
1970
2095
  export const DEFAULT_FORK_PREAMBLE =
1971
2096
  "You are a delegated subagent running from a fork of the parent session. " +
@@ -2057,6 +2182,19 @@ export function resolveMaxSubagentSpawnsPerSession(configMaxSpawns?: number): nu
2057
2182
  return configuredMaxSpawns === 0 ? undefined : configuredMaxSpawns;
2058
2183
  }
2059
2184
 
2185
+ export const DEFAULT_MAX_SUBAGENT_SPAWNS_PER_RUN = 64;
2186
+
2187
+ export function normalizeMaxSubagentSpawnsPerRun(value: unknown): number | undefined {
2188
+ const normalized = normalizeNonNegativeInteger(value);
2189
+ return normalized !== undefined && normalized > 0 ? normalized : undefined;
2190
+ }
2191
+
2192
+ export function resolveMaxSubagentSpawnsPerRun(configMaxSpawns?: number): number {
2193
+ return normalizeMaxSubagentSpawnsPerRun(process.env.PI_SUBAGENT_MAX_SPAWNS_PER_RUN)
2194
+ ?? normalizeMaxSubagentSpawnsPerRun(configMaxSpawns)
2195
+ ?? DEFAULT_MAX_SUBAGENT_SPAWNS_PER_RUN;
2196
+ }
2197
+
2060
2198
  // ============================================================================
2061
2199
  // Utility Functions
2062
2200
  // ============================================================================
@@ -17,6 +17,7 @@ import type { AgentProgress, AsyncStatus, Details, DisplayItem, ErrorInfo, Neste
17
17
  const DEFAULT_CONFIG_DIR_NAME = ".pi";
18
18
  const PI_CODING_AGENT_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
19
19
  export const PI_CODING_AGENT_PACKAGE_ROOT_ENV = "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT";
20
+ export const PROMPT_REDACTED = "[prompt redacted]";
20
21
 
21
22
  export function resolveWatchPath(
22
23
  watchPath: string,
@@ -354,7 +355,7 @@ function compactCompletedProgress(progress: AgentProgress): AgentProgress {
354
355
  agent: progress.agent,
355
356
  status: progress.status,
356
357
  activityState: progress.activityState,
357
- task: progress.task,
358
+ task: "[prompt redacted]",
358
359
  skills: progress.skills,
359
360
  toolCount: progress.toolCount,
360
361
  tokens: progress.tokens,
@@ -428,6 +429,7 @@ export function compactForegroundResult(result: SingleResult): SingleResult {
428
429
  const toolCalls = result.toolCalls?.length ? result.toolCalls : extractToolCallSummaries(result.messages);
429
430
  return {
430
431
  ...result,
432
+ task: "[prompt redacted]",
431
433
  messages: undefined,
432
434
  progress: undefined,
433
435
  toolCalls: toolCalls.length ? toolCalls : undefined,
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { keyText, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
- import { Key, matchesKey, truncateToWidth, type Component, type TUI } from "@earendil-works/pi-tui";
5
+ import { Key, matchesKey, truncateToWidth, type Component, type KeyId, type TUI } from "@earendil-works/pi-tui";
6
6
  import { BUILTIN_AGENT_NAMES, discoverAgents } from "../agents/agents.ts";
7
7
  import { resolveExistingReadPaths } from "../shared/settings.ts";
8
8
  import {
@@ -631,7 +631,7 @@ function slashRunWorkflowScript(key: string, child: Record<string, unknown>): st
631
631
  export function registerSlashCommands(
632
632
  pi: ExtensionAPI,
633
633
  state: SubagentState,
634
- options: { fleetKeybindings?: FleetKeybindingsConfig } = {},
634
+ options: { fleetKeybindings?: FleetKeybindingsConfig; foregroundDetachShortcut?: string } = {},
635
635
  ): void {
636
636
  let fleetOpen = false;
637
637
  const showFleet = async (ctx: ExtensionContext) => {
@@ -741,33 +741,42 @@ export function registerSlashCommands(
741
741
  handler: async (ctx) => showFleet(ctx),
742
742
  });
743
743
 
744
+ const detachForegroundRun = (args: string, ctx: ExtensionContext): void => {
745
+ const id = args.trim();
746
+ let control: ReturnType<typeof selectForegroundDetachControl>;
747
+ try {
748
+ control = selectForegroundDetachControl(state, id);
749
+ } catch (error) {
750
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
751
+ return;
752
+ }
753
+ if (!control) {
754
+ ctx.ui.notify(id ? `No active foreground run found for '${id}'.` : "No active foreground single-subagent run to detach.", "info");
755
+ return;
756
+ }
757
+ if (control.mode !== "single") {
758
+ ctx.ui.notify("/subagents-detach currently supports single-subagent runs only.", "error");
759
+ return;
760
+ }
761
+ if (!control.detach?.()) {
762
+ ctx.ui.notify(`Foreground run ${control.runId} is not currently detachable.`, "info");
763
+ return;
764
+ }
765
+ sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or subagent_wait({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
766
+ };
767
+
744
768
  pi.registerCommand("subagents-detach", {
745
769
  description: "Detach the active foreground single-subagent run without terminating it",
746
- handler: async (args, ctx) => {
747
- const id = args.trim();
748
- let control: ReturnType<typeof selectForegroundDetachControl>;
749
- try {
750
- control = selectForegroundDetachControl(state, id);
751
- } catch (error) {
752
- ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
753
- return;
754
- }
755
- if (!control) {
756
- ctx.ui.notify(id ? `No active foreground run found for '${id}'.` : "No active foreground single-subagent run to detach.", "info");
757
- return;
758
- }
759
- if (control.mode !== "single") {
760
- ctx.ui.notify("/subagents-detach currently supports single-subagent runs only.", "error");
761
- return;
762
- }
763
- if (!control.detach?.()) {
764
- ctx.ui.notify(`Foreground run ${control.runId} is not currently detachable.`, "info");
765
- return;
766
- }
767
- sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or subagent_wait({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
768
- },
770
+ handler: async (args, ctx) => detachForegroundRun(args, ctx),
769
771
  });
770
772
 
773
+ if (options.foregroundDetachShortcut) {
774
+ pi.registerShortcut(options.foregroundDetachShortcut as KeyId, {
775
+ description: "Detach the active foreground subagent and keep it running in the background",
776
+ handler: async (ctx) => detachForegroundRun("", ctx),
777
+ });
778
+ }
779
+
771
780
  pi.registerCommand("subagents-stop", {
772
781
  description: "Stop a current-session async subagent run",
773
782
  handler: async (args, ctx) => {
@@ -81,6 +81,7 @@ function buildParallelInitialResult(params: SubagentParamsLike): AgentToolResult
81
81
  content: [{ type: "text", text: tasks.map((task) => `${task.agent}: ${task.task}`).join("\n\n") }],
82
82
  details: {
83
83
  mode: "parallel",
84
+ ...(params.async ? { background: true } : {}),
84
85
  ...(params.context ? { context: params.context } : {}),
85
86
  results: tasks.map((task, index) => createPlaceholderResult(task.agent, task.task, "running", index)),
86
87
  progress: tasks.map((task, index) => ({
@@ -136,6 +137,7 @@ function buildChainInitialResult(params: SubagentParamsLike): AgentToolResult<De
136
137
  }],
137
138
  details: {
138
139
  mode: "chain",
140
+ ...(params.async ? { background: true } : {}),
139
141
  ...(params.context ? { context: params.context } : {}),
140
142
  results,
141
143
  progress: results.map((result, index) => ({
@@ -164,6 +166,7 @@ function buildSingleInitialResult(params: SubagentParamsLike): AgentToolResult<D
164
166
  content: [{ type: "text", text: task }],
165
167
  details: {
166
168
  mode: "single",
169
+ ...(params.async ? { background: true } : {}),
167
170
  ...(params.context ? { context: params.context } : {}),
168
171
  results: [createPlaceholderResult(agent, task, "running", 0)],
169
172
  progress: [{