gentle-pi 4.6.0 → 4.8.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 (536) hide show
  1. package/README.md +65 -55
  2. package/assets/agents/gentle-ai-explore.md +4 -3
  3. package/assets/agents/gentle-ai-verify.md +23 -6
  4. package/assets/agents/gentle-ai-worker.md +9 -6
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +2 -3
  7. package/assets/agents/jd-judge-b.md +2 -3
  8. package/assets/agents/review-readability.md +1 -5
  9. package/assets/agents/review-reliability.md +1 -5
  10. package/assets/agents/review-resilience.md +1 -5
  11. package/assets/agents/review-risk.md +1 -5
  12. package/assets/design-canvas/canvas-api.js +45 -0
  13. package/assets/design-canvas/canvas-boards.js +456 -0
  14. package/assets/design-canvas/canvas-boot.js +217 -0
  15. package/assets/design-canvas/canvas-checks.js +491 -0
  16. package/assets/design-canvas/canvas-comments.js +315 -0
  17. package/assets/design-canvas/canvas-compare.js +159 -0
  18. package/assets/design-canvas/canvas-events.js +75 -0
  19. package/assets/design-canvas/canvas-export.js +393 -0
  20. package/assets/design-canvas/canvas-focus.js +203 -0
  21. package/assets/design-canvas/canvas-handoffs.js +150 -0
  22. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  23. package/assets/design-canvas/canvas-i18n.js +108 -0
  24. package/assets/design-canvas/canvas-layout.js +526 -0
  25. package/assets/design-canvas/canvas-menu.js +213 -0
  26. package/assets/design-canvas/canvas-messages.js +86 -0
  27. package/assets/design-canvas/canvas-minimap.js +163 -0
  28. package/assets/design-canvas/canvas-parts.js +401 -0
  29. package/assets/design-canvas/canvas-popover.js +234 -0
  30. package/assets/design-canvas/canvas-rail.js +348 -0
  31. package/assets/design-canvas/canvas-sizes.js +524 -0
  32. package/assets/design-canvas/canvas-store.js +164 -0
  33. package/assets/design-canvas/canvas-tokens.js +674 -0
  34. package/assets/design-canvas/canvas-ui.js +24 -0
  35. package/assets/design-canvas/canvas-view.js +184 -0
  36. package/assets/design-canvas/canvas.css +759 -16
  37. package/assets/design-canvas/canvas.js +2 -1497
  38. package/assets/design-canvas/index.html +117 -36
  39. package/assets/design-canvas/inspector.js +546 -16
  40. package/assets/install-wizard/wizard.js +6 -1
  41. package/assets/migrations/agent-body-history.json +40 -1
  42. package/assets/orchestrator-delegation-reference.md +10 -16
  43. package/assets/orchestrator-delegation.md +5 -5
  44. package/assets/orchestrator-full-delegation-card.md +64 -0
  45. package/assets/orchestrator-full-delegation.md +34 -0
  46. package/assets/orchestrator-memory.md +5 -5
  47. package/assets/orchestrator-prompts.md +2 -2
  48. package/assets/orchestrator-quota-recovery.md +5 -0
  49. package/assets/orchestrator-skills.md +14 -13
  50. package/assets/orchestrator-tracking.md +10 -14
  51. package/assets/orchestrator-verification.md +12 -8
  52. package/assets/orchestrator-writer.md +4 -4
  53. package/assets/orchestrator.md +21 -25
  54. package/bin/gentle-shell.mjs +292 -65
  55. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  60. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  61. package/docs/agent-status.md +61 -0
  62. package/docs/assets/brand/sponsor-banner.svg +60 -0
  63. package/docs/bundled-install.md +20 -10
  64. package/docs/delegated-verification.md +46 -8
  65. package/docs/desktop-rpc.md +1253 -0
  66. package/docs/gentle-agents-activity.md +40 -0
  67. package/docs/gentle-shell.md +91 -30
  68. package/docs/install-wizard.md +30 -21
  69. package/docs/odd-preparation-continuity.md +24 -0
  70. package/docs/permission-modes.md +17 -4
  71. package/docs/prompt-budget.md +12 -0
  72. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  73. package/docs/readme-reference.md +142 -45
  74. package/docs/render-cache-performance.md +11 -1
  75. package/docs/review-coordinator.md +53 -0
  76. package/docs/review-delivery-preflight.md +22 -0
  77. package/docs/review-request-context.md +19 -0
  78. package/docs/review-windows-acl.md +18 -0
  79. package/docs/voice.md +6 -3
  80. package/docs/work-continuity.md +11 -1
  81. package/docs/yolo-mode.md +5 -5
  82. package/extensions/ask-user-choice.ts +1 -0
  83. package/extensions/ask-user-question.ts +3 -2
  84. package/extensions/child-context.ts +21 -7
  85. package/extensions/child-safety.ts +3 -0
  86. package/extensions/gentle-agent-status.ts +99 -0
  87. package/extensions/gentle-agents.ts +559 -66
  88. package/extensions/gentle-ai.ts +2001 -518
  89. package/extensions/gentle-design.ts +69 -3
  90. package/extensions/gentle-desktop-rpc.ts +143 -0
  91. package/extensions/gentle-guide.ts +3 -0
  92. package/extensions/gentle-shell.ts +398 -115
  93. package/extensions/gentle-todo.ts +66 -27
  94. package/extensions/gentle-tps.ts +48 -0
  95. package/extensions/quiet-tools.ts +38 -8
  96. package/extensions/skill-registry.ts +349 -167
  97. package/extensions/startup-banner.ts +30 -3
  98. package/lib/agent-assets.ts +30 -6
  99. package/lib/agent-profile-pin.ts +3 -3
  100. package/lib/agent-profiles.ts +160 -2
  101. package/lib/agent-status.ts +105 -0
  102. package/lib/agent-tool-overlay.ts +117 -0
  103. package/lib/agents-config.ts +93 -6
  104. package/lib/agents-history.ts +24 -5
  105. package/lib/agents-message-delivery.ts +17 -0
  106. package/lib/agents-messaging.ts +55 -7
  107. package/lib/agents-protocol.ts +15 -0
  108. package/lib/agents-report-cap.ts +115 -0
  109. package/lib/agents-runner.ts +272 -16
  110. package/lib/agents-session-transport.ts +17 -1
  111. package/lib/auto-permission-runtime.ts +1 -1
  112. package/lib/background-jobs-tools.ts +9 -4
  113. package/lib/bounded-writer-admission.ts +197 -32
  114. package/lib/card-content-policy.ts +8 -6
  115. package/lib/child-context-files.ts +21 -6
  116. package/lib/codemode-renderer.ts +1 -0
  117. package/lib/command-palette.ts +133 -17
  118. package/lib/context-backstop.ts +14 -5
  119. package/lib/delivery-conflict-markers.ts +349 -0
  120. package/lib/design-canvas-assets.ts +36 -0
  121. package/lib/design-canvas-server.ts +241 -23
  122. package/lib/design-comments.ts +94 -4
  123. package/lib/design-handoffs.ts +2 -1
  124. package/lib/design-layout.ts +125 -0
  125. package/lib/design-parts.ts +281 -0
  126. package/lib/design-system-tokens.ts +111 -0
  127. package/lib/desktop-agents-service.ts +294 -0
  128. package/lib/desktop-design-service.ts +233 -0
  129. package/lib/desktop-jobs-service.ts +263 -0
  130. package/lib/desktop-rpc-agents.ts +294 -0
  131. package/lib/desktop-rpc-config.ts +731 -0
  132. package/lib/desktop-rpc-design.ts +138 -0
  133. package/lib/desktop-rpc-jobs.ts +181 -0
  134. package/lib/desktop-rpc-permissions.ts +177 -0
  135. package/lib/desktop-rpc-profiles.ts +196 -0
  136. package/lib/desktop-rpc-usage.ts +229 -0
  137. package/lib/desktop-rpc.ts +225 -0
  138. package/lib/desktop-usage-service.ts +310 -0
  139. package/lib/destructive-command-guard.ts +236 -17
  140. package/lib/execution-surface-guard.ts +20 -0
  141. package/lib/exploration-budget.ts +4 -2
  142. package/lib/gentle-ai-binary.ts +1 -1
  143. package/lib/gentle-ai-renderer.ts +13 -1
  144. package/lib/gentle-design.ts +204 -14
  145. package/lib/gentle-shell-bundled.ts +106 -28
  146. package/lib/gentle-shell-launcher.ts +43 -8
  147. package/lib/herdr-activity.ts +14 -2
  148. package/lib/herdr-busy.ts +45 -0
  149. package/lib/hidden-tools.ts +35 -0
  150. package/lib/image-attachments.ts +33 -0
  151. package/lib/image-disk-cache.ts +137 -0
  152. package/lib/inprocess-reviewer.ts +358 -144
  153. package/lib/jobs-view.ts +198 -11
  154. package/lib/model-fallback-policy.ts +9 -0
  155. package/lib/model-routing-authority.ts +31 -4
  156. package/lib/nan-provider.ts +42 -28
  157. package/lib/native-choice-list.ts +20 -2
  158. package/lib/native-review-cli.ts +172 -20
  159. package/lib/orchestrator-discovery.ts +39 -2
  160. package/lib/orchestrator-mode-policy.ts +105 -0
  161. package/lib/questionnaire/questionnaire-view.ts +105 -12
  162. package/lib/rdd-mode-control.ts +32 -0
  163. package/lib/reply-language-anchor.ts +129 -0
  164. package/lib/request-context-placement.ts +53 -0
  165. package/lib/review-blocker.ts +92 -0
  166. package/lib/review-candidate-symlink-scan.ts +136 -0
  167. package/lib/review-candidate-view-owner.ts +81 -44
  168. package/lib/review-candidate-view.ts +11 -1
  169. package/lib/review-continuation-registry.ts +116 -0
  170. package/lib/review-coordinator.ts +407 -0
  171. package/lib/review-delivery-preflight.ts +85 -0
  172. package/lib/review-failure-facts.ts +49 -0
  173. package/lib/review-host-relay.ts +51 -11
  174. package/lib/review-integration-v2.ts +63 -4
  175. package/lib/review-relay-phase-timing.ts +45 -0
  176. package/lib/review-start-context.ts +17 -0
  177. package/lib/reviewer-stream.ts +87 -0
  178. package/lib/session-profile-freeze.ts +4 -2
  179. package/lib/shell-bar.ts +140 -58
  180. package/lib/shell-changes.ts +2 -0
  181. package/lib/shell-panel.ts +17 -3
  182. package/lib/shell-prompt.ts +16 -3
  183. package/lib/shell-sidebar-layout.ts +112 -40
  184. package/lib/shell-sidebar.ts +7 -0
  185. package/lib/shell-todo.ts +10 -3
  186. package/lib/shell-usage.ts +10 -0
  187. package/lib/verifier-admission.ts +1 -1
  188. package/lib/vim-editor-adapter.ts +9 -2
  189. package/lib/visual-customization-policy.ts +36 -16
  190. package/lib/visual-customize-view.ts +216 -21
  191. package/lib/visual-layout-preview.ts +9 -5
  192. package/lib/visual-profiles.ts +2 -2
  193. package/lib/windows-session-transport.ts +53 -2
  194. package/lib/writer-batch-admission.ts +55 -0
  195. package/lib/yolo-session-policy.ts +46 -16
  196. package/package.json +3 -2
  197. package/prompts/skill-creation.md +1 -10
  198. package/runtime/design-canvas-assets.mjs +37 -0
  199. package/runtime/gentle-ai-binary.mjs +1 -1
  200. package/runtime/gentle-shell-bundled.mjs +106 -28
  201. package/runtime/gentle-shell-launcher.mjs +42 -7
  202. package/runtime/native-review-cli.mjs +169 -17
  203. package/runtime/review-integration-v2.mjs +63 -4
  204. package/scripts/bootstrap.cmd +2 -2
  205. package/scripts/bootstrap.sh +41 -4
  206. package/scripts/build-full-delegation-card.mjs +179 -0
  207. package/scripts/build-runtime-modules.mjs +1 -0
  208. package/scripts/bundled-install.mjs +38 -8
  209. package/scripts/download-progress.mjs +68 -0
  210. package/scripts/gentle-ai-installer.mjs +41 -18
  211. package/scripts/gentle-ai-proxy.mjs +294 -0
  212. package/scripts/install-gentle-ai.mjs +14 -1
  213. package/scripts/installer-downloads.mjs +34 -8
  214. package/scripts/installer-preflight.mjs +33 -22
  215. package/scripts/installer-probes.mjs +25 -5
  216. package/scripts/installer-runner.mjs +27 -12
  217. package/scripts/installer-server.mjs +46 -16
  218. package/scripts/installer-windows.mjs +2 -2
  219. package/scripts/pi-update.mjs +166 -27
  220. package/scripts/prepare-verifier.mjs +107 -0
  221. package/scripts/render-cache-host.mjs +72 -0
  222. package/scripts/render-cache-performance-worker.mjs +5 -4
  223. package/scripts/render-cache-performance.mjs +6 -1
  224. package/scripts/run-test-suite.mjs +40 -28
  225. package/scripts/update-agent-body-history.mjs +55 -8
  226. package/scripts/verify-package-files.mjs +50 -19
  227. package/scripts/voice-worker.cjs +32 -6
  228. package/skills/branch-pr/SKILL.md +16 -16
  229. package/skills/comment-writer/SKILL.md +1 -1
  230. package/skills/design/SKILL.md +16 -13
  231. package/skills/gentle-ai/SKILL.md +7 -7
  232. package/skills/gentle-ui-design/SKILL.md +46 -0
  233. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  234. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  235. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  236. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  237. package/skills/judgment-day/SKILL.md +2 -2
  238. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  239. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  240. package/skills/skill-improver/SKILL.md +2 -2
  241. package/skills/skill-registry/SKILL.md +11 -11
  242. package/skills/tui-design/SKILL.md +1 -1
  243. package/skills/work-unit-commits/SKILL.md +10 -11
  244. package/tests/agent-home.test.ts +28 -9
  245. package/tests/agent-profiles-workflow.test.ts +163 -0
  246. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  247. package/tests/agent-risk-escalation.test.ts +1 -1
  248. package/tests/agent-status.test.ts +143 -0
  249. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  250. package/tests/agent-tool-overlay.test.ts +89 -0
  251. package/tests/agents-config.test.ts +106 -1
  252. package/tests/agents-history.test.ts +31 -0
  253. package/tests/agents-jobs-frames.test.ts +93 -0
  254. package/tests/agents-message-delivery.test.ts +36 -0
  255. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  256. package/tests/agents-queries.test.ts +144 -4
  257. package/tests/agents-report-cap.test.ts +126 -0
  258. package/tests/agents-runner-drain.test.ts +193 -0
  259. package/tests/agents-runner.test.ts +215 -3
  260. package/tests/agents-session-transport.test.ts +34 -0
  261. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  262. package/tests/append-system-prompt-route.test.ts +12 -1
  263. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  264. package/tests/artifact-language.test.ts +1 -1
  265. package/tests/ask-user-choice.test.ts +4 -3
  266. package/tests/ask-user-question.test.ts +99 -1
  267. package/tests/audit-leftovers-contract.test.ts +51 -0
  268. package/tests/auto-permission-runtime.test.ts +1 -1
  269. package/tests/autonomous-guard.test.ts +346 -10
  270. package/tests/bounded-stop-contract.test.ts +51 -3
  271. package/tests/branch-pr-skill.test.ts +10 -1
  272. package/tests/bridge-cost.test.ts +19 -4
  273. package/tests/bundled-install.test.ts +31 -6
  274. package/tests/card-content-policy.test.ts +3 -3
  275. package/tests/chained-pr-skill.test.ts +8 -6
  276. package/tests/child-context-files.test.ts +64 -8
  277. package/tests/child-safety.test.ts +11 -0
  278. package/tests/child-skills-catalog.test.ts +56 -0
  279. package/tests/codegraph-tools.test.ts +11 -5
  280. package/tests/codemode-rendering.test.ts +4 -1
  281. package/tests/command-palette.test.ts +284 -1
  282. package/tests/delegate-for-reason-contract.test.ts +32 -10
  283. package/tests/delivery-conflict-markers.test.ts +348 -0
  284. package/tests/design-canvas-all-sizes.test.ts +631 -0
  285. package/tests/design-canvas-allowlist.test.ts +32 -0
  286. package/tests/design-canvas-assets.test.ts +11 -695
  287. package/tests/design-canvas-boards.test.ts +77 -0
  288. package/tests/design-canvas-checks.test.ts +655 -0
  289. package/tests/design-canvas-compare.test.ts +79 -0
  290. package/tests/design-canvas-events.test.ts +59 -0
  291. package/tests/design-canvas-export.test.ts +1168 -0
  292. package/tests/design-canvas-focus.test.ts +113 -0
  293. package/tests/design-canvas-handoffs.test.ts +59 -0
  294. package/tests/design-canvas-i18n-review.test.ts +513 -0
  295. package/tests/design-canvas-i18n-views.test.ts +259 -0
  296. package/tests/design-canvas-i18n.test.ts +526 -0
  297. package/tests/design-canvas-inspector.test.ts +937 -0
  298. package/tests/design-canvas-layout.test.ts +1222 -0
  299. package/tests/design-canvas-minimap.test.ts +413 -0
  300. package/tests/design-canvas-modules.test.ts +90 -0
  301. package/tests/design-canvas-parts.test.ts +721 -0
  302. package/tests/design-canvas-rail.test.ts +799 -0
  303. package/tests/design-canvas-server.test.ts +855 -17
  304. package/tests/design-canvas-sizes.test.ts +548 -0
  305. package/tests/design-canvas-store.test.ts +180 -0
  306. package/tests/design-canvas-tokens.test.ts +965 -0
  307. package/tests/design-canvas-view.test.ts +299 -0
  308. package/tests/design-comments.test.ts +201 -1
  309. package/tests/design-handoffs.test.ts +20 -0
  310. package/tests/design-layout.test.ts +100 -0
  311. package/tests/design-parts.test.ts +260 -0
  312. package/tests/design-system-tokens.test.ts +215 -0
  313. package/tests/desktop-rpc-agents.test.ts +893 -0
  314. package/tests/desktop-rpc-config.test.ts +1452 -0
  315. package/tests/desktop-rpc-design.test.ts +662 -0
  316. package/tests/desktop-rpc-jobs.test.ts +796 -0
  317. package/tests/desktop-rpc-permissions.test.ts +311 -0
  318. package/tests/desktop-rpc-profiles.test.ts +140 -0
  319. package/tests/desktop-rpc-safety.test.ts +119 -0
  320. package/tests/desktop-rpc-usage.test.ts +697 -0
  321. package/tests/desktop-rpc.test.ts +252 -0
  322. package/tests/destructive-command-guard.test.ts +52 -0
  323. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  324. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  325. package/tests/download-progress.test.ts +71 -0
  326. package/tests/engram-safety.test.ts +111 -0
  327. package/tests/execution-surface-guard.test.ts +55 -0
  328. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  329. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  330. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +26 -31
  331. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  332. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  333. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  334. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  335. package/tests/fixtures/session-profile-v1/replay.ts +53 -6
  336. package/tests/full-delegation-closure.test.ts +160 -0
  337. package/tests/full-delegation-notices.test.ts +76 -0
  338. package/tests/generic-agent-tools.test.ts +3 -3
  339. package/tests/gentle-agent-status.test.ts +74 -0
  340. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  341. package/tests/gentle-agents.test.ts +1403 -20
  342. package/tests/gentle-ai-binary.test.ts +3 -1
  343. package/tests/gentle-ai-child-guards.test.ts +1 -0
  344. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  345. package/tests/gentle-ai-exploration-budget.test.ts +18 -2
  346. package/tests/gentle-ai-installer.test.ts +135 -51
  347. package/tests/gentle-ai-proxy.test.ts +434 -0
  348. package/tests/gentle-ai-renderer.test.ts +36 -2
  349. package/tests/gentle-ai.test.ts +233 -43
  350. package/tests/gentle-design.test.ts +386 -1
  351. package/tests/gentle-herdr-activity.test.ts +9 -6
  352. package/tests/gentle-shell-bin.test.ts +123 -0
  353. package/tests/gentle-shell-bundled.test.ts +293 -31
  354. package/tests/gentle-shell-launcher.test.ts +78 -11
  355. package/tests/gentle-shell.test.ts +1017 -146
  356. package/tests/gentle-todo.test.ts +51 -11
  357. package/tests/gentle-tps.test.ts +123 -0
  358. package/tests/gentle-ui-design-skill.test.ts +59 -0
  359. package/tests/herdr-busy.test.ts +59 -0
  360. package/tests/herdr-task-summary-policy.test.ts +8 -4
  361. package/tests/hidden-tools.test.ts +188 -0
  362. package/tests/image-disk-cache.test.ts +163 -0
  363. package/tests/independent-recovery-delivery.test.ts +97 -0
  364. package/tests/inprocess-reviewer.test.ts +249 -4
  365. package/tests/install-wizard.test.ts +27 -1
  366. package/tests/installer-downloads.test.ts +30 -1
  367. package/tests/installer-posix-bootstrap.test.ts +115 -14
  368. package/tests/installer-preflight.test.ts +54 -5
  369. package/tests/installer-probes.test.ts +146 -0
  370. package/tests/installer-runner.test.ts +79 -44
  371. package/tests/installer-server.test.ts +215 -13
  372. package/tests/installer-windows-bootstrap.test.ts +19 -1
  373. package/tests/jobs-view.test.ts +260 -6
  374. package/tests/judgment-day-severity-admission.test.ts +46 -0
  375. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  376. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  377. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  378. package/tests/modal-mouse-boundaries.test.ts +136 -0
  379. package/tests/model-fallback-policy.test.ts +26 -7
  380. package/tests/model-routing-authority.test.ts +178 -2
  381. package/tests/nan-provider-runtime.test.ts +17 -3
  382. package/tests/nan-provider.test.ts +111 -56
  383. package/tests/native-choice-list.test.ts +77 -2
  384. package/tests/native-review-capability-contract.test.ts +17 -1
  385. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  386. package/tests/native-review-cli.test.ts +269 -1
  387. package/tests/native-review-parity.test.ts +24 -5
  388. package/tests/native-review-refusal-identity.test.ts +25 -0
  389. package/tests/no-self-pause-contract.test.ts +13 -2
  390. package/tests/odd-integration.test.ts +11 -3
  391. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  392. package/tests/odd-routing-contract.test.ts +80 -28
  393. package/tests/orchestrator-budget.test.ts +35 -5
  394. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  395. package/tests/orchestrator-delegation-mode.test.ts +154 -0
  396. package/tests/orchestrator-discovery.test.ts +28 -0
  397. package/tests/orchestrator-mode-policy.test.ts +175 -0
  398. package/tests/orchestrator-prompt-budget.test.ts +13 -2
  399. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  400. package/tests/orchestrator-rdd-ownership.test.ts +4 -3
  401. package/tests/orchestrator-work-search.test.ts +4 -2
  402. package/tests/package-files.test.ts +25 -1
  403. package/tests/package-manifest.test.ts +16 -13
  404. package/tests/parallel-reason-contract.test.ts +6 -3
  405. package/tests/permission-allowlist.test.ts +372 -0
  406. package/tests/persona-neutral-voseo.test.ts +4 -4
  407. package/tests/persona-reply-language.test.ts +1 -1
  408. package/tests/persona-single-channel.test.ts +13 -5
  409. package/tests/pi-update-launcher.test.ts +25 -7
  410. package/tests/pi-update-source.test.ts +113 -6
  411. package/tests/pi-update.test.ts +294 -19
  412. package/tests/pnpm-workspace-config.test.ts +58 -0
  413. package/tests/pnpm-workspace-policy.test.ts +47 -0
  414. package/tests/primary-context-files.test.ts +233 -0
  415. package/tests/primary-context-three-files.test.ts +174 -0
  416. package/tests/primary-session-prompt.test.ts +13 -0
  417. package/tests/profile-pin.test.ts +29 -2
  418. package/tests/profile-tier-footer.test.ts +5 -0
  419. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  420. package/tests/provider-defect-handoff.test.ts +9 -2
  421. package/tests/questionnaire-view.test.ts +115 -0
  422. package/tests/quiet-bash-runtime.test.ts +1 -1
  423. package/tests/quiet-tool-rendering.test.ts +48 -0
  424. package/tests/rdd-aware-verification-contract.test.ts +17 -12
  425. package/tests/rdd-customize.test.ts +287 -0
  426. package/tests/rdd-mode-cache.test.ts +450 -0
  427. package/tests/rdd-mode-control.test.ts +407 -0
  428. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  429. package/tests/rdd-off-independent-regression.test.ts +69 -0
  430. package/tests/rdd-status-line.test.ts +112 -1
  431. package/tests/render-cache-performance.test.ts +171 -2
  432. package/tests/reply-language-anchor-placement.test.ts +184 -0
  433. package/tests/reply-language-anchor.test.ts +189 -0
  434. package/tests/request-context-append-only.test.ts +218 -0
  435. package/tests/request-context-placement.test.ts +148 -0
  436. package/tests/review-agent-end-preflight.test.ts +80 -2
  437. package/tests/review-blocker.test.ts +193 -0
  438. package/tests/review-candidate-owner-retry.test.ts +1 -1
  439. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  440. package/tests/review-candidate-view.test.ts +66 -1
  441. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  442. package/tests/review-candidate-windows-probe.test.ts +63 -0
  443. package/tests/review-committed-restart-ack.test.ts +129 -0
  444. package/tests/review-continuation-registry.test.ts +107 -0
  445. package/tests/review-contract-prompt.test.ts +1 -1
  446. package/tests/review-controller-native-routing.test.ts +261 -5
  447. package/tests/review-controller-workspace-root.test.ts +230 -3
  448. package/tests/review-controller.test.ts +98 -12
  449. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  450. package/tests/review-coordinator-findings.test.ts +206 -0
  451. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  452. package/tests/review-coordinator-runtime.test.ts +117 -0
  453. package/tests/review-coordinator.test.ts +462 -0
  454. package/tests/review-delivery-preflight.test.ts +462 -0
  455. package/tests/review-due-compaction.test.ts +31 -0
  456. package/tests/review-due-public-boundary.test.ts +26 -0
  457. package/tests/review-failure-facts.test.ts +87 -0
  458. package/tests/review-host-relay-routing.test.ts +258 -4
  459. package/tests/review-host-relay.test.ts +39 -0
  460. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  461. package/tests/review-integration-v2.test.ts +46 -3
  462. package/tests/review-json-arguments.test.ts +105 -11
  463. package/tests/review-last-event-closure.test.ts +68 -0
  464. package/tests/review-ledger-contract.test.ts +19 -40
  465. package/tests/review-loadout-rdd-off-sdk.test.ts +95 -32
  466. package/tests/review-one-call-findings.test.ts +131 -0
  467. package/tests/review-one-call-followups.test.ts +308 -0
  468. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  469. package/tests/review-one-call.test.ts +452 -0
  470. package/tests/review-owner-identity.test.ts +60 -24
  471. package/tests/review-relay-phase-timing.test.ts +128 -0
  472. package/tests/review-relay-transport-agent.test.ts +39 -2
  473. package/tests/review-reviewer-evidence.test.ts +223 -0
  474. package/tests/review-risk-assessment.test.ts +126 -8
  475. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  476. package/tests/review-session-standing-permission-controller.test.ts +53 -3
  477. package/tests/review-start-context.test.ts +19 -0
  478. package/tests/review-tool-prose-budget.test.ts +122 -0
  479. package/tests/reviewer-stream.test.ts +149 -0
  480. package/tests/run-test-suite.test.ts +122 -1
  481. package/tests/runtime-harness.mjs +4 -1
  482. package/tests/sensitive-path-tools.test.ts +181 -5
  483. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  484. package/tests/session-profile-binding.test.ts +19 -1
  485. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  486. package/tests/session-profile-extension.test.ts +2 -2
  487. package/tests/session-profile-v1-compat.test.ts +35 -1
  488. package/tests/shell-bar.test.ts +186 -42
  489. package/tests/shell-panel.test.ts +50 -22
  490. package/tests/shell-prompt.test.ts +17 -0
  491. package/tests/shell-sidebar-fullscreen.test.ts +5 -5
  492. package/tests/shell-sidebar-layout.test.ts +294 -23
  493. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  494. package/tests/shell-surface-transparent.test.ts +89 -0
  495. package/tests/shell-todo.test.ts +12 -0
  496. package/tests/shell-usage.test.ts +59 -10
  497. package/tests/skill-contradictions-contract.test.ts +122 -0
  498. package/tests/skill-registry-watcher.test.ts +216 -2
  499. package/tests/skill-registry.test.ts +1461 -5
  500. package/tests/startup-banner.test.ts +152 -1
  501. package/tests/startup-home-repo.test.ts +2 -0
  502. package/tests/support/design-canvas-dom.ts +369 -0
  503. package/tests/support/review-coordinator-runtime.ts +264 -0
  504. package/tests/task-size-routing-contract.test.ts +45 -12
  505. package/tests/test-strength-contract.test.ts +2 -1
  506. package/tests/todo-request-append-only.test.ts +214 -0
  507. package/tests/tool-batching-contract.test.ts +3 -1
  508. package/tests/update-agent-body-history.test.ts +138 -0
  509. package/tests/verification-tiers-contract.test.ts +229 -0
  510. package/tests/verifier-admission.test.ts +49 -0
  511. package/tests/verifier-preparation.test.ts +229 -0
  512. package/tests/verify-agent-contract.test.ts +20 -2
  513. package/tests/verify-first-launch-contract.test.ts +162 -11
  514. package/tests/vim-editor-adapter.test.ts +2 -2
  515. package/tests/visual-customization-policy.test.ts +39 -6
  516. package/tests/visual-customize-view.test.ts +573 -9
  517. package/tests/visual-layout-preview.test.ts +15 -1
  518. package/tests/visual-profiles.test.ts +11 -0
  519. package/tests/voice-worker.test.ts +73 -2
  520. package/tests/windows-session-transport.test.ts +126 -0
  521. package/tests/work-continuity-contract.test.ts +77 -6
  522. package/tests/writer-admission-messages.test.ts +232 -0
  523. package/tests/writer-batch-admission.test.ts +66 -0
  524. package/tests/writer-edit-surface-scope.test.ts +52 -20
  525. package/tests/writer-feature-document-admission.test.ts +276 -0
  526. package/tests/yolo-customize.test.ts +27 -4
  527. package/tests/yolo-mode.test.ts +62 -18
  528. package/tests/yolo-session-policy.test.ts +270 -1
  529. package/skills/_shared/review-ledger-contract.md +0 -106
  530. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  531. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  532. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  533. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  534. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  535. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  536. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -22,8 +22,10 @@ import { join, resolve, isAbsolute } from "node:path";
22
22
  import { fileURLToPath } from "node:url";
23
23
  import { createLocalBashOperations, keyHint, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
24
24
  import { createJobRegistry, isStandaloneSleep, type JobExecOperations, type JobRecord } from "../lib/background-jobs.ts";
25
- import { JOB_GLYPH, JOB_NOTICE_TYPE, jobDetails, jobNoticeText, monitorEventsText, monitorStoppedText, registerBackgroundJobTools } from "../lib/background-jobs-tools.ts";
25
+ import { JOB_GLYPH, JOB_NOTICE_TYPE, jobDetails, jobNoticeText, monitorEventsText, monitorStoppedText, registerBackgroundJobTools, type BackgroundJobsChange } from "../lib/background-jobs-tools.ts";
26
26
  import { createMonitorController, mergeMonitorBatches, type MonitorNotice } from "../lib/background-monitor.ts";
27
+ import { DESKTOP_JOBS_SERVICE_CHANNEL, DESKTOP_JOBS_SERVICE_SCHEMA, projectDesktopJob, selectDesktopJobs, type DesktopJobsCancelOutcome, type DesktopJobsOwnerRead, type DesktopJobsService } from "../lib/desktop-rpc-jobs.ts";
28
+ import { DESKTOP_AGENTS_SERVICE_CHANNEL, DESKTOP_AGENTS_SERVICE_SCHEMA, accumulateTaskUsage, projectDesktopAgent, selectDesktopAgents, type DesktopAgentsCancelOutcome, type DesktopAgentsOwnerRead, type DesktopAgentsService } from "../lib/desktop-rpc-agents.ts";
27
29
  import { JobsView } from "../lib/jobs-view.ts";
28
30
  import { JOBS_FINISHED_TTL_MS } from "../lib/jobs-widget.ts";
29
31
  import { JOBS_SIDEBAR_EVENT, JOBS_STATUS_KEY } from "../lib/jobs-sidebar-state.ts";
@@ -34,6 +36,7 @@ import { NativePointerRegion } from "../lib/native-pointer-region.ts";
34
36
  import { resolveVisualSettings } from "../lib/visual-customization-policy.ts";
35
37
  import { createCompletionQueue } from "../lib/agents-completion-delivery.ts";
36
38
  import { createAgentMessageQueue, type PendingAgentMessage } from "../lib/agents-message-delivery.ts";
39
+ import { capReport, withReportCap } from "../lib/agents-report-cap.ts";
37
40
  import { parseModelRef, AGENT_MODE, PROFILE_SOURCE, PROVIDER_REVIEW_ROLES, discoverAgents, formatModelRef, loadAgentsConfig, resolveAgentProfile, unmatchedProfileKeys, withPinnedModelProfiles, type AgentDefinition, type AgentMode, type ProfileSource } from "../lib/agents-config.ts";
38
41
  import { freezeSessionProfileAtStartup, inheritedProfileDriftNotice, resolveSessionProfile, sessionProfileRoutingAt, type InheritedProfileOptions, type SessionProfileResolution } from "../lib/session-profile-freeze.ts";
39
42
  import { resolveProfilePin, resolveUnversionedProjectProfile } from "../lib/agent-profile-pin.ts";
@@ -41,14 +44,14 @@ import { requireSessionProfileAuthority } from "../lib/session-profile-authority
41
44
  import { resolveBackgroundSubagentsPolicy } from "../lib/background-subagents-policy.ts";
42
45
  import { installBackgroundCacheWarming } from "../lib/background-cache-warming.ts";
43
46
  import { isFinished, MISSING_TOOLS_NOTE_PREFIX, TASK_EVENT, TASK_STATUS, TaskStore, type AskRequest, type TaskRecord } from "../lib/agents-protocol.ts";
44
- import { AgentRunner, piCommand, abortReasonText, REQUESTED_TOOLS_ENV, type AskAnswer, type RunnerDeps, type TaskRequest } from "../lib/agents-runner.ts";
47
+ import { AgentRunner, piCommand, abortReasonText, CHILD_JOBS_ENV, REQUESTED_TOOLS_ENV, type AskAnswer, type RunnerDeps, type TaskRequest } from "../lib/agents-runner.ts";
45
48
  import { parseChildPackageInjection } from "../lib/child-package-injection.ts";
46
- import { ChildMessenger, type IpcEndpoint } from "../lib/agents-messaging.ts";
49
+ import { CHILD_MESSAGE_MAX_BYTES, ChildMessenger, formatChildJobState, type IpcEndpoint } from "../lib/agents-messaging.ts";
47
50
  import { ActiveSessionClient, ActiveSessionListener, SessionPresenceError, SessionPresenceRegistry, type PresenceRecord, type ReceivedNotification, type SentNotification, type SessionPresenceCandidate } from "../lib/agents-session-transport.ts";
48
- import { WindowsActiveSessionClient, WindowsActiveSessionListener, WindowsSessionPresenceRegistry, type WindowsSessionRegistryPhaseObserver } from "../lib/windows-session-transport.ts";
51
+ import { WindowsActiveSessionClient, WindowsActiveSessionListener, WindowsSessionPresenceRegistry, WindowsSessionRegistryPhaseSequence, isWindowsSessionBootstrapDiagnosticCode, type WindowsSessionBootstrapDiagnosticCode, type WindowsSessionBootstrapDiagnosticObserver, type WindowsSessionRegistryPhaseObserver } from "../lib/windows-session-transport.ts";
49
52
  import { hasReviewSessionPermission, resolveCanonicalGitRepositoryIdentitySync, type ReviewSessionManager } from "../lib/review-session-standing-permission.ts";
50
53
  import { inheritedUnsafeGitEnvironmentKeys } from "../lib/review-repository.ts";
51
- import { historyDir, loadHistory, loadStoredTask, pruneHistory, saveTask } from "../lib/agents-history.ts";
54
+ import { historyDir, loadHistory, loadStoredTask, pruneHistory, saveTask, type StoredTask } from "../lib/agents-history.ts";
52
55
  import { sessionToMarkdown } from "../lib/agents-transcript.ts";
53
56
  import { AgentsView } from "../lib/agents-view.ts";
54
57
  import { withOverlayRepaint } from "../lib/overlay-repaint.ts";
@@ -67,6 +70,7 @@ import { OrchestratorScopeCache, type RepositoryFact } from "../lib/orchestrator
67
70
  import { createRpcActivityPublisher, type RpcActivityPublisher } from "../lib/agents-rpc-publisher.ts";
68
71
  import { isInteractiveRpcHost } from "../lib/rpc-host.ts";
69
72
  import { createNativeFullscreenInteraction } from "../lib/native-fullscreen-interaction.ts";
73
+ import { HERDR_BUSY_CHANNEL, nextHerdrBusyAction, type HerdrBusyEmitted } from "../lib/herdr-busy.ts";
70
74
  import { AGENTS_GLYPH, agentsCardTone, agentsSpend, agentsSummary, renderAgentsAlert, renderAgentsCard, renderAgentsSection, widgetExpiryMs, widgetRows } from "../lib/agents-widget.ts";
71
75
  import { CARD_TONE, cardAwaitingResult, cardBodyRows, cardBottom, cardInnerWidth, cardRunningLine, cardTop, floatRows, headingFits, markCardResult, panelHeaderRow, panelInnerWidth, renderCard, type CardRowContext, type CardTheme, type CardTone } from "../lib/shell-card.ts";
72
76
  import { openInExternalEditor } from "./gentle-shell.ts";
@@ -76,6 +80,8 @@ import { allowedEditSurfaces, inheritAllowedEditSurfaces, isBoundedWriter, isDev
76
80
  import { CHILD_METRICS_EVENT, CHILD_METRICS_REVOKED, childEvent, launchSelection, type LaunchSelection } from "../lib/runtime-metrics-children.ts";
77
81
  import { runtimeMetricsEnvAllows, type RuntimeMetricsPolicyDeps } from "../lib/runtime-metrics-policy.ts";
78
82
  import { publishTaskStatusChanges } from "../lib/notification-events.ts";
83
+ import { appendSystemPromptOnce } from "../lib/append-system-prompt.ts";
84
+ import { codemodeReaches, COORDINATION_TOOLS_ROUTE, hideBehindCodemode } from "../lib/hidden-tools.ts";
79
85
 
80
86
  // Gentle Agents: subagents as isolated `pi --mode rpc` children, a task
81
87
  // store that notifies per task, and a Gentle Shell card above the editor.
@@ -100,6 +106,31 @@ function messagePeerLabel(profile: string, sessionId: string): string | undefine
100
106
  return matches.length === 1 && matches[0].recent ? sanitizeDisplayLabel(matches[0].label) || undefined : undefined;
101
107
  } catch { return undefined; }
102
108
  }
109
+ /** Human-readable labels for the recipient picker. A raw session id gives a person
110
+ * nothing to choose by, so the published session label and the workspace are used when
111
+ * they exist, and a short id suffix keeps every label unique: the chosen label is mapped
112
+ * back to a peer by exact match, so a collision would select the wrong one. */
113
+ function recipientSelectionLabels(profile: string, candidates: readonly PresenceRecord[], activations: readonly PresenceRecord[] = candidates): string[] {
114
+ let discovered: ReturnType<typeof discoverOrchestrators> = [];
115
+ // Discovery must see every activation: it fails closed when one session resolves to
116
+ // several, and deduplicating before this point would silently label an ambiguous peer.
117
+ try { discovered = discoverOrchestrators(profile, activations); } catch { /* labels are best-effort, never routing */ }
118
+ const peersById = new Map(discovered.map(peer => [peer.sessionId, peer] as const));
119
+ const bases = candidates.map((candidate) => {
120
+ const peer = peersById.get(candidate.sessionId);
121
+ const name = peer?.label ?? peer?.legacyLabel;
122
+ if (!name) return "Orchestrator";
123
+ const workspace = peer?.workspace?.split(/[\\/]/).filter(Boolean).at(-1);
124
+ return workspace && workspace !== name ? `${name} (${workspace})` : name;
125
+ });
126
+ // Short ids stay whole (fixtures and test sessions); long ones are suffixed.
127
+ const suffix = (sessionId: string, length: number): string => sessionId.length <= 8 ? sessionId : sessionId.slice(-length);
128
+ for (const length of [4, 6, 8]) {
129
+ const labels = bases.map((base, index) => `${base} · ${suffix(candidates[index]!.sessionId, length)}`);
130
+ if (new Set(labels).size === labels.length) return labels;
131
+ }
132
+ return bases.map((base, index) => `${base} · ${candidates[index]!.sessionId}`);
133
+ }
103
134
  export const AGENTS_STALE_RESULT_TYPE = "gentle-agents.stale-result";
104
135
  export const AGENTS_STALE_NOTICE_TYPE = "gentle-agents.stale-notice";
105
136
  const RENDER_COALESCE_MS = 400;
@@ -125,6 +156,12 @@ const NATIVE_PARENT_WAKE_TEXT = `${PARENT_WAKE_TEXT} Reply in the language of th
125
156
  // How long a dispatched wake may take to start a parent run before a later
126
157
  // delivery may send another one.
127
158
  export const PARENT_WAKE_GRACE_MS = 30_000;
159
+ // How often a parent that is busy without a run is re-checked while content is
160
+ // held for it. See `armHoldRecheck`.
161
+ export const HOLD_RECHECK_MS = 1000;
162
+ // How long a user prompt seen at `input` suppresses the idle wake while it is
163
+ // still in its pre-run phase. See the `input` handler.
164
+ export const INPUT_PROMPT_GRACE_MS = 2000;
128
165
  // A delivery or wake the host rejected while the parent was idle is retried
129
166
  // after the grace at most this many times in a row, so a permanently broken
130
167
  // runtime never retries forever.
@@ -152,7 +189,7 @@ export interface SessionTransportClient {
152
189
  }
153
190
 
154
191
  export interface SessionTransportFactory {
155
- createRegistry(agentHome: string, observeWindowsPhase?: WindowsSessionRegistryPhaseObserver): Promise<SessionTransportRegistry>;
192
+ createRegistry(agentHome: string, observeWindowsPhase?: WindowsSessionRegistryPhaseObserver, observeWindowsBootstrap?: WindowsSessionBootstrapDiagnosticObserver): Promise<SessionTransportRegistry>;
156
193
  createListener(registry: SessionTransportRegistry, sessionId: string, onNotification: (notification: ReceivedNotification) => Promise<void>): SessionTransportListener;
157
194
  createClient(registry: SessionTransportRegistry, sessionId: string): SessionTransportClient;
158
195
  }
@@ -383,6 +420,46 @@ function registerChildMessaging(pi: ExtensionAPI, ipc: IpcEndpoint): void {
383
420
  });
384
421
  }
385
422
 
423
+ // gentle-shell#2266: a child admitted for background jobs registers the tools
424
+ // against its own private registry and reports its job state back over owned
425
+ // IPC, so the runner can drain one bounded window at settlement instead of
426
+ // killing a job mid-flight. The monitor stays parent-only.
427
+ function registerChildBackgroundJobs(pi: ExtensionAPI, env: NodeJS.ProcessEnv, overrides: Partial<AgentsDeps>, ipc: IpcEndpoint): void {
428
+ const home = overrides.home ?? os.homedir();
429
+ const agentHome = overrides.agentHome ?? resolveAgentHomeDirectory({ env, home, agentHome: overrides.agentHome, homeOverridden: overrides.home !== undefined });
430
+ const now = overrides.now ?? (() => Date.now());
431
+ let outputDir: string | undefined;
432
+ let nextFrame = 0;
433
+ const reportJobs = (): void => {
434
+ const running = jobs.running();
435
+ try { ipc.send({ id: `j${++nextFrame}`, kind: "job", message: formatChildJobState({ running, pending: running > 0 }) }); }
436
+ catch { /* A lost report only costs the drain, never the job. */ }
437
+ };
438
+ const jobs = createJobRegistry({
439
+ outputDir: overrides.jobOutputDir ?? (() => (outputDir ??= mkdtempSync(join(os.tmpdir(), "gentle-jobs-")))),
440
+ now,
441
+ shell: overrides.jobShell ?? ((cwd) => {
442
+ const settings = SettingsManager.create(cwd, agentHome);
443
+ return { operations: createLocalBashOperations({ shellPath: settings.getShellPath() }), commandPrefix: settings.getShellCommandPrefix() };
444
+ }),
445
+ onSettled: (job: JobRecord) => {
446
+ reportJobs();
447
+ try { pi.sendMessage({ customType: JOB_NOTICE_TYPE, content: jobNoticeText(job), display: true, details: jobDetails(job) }, { deliverAs: "steer", triggerTurn: true }); }
448
+ catch { /* The notice is best-effort; the job outcome and the drain still stand. */ }
449
+ },
450
+ });
451
+ registerBackgroundJobTools(pi, { registry: jobs, sessionId: (ctx) => ctx.sessionManager.getSessionId() ?? "", now, onChange: reportJobs });
452
+ // agent_settled reports the jobs still running so the runner can drain before
453
+ // it requests the orderly shutdown.
454
+ pi.on("agent_settled", () => reportJobs());
455
+ pi.on("session_shutdown", () => {
456
+ if (!outputDir) return;
457
+ const dir = outputDir;
458
+ outputDir = undefined;
459
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* A leftover temp directory is harmless. */ }
460
+ });
461
+ }
462
+
386
463
  const posixSessionTransport: SessionTransportFactory = {
387
464
  createRegistry(agentHome) { return SessionPresenceRegistry.create(agentHome); },
388
465
  createListener(registry: SessionPresenceRegistry, sessionId, onNotification) { return Object.assign(new ActiveSessionListener(registry, sessionId, onNotification), { closesRegistry: false }); },
@@ -390,7 +467,7 @@ const posixSessionTransport: SessionTransportFactory = {
390
467
  };
391
468
 
392
469
  const windowsSessionTransport: SessionTransportFactory = {
393
- createRegistry(agentHome, observeWindowsPhase) { return WindowsSessionPresenceRegistry.create(agentHome, observeWindowsPhase); },
470
+ createRegistry(agentHome, observeWindowsPhase, observeWindowsBootstrap) { return WindowsSessionPresenceRegistry.create(agentHome, observeWindowsPhase, observeWindowsBootstrap); },
394
471
  createListener(registry: WindowsSessionPresenceRegistry, sessionId, onNotification) { return Object.assign(new WindowsActiveSessionListener(registry, sessionId, onNotification), { closesRegistry: true }); },
395
472
  createClient(registry: WindowsSessionPresenceRegistry, sessionId) { return new WindowsActiveSessionClient(registry, sessionId); },
396
473
  };
@@ -630,9 +707,9 @@ export function resolveDefaultSubagentMode(input: {
630
707
 
631
708
  // What the model reads when a background task ends: the outcome first, then
632
709
  // the answer itself. The expanded card shows the same text.
633
- export function completionText(task: TaskRecord): string {
710
+ export function completionText(task: TaskRecord, report: string = finishedText(task)): string {
634
711
  const outcome = task.status === "completed" ? "finished" : task.status.replace("_", " ");
635
- return `Subagent ${task.agent} (task ${task.id}, "${task.label}") ${outcome}.\n\n${finishedText(task)}`;
712
+ return `Subagent ${task.agent} (task ${task.id}, "${task.label}") ${outcome}.\n\n${report}`;
636
713
  }
637
714
 
638
715
  const COMPLETION_HEADER = /^Subagent [^\n]+ \(task [^\n]*\) [^\n]+\.$/;
@@ -681,7 +758,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
681
758
  pi.on("tool_call", () => ({ block: true, reason: "Retired SDD child launch is not supported." }));
682
759
  return;
683
760
  }
684
- if (childIpc) registerChildMessaging(pi, childIpc);
761
+ if (childIpc) {
762
+ registerChildMessaging(pi, childIpc);
763
+ if (env[CHILD_JOBS_ENV] === "1") registerChildBackgroundJobs(pi, env, overrides, childIpc);
764
+ }
685
765
  registerMissingToolsCheck(pi, env);
686
766
  return;
687
767
  }
@@ -708,6 +788,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
708
788
  const stopStatusNotifications = publishTaskStatusChanges(store, pi.events, () => performance.now());
709
789
  pi.on("session_shutdown", () => { stopStatusNotifications(); });
710
790
  const restoredTaskIds = new Set<string>();
791
+ // The latest resumed-session history restoration; list_tasks waits for it.
792
+ let sessionRestoration: Promise<void> = Promise.resolve();
711
793
  const tasksDir = historyDir(deps.home, agentHome);
712
794
  let ui: ExtensionContext["ui"] | undefined;
713
795
  // The session that owns the Agents widget, so a click on an agent row opens its /gentle:agents view.
@@ -941,6 +1023,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
941
1023
  type SessionTransport = { generation: number; sessionId: string; sessionManager: ExtensionContext["sessionManager"]; client: SessionTransportClient; listener: SessionTransportListener; registry: SessionTransportRegistry; close(): Promise<void> };
942
1024
  let transportGeneration = 0;
943
1025
  let activeSessionTransport: SessionTransport | undefined;
1026
+ // A session whose first startup failed gets exactly one later re-arm attempt.
1027
+ let transportRearm: { sessionManager: ExtensionContext["sessionManager"]; sessionId: string; ctx: ExtensionContext } | undefined;
944
1028
  const pendingTransportStartups = new Set<Promise<void>>();
945
1029
  const validTransportSessionId = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value);
946
1030
  const closeSessionTransport = async (transport: SessionTransport | undefined) => {
@@ -952,16 +1036,22 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
952
1036
  operation.then(() => { pendingTransportStartups.delete(operation); }, () => { pendingTransportStartups.delete(operation); });
953
1037
  return operation;
954
1038
  };
955
- const startSessionTransport = (ctx: ExtensionContext) => {
1039
+ const startSessionTransport = (ctx: ExtensionContext, rearm = false) => {
956
1040
  const previous = activeSessionTransport;
957
1041
  const generation = ++transportGeneration;
958
1042
  const sessionManager = ctx.sessionManager;
959
1043
  activeSessionTransport = undefined;
1044
+ transportRearm = undefined;
960
1045
  const operation = (async () => {
961
1046
  let registry: SessionTransportRegistry | undefined;
962
1047
  let listener: SessionTransportListener | undefined;
963
1048
  let client: SessionTransportClient | undefined;
964
1049
  let closePromise: Promise<void> | undefined;
1050
+ let sessionId: string | undefined;
1051
+ let startupPhase: "registry" | "listener" = "registry";
1052
+ const phases = new WindowsSessionRegistryPhaseSequence();
1053
+ let bootstrap: WindowsSessionBootstrapDiagnosticCode | undefined;
1054
+ const observeBootstrap = (code: WindowsSessionBootstrapDiagnosticCode) => { if (bootstrap === undefined && isWindowsSessionBootstrapDiagnosticCode(code)) bootstrap = code; return undefined; };
965
1055
  const closeStartupTransport = () => {
966
1056
  if (closePromise) return closePromise;
967
1057
  closePromise = Promise.resolve().then(async () => {
@@ -975,17 +1065,18 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
975
1065
  };
976
1066
  try {
977
1067
  if (previous) trackTransportOperation(closeSessionTransport(previous));
978
- const sessionId = sessionManager.getSessionId();
1068
+ sessionId = sessionManager.getSessionId();
979
1069
  if (!validTransportSessionId(sessionId) || sessions !== sessionManager || generation !== transportGeneration) return;
980
- registry = await sessionTransport.createRegistry(agentHome);
1070
+ registry = await sessionTransport.createRegistry(agentHome, (event) => phases.observe(event), observeBootstrap);
981
1071
  if (sessions !== sessionManager || generation !== transportGeneration) {
982
1072
  await closeStartupTransport();
983
1073
  return;
984
1074
  }
1075
+ startupPhase = "listener";
985
1076
  listener = sessionTransport.createListener(registry, sessionId, async (notification) => {
986
1077
  const active = activeSessionTransport;
987
1078
  if (!active || active.generation !== generation || active.sessionManager !== sessionManager || active.sessionId !== sessionId || sessions !== sessionManager || activeSessionId() !== sessionId) throw new Error("stale session transport");
988
- pi.sendMessage({ customType: AGENTS_ORCHESTRATOR_MESSAGE_TYPE, content: `Session message from ${notification.senderSessionId} (correlation ${notification.id}): ${notification.message}`, display: true, details: { gentleAgents: { senderSessionId: notification.senderSessionId, recipientSessionId: sessionId, correlationId: notification.id, direction: "incoming", message: notification.message, senderLabel: messagePeerLabel(agentHome, notification.senderSessionId), recipientLabel: sanitizeDisplayLabel(sessionManager.getSessionName?.() ?? "") } } }, { deliverAs: "followUp", triggerTurn: true });
1079
+ deliverOrchestratorMessage({ customType: AGENTS_ORCHESTRATOR_MESSAGE_TYPE, content: `Session message from ${notification.senderSessionId} (correlation ${notification.id}): ${notification.message}`, display: true, details: { gentleAgents: { senderSessionId: notification.senderSessionId, recipientSessionId: sessionId, correlationId: notification.id, direction: "incoming", message: notification.message, senderLabel: messagePeerLabel(agentHome, notification.senderSessionId), recipientLabel: sanitizeDisplayLabel(sessionManager.getSessionName?.() ?? "") } } }, sessionId);
989
1080
  });
990
1081
  client = sessionTransport.createClient(registry, sessionId);
991
1082
  if (sessions !== sessionManager || generation !== transportGeneration || activeSessionId() !== sessionId) {
@@ -1009,15 +1100,35 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1009
1100
  publishActivityPrompt();
1010
1101
  } catch {
1011
1102
  if (activeSessionTransport?.generation === generation) activeSessionTransport = undefined;
1103
+ // Only fixed, validated observer fields cross the UI boundary. Never
1104
+ // interpolate the exception or report a retired session's failure.
1105
+ const current = () => sessions === sessionManager && generation === transportGeneration && validTransportSessionId(sessionId) && activeSessionId() === sessionId;
1106
+ if (current()) {
1107
+ const observation = phases.snapshot();
1108
+ const diagnostic = startupPhase === "registry" && observation.availability === "observed" && observation.firstFailurePhase !== null
1109
+ ? `phase=${observation.firstFailurePhase} class=${observation.firstFailureClass} code=${observation.firstFailureCode} lastStartupMarker=${observation.lastStartupMarker ?? "unavailable"}`
1110
+ : `phase=${startupPhase} diagnostics=unavailable`;
1111
+ try { ctx.ui.notify(`Session transport startup failed: ${diagnostic}${bootstrap ? ` bootstrap=${bootstrap}` : ""}.`, "warning"); } catch {}
1112
+ }
1012
1113
  await closeStartupTransport();
1114
+ // Armed only after cleanup, so the re-arm never overlaps the failed helper.
1115
+ if (!rearm && current()) transportRearm = { sessionManager, sessionId: sessionId!, ctx };
1013
1116
  }
1014
1117
  })();
1015
1118
  trackTransportOperation(operation);
1016
1119
  return operation;
1017
1120
  };
1121
+ // The single re-arm runs on a later session event of the same session while it
1122
+ // still has no transport; its own failure warns again and arms nothing.
1123
+ const rearmSessionTransport = (ctx: ExtensionContext | undefined) => {
1124
+ const pending = transportRearm;
1125
+ if (!pending || ctx?.sessionManager !== pending.sessionManager || sessions !== pending.sessionManager || activeSessionId() !== pending.sessionId || activeSessionTransport) return;
1126
+ void startSessionTransport(pending.ctx, true);
1127
+ };
1018
1128
  const shutdownSessionTransport = async () => {
1019
1129
  const active = activeSessionTransport;
1020
1130
  activeSessionTransport = undefined;
1131
+ transportRearm = undefined;
1021
1132
  transportGeneration++;
1022
1133
  if (active) await closeSessionTransport(active);
1023
1134
  while (pendingTransportStartups.size > 0) {
@@ -1072,6 +1183,17 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1072
1183
  .catch(() => {});
1073
1184
  };
1074
1185
 
1186
+ // A launched task is written to disk immediately so abrupt parent process
1187
+ // termination (SIGKILL, host reboot, crash) leaves a durable record (#1741).
1188
+ // Pruning is deferred until final persistence in onFinish. saveTask keeps
1189
+ // one task's writes in call order, and a task that is already terminal is
1190
+ // skipped here so its onFinish record is the last one on disk.
1191
+ const persistLaunch = (id: string) => {
1192
+ const task = store.get(id);
1193
+ if (!task || isFinished(task.status)) return;
1194
+ void saveTask(tasksDir, task, store.thread(id)).catch(() => {});
1195
+ };
1196
+
1075
1197
  // A background result used to be handed straight to the host as a followUp
1076
1198
  // message, but the host only drains that queue when the parent agent stops
1077
1199
  // calling tools entirely, so in a long orchestrator run the notification
@@ -1086,6 +1208,9 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1086
1208
  type JobNotice = { job: JobRecord; kind: "exit" } | MonitorNotice;
1087
1209
  const jobNotices: JobNotice[] = [];
1088
1210
  let jobOutputDir: string | undefined;
1211
+ // Shutdown stops every job through stopAll and then refreshes once; that
1212
+ // final refresh must not notify Desktop consumers (the channel is closing).
1213
+ let shuttingDown = false;
1089
1214
  const jobs = createJobRegistry({
1090
1215
  outputDir: deps.jobOutputDir ?? (() => (jobOutputDir ??= mkdtempSync(join(os.tmpdir(), "gentle-jobs-")))),
1091
1216
  now: deps.now,
@@ -1101,6 +1226,142 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1101
1226
  now: deps.now,
1102
1227
  deliver: (notice) => queueJobNotice(notice),
1103
1228
  });
1229
+ // Desktop's jobs slice reaches the single parent registry and monitor
1230
+ // controller only through this versioned, adapter-shaped seam — the jobs
1231
+ // analogue of the usage/design owner services. The adapter never runs or
1232
+ // stops a job itself: `cancel` is `job_stop`'s exact stop path
1233
+ // (`monitors.cancel` then `registry.stop`), and `observe` is driven by the
1234
+ // same actual registry changes below. There is no second registry, process
1235
+ // manager, or store.
1236
+ const desktopJobsObservers = new Set<(sessionId: string) => void>();
1237
+ const notifyDesktopJobs = (sessionId: string): void => {
1238
+ if (desktopJobsObservers.size === 0) return;
1239
+ for (const observer of [...desktopJobsObservers]) {
1240
+ try { observer(sessionId); } catch { /* an observer never breaks jobs */ }
1241
+ }
1242
+ };
1243
+ const unsubscribeDesktopJobsService = pi.events.on(DESKTOP_JOBS_SERVICE_CHANNEL, (payload: unknown) => {
1244
+ if (!payload || typeof payload !== "object") return;
1245
+ const request = payload as Partial<{ context: ExtensionContext; respond(service: DesktopJobsService): void }>;
1246
+ if (typeof request.respond !== "function" || !request.context) return;
1247
+ const ctx = request.context;
1248
+ try {
1249
+ let disposed = false;
1250
+ const subscriptions = new Set<(sessionId: string) => void>();
1251
+ const sessionId = ctx.sessionManager?.getSessionId?.() ?? "";
1252
+ const read = (): DesktopJobsOwnerRead => ({
1253
+ sessionId,
1254
+ jobs: disposed ? [] : selectDesktopJobs(jobs.list(sessionId), deps.now()),
1255
+ });
1256
+ const cancel = (id: string): DesktopJobsCancelOutcome => {
1257
+ if (disposed) return { kind: "not_found" };
1258
+ const job = jobs.get(id);
1259
+ // The same ownership check job_stop performs: a foreign or unknown
1260
+ // id is a typed not_found, never a stop of someone else's job.
1261
+ if (!job || job.ownerSessionId !== sessionId) return { kind: "not_found" };
1262
+ const wasRunning = job.status === "running";
1263
+ monitors.cancel(job.id);
1264
+ jobs.stop(job.id);
1265
+ return { kind: "ok", job: projectDesktopJob(job), changed: wasRunning };
1266
+ };
1267
+ request.respond({
1268
+ schema: DESKTOP_JOBS_SERVICE_SCHEMA,
1269
+ read,
1270
+ cancel,
1271
+ observe: (onChange) => {
1272
+ if (disposed) return () => {};
1273
+ subscriptions.add(onChange);
1274
+ desktopJobsObservers.add(onChange);
1275
+ return () => {
1276
+ subscriptions.delete(onChange);
1277
+ desktopJobsObservers.delete(onChange);
1278
+ };
1279
+ },
1280
+ dispose: () => {
1281
+ disposed = true;
1282
+ for (const onChange of subscriptions) desktopJobsObservers.delete(onChange);
1283
+ subscriptions.clear();
1284
+ },
1285
+ });
1286
+ } catch {
1287
+ /* obsolete trusted context: discovery expires closed */
1288
+ }
1289
+ });
1290
+ // Desktop subagents owner adapter: the agents analogue of the jobs/usage
1291
+ // owner services. The adapter never runs, stops, or spawns a subagent
1292
+ // itself: `cancel` is the exact `runner.cancel` stop path the agents panel
1293
+ // stop uses, `read` projects the single `TaskStore`, and `observe` is
1294
+ // driven by the same actual TaskStore transitions below. There is no second
1295
+ // store, runner, or process manager. `runner` is declared later in this
1296
+ // module; the adapter closes over the binding lazily.
1297
+ const desktopAgentsObservers = new Set<(sessionId: string) => void>();
1298
+ const notifyDesktopAgents = (sessionId: string): void => {
1299
+ if (desktopAgentsObservers.size === 0) return;
1300
+ for (const observer of [...desktopAgentsObservers]) {
1301
+ try { observer(sessionId); } catch { /* an observer never breaks agents */ }
1302
+ }
1303
+ };
1304
+ const unsubscribeDesktopAgentsService = pi.events.on(DESKTOP_AGENTS_SERVICE_CHANNEL, (payload: unknown) => {
1305
+ if (!payload || typeof payload !== "object") return;
1306
+ const request = payload as Partial<{ context: ExtensionContext; respond(service: DesktopAgentsService): void }>;
1307
+ if (typeof request.respond !== "function" || !request.context) return;
1308
+ const ctx = request.context;
1309
+ try {
1310
+ let disposed = false;
1311
+ const subscriptions = new Set<(sessionId: string) => void>();
1312
+ const sessionId = ctx.sessionManager?.getSessionId?.() ?? "";
1313
+ const read = (): DesktopAgentsOwnerRead => ({
1314
+ sessionId,
1315
+ agents: disposed ? [] : selectDesktopAgents(store.list(sessionId)),
1316
+ });
1317
+ const cancel = (id: string): DesktopAgentsCancelOutcome => {
1318
+ if (disposed) return { kind: "not_found" };
1319
+ const before = store.get(id);
1320
+ // The same ownership check the agents panel stop performs: a foreign
1321
+ // or unknown id is a typed not_found, never a stop of someone else's task.
1322
+ if (!before || before.parentSessionId !== sessionId) return { kind: "not_found" };
1323
+ // The same owner path the agents panel stop uses: runner.cancel. Its
1324
+ // boolean is honored verbatim, and `changed` reflects the store's actual
1325
+ // synchronous transition, not the request. A queued task transitions to
1326
+ // cancelled here; a running task's cancellation is asynchronous (no
1327
+ // synchronous transition), so a repeated in-flight cancel is `changed:
1328
+ // false` and never emits an immediate fabricated event.
1329
+ const requested = runner.cancel(id, "cancelled: stopped from desktop");
1330
+ const after = store.get(id) ?? before;
1331
+ const changed = requested && after.status !== before.status;
1332
+ return { kind: "ok", agent: projectDesktopAgent(after), requested, changed };
1333
+ };
1334
+ request.respond({
1335
+ schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
1336
+ read,
1337
+ cancel,
1338
+ observe: (onChange) => {
1339
+ if (disposed) return () => {};
1340
+ subscriptions.add(onChange);
1341
+ desktopAgentsObservers.add(onChange);
1342
+ return () => {
1343
+ subscriptions.delete(onChange);
1344
+ desktopAgentsObservers.delete(onChange);
1345
+ };
1346
+ },
1347
+ dispose: () => {
1348
+ disposed = true;
1349
+ for (const onChange of subscriptions) desktopAgentsObservers.delete(onChange);
1350
+ subscriptions.clear();
1351
+ },
1352
+ });
1353
+ } catch {
1354
+ /* obsolete trusted context: discovery expires closed */
1355
+ }
1356
+ });
1357
+ // Actual TaskStore transitions (task add and every status change) notify the
1358
+ // Desktop bridge. Restored-from-disk snapshots are silent, matching the
1359
+ // status-change notification contract. The usage breakdown recorded at
1360
+ // completion is a status-unchanged update, so `onFinish` notifies it
1361
+ // explicitly; the bridge coalesces both into one event.
1362
+ const stopAgentsStatusNotifications = store.subscribeStatusChanges((change) => {
1363
+ notifyDesktopAgents(change.sessionId);
1364
+ });
1104
1365
  // A parent that sleeps while background work runs only burns the turn: each
1105
1366
  // completion already arrives as a session message (#1903). bash_background
1106
1367
  // and monitor stay allowed because they are the sanctioned way to wait.
@@ -1185,17 +1446,21 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1185
1446
  // Idle wake-up state. Child content stored while the parent is idle owes a
1186
1447
  // wake, and one wake covers everything stored before the run it starts.
1187
1448
  // While a prompt is starting (a dispatched wake, or any prompt seen at
1188
- // before_agent_start) no second wake is sent: two prompts racing through
1449
+ // input or before_agent_start) no second wake is sent: two prompts racing through
1189
1450
  // Pi's asynchronous pre-run phase can both reach the agent, and the loser
1190
1451
  // resets the winner's run state. A prompt that never starts a run (handled
1191
1452
  // by an input handler, or rejected) emits no extension event, so the
1192
- // starting state expires after PARENT_WAKE_GRACE_MS and an owed wake is
1193
- // sent then; it never suppresses later wakes for longer than that.
1453
+ // starting state expires after PARENT_WAKE_GRACE_MS (INPUT_PROMPT_GRACE_MS
1454
+ // when marked at input) and an owed wake is sent then; it never suppresses later wakes for longer than that.
1194
1455
  let wakeOwed = false;
1195
1456
  let wakeQueued = false;
1196
1457
  let promptStarting = false;
1197
1458
  let cancelPromptGrace: (() => void) | undefined;
1198
1459
  let cancelBoundaryFlush: (() => void) | undefined;
1460
+ let cancelHoldRecheck: (() => void) | undefined;
1461
+ // Completions sit in an opaque queue; this notes that one may be waiting.
1462
+ // It is cleared by the next flush that reaches a deliverable route.
1463
+ let completionsMaybePending = false;
1199
1464
  // An idle parent has no turn boundary coming, so a failed idle delivery or
1200
1465
  // wake is retried by one bounded timer that runs a full flush.
1201
1466
  let cancelDeliveryRetry: (() => void) | undefined;
@@ -1235,6 +1500,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1235
1500
  // A parent that is busy without a run (compaction, or a prompt's pre-run
1236
1501
  // compaction) is not streaming, so steer + triggerTurn would also start a
1237
1502
  // direct turn. Its content stays queued ("hold") until a later boundary.
1503
+ //
1504
+ // Three sources use this one router: child completions, child messages
1505
+ // (queries and notifications), and incoming orchestrator session messages.
1506
+ // The route decision is also the single point where a receiver-side
1507
+ // admission policy for session messages (#1518) would plug in.
1238
1508
  type ParentRoute = "idle" | "run" | "hold";
1239
1509
  // Throws for a missing or stale parent context, so delivery fails closed.
1240
1510
  const parentRoute = (): ParentRoute => {
@@ -1253,14 +1523,36 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1253
1523
  cancelPromptGrace?.();
1254
1524
  cancelPromptGrace = undefined;
1255
1525
  };
1256
- const beginPromptStart = () => {
1526
+ const beginPromptStart = (graceMs = PARENT_WAKE_GRACE_MS) => {
1257
1527
  endPromptStart();
1258
1528
  promptStarting = true;
1259
1529
  cancelPromptGrace = deps.schedule(() => {
1260
1530
  cancelPromptGrace = undefined;
1261
1531
  promptStarting = false;
1262
1532
  requestWake();
1263
- }, PARENT_WAKE_GRACE_MS);
1533
+ }, graceMs);
1534
+ };
1535
+
1536
+ const hasHeldContent = (): boolean =>
1537
+ heldOrchestratorMessages.length > 0 || wakeOwed || completionsMaybePending || messages.pendingCount() > 0 || jobNotices.length > 0;
1538
+ const stopHoldRecheck = () => {
1539
+ cancelHoldRecheck?.();
1540
+ cancelHoldRecheck = undefined;
1541
+ };
1542
+ // Events (`agent_*`, `turn_end`, `session_compact*`, `session_tree`) are the
1543
+ // fast path that releases held content. They are not a guarantee: a busy
1544
+ // state without a run can end without any event (a cancelled `/tree`
1545
+ // summarization emits none) or be added to the host later. So while content
1546
+ // is held for a parent that is busy without a run, one re-check is armed;
1547
+ // it re-arms itself only while that state and the held content persist.
1548
+ // Nothing is armed when nothing is held, and an idle or running parent is
1549
+ // never polled.
1550
+ const armHoldRecheck = () => {
1551
+ if (cancelHoldRecheck || !hasHeldContent()) return;
1552
+ cancelHoldRecheck = deps.schedule(() => {
1553
+ cancelHoldRecheck = undefined;
1554
+ flushAll();
1555
+ }, HOLD_RECHECK_MS);
1264
1556
  };
1265
1557
 
1266
1558
  // Every wake requested during one synchronous delivery pass is coalesced
@@ -1277,6 +1569,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1277
1569
  try { route = parentRoute(); } catch { return; }
1278
1570
  // A run in progress already carries the stored content; a parent busy
1279
1571
  // without a run keeps the wake owed until a later boundary flush.
1572
+ if (route === "hold") armHoldRecheck();
1280
1573
  if (route !== "idle") return;
1281
1574
  wakeOwed = false;
1282
1575
  endDeliveryRetry();
@@ -1307,9 +1600,12 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1307
1600
  }
1308
1601
  };
1309
1602
 
1310
- const sendToParent = (message: Parameters<ExtensionAPI["sendMessage"]>[0], route: Exclude<ParentRoute, "hold">) => {
1603
+ // `runMode` is how a message joins a run in progress: child content steers
1604
+ // (see the #867 rationale above); an orchestrator session message is a
1605
+ // follow-up, so it never interrupts the turn the parent is working on.
1606
+ const sendToParent = (message: Parameters<ExtensionAPI["sendMessage"]>[0], route: Exclude<ParentRoute, "hold">, runMode: "steer" | "followUp" = "steer") => {
1311
1607
  if (route === "run") {
1312
- pi.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
1608
+ pi.sendMessage(message, { deliverAs: runMode, triggerTurn: true });
1313
1609
  return;
1314
1610
  }
1315
1611
  pi.sendMessage(message, { triggerTurn: false });
@@ -1321,7 +1617,40 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1321
1617
  // Ownership is consulted at delivery time, matching onNotification and
1322
1618
  // onQuery: a completion owned by another session is dropped, not delivered.
1323
1619
  if (activeSessionId() !== task.parentSessionId) return;
1324
- sendToParent({ customType: AGENTS_RESULT_TYPE, content: completionText(task), display: true, details: taskDetails(task) }, route);
1620
+ // P9b: only the delivered copy is capped; subagent_result keeps the full text.
1621
+ let cwd = process.cwd();
1622
+ try { cwd = sessions?.getCwd() ?? cwd; } catch { /* A stale manager keeps the process directory, like the runner's config. */ }
1623
+ const capped = capReport(finishedText(task), loadAgentsConfig({ cwd, home: deps.home, agentHome }).reportMaxBytes, task.id, task.agent);
1624
+ sendToParent({ customType: AGENTS_RESULT_TYPE, content: completionText(task, capped.text), display: true, details: withReportCap(taskDetails(task), capped) }, route);
1625
+ };
1626
+
1627
+ // Incoming orchestrator session messages. The transport has already
1628
+ // acknowledged the sender when the listener runs, so a message held for a
1629
+ // busy parent that is then dropped by a session change is lost, exactly like
1630
+ // pending child content. A stale or missing parent context throws instead,
1631
+ // so the sender learns that delivery failed.
1632
+ interface HeldOrchestratorMessage { message: Parameters<ExtensionAPI["sendMessage"]>[0]; recipientSessionId: string }
1633
+ let heldOrchestratorMessages: HeldOrchestratorMessage[] = [];
1634
+ const deliverOrchestratorMessage = (message: Parameters<ExtensionAPI["sendMessage"]>[0], recipientSessionId: string) => {
1635
+ const route = parentRoute();
1636
+ if (route === "hold") {
1637
+ heldOrchestratorMessages.push({ message, recipientSessionId });
1638
+ armHoldRecheck();
1639
+ return;
1640
+ }
1641
+ sendToParent(message, route, "followUp");
1642
+ };
1643
+ const flushOrchestratorMessages = () => {
1644
+ if (heldOrchestratorMessages.length === 0) return;
1645
+ const route = deliveryRoute(false);
1646
+ if (!route) return;
1647
+ const held = heldOrchestratorMessages;
1648
+ heldOrchestratorMessages = [];
1649
+ for (const { message, recipientSessionId } of held) {
1650
+ if (activeSessionId() !== recipientSessionId) continue;
1651
+ try { sendToParent(message, route, "followUp"); }
1652
+ catch { /* Best-effort delivery: at most once, even if forwarding fails. */ }
1653
+ }
1325
1654
  };
1326
1655
 
1327
1656
  // A stale report must not re-enter the LLM conversation, but the parent is
@@ -1352,7 +1681,12 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1352
1681
  const deliveryRoute = (rethrow: boolean): Exclude<ParentRoute, "hold"> | undefined => {
1353
1682
  try {
1354
1683
  const route = parentRoute();
1355
- return route === "hold" ? undefined : route;
1684
+ if (route === "hold") {
1685
+ armHoldRecheck();
1686
+ return undefined;
1687
+ }
1688
+ stopHoldRecheck();
1689
+ return route;
1356
1690
  } catch (error) {
1357
1691
  if (rethrow) throw error;
1358
1692
  return undefined;
@@ -1375,6 +1709,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1375
1709
  const flushCompletions = () => {
1376
1710
  const route = deliveryRoute(false);
1377
1711
  if (!route) return;
1712
+ completionsMaybePending = false;
1378
1713
  for (const entry of completions.takeDeliverable(deps.now())) {
1379
1714
  try {
1380
1715
  if (entry.stale) deliverStale(entry.task, entry.settledAt, route);
@@ -1384,6 +1719,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1384
1719
  // lose the completion: it waits for the next boundary instead, and
1385
1720
  // an idle parent, which has none coming, gets a bounded retry.
1386
1721
  completions.requeue(entry);
1722
+ // Still pending, so a later held-only re-check must see it.
1723
+ completionsMaybePending = true;
1387
1724
  if (route === "idle") armDeliveryRetry();
1388
1725
  }
1389
1726
  }
@@ -1395,25 +1732,30 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1395
1732
  const flushJobNotices = () => {
1396
1733
  const route = deliveryRoute(false);
1397
1734
  if (!route) return;
1398
- const failed: JobNotice[] = [];
1735
+ const retained: JobNotice[] = [];
1736
+ let deliveryFailed = false;
1399
1737
  for (const notice of jobNotices.splice(0)) {
1400
1738
  const { job } = notice;
1401
- if (activeSessionId() !== job.ownerSessionId) continue;
1739
+ if (activeSessionId() !== job.ownerSessionId) {
1740
+ retained.push(notice);
1741
+ continue;
1742
+ }
1402
1743
  const content = notice.kind === "events" ? monitorEventsText(job, notice.batch)
1403
1744
  : notice.kind === "stopped" ? monitorStoppedText(job, notice.reason) : jobNoticeText(job);
1404
1745
  const event = notice.kind === "events" ? "events" : notice.kind === "stopped" ? notice.reason : undefined;
1405
1746
  try {
1406
1747
  sendToParent({ customType: JOB_NOTICE_TYPE, content, display: true, details: jobDetails(job, event) }, route);
1407
1748
  } catch {
1408
- failed.push(notice);
1749
+ retained.push(notice);
1750
+ deliveryFailed = true;
1409
1751
  }
1410
1752
  }
1411
- if (failed.length === 0) return;
1412
- jobNotices.unshift(...failed);
1413
- if (route === "idle") armDeliveryRetry();
1753
+ jobNotices.unshift(...retained);
1754
+ if (deliveryFailed && route === "idle") armDeliveryRetry();
1414
1755
  };
1415
1756
 
1416
1757
  const flushAll = () => {
1758
+ flushOrchestratorMessages();
1417
1759
  flushMessages();
1418
1760
  flushCompletions();
1419
1761
  flushJobNotices();
@@ -1441,7 +1783,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1441
1783
  wakeVisibilityWarning = false;
1442
1784
  parentRunActive = false;
1443
1785
  wakeOwed = false;
1786
+ heldOrchestratorMessages = [];
1787
+ completionsMaybePending = false;
1444
1788
  endPromptStart();
1789
+ stopHoldRecheck();
1445
1790
  cancelBoundaryFlush?.();
1446
1791
  cancelBoundaryFlush = undefined;
1447
1792
  endDeliveryRetry();
@@ -1467,6 +1812,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1467
1812
  ...finished.map(({ id, label, startedAt, status, endedAt, exitCode }) => ({ id, label, startedAt, status, endedAt, exitCode })),
1468
1813
  ] } });
1469
1814
  } catch { /* Display only. */ }
1815
+ // Every actual registry change funnels through this refresh, including
1816
+ // monitor self-timeout/flood stops (their `stopFor` delivers a notice
1817
+ // here). Notify Desktop consumers; the bridge dedupes byte-identical
1818
+ // lists so a stop that also flushes pending lines still emits once.
1819
+ if (!shuttingDown) notifyDesktopJobs(sessionId);
1470
1820
  }
1471
1821
  };
1472
1822
 
@@ -1501,6 +1851,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1501
1851
  const settleCompletion = (task: TaskRecord) => {
1502
1852
  messages.invalidateTask(task.id);
1503
1853
  completions.enqueue(task, deps.now());
1854
+ completionsMaybePending = true;
1504
1855
  if (activeAgentRuns === 0) flushAll();
1505
1856
  };
1506
1857
 
@@ -1516,8 +1867,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1516
1867
  // compaction ran inside or right before the run. `before_agent_start`
1517
1868
  // marks a prompt that is about to start a run, and the compaction events
1518
1869
  // release content held while the parent compacted without a run.
1519
- pi.on("before_agent_start", () => {
1870
+ pi.on("before_agent_start", (event) => {
1520
1871
  if (!parentRunActive) beginPromptStart();
1872
+ const options = event?.systemPromptOptions;
1873
+ if (codemodeReaches(options?.selectedTools) && ["orchestrator_list", "orchestrator_consult", "orchestrator_send_message"].some((name) => options?.selectedTools?.includes(name))) appendSystemPromptOnce(options, COORDINATION_TOOLS_ROUTE);
1521
1874
  });
1522
1875
  pi.on("agent_start", () => {
1523
1876
  activeAgentRuns += 1;
@@ -1548,6 +1901,23 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1548
1901
  pi.on("turn_end", () => flushAll());
1549
1902
  pi.on("session_compact", scheduleBoundaryFlush);
1550
1903
  pi.on("session_compact_failed", scheduleBoundaryFlush);
1904
+ pi.on("session_tree", scheduleBoundaryFlush);
1905
+ // A user prompt is "starting" from `input`, through input handlers, auth and
1906
+ // model checks, until `before_agent_start`, while the host still reports
1907
+ // idle. A wake dispatched in that window races the prompt into
1908
+ // Agent.prompt(): the user's prompt can be rejected as already processing.
1909
+ // The starting prompt carries the stored content itself, so no wake is
1910
+ // needed. An input another extension handles never starts a run and emits
1911
+ // no event, so this suppression expires quickly (INPUT_PROMPT_GRACE_MS) and
1912
+ // the owed wake then goes out; a pre-run phase longer than that only
1913
+ // re-opens the old window. A pre-prompt compaction makes the route "hold",
1914
+ // and `before_agent_start` re-arms the starting state. A start window that
1915
+ // is already open is never shortened: a dispatched wake reaches `input`
1916
+ // too, and its own PARENT_WAKE_GRACE_MS window must keep a second wake out.
1917
+ pi.on("input", (event) => {
1918
+ if (parentRunActive || promptStarting || event.streamingBehavior !== undefined) return;
1919
+ beginPromptStart(INPUT_PROMPT_GRACE_MS);
1920
+ });
1551
1921
 
1552
1922
  const runner = new AgentRunner(store, loadAgentsConfig({ cwd: process.cwd(), home: deps.home, agentHome }), deps, {
1553
1923
  askUser: (_taskId, ask, raw) => answerThroughUi(ui, ask, raw),
@@ -1573,7 +1943,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1573
1943
  },
1574
1944
  onQuerySettled: (taskId, requestId, outcome) => {
1575
1945
  if (outcome === "replied") messages.consumeQuery(taskId, requestId);
1576
- else messages.expireQuery(taskId, requestId);
1946
+ // A busy parent still sees a question that expired in its queue (S15 P9a).
1947
+ else messages.markQueryExpired(taskId, requestId);
1577
1948
  },
1578
1949
  onFallback: (task, change) => announceFallback({ agent: task.agent, from: change.from, to: change.to, category: change.category, ...(change.launch ? { launch: true } : {}) }, task.parentSessionId, task.id),
1579
1950
  onSuccessfulMutation: (task, tool) => {
@@ -1639,18 +2010,31 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1639
2010
  if (event && metrics.current()) pi.events.emit(CHILD_METRICS_EVENT, event);
1640
2011
  }
1641
2012
  } catch { /* Metrics must never interrupt task finalization. */ }
2013
+ try {
2014
+ // Record the final-assistant token breakdown so the Desktop list can
2015
+ // project per-helper usage; in-flight tasks stay without it. This is a
2016
+ // status-unchanged update, so the agents owner notifies explicitly and
2017
+ // the Desktop bridge coalesces it with the terminal status change.
2018
+ if (observations && observations.responses.length > 0) {
2019
+ store.update(task.id, { usage: accumulateTaskUsage(observations.responses) });
2020
+ notifyDesktopAgents(parentSessionId);
2021
+ }
2022
+ } catch { /* Best-effort usage bookkeeping cannot strand runner waiters. */ }
1642
2023
  try {
1643
2024
  ownedTaskIds.delete(task.id);
1644
2025
  messages.invalidateTask(task.id);
1645
2026
  requestRender();
1646
- persist(task);
2027
+ // Persist the post-breakdown record so a restored finished task keeps
2028
+ // its final usage. `task` is the onFinish argument, which predates the
2029
+ // usage update above; the store now carries the merged record.
2030
+ persist(store.get(task.id) ?? task);
1647
2031
  const yielded = yieldedTaskIds.delete(task.id);
1648
2032
  if ((task.mode === AGENT_MODE.BACKGROUND && task.status !== TASK_STATUS.CANCELLED) || (yielded && task.status !== TASK_STATUS.CANCELLED && activeSessionId() === task.parentSessionId)) settleCompletion(task);
1649
2033
  } catch { /* Best-effort completion bookkeeping cannot strand runner waiters. */ }
1650
2034
  },
1651
2035
  });
1652
2036
 
1653
- registerBackgroundJobTools(pi, { registry: jobs, monitors, sessionId: (ctx) => ctx.sessionManager.getSessionId() ?? "", now: deps.now, onChange: () => { refreshJobStatus(); requestRender(); } });
2037
+ registerBackgroundJobTools(pi, { registry: jobs, monitors, sessionId: (ctx) => ctx.sessionManager.getSessionId() ?? "", now: deps.now, onChange: (change: BackgroundJobsChange) => { refreshJobStatus(); requestRender(); } });
1654
2038
 
1655
2039
  pi.registerMessageRenderer(AGENTS_MESSAGE_TYPE, (message, options, theme) => {
1656
2040
  const details = (message.details as { gentleAgents?: { taskId?: unknown; agent?: unknown } } | undefined)?.gentleAgents;
@@ -1761,16 +2145,39 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1761
2145
  return confirmation;
1762
2146
  };
1763
2147
 
2148
+ // A task stored on disk that never reached a terminal state was in flight
2149
+ // when the parent process was abruptly terminated (kill -9, host reboot,
2150
+ // OOM). When loaded into a new process where it has no live runner, it is
2151
+ // reconciled into a terminal failed state and updated on disk (#1741).
2152
+ const reconcileStored = async (stored: StoredTask): Promise<StoredTask> => {
2153
+ if (isFinished(stored.task.status)) return stored;
2154
+ const reconciledTask: TaskRecord = {
2155
+ ...stored.task,
2156
+ status: TASK_STATUS.FAILED,
2157
+ error: stored.task.error ?? "interrupted: parent process terminated while task was in flight",
2158
+ lastStep: "interrupted",
2159
+ endedAt: stored.task.endedAt ?? deps.now(),
2160
+ };
2161
+ try { await saveTask(tasksDir, reconciledTask, stored.thread); } catch { /* best effort */ }
2162
+ return { task: reconciledTask, thread: stored.thread };
2163
+ };
2164
+
1764
2165
  // Tasks from earlier sessions come back from disk on demand.
1765
2166
  const resolveTask = async (id: string): Promise<TaskRecord | undefined> => {
1766
2167
  const live = store.get(id);
1767
- if (live) return live;
2168
+ if (live && !restoredTaskIds.has(id)) return live;
1768
2169
  const stored = await loadStoredTask(tasksDir, id);
1769
2170
  if (stored) {
1770
- restoredTaskIds.add(stored.task.id);
1771
- store.restore(stored.task, stored.thread);
2171
+ if (!isFinished(stored.task.status) && stored.task.parentSessionId !== activeSessionId()) {
2172
+ return undefined;
2173
+ }
2174
+ const reconciled = await reconcileStored(stored);
2175
+ restoredTaskIds.add(reconciled.task.id);
2176
+ store.restore(reconciled.task, reconciled.thread);
2177
+ store.update(reconciled.task.id, reconciled.task);
2178
+ return reconciled.task;
1772
2179
  }
1773
- return stored?.task;
2180
+ return live;
1774
2181
  };
1775
2182
 
1776
2183
  // A guessed id ("1") leads back to real ids instead of a dead end, so the
@@ -1801,8 +2208,12 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1801
2208
  // The session may have moved on while disk was read; a stale restore
1802
2209
  // must never land in the wrong session's store.
1803
2210
  if (ctx.sessionManager.getSessionId() !== sessionId) return;
1804
- for (const { task, thread } of history) {
1805
- if (task.parentSessionId !== sessionId) continue;
2211
+ // An in-flight record has no live runner here, so it is reconciled
2212
+ // before the widget or store can show it as still running (#1741).
2213
+ const own = history.filter(({ task }) => task.parentSessionId === sessionId && !store.get(task.id));
2214
+ const reconciled = await Promise.all(own.map(reconcileStored));
2215
+ if (ctx.sessionManager.getSessionId() !== sessionId) return;
2216
+ for (const { task, thread } of reconciled) {
1806
2217
  if (store.restore(task, thread)) restoredTaskIds.add(task.id);
1807
2218
  }
1808
2219
  } catch { /* Partial history is acceptable; the live session keeps running. */ }
@@ -1879,9 +2290,35 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1879
2290
  await writeFile(path, markdown, "utf8");
1880
2291
  return path;
1881
2292
  };
2293
+ // gentle-shell#626: herdr's pane busy while owned subagents of the active
2294
+ // session run, even when the parent itself settled around a background
2295
+ // child. Pure edge-triggered projection (lib/herdr-busy.ts), recomputed on
2296
+ // every summary notification and on the session lifecycle edges; the
2297
+ // consumer owns blocked-over-busy precedence, so no gating happens here.
2298
+ let emittedBusy: HerdrBusyEmitted;
2299
+ const refreshHerdrBusy = (): void => {
2300
+ const sessionId = activeSessionId();
2301
+ if (!sessionId) {
2302
+ // No active session owns work: never raise, and lower anything this
2303
+ // runtime already raised so busy never outlives its session.
2304
+ if (emittedBusy?.active) pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
2305
+ emittedBusy = { active: false };
2306
+ return;
2307
+ }
2308
+ const action = nextHerdrBusyAction(store.list(sessionId).filter((task) => ownedTaskIds.has(task.id)), emittedBusy);
2309
+ if (action.kind === "none") return;
2310
+ if (action.kind === "lower") pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
2311
+ else {
2312
+ if (action.kind === "lower-then-raise") pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
2313
+ pi.events.emit(HERDR_BUSY_CHANNEL, { active: true, label: action.label });
2314
+ }
2315
+ emittedBusy = action.kind === "lower" ? { active: false } : { active: true, label: action.label };
2316
+ };
2317
+
1882
2318
  // A status change is worth a frame right away; deltas inside a task are
1883
2319
  // coalesced so a chatty child cannot flood the terminal.
1884
2320
  store.subscribeSummary(() => {
2321
+ refreshHerdrBusy();
1885
2322
  publishActivity();
1886
2323
  if (sidebarTui) invalidateSidebar(sidebarTui);
1887
2324
  host?.requestRender();
@@ -2006,7 +2443,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2006
2443
  };
2007
2444
  };
2008
2445
 
2009
- const roots = (ctx: ExtensionContext) => ({ cwd: ctx.sessionManager.getCwd(), home: deps.home, agentHome });
2446
+ const roots = (ctx: ExtensionContext) => ({ cwd: ctx.sessionManager.getCwd(), home: deps.home, agentHome, configHome: gentlePiConfigHome(deps.env) });
2010
2447
  // Issue #2400: parent sessions already told about model_profiles keys that
2011
2448
  // match no agent and suggest none, so the notice fires once per session.
2012
2449
  const unmatchedKeysNotifiedSessions = new Set<string>();
@@ -2263,6 +2700,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2263
2700
  launched = true;
2264
2701
  const foreign = foreignRequests.get(request);
2265
2702
  if (foreign && launchedTaskId) foreignTasks.set(launchedTaskId, foreign);
2703
+ if (launchedTaskId) persistLaunch(launchedTaskId);
2266
2704
  },
2267
2705
  ...(observe ? { canCollectResponseObservations: metrics.valid, prepareResponseObservations: async () => {
2268
2706
  if (metrics.finished || owner !== metricsOwner || request.parentSessionId !== activeSessionId() || !runtimeMetricsEnvAllows(deps.env)) return false;
@@ -2277,8 +2715,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2277
2715
  const foreignRequest = foreignRequests.get(request);
2278
2716
  if (launched && foreignRequest) foreignTasks.set(task.id, foreignRequest);
2279
2717
  ownedTaskIds.add(task.id);
2718
+ persistLaunch(task.id);
2280
2719
  publishWork?.(task.id);
2281
2720
  publishActivityPrompt(); // Admission's summary notification precedes runtime ownership.
2721
+ refreshHerdrBusy(); // So does the busy raise: ownership lands after that notification.
2282
2722
  store.subscribe(task.id, () => { publishActivity(); requestRender(); });
2283
2723
  if (request.mode === AGENT_MODE.BACKGROUND) return text(`Started ${task.agent} in the background as task ${task.id}. Retain that id; completion is pushed automatically. Never sleep or periodically poll subagent_status/subagent_result for completion or cache maintenance. Inspect status only at a real orchestration decision boundary; never relaunch equivalent queued/running work.`, taskDetails(task));
2284
2724
  // A tool call aborted by the host (a human interrupting the turn, a timeout)
@@ -2312,7 +2752,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2312
2752
  messages.invalidateTask(finished.id);
2313
2753
  // The id rides in the text too: details never reach the model, which
2314
2754
  // otherwise guesses ordinal ids for subagent_continue (#1731 T19).
2315
- return text(completionText(finished), taskDetails(finished));
2755
+ const capped = capReport(finishedText(finished), loadAgentsConfig(roots(ctx)).reportMaxBytes, finished.id, finished.agent);
2756
+ return text(completionText(finished, capped.text), withReportCap(taskDetails(finished), capped));
2316
2757
  } finally {
2317
2758
  signal?.removeEventListener("abort", onAbort);
2318
2759
  }
@@ -2475,11 +2916,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2475
2916
  pi.registerTool({
2476
2917
  name: "orchestrator_session_id",
2477
2918
  label: "Orchestrator session ID",
2478
- description: "Return this session's stable routing ID, Initial alias (FIRST TASK), Current alias (CURRENT TASK), and separate human Session name. Subject updates Current even when named; Initial is the first declared branch topic, unknown for legacy history. Without subject, explicit state.work.topic updates Current; keep it current as tasks change. Before delegation or cross-session coordination, declare a short recognizable non-sensitive subject, not a prompt. Do not require a subject declaration for small direct tasks. Do not query all peers. Names never authenticate. Existing Pi names and human renames are preserved. Progress is published automatically from the todo list; publish state only for objective, decisions, blockers or work, never just progress. Classified work must publish objective and work.topic/area at session start and every task-topic change; never retain old task state. Catalog flags never-published peers. Owner-curated state: 2048 UTF-8 bytes total; null withdraws, omission leaves unchanged. Never include credentials, internal instructions, or raw prompts. Historical notes are not consent or an owner reply.",
2919
+ description: "Return this session's stable routing ID, Initial alias (FIRST TASK), Current alias (CURRENT TASK), and separate human Session name. Subject updates Current even when named; Initial is the first declared branch topic, unknown for legacy history. Without subject, explicit state.work.topic updates Current; keep it current as tasks change. Before delegation or cross-session coordination, declare a short recognizable non-sensitive subject, not a prompt. Do not require a subject declaration for small direct tasks. Do not query all peers. Names never authenticate. Existing Pi names and human renames are preserved. Progress is published automatically from the todo list; publish state only for objective, decisions, blockers or work, never just progress. If you publish classified work, keep objective and work.topic/area current on each task-topic change; never retain old task state. Catalog flags never-published peers. Owner-curated state: 2048 UTF-8 bytes total; null withdraws, omission leaves unchanged. Never include credentials, internal instructions, or raw prompts. Historical notes are not consent or an owner reply.",
2479
2920
  ...orchestratorToolRenderers("session", expandHint),
2480
2921
  parameters: { type: "object", additionalProperties: false, properties: {
2481
2922
  subject: { type: "string", maxLength: 120, description: "Short task subject; updates aliases independently of human names and names unnamed Pi sessions." },
2482
- state: { anyOf: [{ type: "null" }, { type: "object", additionalProperties: false, properties: {
2923
+ state: { anyOf: [{ type: "null" }, { type: "string" }, { type: "object", additionalProperties: false, properties: {
2483
2924
  objective: { type: "string" }, progress: { type: "string" }, decisions: { type: "string" }, blockers: { type: "string" },
2484
2925
  work: { type: "object", additionalProperties: false,
2485
2926
  description: "Historical, non-authoritative; topic requires area. Text and work JSON share 2048 UTF-8 bytes. Reject exact duplicate tags/refs; no ref resolution or routing.",
@@ -2495,7 +2936,17 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2495
2936
  async execute(_id, params, _signal, _onUpdate, ctx) {
2496
2937
  const transport = activeTransportFor(ctx);
2497
2938
  if (!transport) return text("Error: session messaging is not ready.", { error: "not ready" });
2498
- const { subject, state } = params as { subject?: unknown; state?: unknown };
2939
+ const { subject, state: rawState } = params as { subject?: unknown; state?: unknown };
2940
+ // Agents sometimes serialize the state object as a JSON string; accept
2941
+ // it with the same rules instead of a cryptic schema rejection, and
2942
+ // name the nesting rule when the parsed shape is flat.
2943
+ let state = rawState;
2944
+ if (typeof rawState === "string") {
2945
+ try { state = JSON.parse(rawState); }
2946
+ catch { throw new Error("invalid-state-json: state must be a JSON object string with objective/progress/decisions/blockers and optional work{area,topic,tags,refs,tasks} nested under \"work\"."); }
2947
+ if (state !== null && (typeof state !== "object" || Array.isArray(state))) throw new Error("invalid-state-json: the JSON string must encode an object or null.");
2948
+ if (state && Object.keys(state).some(key => !["objective", "progress", "decisions", "blockers", "work"].includes(key))) throw new Error("invalid-state-json: unknown top-level fields; area/topic/tags/refs/tasks must be nested under \"work\", not at the top level of state.");
2949
+ }
2499
2950
  const declared = normalizeTaskSubject(subject);
2500
2951
  // An owner object without `progress` keeps the automatic todo progress still on
2501
2952
  // display; null and an explicit `progress` win, and an over-budget merge does not fail the call.
@@ -2524,6 +2975,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2524
2975
  pi.registerTool({
2525
2976
  name: "orchestrator_consult",
2526
2977
  label: "Consult published context",
2978
+ prepareLoadout: hideBehindCodemode("orchestrator_consult"),
2527
2979
  ...orchestratorToolRenderers("consult", expandHint),
2528
2980
  description: "Read published metadata (default), request bounded helper reasoning with explicit UI model-cost permission and a question, or revoke-reasoning for an exact target. Never an owner reply, consent or private context access.",
2529
2981
  parameters: { type: "object", additionalProperties: false, required: ["recipient_session_id"], properties: {
@@ -2574,6 +3026,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2574
3026
  pi.registerTool({
2575
3027
  name: "orchestrator_list",
2576
3028
  label: "List orchestrators",
3029
+ prepareLoadout: hideBehindCodemode("orchestrator_list"),
2577
3030
  ...orchestratorToolRenderers("list", expandHint),
2578
3031
  description: "List other sessions advertised by the trusted local profile. Omit filter for the existing list; filter searches published classified work only: bounded, non-exhaustive, no authority, unknown reachability. Classified work must publish at session start and each task-topic change; flag peers doing classified work who never published state.",
2579
3032
  parameters: Type.Object({
@@ -2654,6 +3107,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2654
3107
  pi.registerTool({
2655
3108
  name: "orchestrator_send_message",
2656
3109
  label: "Send orchestrator message",
3110
+ prepareLoadout: hideBehindCodemode("orchestrator_send_message"),
2657
3111
  renderShell: "self",
2658
3112
  renderCall(args, theme, context) {
2659
3113
  return outgoingMessageCall(args as { message?: unknown }, theme, context, expandHint(context.expanded));
@@ -2689,15 +3143,18 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2689
3143
  }
2690
3144
  if (recipient === undefined) {
2691
3145
  try {
2692
- const candidates = (await transport.listener.registry.listActivations(transport.sessionId)).filter((candidate) => candidate.sessionId !== transport.sessionId);
3146
+ const activations = (await transport.listener.registry.listActivations(transport.sessionId)).filter((candidate) => candidate.sessionId !== transport.sessionId);
3147
+ // A transport may report more than one activation for one session; the picker maps
3148
+ // the chosen label back to a single activation, so keep one entry per session ID.
3149
+ const candidates = [...new Map(activations.map((candidate) => [candidate.sessionId, candidate] as const)).values()];
2693
3150
  if (activeTransportFor(ctx) !== transport || signal?.aborted) return text("Message selection was cancelled.", { error: "cancelled" });
2694
3151
  if (candidates.length === 0) return text("No other sessions are currently advertised; message delivery is unavailable.", { error: "unavailable" });
2695
3152
  if (candidates.length === 1) {
2696
3153
  recipient = candidates[0].sessionId;
2697
3154
  activation = candidates[0];
2698
- } else if (!ctx.hasUI) return text("Several recipient orchestrators are available. Ask the user to choose a recipient label; do not ask for a session ID.", { gentleAgents: { candidates: candidates.map((candidate) => ({ label: `Orchestrator ${candidate.sessionId}`, sessionId: candidate.sessionId })) } });
2699
- else {
2700
- const labels = candidates.map((candidate) => `Orchestrator ${candidate.sessionId}`);
3155
+ } else {
3156
+ const labels = recipientSelectionLabels(agentHome, candidates, activations);
3157
+ if (!ctx.hasUI) return text(`Several recipient orchestrators are available. Ask the user to choose one of these recipient labels; do not ask for a session ID:\n${labels.map((label) => `- ${label}`).join("\n")}\nSending still requires interactive human consent.`, { gentleAgents: { candidates: candidates.map((candidate, index) => ({ label: labels[index]!, sessionId: candidate.sessionId })) } });
2701
3158
  const selected = await ctx.ui.select("Select recipient orchestrator", labels, { signal });
2702
3159
  if (selected === undefined || activeTransportFor(ctx) !== transport || signal?.aborted) return text("Message selection was cancelled.", { error: "cancelled" });
2703
3160
  const index = labels.indexOf(selected);
@@ -2728,26 +3185,26 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2728
3185
  });
2729
3186
 
2730
3187
  tool("list_agents", "List the subagents defined for this project and user, with their descriptions and declared tool inventory.", { properties: {} }, async (_params, ctx) => {
2731
- const { agents, errors } = discoverAgents(roots(ctx));
3188
+ const { agents, errors, notices } = discoverAgents(roots(ctx));
2732
3189
  const lines = agents.map((agent) => `- ${agent.name} (${agent.scope}): ${agent.description || "no description"} ${declaredToolInventory(agent)}`);
2733
- const problems = errors.map((error) => `! ${error}`);
3190
+ const problems = [...errors, ...notices].map((problem) => `! ${problem}`);
2734
3191
  return text(lines.length === 0 ? "No subagents defined." : [...lines, ...problems].join("\n"));
2735
3192
  });
2736
3193
 
2737
3194
  tool(
2738
3195
  "run",
2739
- "Delegate a task to a named subagent. Task mode waits for the answer; background mode returns a task id immediately.",
3196
+ "Delegate a task to a named subagent. Admission rejects writers without repository-relative `## Allowed edit surfaces`; below the context backstop, organic writers without `Spec: odd/tasks/<existing>.md, T<n>` (2+ disjoint writers alone in one message pass) and `gentle-ai-verify` without that or `Risk: item N`.",
2740
3197
  {
2741
3198
  required: ["agent", "task"],
2742
3199
  properties: {
2743
3200
  agent: { type: "string", description: "Subagent name from subagent_list_agents." },
2744
3201
  task: { type: "string", description: "What the subagent must do, self-contained." },
2745
- label: { type: "string", description: "Three to six words naming the work, shown on the agents card, e.g. 'map footer data sources'." },
3202
+ label: { type: "string", description: "Three to six words naming the work for the agents card, e.g. 'map footer data sources'." },
2746
3203
  context: { type: "string", description: "Optional extra context appended to the task." },
2747
3204
  work: workDescriptorSchema,
2748
- workspace_root: { type: "string", description: "Optional canonical main or linked Git worktree within the parent's same clone only; mutually exclusive with repository_root." },
2749
- repository_root: { type: "string", description: "Optional canonical independent Git repository; requires direct interactive session-scoped consent before queueing; mutually exclusive with workspace_root." },
2750
- mode: { type: "string", enum: ["task", "background"], description: "task waits for the result (default); background returns immediately." },
3205
+ workspace_root: { type: "string", description: "Optional canonical main or linked Git worktree within the parent's clone only; exclusive with repository_root." },
3206
+ repository_root: { type: "string", description: "Optional canonical independent Git repository; needs direct interactive session-scoped consent before queueing; exclusive with workspace_root." },
3207
+ mode: { type: "string", enum: ["task", "background"], description: "task waits for the result (default); background returns a task id at once." },
2751
3208
  },
2752
3209
  },
2753
3210
  async (params, ctx, signal) => {
@@ -2810,15 +3267,30 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2810
3267
  });
2811
3268
 
2812
3269
  tool("list_tasks", "List the subagent tasks of this session, newest first.", { properties: {} }, async (_params, ctx) => {
2813
- const tasks = store.list(ctx.sessionManager.getSessionId() ?? "");
2814
- return text(tasks.length === 0 ? "No subagent tasks in this session." : tasks.map(describeTask).join("\n"));
3270
+ await sessionRestoration;
3271
+ const sessionId = ctx.sessionManager.getSessionId() ?? "";
3272
+ const tasks = store.list(sessionId);
3273
+ for (const task of tasks) {
3274
+ if (!isFinished(task.status) && restoredTaskIds.has(task.id)) {
3275
+ await resolveTask(task.id);
3276
+ }
3277
+ }
3278
+ const reconciledTasks = store.list(sessionId);
3279
+ return text(reconciledTasks.length === 0 ? "No subagent tasks in this session." : reconciledTasks.map(describeTask).join("\n"));
2815
3280
  });
2816
3281
 
2817
- tool("reply", "Reply once to a live query from a child of the current parent session.", { required: ["task_id", "request_id", "message"], properties: { task_id: { type: "string" }, request_id: { type: "string" }, message: { type: "string" } } }, async (params, ctx) => {
3282
+ tool("reply", "Reply once to a child query; a late reply arrives as a message.", { required: ["task_id", "request_id", "message"], properties: { task_id: { type: "string" }, request_id: { type: "string" }, message: { type: "string" } } }, async (params, ctx) => {
2818
3283
  const taskId = String(params.task_id);
2819
3284
  const requestId = String(params.request_id);
2820
- const accepted = await runner.reply(taskId, requestId, typeof params.message === "string" ? params.message : "", ctx.sessionManager.getSessionId() ?? "");
2821
- return accepted ? text("Reply accepted for delivery.") : text("Error: query is unavailable.", { error: "query unavailable" });
3285
+ const message = typeof params.message === "string" ? params.message : "";
3286
+ const sessionId = ctx.sessionManager.getSessionId() ?? "";
3287
+ if (await runner.reply(taskId, requestId, message, sessionId)) return text("Reply accepted for delivery.");
3288
+ // S15 P9a: a busy parent answers after the deadline; the answer still reaches a running child.
3289
+ const late = runner.replyLate(taskId, requestId, message, sessionId);
3290
+ if (late === "delivered") return text(`Query ${requestId} had expired; the answer was delivered to task ${taskId} as a message.`);
3291
+ if (late === "too large") return text(`Error: the reply exceeds the ${CHILD_MESSAGE_MAX_BYTES}-byte message limit and was not delivered; query ${requestId} can still be answered with a shorter reply.`, { error: "reply too large" });
3292
+ if (late === "not running") return text(`Error: query ${requestId} had expired and task ${taskId} is no longer running, so the answer was not delivered. Pass it with subagent_continue.`, { error: "query expired" });
3293
+ return text("Error: query is unavailable.", { error: "query unavailable" });
2822
3294
  });
2823
3295
 
2824
3296
  tool("cancel", "Cancel a queued or running subagent task.", { required: ["task_id"], properties: { task_id: { type: "string" } } }, async (params) => {
@@ -2864,7 +3336,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2864
3336
  }
2865
3337
 
2866
3338
  pi.registerCommand(JOBS_COMMAND_NAME, {
2867
- description: "Show background jobs: running first, newest first within each group; status, command, output tail; s stops the selected job.",
3339
+ description: "Show background jobs: running first, newest first within each group; status, command, output tail. Click a job to inspect it; click Stop or press s to stop the selected running job.",
2868
3340
  handler: async (_args, ctx) => {
2869
3341
  if (!ctx.hasUI) return;
2870
3342
  if (ctx.mode !== "tui") {
@@ -2918,6 +3390,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2918
3390
  publishActivityPrompt();
2919
3391
  });
2920
3392
  pi.on("session_start", async (event, ctx) => {
3393
+ shuttingDown = false;
2921
3394
  // gentle-shell#1064 slice 3b-ii: a parent session that has no explicit
2922
3395
  // profile binding freezes `p → P → G` now. This handler is parent-only (a
2923
3396
  // child returns before registering it) and runs for every reason Pi
@@ -2934,11 +3407,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2934
3407
  });
2935
3408
  } catch { /* A launch freezes lazily through the same resolver. */ }
2936
3409
  stateCache.load(ctx.sessionManager);
2937
- // A resumed, reloaded, or replaced session starts with an empty completion
2938
- // queue so nothing pending from another session can replay here.
3410
+ // A resumed, reloaded, or replaced session starts with empty completion
3411
+ // and message queues so nothing pending from another session can replay here.
2939
3412
  completions.dropAll();
2940
3413
  messages.dropAll();
2941
- jobNotices.length = 0;
3414
+ // Job notices remain owner-scoped and survive until their session resumes.
2942
3415
  resetParentDelivery(ctx);
2943
3416
  presence?.dispose();
2944
3417
  registryFor(ctx);
@@ -2954,12 +3427,21 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2954
3427
  // resolveTask path for anything else.
2955
3428
  const sessionId = ctx.sessionManager.getSessionId();
2956
3429
  const preexisting = event.reason === "resume" || (event.reason === "startup" && ctx.sessionManager.getEntries().length > 0);
2957
- if (preexisting && sessionId) void restoreSessionHistory(ctx, sessionId);
3430
+ if (preexisting && sessionId) sessionRestoration = restoreSessionHistory(ctx, sessionId);
2958
3431
  try {
2959
3432
  presence = startPresence(ctx.sessionManager);
2960
3433
  resetActivityPublish();
2961
3434
  publishActivityPrompt();
2962
- } catch { presence = undefined; }
3435
+ } catch {
3436
+ presence = undefined;
3437
+ // Fixed text only: the failure may carry a profile path or session id.
3438
+ try { ctx.ui.notify("Session presence unavailable: phase=presence class=transport code=presence-cleared.", "warning"); } catch {}
3439
+ }
3440
+ // /reload and /resume recompute busy from live owned work only: a task
3441
+ // restored from disk never enters ownedTaskIds, so counting it would
3442
+ // report working for work this runtime no longer owns. An unchanged
3443
+ // label dedups; a session without owned running work lowers.
3444
+ refreshHerdrBusy();
2963
3445
  void startSessionTransport(ctx);
2964
3446
  // The desktop app's own pi process: publish live subagent state through
2965
3447
  // setWidget's RPC-mode string[] path. Plain headless RPC (no variable) and
@@ -2985,9 +3467,20 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2985
3467
  rpcActivityPublisher.start();
2986
3468
  }
2987
3469
  });
3470
+ pi.on("agent_start", (_event, ctx) => rearmSessionTransport(ctx));
3471
+ pi.on("turn_end", (_event, ctx) => rearmSessionTransport(ctx));
2988
3472
  pi.on("session_shutdown", async () => {
3473
+ shuttingDown = true;
3474
+ stopAgentsStatusNotifications();
3475
+ // Both Desktop owner services leave the bus with the session, so a
3476
+ // replaced runtime is never discovered through a stale owner.
3477
+ unsubscribeDesktopJobsService();
3478
+ unsubscribeDesktopAgentsService();
2989
3479
  completions.dropAll();
2990
3480
  messages.dropAll();
3481
+ // No stale busy may survive the runtime.
3482
+ if (emittedBusy?.active) pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
3483
+ emittedBusy = { active: false };
2991
3484
  // Jobs never outlive their session: a stopped job sends no notice.
2992
3485
  monitors.cancelAll();
2993
3486
  const jobsStopped = jobs.stopAll();