@narumitw/pi-subagents 2.0.5 → 2.1.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 (178) hide show
  1. package/README.md +152 -50
  2. package/dist/chunks/{auto-transport-SY2VHUFH.ts → auto-transport-FUUKFDIG.ts} +6 -6
  3. package/dist/chunks/{capability-grant-CGEWOEKE.ts → capability-grant-PR72SWWS.ts} +4 -4
  4. package/dist/chunks/{chunk-DPPVEQAM.ts → chunk-4AQSF7AS.ts} +1 -1
  5. package/dist/chunks/chunk-4AQSF7AS.ts.map +7 -0
  6. package/dist/chunks/chunk-6H6TBBED.ts +108 -0
  7. package/dist/chunks/chunk-6H6TBBED.ts.map +7 -0
  8. package/dist/chunks/{chunk-DSOOH73Y.ts → chunk-7AAJEUSL.ts} +3 -3
  9. package/dist/chunks/{chunk-DSOOH73Y.ts.map → chunk-7AAJEUSL.ts.map} +2 -2
  10. package/dist/chunks/{chunk-7QPPBBXZ.ts → chunk-D4CR7T73.ts} +21 -3
  11. package/dist/chunks/chunk-D4CR7T73.ts.map +7 -0
  12. package/dist/chunks/{chunk-434NII74.ts → chunk-DIHBUR2E.ts} +54 -8
  13. package/dist/chunks/chunk-DIHBUR2E.ts.map +7 -0
  14. package/dist/chunks/{chunk-NIF42QMF.ts → chunk-FEVPWRMU.ts} +7 -4
  15. package/dist/chunks/chunk-FEVPWRMU.ts.map +7 -0
  16. package/dist/chunks/{chunk-YBUWBRF7.ts → chunk-FXI45N3J.ts} +5 -5
  17. package/dist/chunks/{chunk-S2IWVK3J.ts → chunk-ILEQ27AL.ts} +3 -2
  18. package/dist/chunks/chunk-ILEQ27AL.ts.map +7 -0
  19. package/dist/chunks/{chunk-DQMN4OYM.ts → chunk-ITVWPNU4.ts} +12 -106
  20. package/dist/chunks/chunk-ITVWPNU4.ts.map +7 -0
  21. package/dist/chunks/{chunk-QDVGH2X7.ts → chunk-IWC32VPY.ts} +2 -1
  22. package/dist/chunks/{chunk-QDVGH2X7.ts.map → chunk-IWC32VPY.ts.map} +2 -2
  23. package/dist/chunks/{chunk-I2FAK44T.ts → chunk-JSZIP73U.ts} +48 -10
  24. package/dist/chunks/chunk-JSZIP73U.ts.map +7 -0
  25. package/dist/chunks/{chunk-ZHTNCZIA.ts → chunk-JU6LUNLP.ts} +2 -2
  26. package/dist/chunks/{chunk-PSK43Y6A.ts → chunk-LASD73CM.ts} +2 -2
  27. package/dist/chunks/{chunk-C4L6P266.ts → chunk-LEOYDZI3.ts} +1 -1
  28. package/dist/chunks/{chunk-C4L6P266.ts.map → chunk-LEOYDZI3.ts.map} +2 -2
  29. package/dist/chunks/{chunk-H3BFJ7HJ.ts → chunk-LL4LP2T7.ts} +5 -5
  30. package/dist/chunks/chunk-N2T5IN4X.ts +18 -0
  31. package/dist/chunks/chunk-N2T5IN4X.ts.map +7 -0
  32. package/dist/chunks/{chunk-G3RSMSXJ.ts → chunk-NTRPLF46.ts} +1 -1
  33. package/dist/chunks/chunk-NTRPLF46.ts.map +7 -0
  34. package/dist/chunks/{chunk-CBP76ARQ.ts → chunk-PABJJYP6.ts} +174 -47
  35. package/dist/chunks/chunk-PABJJYP6.ts.map +7 -0
  36. package/dist/chunks/{chunk-EFBPISNT.ts → chunk-PBZMBTNJ.ts} +104 -103
  37. package/dist/chunks/chunk-PBZMBTNJ.ts.map +7 -0
  38. package/dist/chunks/{chunk-SCZ33MYW.ts → chunk-PGLSFLYW.ts} +2 -2
  39. package/dist/chunks/{chunk-O4VO6JUJ.ts → chunk-TM2R67J3.ts} +3 -3
  40. package/dist/chunks/{chunk-QBORTI4W.ts → chunk-TMZRHIIK.ts} +32 -3
  41. package/dist/chunks/chunk-TMZRHIIK.ts.map +7 -0
  42. package/dist/chunks/chunk-TZ34IQ3M.ts +59 -0
  43. package/dist/chunks/chunk-TZ34IQ3M.ts.map +7 -0
  44. package/dist/chunks/chunk-VBDGNNLM.ts +214 -0
  45. package/dist/chunks/chunk-VBDGNNLM.ts.map +7 -0
  46. package/dist/chunks/{chunk-7OBINKFM.ts → chunk-VDG7LTYE.ts} +11 -11
  47. package/dist/chunks/chunk-VDG7LTYE.ts.map +7 -0
  48. package/dist/chunks/{chunk-AEUYS7JC.ts → chunk-X4NMONPE.ts} +1 -1
  49. package/dist/chunks/chunk-X4NMONPE.ts.map +7 -0
  50. package/dist/chunks/{chunk-HKC4ES4B.ts → chunk-YPJEN6NU.ts} +2 -2
  51. package/dist/chunks/{completion-delivery-YPOWSSV3.ts → completion-delivery-JVLNQRWX.ts} +5 -4
  52. package/dist/chunks/{config-status-J4GPWP46.ts → config-status-FKGDECZ3.ts} +7 -6
  53. package/dist/chunks/{config-ui-2YUCUEBM.ts → config-ui-DDKERQHI.ts} +297 -231
  54. package/dist/chunks/config-ui-DDKERQHI.ts.map +7 -0
  55. package/dist/chunks/{consult-IV7UBNQQ.ts → consult-PQ6PRAKC.ts} +14 -13
  56. package/dist/chunks/consult-PQ6PRAKC.ts.map +7 -0
  57. package/dist/chunks/{create-stateful-transport-ZP3IXNV3.ts → create-stateful-transport-JWC2EFYL.ts} +6 -6
  58. package/dist/chunks/{delegation-contract-WJPT4FVS.ts → delegation-contract-LA56I5DT.ts} +2 -2
  59. package/dist/chunks/{discovery-K25T3SH4.ts → discovery-MIFB2U4Y.ts} +3 -3
  60. package/dist/chunks/{execution-LA7HN5YF.ts → execution-Q2JZLKJA.ts} +19 -16
  61. package/dist/chunks/execution-Q2JZLKJA.ts.map +7 -0
  62. package/dist/chunks/{in-process-transport-4RF3J6XK.ts → in-process-transport-HJ6TZXC3.ts} +9 -9
  63. package/dist/chunks/{inspect-XV2QALMR.ts → inspect-UH2TKH6E.ts} +25 -10
  64. package/dist/chunks/inspect-UH2TKH6E.ts.map +7 -0
  65. package/dist/chunks/{persistence-VSGXAW4P.ts → persistence-XHPJBZL7.ts} +11 -7
  66. package/dist/chunks/persistence-XHPJBZL7.ts.map +7 -0
  67. package/dist/chunks/{registry-E6XPJB7L.ts → registry-XDXPECWF.ts} +136 -15
  68. package/dist/chunks/registry-XDXPECWF.ts.map +7 -0
  69. package/dist/chunks/{retained-semantic-state-7WXSGRJU.ts → retained-semantic-state-GM75FZGE.ts} +3 -3
  70. package/dist/chunks/{rpc-transport-NEHBHWX4.ts → rpc-transport-7R7DVCEB.ts} +12 -16
  71. package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +7 -0
  72. package/dist/chunks/{spawn-idempotency-QGHO2WKC.ts → spawn-idempotency-BNHOSMZW.ts} +2 -2
  73. package/dist/chunks/{subprocess-transport-NSHOGDC4.ts → subprocess-transport-VHZJRBTW.ts} +15 -14
  74. package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +7 -0
  75. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +164 -0
  76. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +7 -0
  77. package/dist/index.ts +427 -30
  78. package/dist/index.ts.map +3 -3
  79. package/docs/async-runtime-protocol.md +69 -0
  80. package/docs/implementation-notes/pi-subagents-capability-matrix.md +62 -0
  81. package/docs/implementation-notes/pi-subagents-current-direction.md +99 -0
  82. package/docs/implementation-notes/pi-subagents-rpc-v1.md +153 -0
  83. package/docs/pi-subagents-diagrams.md +183 -0
  84. package/package.json +9 -8
  85. package/src/agents/types.ts +2 -0
  86. package/src/async-subagent-benchmark.ts +532 -0
  87. package/src/completion-delivery.ts +71 -4
  88. package/src/completion-render.ts +1 -0
  89. package/src/completion-requirement.ts +308 -0
  90. package/src/config-registration.ts +5 -5
  91. package/src/config-status.ts +66 -70
  92. package/src/config-ui.ts +244 -150
  93. package/src/consult-resources.ts +1 -1
  94. package/src/consult.ts +3 -8
  95. package/src/delegation-contract.ts +55 -9
  96. package/src/execution-plan.ts +1 -1
  97. package/src/execution-ui.ts +40 -29
  98. package/src/execution.ts +2 -3
  99. package/src/inspect.ts +24 -1
  100. package/src/orchestration-metrics.ts +1 -1
  101. package/src/panel-execution.ts +2 -3
  102. package/src/panel-failure.ts +1 -1
  103. package/src/panel-render.ts +1 -1
  104. package/src/parallel-limit-ui.ts +6 -5
  105. package/src/params.ts +2 -1
  106. package/src/persistence.ts +9 -0
  107. package/src/process-control.ts +43 -0
  108. package/src/registry-types.ts +5 -0
  109. package/src/registry.ts +162 -18
  110. package/src/render.ts +2 -1
  111. package/src/rpc-transport.ts +1 -1
  112. package/src/runner-outcome.ts +1 -1
  113. package/src/runner-result.ts +1 -1
  114. package/src/runner-types.ts +102 -0
  115. package/src/runner.ts +11 -192
  116. package/src/settings/inspection.ts +27 -0
  117. package/src/settings/schema.ts +9 -0
  118. package/src/settings-reader.ts +7 -0
  119. package/src/settings.ts +20 -0
  120. package/src/spawn-idempotency.ts +5 -0
  121. package/src/stateful-agent-view.ts +15 -19
  122. package/src/stateful-guidance.ts +14 -4
  123. package/src/stateful-limit-ui.ts +23 -20
  124. package/src/stateful-limits.ts +10 -10
  125. package/src/stateful-registration.ts +126 -9
  126. package/src/stateful-render.ts +27 -2
  127. package/src/subagent-details.ts +43 -0
  128. package/src/subagents-extension.ts +66 -8
  129. package/src/subagents.ts +2 -0
  130. package/src/subprocess-transport.ts +2 -1
  131. package/src/supervision.ts +2 -1
  132. package/src/timeout-finalization.ts +1 -1
  133. package/src/tool-schema-compatibility.ts +73 -0
  134. package/src/transport-types.ts +6 -0
  135. package/src/transport-ui.ts +18 -46
  136. package/src/usage-recording-config.ts +13 -0
  137. package/src/usage-recording-store.ts +183 -0
  138. package/src/usage-recording.ts +478 -0
  139. package/src/verification-harness.ts +1 -1
  140. package/src/workflow-ui.ts +17 -9
  141. package/dist/chunks/chunk-434NII74.ts.map +0 -7
  142. package/dist/chunks/chunk-7OBINKFM.ts.map +0 -7
  143. package/dist/chunks/chunk-7QPPBBXZ.ts.map +0 -7
  144. package/dist/chunks/chunk-AEUYS7JC.ts.map +0 -7
  145. package/dist/chunks/chunk-CBP76ARQ.ts.map +0 -7
  146. package/dist/chunks/chunk-DPPVEQAM.ts.map +0 -7
  147. package/dist/chunks/chunk-DQMN4OYM.ts.map +0 -7
  148. package/dist/chunks/chunk-EFBPISNT.ts.map +0 -7
  149. package/dist/chunks/chunk-G3RSMSXJ.ts.map +0 -7
  150. package/dist/chunks/chunk-I2FAK44T.ts.map +0 -7
  151. package/dist/chunks/chunk-NIF42QMF.ts.map +0 -7
  152. package/dist/chunks/chunk-QBORTI4W.ts.map +0 -7
  153. package/dist/chunks/chunk-S2IWVK3J.ts.map +0 -7
  154. package/dist/chunks/config-ui-2YUCUEBM.ts.map +0 -7
  155. package/dist/chunks/consult-IV7UBNQQ.ts.map +0 -7
  156. package/dist/chunks/execution-LA7HN5YF.ts.map +0 -7
  157. package/dist/chunks/inspect-XV2QALMR.ts.map +0 -7
  158. package/dist/chunks/persistence-VSGXAW4P.ts.map +0 -7
  159. package/dist/chunks/registry-E6XPJB7L.ts.map +0 -7
  160. package/dist/chunks/rpc-transport-NEHBHWX4.ts.map +0 -7
  161. package/dist/chunks/subprocess-transport-NSHOGDC4.ts.map +0 -7
  162. /package/dist/chunks/{auto-transport-SY2VHUFH.ts.map → auto-transport-FUUKFDIG.ts.map} +0 -0
  163. /package/dist/chunks/{capability-grant-CGEWOEKE.ts.map → capability-grant-PR72SWWS.ts.map} +0 -0
  164. /package/dist/chunks/{chunk-YBUWBRF7.ts.map → chunk-FXI45N3J.ts.map} +0 -0
  165. /package/dist/chunks/{chunk-ZHTNCZIA.ts.map → chunk-JU6LUNLP.ts.map} +0 -0
  166. /package/dist/chunks/{chunk-PSK43Y6A.ts.map → chunk-LASD73CM.ts.map} +0 -0
  167. /package/dist/chunks/{chunk-H3BFJ7HJ.ts.map → chunk-LL4LP2T7.ts.map} +0 -0
  168. /package/dist/chunks/{chunk-SCZ33MYW.ts.map → chunk-PGLSFLYW.ts.map} +0 -0
  169. /package/dist/chunks/{chunk-O4VO6JUJ.ts.map → chunk-TM2R67J3.ts.map} +0 -0
  170. /package/dist/chunks/{chunk-HKC4ES4B.ts.map → chunk-YPJEN6NU.ts.map} +0 -0
  171. /package/dist/chunks/{completion-delivery-YPOWSSV3.ts.map → completion-delivery-JVLNQRWX.ts.map} +0 -0
  172. /package/dist/chunks/{config-status-J4GPWP46.ts.map → config-status-FKGDECZ3.ts.map} +0 -0
  173. /package/dist/chunks/{create-stateful-transport-ZP3IXNV3.ts.map → create-stateful-transport-JWC2EFYL.ts.map} +0 -0
  174. /package/dist/chunks/{delegation-contract-WJPT4FVS.ts.map → delegation-contract-LA56I5DT.ts.map} +0 -0
  175. /package/dist/chunks/{discovery-K25T3SH4.ts.map → discovery-MIFB2U4Y.ts.map} +0 -0
  176. /package/dist/chunks/{in-process-transport-4RF3J6XK.ts.map → in-process-transport-HJ6TZXC3.ts.map} +0 -0
  177. /package/dist/chunks/{retained-semantic-state-7WXSGRJU.ts.map → retained-semantic-state-GM75FZGE.ts.map} +0 -0
  178. /package/dist/chunks/{spawn-idempotency-QGHO2WKC.ts.map → spawn-idempotency-BNHOSMZW.ts.map} +0 -0
package/src/runner.ts CHANGED
@@ -2,20 +2,10 @@ import { spawn } from "node:child_process";
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 type { AgentToolResult } from "@earendil-works/pi-agent-core";
6
5
  import type { Message } from "@earendil-works/pi-ai";
7
6
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
8
- import type { SchedulingDecision } from "./adaptive-scheduler.js";
9
- import type {
10
- AgentConfig,
11
- AgentScope,
12
- AgentSource,
13
- SubagentThinkingLevel,
14
- } from "./agents/types.js";
15
- import { type CapabilityGrant, revokeCapabilityGrant } from "./capability-grant.js";
16
- import type { TargetPolicyAudit } from "./cwd-policy.js";
17
- import type { DelegationContract } from "./delegation-contract.js";
18
- import type { ExecutionPlan } from "./execution-plan.js";
7
+ import type { AgentConfig, SubagentThinkingLevel } from "./agents/types.js";
8
+ import { revokeCapabilityGrant } from "./capability-grant.js";
19
9
  import {
20
10
  appendBounded,
21
11
  DEFAULT_MAX_CONTEXT_BYTES,
@@ -25,139 +15,51 @@ import {
25
15
  MAX_SUBAGENT_TIMEOUT_MS,
26
16
  truncateUtf8,
27
17
  } from "./limits.js";
28
- import type { OrchestrationMetrics } from "./orchestration-metrics.js";
29
- import { type ClassifiedSubagentOutcome, classifyStructuredOutcome } from "./outcome.js";
30
- import type { PanelSynthesis } from "./panel-contract.js";
31
- import type { PanelEvidenceArtifact } from "./panel-evidence.js";
32
- import type { PanelFailure } from "./panel-failure.js";
33
- import type { PanelPhaseBudgets, PanelPreset } from "./panel-planning.js";
18
+ import { classifyStructuredOutcome } from "./outcome.js";
34
19
  import { buildPiArgs } from "./pi-args.js";
35
20
  import { resolvePiInvocation } from "./pi-invocation.js";
21
+ import { KILL_GRACE_MS, terminateProcess } from "./process-control.js";
36
22
  import { JsonLineDecoder } from "./protocol.js";
37
- import {
38
- type AnyStructuredSubagentResult,
39
- parseAnyStructuredSubagentResult,
40
- type SubagentResultFormat,
41
- } from "./result-contract.js";
23
+ import { parseAnyStructuredSubagentResult } from "./result-contract.js";
42
24
  import { formatResultFailure, getResultFinalOutput, isResultError } from "./runner-outcome.js";
43
25
  import { getFinalOutput } from "./runner-result.js";
26
+ import type { ChildLaunchPolicy, RecentActivityItem, SingleResult } from "./runner-types.js";
44
27
  import {
45
28
  addUsageValue,
46
29
  mergeUsageStats,
47
30
  protocolUsageCost,
48
31
  protocolUsageCount,
49
- type UsageStats,
50
32
  } from "./runner-usage.js";
33
+ import type { OnUpdateCallback, SubagentDetails } from "./subagent-details.js";
51
34
  import {
52
35
  formatTimeoutCheckpoint,
53
36
  formatTurnTerminationMessage,
54
37
  journalMessages,
55
38
  TimeoutProgressJournal,
56
39
  TURN_TERMINATION_VERSION,
57
- type TurnTerminationReport,
58
40
  } from "./timeout-checkpoint.js";
59
41
  import {
60
42
  buildTimeoutFinalizationPrompt,
61
43
  resolveTimeoutFinalizationMs,
62
44
  } from "./timeout-finalization.js";
63
- import { TurnBudgetMonitor, type TurnBudgetStop, type TurnLimits } from "./turn-budget.js";
64
- import type { WorkItemLedgerSnapshot } from "./work-item-ledger.js";
65
-
66
- export const KILL_GRACE_MS = 5000;
45
+ import { TurnBudgetMonitor, type TurnBudgetStop } from "./turn-budget.js";
67
46
 
68
47
  export type { PiArgsOptions } from "./pi-args.js";
69
48
  export { buildPiArgs } from "./pi-args.js";
49
+ export { KILL_GRACE_MS, terminateProcess } from "./process-control.js";
70
50
  export {
71
51
  formatResultFailure,
72
52
  getResultFinalOutput,
73
53
  isResultError,
74
54
  } from "./runner-outcome.js";
55
+ export type { ChildLaunchPolicy, RecentActivityItem, SingleResult } from "./runner-types.js";
75
56
  export type { UsageStats } from "./runner-usage.js";
76
- export type RecentActivityItem =
77
- | { type: "text"; text: string }
78
- | { type: "toolCall"; name: string; args: Record<string, unknown> };
57
+ export type { OnUpdateCallback, PanelDetails, SubagentDetails } from "./subagent-details.js";
79
58
 
80
59
  const MAX_RECENT_ACTIVITY_ITEMS = 10;
81
60
  const MAX_RECENT_ACTIVITY_BYTES = 8 * 1024;
82
61
  const MAX_RECENT_ACTIVITY_ARGUMENT_BYTES = 1024;
83
62
 
84
- export interface SingleResult {
85
- agent: string;
86
- agentSource: AgentSource | "unknown";
87
- task: string;
88
- exitCode: number;
89
- messages: Message[];
90
- stderr: string;
91
- usage: UsageStats;
92
- model?: string;
93
- actualProvider?: string;
94
- actualModel?: string;
95
- recentActivity?: RecentActivityItem[];
96
- recentActivityTotal?: number;
97
- thinkingLevel?: SubagentThinkingLevel;
98
- stopReason?: string;
99
- errorMessage?: string;
100
- step?: number;
101
- finalOutput?: string;
102
- partialOutput?: string;
103
- timeoutSummary?: string;
104
- timeoutSummaryError?: string;
105
- termination?: TurnTerminationReport;
106
- timedOut?: boolean;
107
- timeoutMs?: number;
108
- aborted?: boolean;
109
- truncated?: boolean;
110
- malformedEvents?: number;
111
- launchFailed?: boolean;
112
- processStarted?: boolean;
113
- target?: TargetPolicyAudit;
114
- policy?: {
115
- inherited: string[];
116
- overridden: string[];
117
- unsupported: string[];
118
- };
119
- contract?: DelegationContract;
120
- resultFormat?: SubagentResultFormat;
121
- structuredResult?: AnyStructuredSubagentResult;
122
- resultContractInvalid?: boolean;
123
- outcome?: ClassifiedSubagentOutcome;
124
- attemptCount?: number;
125
- hedged?: boolean;
126
- executionPlan?: ExecutionPlan;
127
- capabilityGrant?: CapabilityGrant;
128
- }
129
-
130
- export interface PanelDetails {
131
- id: string;
132
- preset: PanelPreset;
133
- sharedTaskPreview: string;
134
- state: "running" | "completed" | "degraded" | "insufficient-panel" | "failed" | "cancelled";
135
- reviewerIds: string[];
136
- validReviewCount: number;
137
- failedReviewCount: number;
138
- blockingObjectionCount: number;
139
- dissentCount: number;
140
- budgets: PanelPhaseBudgets;
141
- evidence: PanelEvidenceArtifact[];
142
- failures: PanelFailure[];
143
- synthesis?: PanelSynthesis;
144
- synthesizerResult?: SingleResult;
145
- cleanupComplete: boolean;
146
- }
147
-
148
- export interface SubagentDetails {
149
- mode: "single" | "parallel" | "chain" | "workflow" | "panel";
150
- agentScope: AgentScope;
151
- projectAgentsDir: string | null;
152
- results: SingleResult[];
153
- aggregator?: SingleResult;
154
- workflow?: WorkItemLedgerSnapshot;
155
- schedulerDecisions?: SchedulingDecision[];
156
- metrics?: OrchestrationMetrics;
157
- panel?: PanelDetails;
158
- isError?: boolean;
159
- }
160
-
161
63
  function boundMessageText(
162
64
  message: Message,
163
65
  maxBytes: number,
@@ -338,89 +240,6 @@ async function writePromptToTempFile(
338
240
  return { dir: tmpDir, filePath };
339
241
  }
340
242
 
341
- function signalProcess(proc: ReturnType<typeof spawn>, signal: NodeJS.Signals): void {
342
- if (process.platform !== "win32" && proc.pid) {
343
- try {
344
- process.kill(-proc.pid, signal);
345
- return;
346
- } catch {
347
- // Fall back to signaling the immediate child when process-group signaling is unavailable.
348
- }
349
- }
350
- try {
351
- proc.kill(signal);
352
- } catch {
353
- // The process may already have exited.
354
- }
355
- }
356
-
357
- export function terminateProcess(
358
- proc: ReturnType<typeof spawn>,
359
- graceMs = KILL_GRACE_MS,
360
- ): () => void {
361
- const leaderExited = proc.exitCode !== null || proc.signalCode !== null;
362
- const capturedOutputClosed = [proc.stdout, proc.stderr].every(
363
- (stream) => !stream || stream.readableEnded || stream.destroyed,
364
- );
365
- let closed = leaderExited && capturedOutputClosed;
366
- const onClose = () => {
367
- closed = true;
368
- };
369
- proc.once("close", onClose);
370
- if (!closed) signalProcess(proc, "SIGTERM");
371
- const escalation = setTimeout(() => {
372
- if (!closed) signalProcess(proc, "SIGKILL");
373
- }, graceMs);
374
- escalation.unref();
375
- return () => {
376
- clearTimeout(escalation);
377
- proc.off("close", onClose);
378
- };
379
- }
380
-
381
- export type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
382
-
383
- export interface ChildLaunchPolicy {
384
- tools?: string[];
385
- disableExtensions?: boolean;
386
- disableSkills?: boolean;
387
- disablePromptTemplates?: boolean;
388
- disableContextFiles?: boolean;
389
- projectTrust?: boolean;
390
- baseSystemPrompt?: string;
391
- appendSystemPromptPaths?: string[];
392
- /** Package-owned explicit child extensions loaded even when unrelated extensions are disabled. */
393
- extensionPaths?: string[];
394
- /** Package-owned tools added to the child allowlist without changing delegated execution tools. */
395
- additionalTools?: string[];
396
- /** Ephemeral child-process environment consumed and cleared by a package-owned bridge. */
397
- env?: NodeJS.ProcessEnv;
398
- /** Internal timeout recovery control; omitted means enabled. */
399
- finalizeOnTimeout?: boolean;
400
- /** Internal hard deadline for the summary attempt. */
401
- timeoutFinalizationMs?: number;
402
- /** Optional stateful result contract retained during timeout finalization. */
403
- timeoutResultFormat?: SubagentResultFormat;
404
- /** Optional non-wall-clock limits for this turn. */
405
- turnLimits?: TurnLimits;
406
- /** Override the timeout reason when an orchestration deadline caps this child. */
407
- workTimeoutReason?: "work_timeout" | "orchestration_timeout";
408
- /** Public limit value reported when the effective child timeout is only the remaining budget. */
409
- workTimeoutReportLimit?: number;
410
- /** Absolute blocking-workflow deadline that also caps model finalization. */
411
- orchestrationDeadlineAt?: number;
412
- /** Completion contract requested for this turn. */
413
- resultFormat?: SubagentResultFormat;
414
- /** Normalized request contract retained in result details. */
415
- contract?: DelegationContract;
416
- /** Original task summary shown in result details when the executed prompt has contract metadata. */
417
- displayTask?: string;
418
- /** Immutable audit or enforcement decision made before launch. */
419
- executionPlan?: ExecutionPlan;
420
- /** Executor-owned authority lifetime bound to the accepted plan generation. */
421
- capabilityGrant?: CapabilityGrant;
422
- }
423
-
424
243
  export async function runSingleAgent(
425
244
  defaultCwd: string,
426
245
  agents: AgentConfig[],
@@ -96,6 +96,13 @@ export interface SubagentSettingsSnapshot {
96
96
  error?: string;
97
97
  }
98
98
 
99
+ export interface UsageRecordingSettingsSnapshot {
100
+ path: string;
101
+ enabled: boolean;
102
+ source: SettingsSource;
103
+ error?: string;
104
+ }
105
+
99
106
  export function resolveDelegationWorkflow(
100
107
  blockingEnabled: boolean,
101
108
  statefulEnabled: boolean,
@@ -121,6 +128,26 @@ export function buildSubagentSettingsSnapshot(
121
128
  };
122
129
  }
123
130
 
131
+ export function buildUsageRecordingSettingsSnapshot(
132
+ inspected: InspectedSubagentSettingsDocument,
133
+ ): UsageRecordingSettingsSnapshot {
134
+ if (!inspected.raw || !inspected.settings) {
135
+ return {
136
+ path: inspected.path,
137
+ enabled: false,
138
+ source: "default",
139
+ ...(inspected.error ? { error: inspected.error } : {}),
140
+ };
141
+ }
142
+ const explicit =
143
+ isPlainObject(inspected.raw.usageRecording) && hasOwn(inspected.raw.usageRecording, "enabled");
144
+ return {
145
+ path: inspected.path,
146
+ enabled: inspected.settings.usageRecording?.enabled === true,
147
+ source: explicit ? "user settings" : "default",
148
+ };
149
+ }
150
+
124
151
  export function buildConsultResourceSettingsSnapshot(
125
152
  inspected: InspectedSubagentSettingsDocument,
126
153
  ): ConsultResourceSettingsSnapshot {
@@ -182,5 +182,14 @@ export function normalizeSubagentSettings(value: unknown): SubagentSettings | un
182
182
  }
183
183
  settings.cwdPolicy = cwdPolicy;
184
184
  }
185
+ if (hasOwn(value, "usageRecording")) {
186
+ if (!isPlainObject(value.usageRecording)) return undefined;
187
+ const usageRecording: NonNullable<SubagentSettings["usageRecording"]> = {};
188
+ if (hasOwn(value.usageRecording, "enabled")) {
189
+ if (typeof value.usageRecording.enabled !== "boolean") return undefined;
190
+ usageRecording.enabled = value.usageRecording.enabled;
191
+ }
192
+ settings.usageRecording = usageRecording;
193
+ }
185
194
  return settings;
186
195
  }
@@ -12,6 +12,7 @@ import {
12
12
  buildStatefulLimitSettingsSnapshot,
13
13
  buildStatefulTransportSettingsSnapshot,
14
14
  buildSubagentSettingsSnapshot,
15
+ buildUsageRecordingSettingsSnapshot,
15
16
  type CompletionDeliverySettingsSnapshot,
16
17
  type ConsultResourceSettingsSnapshot,
17
18
  type CwdPolicySettingsSnapshot,
@@ -20,6 +21,7 @@ import {
20
21
  type StatefulLimitSettingsSnapshot,
21
22
  type StatefulTransportSettingsSnapshot,
22
23
  type SubagentSettingsSnapshot,
24
+ type UsageRecordingSettingsSnapshot,
23
25
  } from "./settings/inspection.js";
24
26
  import { isPlainObject, normalizeSubagentSettings } from "./settings/schema.js";
25
27
 
@@ -40,6 +42,7 @@ export {
40
42
  type StatefulLimitSettingsSnapshot,
41
43
  type StatefulTransportSettingsSnapshot,
42
44
  type SubagentSettingsSnapshot,
45
+ type UsageRecordingSettingsSnapshot,
43
46
  } from "./settings/inspection.js";
44
47
  export { hasOwn, normalizeAgentSettings, normalizeSubagentSettings } from "./settings/schema.js";
45
48
 
@@ -162,6 +165,10 @@ export function inspectCompletionDeliverySettings(): CompletionDeliverySettingsS
162
165
  return buildCompletionDeliverySettingsSnapshot(inspectSubagentSettingsDocument());
163
166
  }
164
167
 
168
+ export function inspectUsageRecordingSettings(): UsageRecordingSettingsSnapshot {
169
+ return buildUsageRecordingSettingsSnapshot(inspectSubagentSettingsDocument());
170
+ }
171
+
165
172
  export function inspectStatefulTransportSettings(): StatefulTransportSettingsSnapshot {
166
173
  return buildStatefulTransportSettingsSnapshot(inspectSubagentSettingsDocument());
167
174
  }
package/src/settings.ts CHANGED
@@ -57,6 +57,7 @@ export {
57
57
  inspectStatefulLimitSettings,
58
58
  inspectStatefulTransportSettings,
59
59
  inspectSubagentSettings,
60
+ inspectUsageRecordingSettings,
60
61
  normalizeAgentSettings,
61
62
  normalizeSubagentSettings,
62
63
  readSubagentSettings,
@@ -67,6 +68,7 @@ export {
67
68
  type StatefulTransportSettingsSnapshot,
68
69
  type SubagentSettingsSnapshot,
69
70
  subagentSettingsFilePath,
71
+ type UsageRecordingSettingsSnapshot,
70
72
  } from "./settings-reader.js";
71
73
 
72
74
  const SETTINGS_FILE = SUBAGENT_SETTINGS_FILE;
@@ -162,6 +164,24 @@ export function updateCompletionDeliverySetting(value: CompletionDelivery): void
162
164
  });
163
165
  }
164
166
 
167
+ export function updateUsageRecordingSetting(enabled: boolean): void {
168
+ withSettingsMutationLock(() => {
169
+ const update = readSettingsObjectForUpdate();
170
+ const raw = update.document;
171
+ const usageRecording = raw.usageRecording;
172
+ if (usageRecording !== undefined && !isPlainObject(usageRecording)) {
173
+ throw new Error(`Cannot update invalid ${SETTINGS_FILE} usageRecording settings`);
174
+ }
175
+ writeSettingsObjectUnlocked(
176
+ {
177
+ ...raw,
178
+ usageRecording: { ...(usageRecording ?? {}), enabled },
179
+ },
180
+ update.replaceCanonical,
181
+ );
182
+ });
183
+ }
184
+
165
185
  export function updateBlockingMaxParallelTasksSetting(value: number): void {
166
186
  if (!isPositiveInteger(value) || value > MAX_CONFIGURABLE_PARALLEL_TASKS) {
167
187
  throw new Error(
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import type { AgentScope, SubagentThinkingLevel } from "./agents/types.js";
3
+ import type { CompletionRequirementMode } from "./completion-requirement.js";
3
4
  import type { DelegationContract } from "./delegation-contract.js";
4
5
  import type { SubagentResultFormat } from "./result-contract.js";
5
6
 
@@ -23,6 +24,7 @@ export interface CanonicalSpawnRequest {
23
24
  allowConcurrentWrites: boolean;
24
25
  contract?: DelegationContract;
25
26
  resultFormat: SubagentResultFormat;
27
+ completionRequirement?: CompletionRequirementMode;
26
28
  }
27
29
 
28
30
  export function hashSpawnRequest(request: CanonicalSpawnRequest): string {
@@ -48,6 +50,9 @@ export function hashSpawnRequest(request: CanonicalSpawnRequest): string {
48
50
  allowConcurrentWrites: request.allowConcurrentWrites,
49
51
  ...(request.contract === undefined ? {} : { contract: request.contract }),
50
52
  resultFormat: request.resultFormat,
53
+ ...(request.completionRequirement === "required"
54
+ ? { completionRequirement: "required" }
55
+ : {}),
51
56
  }),
52
57
  )
53
58
  .digest("hex");
@@ -3,28 +3,10 @@ import type { ManagedAgent } from "./registry.js";
3
3
 
4
4
  export function formatStatefulAgentLine(agent: ManagedAgent, now = Date.now()): string {
5
5
  const elapsedSeconds = Math.max(0, Math.floor((now - agent.updatedAt) / 1000));
6
- const actions =
7
- agent.state === "running" || agent.state === "starting"
8
- ? "interrupt, close"
9
- : agent.state === "closed"
10
- ? "inspect"
11
- : "send, close";
12
6
  const task = agent.currentTask ? ` — ${sanitizeStatusLine(agent.currentTask, 80)}` : "";
13
7
  const unread = agent.mailbox.filter((message) => !message.readAt).length;
14
8
  const indent = " ".repeat(agent.depth);
15
- const thinking = agent.thinkingLevel ? ` thinking:${agent.thinkingLevel}` : "";
16
- const timeout = agent.currentTimeoutMs ?? agent.timeoutMs;
17
- const timeoutText = timeout ? ` timeout:${timeout}ms` : "";
18
- const idleTimeout = agent.currentIdleTimeoutMs ?? agent.idleTimeoutMs;
19
- const idleText = idleTimeout ? ` idle:${idleTimeout}ms` : "";
20
- const maxTurns = agent.currentMaxTurns ?? agent.maxTurns;
21
- const turnsText = maxTurns ? ` turns:${maxTurns}` : "";
22
- const maxToolCalls = agent.currentMaxToolCalls ?? agent.maxToolCalls;
23
- const toolsText = maxToolCalls ? ` tools:${maxToolCalls}` : "";
24
- const transport = agent.telemetry?.transport ? ` transport:${agent.telemetry.transport}` : "";
25
- const phase = agent.telemetry?.phase ? ` phase:${agent.telemetry.phase}` : "";
26
- const queued = agent.telemetry?.queuePosition ? ` queue:${agent.telemetry.queuePosition}` : "";
27
- return `${indent}${sanitizeStatusLine(agent.taskPath ?? agent.id, 256)} (${sanitizeStatusLine(agent.id, 128)}) ${sanitizeStatusLine(agent.agent, 128)} ${agent.state} ${elapsedSeconds}s${thinking}${timeoutText}${idleText}${turnsText}${toolsText}${transport}${phase}${queued} unread:${unread} [${actions}]${task}`;
9
+ return `${indent}${sanitizeStatusLine(agent.taskPath ?? agent.id, 256)} · ${sanitizeStatusLine(agent.agent, 128)} · ${agentStateLabel(agent.state)} · updated ${elapsedSeconds}s ago · ${unread} unread${task}`;
28
10
  }
29
11
 
30
12
  export function summarizeStatefulAgent(agent: ManagedAgent) {
@@ -63,6 +45,9 @@ export function summarizeStatefulAgent(agent: ManagedAgent) {
63
45
  truncated: agent.contextTruncated === true,
64
46
  },
65
47
  resultFormat: agent.resultFormat ?? "text",
48
+ completionRequirements: (agent.completionRequirements ?? []).map((record) => ({
49
+ ...record,
50
+ })),
66
51
  structuredResult: agent.structuredResult,
67
52
  termination: agent.termination,
68
53
  outcome: agent.outcome,
@@ -77,6 +62,17 @@ export function summarizeStatefulAgent(agent: ManagedAgent) {
77
62
  };
78
63
  }
79
64
 
65
+ function agentStateLabel(state: ManagedAgent["state"]): string {
66
+ switch (state) {
67
+ case "running":
68
+ return "working";
69
+ case "completed":
70
+ return "finished";
71
+ default:
72
+ return state;
73
+ }
74
+ }
75
+
80
76
  function sanitizeStatusLine(value: string, maxLength: number): string {
81
77
  return (
82
78
  value
@@ -10,26 +10,36 @@ export function createSpawnPromptGuidelines(
10
10
  ? "With subagent_spawn completion delivery set to auto-resume, prefer one subagent_spawn for broad asynchronous research or consequential independent review that covers related branches even when the final answer depends on its result; do not choose blocking parallel fan-out merely to keep delegation in the same turn."
11
11
  : "With subagent_spawn completion delivery set to auto-resume, prefer one subagent_spawn for broad asynchronous research or consequential independent review that covers related branches even when the final answer depends on its result."
12
12
  : blockingEnabled
13
- ? "With subagent_spawn completion delivery set to next-turn (the default), prefer one subagent_spawn for broad asynchronous research or consequential independent review only when the current response does not depend on its result; use the blocking subagent when the final answer depends on the detached result."
13
+ ? "With subagent_spawn completion delivery set to next-turn (the default), prefer one subagent_spawn for broad asynchronous research or consequential independent review only when the current response does not depend on its result; when it does, use subagent_spawn only with useful overlap and call subagent_await after that overlap is complete. Do not migrate new work to the deprecated subagent tool."
14
14
  : "With subagent_spawn completion delivery set to next-turn (the default), use subagent_spawn only when the current response does not depend on its result; complete final-answer-dependent work directly because an idle root is not awakened.";
15
15
  return [
16
16
  "Do not use subagent_spawn for simple or critical-path work that the main agent can perform directly. The main agent retains overall planning, immediate critical-path work, integration, final verification, and the final answer.",
17
17
  "Before one ordinary subagent_spawn, identify concrete useful non-overlapping main-agent work you can start immediately and a supported completion integration path. If none exists, perform the task directly instead of calling subagent_spawn.",
18
18
  "Give subagent_spawn a concise unique taskName using lowercase letters, digits, and underscores so the retained agent has a stable canonical task path.",
19
19
  "Set subagent_spawn thinkingLevel to the lowest sufficient thinking level for the delegated task: use off or minimal for extraction, formatting, or mechanical work; low for straightforward bounded work; medium for ordinary multi-step research or implementation; high for complex debugging, design, review, or cross-file analysis; xhigh for highly ambiguous, cross-system, or high-risk analysis; and max only for the hardest tasks when quality clearly outweighs latency and cost. Omit subagent_spawn thinkingLevel only to preserve the agent or child default.",
20
- "Set subagent_spawn timeoutMs to the shortest realistic work deadline for the task difficulty; use idleTimeoutMs for stalled work and maxTurns or maxToolCalls to stop repeated work without progress. Split oversized tasks instead of extending budgets merely to compensate for broad scope. Omit these fields only to preserve the retained agent or configured defaults.",
20
+ "Set subagent_spawn timeoutMs to the shortest realistic work deadline for the task difficulty; use idleTimeoutMs for stalled work and maxTurns or maxToolCalls to stop repeated work without progress. Scope the task to the smallest named files or questions. When setting subagent_spawn maxTurns or maxToolCalls, leave sufficient headroom for discovery, evidence reads, and final synthesis; otherwise omit them instead of guessing speculative tight values. Split oversized tasks instead of extending budgets merely to compensate for broad scope.",
21
+ "For an ordinary subagent_spawn, omit contract; use a delegation contract only when explicit acceptance, authority, evidence, or admission semantics are required.",
22
+ "Do not set subagent_spawn contract enforcement to enforce with requestedAuthority readPaths, writePaths, network, or secrets; those guarantees are unsupported and reject before child launch, while capabilities and tools remain enforceable.",
23
+ "If subagent_spawn rejects an unsupported guarantee, retry once with those fields removed or enforcement set to audit only when they were advisory; when any field is a required security boundary, stop instead of weakening it.",
21
24
  deliveryGuidance,
25
+ ...(completionDelivery === "auto-resume"
26
+ ? [
27
+ 'Track every final-answer-dependent subagent_spawn by setting completionRequirement to "required" and retaining its returned agentId or taskPath; treat interim output as progress, and synthesize only after every corresponding completion message is visible or terminal.',
28
+ ]
29
+ : []),
22
30
  "Keep ordinary review in the main agent with a review skill and deterministic checks; use subagent_spawn for detached review only when consequential independent verification has concrete parallel value.",
23
31
  "Use a single subagent_spawn for a bounded implementation slice with clear ownership only when it can run beside the identified main-agent work.",
24
32
  "Use a single subagent_spawn without concurrent main-agent work only for an explicit user-requested specialist model, tool profile, or isolation boundary.",
25
33
  ...(blockingEnabled
26
34
  ? [
27
- "Use the blocking subagent instead of subagent_spawn when synchronous output is required before the main agent can continue and waiting is intentional; queued steering cannot be processed until that blocking call returns.",
28
- "When subagent_spawn fits the completion-delivery policy, do not choose a blocking parallel subagent merely to keep delegation in the same turn.",
35
+ "The subagent tool is deprecated; do not select it merely because synchronous output is required. Prefer subagent_spawn with supported completion delivery, and use subagent_await only after useful overlapping main-agent work is complete and an intentional join is required.",
36
+ "Use deprecated subagent instead of subagent_spawn only for an existing caller or an explicit user request whose blocking chain, fan-in, panel, or workflow semantics do not yet have a detached replacement; queued steering cannot be processed until it returns.",
29
37
  ]
30
38
  : []),
31
39
  "Add another subagent_spawn only for truly independent work with safe workspace concurrency and disjoint write ownership; shared workspaces permit concurrent writes by default, so use workspaceMode worktree when repository isolation is required. The main agent still owns integration.",
32
40
  "After subagent_spawn returns, immediately continue the identified local task; do not merely announce the spawn, wait, poll, or end the response while useful local work remains.",
41
+ "When completionRequirement required subagent_spawn work remains active after local work is exhausted, emit at most one brief progress sentence and end the turn; do not repeat waiting updates or use the requested final format, verdict, or conclusion until every required completion is visible or terminal. Current Pi versions do not enforce a hard pre-display barrier.",
42
+ "Do not duplicate assigned work from subagent_spawn while its retained agent is running; use a bounded parent fallback only after its completion reports failure or insufficient evidence.",
33
43
  'Consume and synthesize available subagent_spawn completion messages; use subagent_manage with action "interrupt" or "close" for agents that are no longer needed.',
34
44
  'Completion from subagent_spawn is delivered automatically. Do not poll with subagent_inspect or subagent_mailbox action "read", repeatedly check progress, or duplicate the delegated work.',
35
45
  ];
@@ -28,10 +28,10 @@ export function statefulLimitListScreen(runtime: StatefulLimitRuntime) {
28
28
  const current = runtime.getRuntimeStatus().limits;
29
29
  return {
30
30
  kind: "actions" as const,
31
- title: "Detached Agent Limits",
31
+ title: "Background Agent Limits",
32
32
  lines: [
33
- "These limits apply after /reload or the next Pi session.",
34
- "Reloading can interrupt retained detached work.",
33
+ "These advanced limits apply after /reload or the next Pi session.",
34
+ "Reloading can interrupt subagents saved for follow-up.",
35
35
  ...(inspected.error
36
36
  ? [
37
37
  `Settings cannot be edited: ${safeTerminalText(inspected.error)}`,
@@ -46,7 +46,7 @@ export function statefulLimitListScreen(runtime: StatefulLimitRuntime) {
46
46
  return {
47
47
  id: definition.field,
48
48
  label: definition.label,
49
- description: `Current ${current[definition.field]} · configured ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
49
+ description: `Current: ${current[definition.field]} · after reload: ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
50
50
  action: "pick-stateful-limit" as const,
51
51
  };
52
52
  })
@@ -67,7 +67,7 @@ export function statefulLimitInputScreen(field: StatefulLimitField, runtime: Sta
67
67
  lines: [
68
68
  definition.description,
69
69
  `Current session: ${runtime.getRuntimeStatus().limits[field]}`,
70
- `Configured after reload: ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
70
+ `After reload: ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
71
71
  `Allowed: whole numbers ${definition.minimum === 0 ? "0 or greater" : "1 or greater"}`,
72
72
  `Read from: ${safeTerminalText(inspected.path)}`,
73
73
  ...(inspected.writePath !== inspected.path
@@ -114,9 +114,9 @@ export async function applyStatefulLimitSetting(
114
114
  const confirmed = await ctx.ui.confirm(
115
115
  `Lower ${statefulLimitDefinition(field).label}?`,
116
116
  [
117
- `This configured value would omit ${affectedBefore.length} currently retained agent record${affectedBefore.length === 1 ? "" : "s"} from projected recovery after reload.`,
118
- "No agent is closed now, and this menu will not reload Pi.",
119
- "A later state rewrite can make omitted records unavailable for recovery.",
117
+ `After reload, this value could exclude ${affectedBefore.length} saved subagent record${affectedBefore.length === 1 ? "" : "s"} from recovery.`,
118
+ "No subagent is removed now, and this menu will not reload Pi.",
119
+ "A later state save can make excluded records unavailable for recovery.",
120
120
  ].join("\n\n"),
121
121
  { signal: options.signal },
122
122
  );
@@ -127,7 +127,10 @@ export async function applyStatefulLimitSetting(
127
127
  [field]: next,
128
128
  });
129
129
  if (!sameIds(affectedBefore, affectedAfter)) {
130
- ctx.ui.notify("Detached agents changed while confirming; review the limit again.", "warning");
130
+ ctx.ui.notify(
131
+ "Current subagents changed while confirming; review the limit again.",
132
+ "warning",
133
+ );
131
134
  return { kind: "rejected" as const };
132
135
  }
133
136
  }
@@ -138,7 +141,7 @@ export async function applyStatefulLimitSetting(
138
141
  } catch (error) {
139
142
  if (options.isCurrent() && !options.signal.aborted) {
140
143
  ctx.ui.notify(
141
- `Detached limit was not saved; the previous setting is unchanged: ${formatError(error)}`,
144
+ `Background-agent limit was not saved; the previous setting is unchanged: ${formatError(error)}`,
142
145
  "error",
143
146
  );
144
147
  }
@@ -146,7 +149,7 @@ export async function applyStatefulLimitSetting(
146
149
  }
147
150
  if (options.signal.aborted || !options.isCurrent()) return { kind: "close" as const };
148
151
  ctx.ui.notify(
149
- `Saved ${statefulLimitDefinition(field).label.toLowerCase()}: ${next}. Applies after /reload; clear retained agents before reloading if their work must not be interrupted.`,
152
+ `Saved ${statefulLimitDefinition(field).label.toLowerCase()}: ${next}. Applies after /reload; clear current subagents first if their work must not be interrupted.`,
150
153
  "info",
151
154
  );
152
155
  return { kind: "back" as const };
@@ -154,11 +157,11 @@ export async function applyStatefulLimitSetting(
154
157
 
155
158
  export function formatDetachedLimitSummary(status: StatefulSubagentRuntimeStatus): string {
156
159
  return [
157
- `${status.limits.maxAgents} retained`,
158
- `${status.limits.maxActiveTurns} active turns`,
159
- `${status.limits.maxChildrenPerAgent} children`,
160
- `depth ${status.limits.maxDepth}`,
161
- `${status.limits.maxStoredAgents} stored`,
160
+ `${status.limits.maxAgents} saved`,
161
+ `${status.limits.maxActiveTurns} working at once`,
162
+ `${status.limits.maxChildrenPerAgent} children each`,
163
+ `${status.limits.maxDepth} nested levels`,
164
+ `${status.limits.maxStoredAgents} stored records`,
162
165
  ].join(" · ");
163
166
  }
164
167
 
@@ -172,7 +175,7 @@ export function formatConfiguredDetachedLimitDivergence(
172
175
  ? []
173
176
  : [`${definition.label.toLowerCase()} ${configured}`];
174
177
  });
175
- return changed.length > 0 ? `Configured after reload: ${changed.join(" · ")}` : undefined;
178
+ return changed.length > 0 ? `After /reload: ${changed.join(" · ")}` : undefined;
176
179
  }
177
180
 
178
181
  export function formatConfiguredDetachedLimits(
@@ -185,9 +188,9 @@ export function formatConfiguredDetachedLimits(
185
188
  }
186
189
 
187
190
  export function formatEmptyStatefulRuntime(status: StatefulSubagentRuntimeStatus): string {
188
- if (!status.enabled) return "Stateful subagents are disabled in user settings.";
189
- if (!status.initialized) return "Stateful subagents are not initialized for this session.";
190
- return "No current-session subagents.";
191
+ if (!status.enabled) return "Background subagents are disabled in How subagents run.";
192
+ if (!status.initialized) return "Background subagents have not started in this session.";
193
+ return "No subagents are working or saved for follow-up in this session.";
191
194
  }
192
195
 
193
196
  function parseStatefulLimit(