gentle-pi 4.5.1 → 4.7.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 (428) hide show
  1. package/README.md +17 -15
  2. package/assets/agents/gentle-ai-explore.md +1 -0
  3. package/assets/agents/gentle-ai-verify.md +8 -1
  4. package/assets/agents/gentle-ai-worker.md +4 -0
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +1 -0
  7. package/assets/agents/jd-judge-b.md +1 -0
  8. package/assets/design-canvas/canvas.css +13 -1
  9. package/assets/design-canvas/canvas.js +11 -2
  10. package/assets/install-wizard/wizard.js +1 -0
  11. package/assets/migrations/agent-body-history.json +162 -0
  12. package/assets/orchestrator-delegation-reference.md +7 -7
  13. package/assets/orchestrator-delegation.md +3 -3
  14. package/assets/orchestrator-full-delegation-card.md +65 -0
  15. package/assets/orchestrator-full-delegation.md +34 -0
  16. package/assets/orchestrator-memory.md +3 -3
  17. package/assets/orchestrator-prompts.md +1 -1
  18. package/assets/orchestrator-skills.md +1 -1
  19. package/assets/orchestrator-verification.md +14 -8
  20. package/assets/orchestrator.md +11 -11
  21. package/bin/gentle-shell.mjs +225 -82
  22. package/docs/agent-status.md +61 -0
  23. package/docs/bundled-install.md +7 -5
  24. package/docs/ci-performance.md +11 -0
  25. package/docs/delegated-verification.md +35 -7
  26. package/docs/fast-mode.md +15 -0
  27. package/docs/gentle-agents-activity.md +22 -0
  28. package/docs/gentle-shell.md +113 -25
  29. package/docs/install-wizard.md +2 -2
  30. package/docs/mcp-status.md +52 -0
  31. package/docs/permission-modes.md +9 -4
  32. package/docs/prompt-budget.md +28 -0
  33. package/docs/readme-reference.md +154 -50
  34. package/docs/render-cache-performance.md +11 -1
  35. package/docs/review-coordinator.md +33 -0
  36. package/docs/review-request-context.md +19 -0
  37. package/docs/review-windows-acl.md +18 -0
  38. package/docs/session-profile-format.md +20 -5
  39. package/docs/sound-notifications.md +1 -1
  40. package/docs/star-prompt.md +32 -0
  41. package/docs/voice.md +6 -3
  42. package/docs/work-continuity.md +46 -0
  43. package/docs/yolo-mode.md +5 -5
  44. package/extensions/ask-user-choice.ts +1 -0
  45. package/extensions/ask-user-question.ts +2 -0
  46. package/extensions/child-safety.ts +3 -0
  47. package/extensions/codegraph-tools.ts +38 -4
  48. package/extensions/gentle-agent-status.ts +99 -0
  49. package/extensions/gentle-agents.ts +803 -84
  50. package/extensions/gentle-ai.ts +2491 -596
  51. package/extensions/gentle-fast.ts +61 -0
  52. package/extensions/gentle-guide.ts +174 -0
  53. package/extensions/gentle-herdr-activity.ts +21 -1
  54. package/extensions/gentle-herdr-agent.ts +144 -0
  55. package/extensions/gentle-program-identity.ts +61 -0
  56. package/extensions/gentle-shell.ts +895 -120
  57. package/extensions/gentle-star-prompt.ts +334 -0
  58. package/extensions/gentle-stats.ts +5 -5
  59. package/extensions/gentle-todo.ts +59 -23
  60. package/extensions/gentle-tps.ts +48 -0
  61. package/extensions/history/store.ts +18 -12
  62. package/extensions/quiet-tools.ts +38 -8
  63. package/extensions/skill-registry.ts +210 -21
  64. package/extensions/startup-banner.ts +69 -10
  65. package/lib/agent-assets.ts +74 -17
  66. package/lib/agent-profile-pin.ts +3 -3
  67. package/lib/agent-profiles.ts +161 -3
  68. package/lib/agent-status.ts +105 -0
  69. package/lib/agents-config.ts +58 -3
  70. package/lib/agents-history.ts +24 -5
  71. package/lib/agents-keys.ts +8 -16
  72. package/lib/agents-messaging.ts +47 -5
  73. package/lib/agents-protocol.ts +80 -4
  74. package/lib/agents-runner.ts +287 -15
  75. package/lib/agents-view.ts +6 -1
  76. package/lib/agents-widget.ts +132 -9
  77. package/lib/auto-permission-runtime.ts +1 -1
  78. package/lib/bounded-writer-admission.ts +13 -1
  79. package/lib/bridge-cost.ts +28 -0
  80. package/lib/card-content-policy.ts +8 -6
  81. package/lib/codemode-renderer.ts +16 -0
  82. package/lib/command-palette-catalog.ts +1 -0
  83. package/lib/command-palette.ts +154 -25
  84. package/lib/context-backstop.ts +14 -5
  85. package/lib/destructive-command-guard.ts +48 -4
  86. package/lib/execution-surface-guard.ts +20 -0
  87. package/lib/exploration-budget.ts +64 -0
  88. package/lib/gentle-ai-binary.ts +1 -1
  89. package/lib/gentle-design.ts +3 -0
  90. package/lib/gentle-guide.ts +201 -0
  91. package/lib/gentle-shell-bundled.ts +6 -19
  92. package/lib/gentle-shell-launcher.ts +47 -8
  93. package/lib/herdr-activity.ts +23 -5
  94. package/lib/herdr-busy.ts +45 -0
  95. package/lib/herdr-task-summary-policy.ts +85 -0
  96. package/lib/image-attachments.ts +33 -0
  97. package/lib/image-disk-cache.ts +137 -0
  98. package/lib/inprocess-reviewer.ts +282 -132
  99. package/lib/jobs-sidebar-state.ts +5 -6
  100. package/lib/jobs-view.ts +198 -11
  101. package/lib/jobs-widget.ts +16 -52
  102. package/lib/keymaps-customize.ts +81 -0
  103. package/lib/keymaps.ts +291 -0
  104. package/lib/model-fallback-notice.ts +61 -0
  105. package/lib/model-fallback-policy.ts +141 -0
  106. package/lib/model-fallback-store.ts +143 -0
  107. package/lib/model-routing-authority.ts +32 -6
  108. package/lib/nan-provider.ts +3 -2
  109. package/lib/native-choice-list.ts +20 -2
  110. package/lib/native-review-cli.ts +103 -21
  111. package/lib/notification-customize.ts +48 -51
  112. package/lib/openai-fast-tier.ts +22 -0
  113. package/lib/orchestrator-discovery.ts +5 -1
  114. package/lib/orchestrator-fallback.ts +75 -0
  115. package/lib/orchestrator-mode-policy.ts +105 -0
  116. package/lib/pasted-image-paths.ts +113 -0
  117. package/lib/questionnaire/questionnaire-view.ts +225 -18
  118. package/lib/rdd-mode-control.ts +32 -0
  119. package/lib/reply-language-anchor.ts +104 -0
  120. package/lib/review-blocker.ts +92 -0
  121. package/lib/review-candidate-symlink-scan.ts +136 -0
  122. package/lib/review-candidate-view-owner.ts +85 -44
  123. package/lib/review-candidate-view.ts +10 -7
  124. package/lib/review-continuation-registry.ts +99 -0
  125. package/lib/review-coordinator.ts +163 -0
  126. package/lib/review-failure-facts.ts +49 -0
  127. package/lib/review-host-relay.ts +51 -11
  128. package/lib/review-integration-v2.ts +29 -8
  129. package/lib/review-relay-phase-timing.ts +45 -0
  130. package/lib/review-repository.ts +5 -0
  131. package/lib/review-start-context.ts +17 -0
  132. package/lib/session-profile-append-controller.ts +21 -6
  133. package/lib/session-profile-authority.ts +119 -0
  134. package/lib/session-profile-binding.ts +54 -5
  135. package/lib/session-profile-freeze.ts +107 -9
  136. package/lib/session-profile-integration.ts +313 -0
  137. package/lib/session-profile-persistence.ts +63 -9
  138. package/lib/shell-bar.ts +269 -72
  139. package/lib/shell-card.ts +26 -6
  140. package/lib/shell-changes.ts +2 -0
  141. package/lib/shell-page.ts +120 -0
  142. package/lib/shell-panel.ts +163 -0
  143. package/lib/shell-prompt.ts +53 -1
  144. package/lib/shell-sidebar-layout.ts +198 -53
  145. package/lib/shell-sidebar.ts +61 -1
  146. package/lib/shell-stats.ts +123 -0
  147. package/lib/shell-todo.ts +79 -1
  148. package/lib/shell-usage.ts +12 -2
  149. package/lib/star-prompt.ts +197 -0
  150. package/lib/verifier-admission.ts +18 -8
  151. package/lib/verifier-settle-reminder.ts +64 -0
  152. package/lib/vim-editor-adapter.ts +6 -1
  153. package/lib/visual-customization-policy.ts +67 -12
  154. package/lib/visual-customize-view.ts +373 -40
  155. package/lib/visual-layout-preview.ts +47 -0
  156. package/lib/visual-profiles.ts +2 -2
  157. package/lib/windows-session-transport.ts +53 -2
  158. package/lib/yolo-session-policy.ts +68 -16
  159. package/package.json +2 -1
  160. package/runtime/gentle-ai-binary.mjs +1 -1
  161. package/runtime/gentle-shell-bundled.mjs +6 -19
  162. package/runtime/gentle-shell-launcher.mjs +46 -7
  163. package/runtime/native-review-cli.mjs +100 -18
  164. package/runtime/review-integration-v2.mjs +29 -8
  165. package/runtime/windows-session-transport.ps1 +60 -3
  166. package/scripts/bootstrap.sh +4 -1
  167. package/scripts/build-full-delegation-card.mjs +175 -0
  168. package/scripts/bundled-install.mjs +38 -8
  169. package/scripts/download-progress.mjs +68 -0
  170. package/scripts/gentle-ai-installer.mjs +41 -18
  171. package/scripts/gentle-ai-proxy.mjs +294 -0
  172. package/scripts/install-gentle-ai.mjs +14 -1
  173. package/scripts/installer-preflight.mjs +6 -6
  174. package/scripts/installer-runner.mjs +27 -12
  175. package/scripts/installer-server.mjs +8 -7
  176. package/scripts/pi-update.mjs +113 -3
  177. package/scripts/render-cache-host.mjs +72 -0
  178. package/scripts/render-cache-performance-worker.mjs +5 -4
  179. package/scripts/render-cache-performance.mjs +6 -1
  180. package/scripts/run-test-suite.mjs +41 -13
  181. package/scripts/shell-snapshot.mjs +340 -0
  182. package/scripts/test-packed-runner.mjs +1 -1
  183. package/scripts/update-agent-body-history.mjs +41 -0
  184. package/scripts/verify-installer-tap.mjs +45 -0
  185. package/scripts/verify-package-files.mjs +14 -2
  186. package/scripts/voice-worker.cjs +32 -6
  187. package/skills/design/SKILL.md +11 -8
  188. package/skills/gentle-ai/SKILL.md +4 -4
  189. package/skills/gentle-ui-design/SKILL.md +46 -0
  190. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  191. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  192. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  193. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  194. package/skills/skill-registry/SKILL.md +4 -2
  195. package/skills/tui-design/NOTICE.md +5 -0
  196. package/skills/tui-design/SKILL.md +56 -0
  197. package/skills/tui-design/references/commands.md +75 -0
  198. package/skills/tui-design/references/critique.md +48 -0
  199. package/skills/tui-design/references/design-doc.md +44 -0
  200. package/skills/tui-design/references/terminal-craft.md +64 -0
  201. package/skills/tui-design/references/visual-loop.md +32 -0
  202. package/skills/work-unit-commits/SKILL.md +6 -7
  203. package/tests/agent-home.test.ts +28 -9
  204. package/tests/agent-profiles-workflow.test.ts +163 -0
  205. package/tests/agent-risk-escalation.test.ts +1 -1
  206. package/tests/agent-status.test.ts +143 -0
  207. package/tests/agents-config.test.ts +96 -0
  208. package/tests/agents-history.test.ts +31 -0
  209. package/tests/agents-jobs-frames.test.ts +93 -0
  210. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  211. package/tests/agents-protocol.test.ts +53 -1
  212. package/tests/agents-runner-drain.test.ts +193 -0
  213. package/tests/agents-runner.test.ts +345 -4
  214. package/tests/agents-view.test.ts +27 -0
  215. package/tests/agents-widget.test.ts +312 -10
  216. package/tests/append-system-prompt-route.test.ts +4 -1
  217. package/tests/ask-user-choice.test.ts +4 -3
  218. package/tests/ask-user-question.test.ts +97 -0
  219. package/tests/auto-permission-runtime.test.ts +1 -1
  220. package/tests/autonomous-guard.test.ts +346 -10
  221. package/tests/bounded-scan-contract.test.ts +39 -0
  222. package/tests/bounded-stop-contract.test.ts +43 -3
  223. package/tests/bridge-cost.test.ts +47 -0
  224. package/tests/bundled-install.test.ts +36 -9
  225. package/tests/card-content-policy.test.ts +3 -3
  226. package/tests/chained-pr-skill.test.ts +8 -6
  227. package/tests/child-safety.test.ts +11 -0
  228. package/tests/ci-concurrency.test.ts +11 -0
  229. package/tests/ci-merge-base-identity.test.ts +114 -0
  230. package/tests/codegraph-tools.test.ts +80 -5
  231. package/tests/codemode-rendering.test.ts +22 -2
  232. package/tests/command-palette.test.ts +300 -3
  233. package/tests/commit-slice-signal.test.ts +11 -9
  234. package/tests/delegate-for-reason-contract.test.ts +8 -7
  235. package/tests/design-canvas-assets.test.ts +185 -2
  236. package/tests/destructive-command-guard.test.ts +52 -0
  237. package/tests/download-progress.test.ts +71 -0
  238. package/tests/execution-surface-guard.test.ts +55 -0
  239. package/tests/exploration-budget.test.ts +128 -0
  240. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  241. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  242. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +26 -14
  243. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  244. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  245. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  246. package/tests/fixtures/session-profile-v1/replay.ts +172 -0
  247. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  248. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  249. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  250. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  251. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  252. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  253. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  254. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  255. package/tests/full-delegation-closure.test.ts +131 -0
  256. package/tests/full-delegation-notices.test.ts +76 -0
  257. package/tests/generic-agent-tools.test.ts +3 -3
  258. package/tests/gentle-agent-status.test.ts +74 -0
  259. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  260. package/tests/gentle-agents.test.ts +1491 -38
  261. package/tests/gentle-ai-binary.test.ts +3 -1
  262. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  263. package/tests/gentle-ai-exploration-budget.test.ts +151 -0
  264. package/tests/gentle-ai-installer.test.ts +134 -51
  265. package/tests/gentle-ai-proxy.test.ts +434 -0
  266. package/tests/gentle-ai.test.ts +1101 -52
  267. package/tests/gentle-design.test.ts +21 -0
  268. package/tests/gentle-fast.test.ts +73 -0
  269. package/tests/gentle-guide.test.ts +208 -0
  270. package/tests/gentle-herdr-activity.test.ts +80 -3
  271. package/tests/gentle-herdr-agent.test.ts +111 -0
  272. package/tests/gentle-program-identity.test.ts +197 -0
  273. package/tests/gentle-shell-bin.test.ts +172 -26
  274. package/tests/gentle-shell-bundled.test.ts +207 -31
  275. package/tests/gentle-shell-launcher.test.ts +93 -10
  276. package/tests/gentle-shell.test.ts +1937 -66
  277. package/tests/gentle-stats.test.ts +15 -2
  278. package/tests/gentle-todo.test.ts +67 -4
  279. package/tests/gentle-tps.test.ts +123 -0
  280. package/tests/gentle-ui-design-skill.test.ts +59 -0
  281. package/tests/herdr-busy.test.ts +59 -0
  282. package/tests/herdr-task-summary-policy.test.ts +132 -0
  283. package/tests/history-store-private-mode.test.ts +40 -0
  284. package/tests/image-disk-cache.test.ts +163 -0
  285. package/tests/image-paste-chips.test.ts +42 -0
  286. package/tests/independent-recovery-delivery.test.ts +83 -0
  287. package/tests/inprocess-reviewer.test.ts +298 -4
  288. package/tests/installer-posix-bootstrap.test.ts +68 -6
  289. package/tests/installer-preflight.test.ts +5 -4
  290. package/tests/installer-runner.test.ts +79 -44
  291. package/tests/installer-server.test.ts +14 -11
  292. package/tests/installer-windows-diagnostics.test.ts +4 -5
  293. package/tests/isolated-config-home.ts +28 -0
  294. package/tests/jobs-view.test.ts +260 -6
  295. package/tests/jobs-widget.test.ts +25 -37
  296. package/tests/keymaps-customize.test.ts +114 -0
  297. package/tests/keymaps.test.ts +103 -0
  298. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  299. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  300. package/tests/modal-mouse-boundaries.test.ts +136 -0
  301. package/tests/model-fallback-notice.test.ts +45 -0
  302. package/tests/model-fallback-policy.test.ts +83 -0
  303. package/tests/model-fallback-store.test.ts +111 -0
  304. package/tests/model-routing-authority.test.ts +178 -2
  305. package/tests/nan-provider.test.ts +4 -4
  306. package/tests/native-choice-list.test.ts +77 -2
  307. package/tests/native-review-capability-contract.test.ts +7 -1
  308. package/tests/native-review-cli.test.ts +269 -1
  309. package/tests/no-self-pause-contract.test.ts +22 -0
  310. package/tests/notification-customize.test.ts +58 -34
  311. package/tests/odd-routing-canonical-ratchet.test.ts +6 -6
  312. package/tests/odd-routing-contract.test.ts +1 -1
  313. package/tests/orchestrator-budget.test.ts +7 -2
  314. package/tests/orchestrator-delegation-mode.test.ts +153 -0
  315. package/tests/orchestrator-fallback.test.ts +82 -0
  316. package/tests/orchestrator-mode-policy.test.ts +175 -0
  317. package/tests/orchestrator-prompt-budget.test.ts +133 -0
  318. package/tests/orchestrator-rdd-ownership.test.ts +2 -2
  319. package/tests/package-manifest.test.ts +169 -14
  320. package/tests/pasted-image-paths.test.ts +118 -0
  321. package/tests/permission-allowlist.test.ts +202 -0
  322. package/tests/persona-reply-language.test.ts +20 -1
  323. package/tests/pi-update-launcher.test.ts +40 -8
  324. package/tests/pi-update-source.test.ts +162 -0
  325. package/tests/pnpm-workspace-config.test.ts +58 -0
  326. package/tests/primary-session-prompt.test.ts +13 -0
  327. package/tests/profile-fast-tier.test.ts +311 -0
  328. package/tests/profile-pin.test.ts +29 -2
  329. package/tests/profile-tier-footer.test.ts +84 -0
  330. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  331. package/tests/questionnaire-view.test.ts +265 -0
  332. package/tests/quiet-bash-runtime.test.ts +1 -1
  333. package/tests/quiet-tool-rendering.test.ts +48 -0
  334. package/tests/rdd-aware-verification-contract.test.ts +16 -11
  335. package/tests/rdd-customize.test.ts +287 -0
  336. package/tests/rdd-mode-cache.test.ts +450 -0
  337. package/tests/rdd-mode-control.test.ts +407 -0
  338. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  339. package/tests/rdd-off-independent-regression.test.ts +69 -0
  340. package/tests/rdd-status-line.test.ts +18 -0
  341. package/tests/render-cache-performance.test.ts +171 -2
  342. package/tests/reply-language-anchor.test.ts +173 -0
  343. package/tests/review-agent-end-preflight.test.ts +1 -1
  344. package/tests/review-blocker.test.ts +193 -0
  345. package/tests/review-candidate-owner-retry.test.ts +1 -1
  346. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  347. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  348. package/tests/review-candidate-view.test.ts +52 -1
  349. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  350. package/tests/review-candidate-windows-probe.test.ts +63 -0
  351. package/tests/review-committed-restart-ack.test.ts +129 -0
  352. package/tests/review-continuation-registry.test.ts +76 -0
  353. package/tests/review-controller-native-routing.test.ts +381 -11
  354. package/tests/review-controller-workspace-root.test.ts +230 -3
  355. package/tests/review-controller.test.ts +96 -11
  356. package/tests/review-coordinator-runtime.test.ts +117 -0
  357. package/tests/review-coordinator.test.ts +195 -0
  358. package/tests/review-failure-facts.test.ts +87 -0
  359. package/tests/review-gate.test.ts +24 -0
  360. package/tests/review-host-relay-routing.test.ts +258 -4
  361. package/tests/review-host-relay.test.ts +39 -0
  362. package/tests/review-inspect-preflight.test.ts +197 -0
  363. package/tests/review-integration-v2-forward.test.ts +59 -0
  364. package/tests/review-integration-v2.test.ts +46 -3
  365. package/tests/review-json-arguments.test.ts +65 -10
  366. package/tests/review-last-event-closure.test.ts +68 -0
  367. package/tests/review-loadout-rdd-off-sdk.test.ts +65 -31
  368. package/tests/review-owner-identity.test.ts +60 -24
  369. package/tests/review-relay-phase-timing.test.ts +128 -0
  370. package/tests/review-relay-transport-agent.test.ts +12 -2
  371. package/tests/review-repository.test.ts +52 -1
  372. package/tests/review-reviewer-evidence.test.ts +183 -0
  373. package/tests/review-risk-assessment.test.ts +74 -3
  374. package/tests/review-session-standing-permission-controller.test.ts +21 -1
  375. package/tests/review-sidebar-state.test.ts +5 -5
  376. package/tests/review-start-context.test.ts +19 -0
  377. package/tests/review-tool-prose-budget.test.ts +121 -0
  378. package/tests/run-test-suite.test.ts +183 -6
  379. package/tests/runtime-harness.mjs +4 -1
  380. package/tests/sensitive-path-tools.test.ts +250 -0
  381. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  382. package/tests/session-profile-append-controller.test.ts +63 -0
  383. package/tests/session-profile-authority.test.ts +259 -0
  384. package/tests/session-profile-binding.test.ts +34 -1
  385. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  386. package/tests/session-profile-extension.test.ts +615 -0
  387. package/tests/session-profile-freeze.test.ts +110 -2
  388. package/tests/session-profile-integration.test.ts +857 -0
  389. package/tests/session-profile-persistence.test.ts +57 -0
  390. package/tests/session-profile-v1-compat.test.ts +255 -0
  391. package/tests/shell-bar.test.ts +274 -72
  392. package/tests/shell-card.test.ts +13 -1
  393. package/tests/shell-page.test.ts +108 -0
  394. package/tests/shell-panel.test.ts +360 -0
  395. package/tests/shell-prompt.test.ts +54 -0
  396. package/tests/shell-render-cache.test.ts +5 -0
  397. package/tests/shell-sidebar-fullscreen.test.ts +13 -1
  398. package/tests/shell-sidebar-layout.test.ts +447 -44
  399. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  400. package/tests/shell-stats.test.ts +90 -0
  401. package/tests/shell-surface-transparent.test.ts +89 -0
  402. package/tests/shell-todo.test.ts +12 -0
  403. package/tests/shell-usage.test.ts +14 -0
  404. package/tests/skill-registry.test.ts +902 -2
  405. package/tests/star-prompt.test.ts +470 -0
  406. package/tests/startup-banner.test.ts +209 -2
  407. package/tests/startup-home-repo.test.ts +2 -0
  408. package/tests/support/review-coordinator-runtime.ts +69 -0
  409. package/tests/task-size-routing-contract.test.ts +50 -4
  410. package/tests/verifier-admission.test.ts +49 -0
  411. package/tests/verifier-settle-reminder.test.ts +281 -0
  412. package/tests/verify-first-launch-contract.test.ts +134 -8
  413. package/tests/verify-installer-tap.test.ts +57 -0
  414. package/tests/vim-editor-adapter.test.ts +2 -2
  415. package/tests/visual-customization-policy.test.ts +95 -8
  416. package/tests/visual-customize-view.test.ts +818 -9
  417. package/tests/visual-layout-preview.test.ts +42 -0
  418. package/tests/visual-profiles.test.ts +11 -0
  419. package/tests/voice-worker.test.ts +73 -2
  420. package/tests/windows-session-bootstrap.test.ts +105 -2
  421. package/tests/windows-session-transport.test.ts +126 -0
  422. package/tests/work-continuity-contract.test.ts +114 -0
  423. package/tests/writer-feature-document-admission.test.ts +92 -0
  424. package/tests/writer-surfaces.test.ts +12 -10
  425. package/tests/yolo-customize.test.ts +57 -15
  426. package/tests/yolo-mode-runtime.test.ts +4 -2
  427. package/tests/yolo-mode.test.ts +39 -20
  428. package/tests/yolo-session-policy.test.ts +270 -1
@@ -1,4 +1,10 @@
1
+ import { fallbackNotice, MODEL_FALLBACK_ENTRY, profileFallbackChain, type FallbackChange } from "../lib/model-fallback-notice.ts";
2
+ import { sharedCooldown } from "../lib/model-fallback-policy.ts";
3
+ import { createOrchestratorFallback } from "../lib/orchestrator-fallback.ts";
4
+ import type { ThinkingLevel } from "../lib/model-routing-authority.ts";
1
5
  import { agentsViewKey, agentsCollapseKey, agentsStopKey } from "../lib/agents-keys.ts";
6
+ import { loadKeymaps } from "../lib/keymaps.ts";
7
+ import { CHILD_TIER_ENV } from "../lib/openai-fast-tier.ts";
2
8
  import { spawn } from "node:child_process";
3
9
  import { Type } from "typebox";
4
10
  import { recordReviewMutation } from "../lib/review-reminder-receipt.ts";
@@ -21,27 +27,28 @@ import { createMonitorController, mergeMonitorBatches, type MonitorNotice } from
21
27
  import { JobsView } from "../lib/jobs-view.ts";
22
28
  import { JOBS_FINISHED_TTL_MS } from "../lib/jobs-widget.ts";
23
29
  import { JOBS_SIDEBAR_EVENT, JOBS_STATUS_KEY } from "../lib/jobs-sidebar-state.ts";
24
- import { Text, type Component, type TUI } from "@earendil-works/pi-tui";
30
+ import { Text, truncateToWidth, type Component, type TUI } from "@earendil-works/pi-tui";
25
31
  import { invalidateSidebar } from "../lib/shell-sidebar-layout.ts";
26
- import { sidebarPart, VISUAL_SETTINGS_CHANGED } from "../lib/shell-sidebar.ts";
32
+ import { releaseSidebarHover, setSidebarHover, sidebarPart, VISUAL_SETTINGS_CHANGED } from "../lib/shell-sidebar.ts";
27
33
  import { NativePointerRegion } from "../lib/native-pointer-region.ts";
28
34
  import { resolveVisualSettings } from "../lib/visual-customization-policy.ts";
29
35
  import { createCompletionQueue } from "../lib/agents-completion-delivery.ts";
30
36
  import { createAgentMessageQueue, type PendingAgentMessage } from "../lib/agents-message-delivery.ts";
31
- import { AGENT_MODE, PROFILE_SOURCE, discoverAgents, formatModelRef, loadAgentsConfig, resolveAgentProfile, unmatchedProfileKeys, withPinnedModelProfiles, type AgentDefinition, type AgentMode, type ProfileSource } from "../lib/agents-config.ts";
37
+ 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";
32
38
  import { freezeSessionProfileAtStartup, inheritedProfileDriftNotice, resolveSessionProfile, sessionProfileRoutingAt, type InheritedProfileOptions, type SessionProfileResolution } from "../lib/session-profile-freeze.ts";
33
39
  import { resolveProfilePin, resolveUnversionedProjectProfile } from "../lib/agent-profile-pin.ts";
40
+ import { requireSessionProfileAuthority } from "../lib/session-profile-authority.ts";
34
41
  import { resolveBackgroundSubagentsPolicy } from "../lib/background-subagents-policy.ts";
35
42
  import { installBackgroundCacheWarming } from "../lib/background-cache-warming.ts";
36
43
  import { isFinished, MISSING_TOOLS_NOTE_PREFIX, TASK_EVENT, TASK_STATUS, TaskStore, type AskRequest, type TaskRecord } from "../lib/agents-protocol.ts";
37
- import { AgentRunner, piCommand, abortReasonText, REQUESTED_TOOLS_ENV, type AskAnswer, type RunnerDeps, type TaskRequest } from "../lib/agents-runner.ts";
44
+ import { AgentRunner, piCommand, abortReasonText, CHILD_JOBS_ENV, REQUESTED_TOOLS_ENV, type AskAnswer, type RunnerDeps, type TaskRequest } from "../lib/agents-runner.ts";
38
45
  import { parseChildPackageInjection } from "../lib/child-package-injection.ts";
39
- import { ChildMessenger, type IpcEndpoint } from "../lib/agents-messaging.ts";
46
+ import { ChildMessenger, formatChildJobState, type IpcEndpoint } from "../lib/agents-messaging.ts";
40
47
  import { ActiveSessionClient, ActiveSessionListener, SessionPresenceError, SessionPresenceRegistry, type PresenceRecord, type ReceivedNotification, type SentNotification, type SessionPresenceCandidate } from "../lib/agents-session-transport.ts";
41
- import { WindowsActiveSessionClient, WindowsActiveSessionListener, WindowsSessionPresenceRegistry, type WindowsSessionRegistryPhaseObserver } from "../lib/windows-session-transport.ts";
48
+ import { WindowsActiveSessionClient, WindowsActiveSessionListener, WindowsSessionPresenceRegistry, WindowsSessionRegistryPhaseSequence, isWindowsSessionBootstrapDiagnosticCode, type WindowsSessionBootstrapDiagnosticCode, type WindowsSessionBootstrapDiagnosticObserver, type WindowsSessionRegistryPhaseObserver } from "../lib/windows-session-transport.ts";
42
49
  import { hasReviewSessionPermission, resolveCanonicalGitRepositoryIdentitySync, type ReviewSessionManager } from "../lib/review-session-standing-permission.ts";
43
50
  import { inheritedUnsafeGitEnvironmentKeys } from "../lib/review-repository.ts";
44
- import { historyDir, loadHistory, loadStoredTask, pruneHistory, saveTask } from "../lib/agents-history.ts";
51
+ import { historyDir, loadHistory, loadStoredTask, pruneHistory, saveTask, type StoredTask } from "../lib/agents-history.ts";
45
52
  import { sessionToMarkdown } from "../lib/agents-transcript.ts";
46
53
  import { AgentsView } from "../lib/agents-view.ts";
47
54
  import { withOverlayRepaint } from "../lib/overlay-repaint.ts";
@@ -60,8 +67,9 @@ import { OrchestratorScopeCache, type RepositoryFact } from "../lib/orchestrator
60
67
  import { createRpcActivityPublisher, type RpcActivityPublisher } from "../lib/agents-rpc-publisher.ts";
61
68
  import { isInteractiveRpcHost } from "../lib/rpc-host.ts";
62
69
  import { createNativeFullscreenInteraction } from "../lib/native-fullscreen-interaction.ts";
63
- import { AGENTS_GLYPH, agentsCardTone, renderAgentsCard, widgetExpiryMs, widgetRows } from "../lib/agents-widget.ts";
64
- import { CARD_TONE, panelHeaderRow, renderCard } from "../lib/shell-card.ts";
70
+ import { HERDR_BUSY_CHANNEL, nextHerdrBusyAction, type HerdrBusyEmitted } from "../lib/herdr-busy.ts";
71
+ import { AGENTS_GLYPH, agentsCardTone, agentsSpend, agentsSummary, renderAgentsAlert, renderAgentsCard, renderAgentsSection, widgetExpiryMs, widgetRows } from "../lib/agents-widget.ts";
72
+ 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";
65
73
  import { openInExternalEditor } from "./gentle-shell.ts";
66
74
  import { gentlePiConfigHome } from "../lib/agent-home.ts";
67
75
  import { resolveAgentHomeDirectory } from "../lib/agent-model-resolution.ts";
@@ -93,6 +101,31 @@ function messagePeerLabel(profile: string, sessionId: string): string | undefine
93
101
  return matches.length === 1 && matches[0].recent ? sanitizeDisplayLabel(matches[0].label) || undefined : undefined;
94
102
  } catch { return undefined; }
95
103
  }
104
+ /** Human-readable labels for the recipient picker. A raw session id gives a person
105
+ * nothing to choose by, so the published session label and the workspace are used when
106
+ * they exist, and a short id suffix keeps every label unique: the chosen label is mapped
107
+ * back to a peer by exact match, so a collision would select the wrong one. */
108
+ function recipientSelectionLabels(profile: string, candidates: readonly PresenceRecord[], activations: readonly PresenceRecord[] = candidates): string[] {
109
+ let discovered: ReturnType<typeof discoverOrchestrators> = [];
110
+ // Discovery must see every activation: it fails closed when one session resolves to
111
+ // several, and deduplicating before this point would silently label an ambiguous peer.
112
+ try { discovered = discoverOrchestrators(profile, activations); } catch { /* labels are best-effort, never routing */ }
113
+ const peersById = new Map(discovered.map(peer => [peer.sessionId, peer] as const));
114
+ const bases = candidates.map((candidate) => {
115
+ const peer = peersById.get(candidate.sessionId);
116
+ const name = peer?.label ?? peer?.legacyLabel;
117
+ if (!name) return "Orchestrator";
118
+ const workspace = peer?.workspace?.split(/[\\/]/).filter(Boolean).at(-1);
119
+ return workspace && workspace !== name ? `${name} (${workspace})` : name;
120
+ });
121
+ // Short ids stay whole (fixtures and test sessions); long ones are suffixed.
122
+ const suffix = (sessionId: string, length: number): string => sessionId.length <= 8 ? sessionId : sessionId.slice(-length);
123
+ for (const length of [4, 6, 8]) {
124
+ const labels = bases.map((base, index) => `${base} · ${suffix(candidates[index]!.sessionId, length)}`);
125
+ if (new Set(labels).size === labels.length) return labels;
126
+ }
127
+ return bases.map((base, index) => `${base} · ${candidates[index]!.sessionId}`);
128
+ }
96
129
  export const AGENTS_STALE_RESULT_TYPE = "gentle-agents.stale-result";
97
130
  export const AGENTS_STALE_NOTICE_TYPE = "gentle-agents.stale-notice";
98
131
  const RENDER_COALESCE_MS = 400;
@@ -100,6 +133,8 @@ const CLOCK_TICK_MS = 1000;
100
133
  const TOOL_PREFIX = "subagent_";
101
134
  // Wakes an idle parent after child content was stored as a custom message.
102
135
  // It names itself as automated so the model never attributes it to the human.
136
+ // Persisted Bridge identities embed this exact text, so changing it would
137
+ // unhide the wakes of existing sessions.
103
138
  const PARENT_WAKE_TEXT = "[System-generated Gentle Agents notification, not written by the user] Subagent output was delivered to this session above. Review it and continue.";
104
139
  const PARENT_WAKE_TYPE = "gentle-agents.wake";
105
140
  const BRIDGE_WAKE_IDENTITY_TYPE = "gentle-agents.wake-identity";
@@ -109,10 +144,19 @@ interface BridgeWakeIdentity {
109
144
  text: string;
110
145
  }
111
146
  const bridgeWakeText = (nonce: string): string => `${PARENT_WAKE_TEXT} [gentle-agents wake: ${nonce}]`;
112
- const NATIVE_PARENT_WAKE_TEXT = "Review the delivered subagent output and continue.";
147
+ // Pi gives the hidden native wake to the model with the user role, so an
148
+ // unlabeled English wake read as an English human turn and switched the reply
149
+ // language. It disowns authorship and pins the human's language.
150
+ const NATIVE_PARENT_WAKE_TEXT = `${PARENT_WAKE_TEXT} Reply in the language of the human's own last message, not the language of this notification or of the subagent output.`;
113
151
  // How long a dispatched wake may take to start a parent run before a later
114
152
  // delivery may send another one.
115
153
  export const PARENT_WAKE_GRACE_MS = 30_000;
154
+ // How often a parent that is busy without a run is re-checked while content is
155
+ // held for it. See `armHoldRecheck`.
156
+ export const HOLD_RECHECK_MS = 1000;
157
+ // How long a user prompt seen at `input` suppresses the idle wake while it is
158
+ // still in its pre-run phase. See the `input` handler.
159
+ export const INPUT_PROMPT_GRACE_MS = 2000;
116
160
  // A delivery or wake the host rejected while the parent was idle is retried
117
161
  // after the grace at most this many times in a row, so a permanently broken
118
162
  // runtime never retries forever.
@@ -140,7 +184,7 @@ export interface SessionTransportClient {
140
184
  }
141
185
 
142
186
  export interface SessionTransportFactory {
143
- createRegistry(agentHome: string, observeWindowsPhase?: WindowsSessionRegistryPhaseObserver): Promise<SessionTransportRegistry>;
187
+ createRegistry(agentHome: string, observeWindowsPhase?: WindowsSessionRegistryPhaseObserver, observeWindowsBootstrap?: WindowsSessionBootstrapDiagnosticObserver): Promise<SessionTransportRegistry>;
144
188
  createListener(registry: SessionTransportRegistry, sessionId: string, onNotification: (notification: ReceivedNotification) => Promise<void>): SessionTransportListener;
145
189
  createClient(registry: SessionTransportRegistry, sessionId: string): SessionTransportClient;
146
190
  }
@@ -235,15 +279,15 @@ export function agentRuntimePaths(home: string, agentHome = join(home, ".pi", "a
235
279
 
236
280
  const workDescriptorSchema = {
237
281
  type: "object", additionalProperties: false,
238
- description: "Explicit non-authoritative classification, not child context. Topic requires area; limits are UTF-8 bytes. No nested tasks.",
282
+ description: "Non-authoritative, not child context; topic requires area; UTF-8 byte limits. No nested tasks.",
239
283
  properties: {
240
284
  area: { type: "string", maxLength: 64 }, topic: { type: "string", maxLength: 64 },
241
285
  tags: { type: "array", maxItems: 8, uniqueItems: true, items: { type: "string", maxLength: 64 } },
242
286
  refs: { type: "array", maxItems: 8, uniqueItems: true, items: {
243
287
  type: "object", additionalProperties: false, required: ["kind", "repository", "id"], properties: {
244
288
  kind: { type: "string", enum: ["issue", "pr", "task"] },
245
- repository: { type: "string", maxLength: 256, description: "Explicit public host/owner/repo; not a URL or inferred identity." },
246
- id: { type: "string", maxLength: 256, description: "Canonical positive decimal issue/PR ID or opaque historical task ID; never a peer route." },
289
+ repository: { type: "string", maxLength: 256, description: "Explicit public host/owner/repo, not URL or inferred identity." },
290
+ id: { type: "string", maxLength: 256, description: "Issue/PR: canonical positive decimal; task: opaque historical ID. Never a peer route." },
247
291
  },
248
292
  } },
249
293
  },
@@ -371,6 +415,46 @@ function registerChildMessaging(pi: ExtensionAPI, ipc: IpcEndpoint): void {
371
415
  });
372
416
  }
373
417
 
418
+ // gentle-shell#2266: a child admitted for background jobs registers the tools
419
+ // against its own private registry and reports its job state back over owned
420
+ // IPC, so the runner can drain one bounded window at settlement instead of
421
+ // killing a job mid-flight. The monitor stays parent-only.
422
+ function registerChildBackgroundJobs(pi: ExtensionAPI, env: NodeJS.ProcessEnv, overrides: Partial<AgentsDeps>, ipc: IpcEndpoint): void {
423
+ const home = overrides.home ?? os.homedir();
424
+ const agentHome = overrides.agentHome ?? resolveAgentHomeDirectory({ env, home, agentHome: overrides.agentHome, homeOverridden: overrides.home !== undefined });
425
+ const now = overrides.now ?? (() => Date.now());
426
+ let outputDir: string | undefined;
427
+ let nextFrame = 0;
428
+ const reportJobs = (): void => {
429
+ const running = jobs.running();
430
+ try { ipc.send({ id: `j${++nextFrame}`, kind: "job", message: formatChildJobState({ running, pending: running > 0 }) }); }
431
+ catch { /* A lost report only costs the drain, never the job. */ }
432
+ };
433
+ const jobs = createJobRegistry({
434
+ outputDir: overrides.jobOutputDir ?? (() => (outputDir ??= mkdtempSync(join(os.tmpdir(), "gentle-jobs-")))),
435
+ now,
436
+ shell: overrides.jobShell ?? ((cwd) => {
437
+ const settings = SettingsManager.create(cwd, agentHome);
438
+ return { operations: createLocalBashOperations({ shellPath: settings.getShellPath() }), commandPrefix: settings.getShellCommandPrefix() };
439
+ }),
440
+ onSettled: (job: JobRecord) => {
441
+ reportJobs();
442
+ try { pi.sendMessage({ customType: JOB_NOTICE_TYPE, content: jobNoticeText(job), display: true, details: jobDetails(job) }, { deliverAs: "steer", triggerTurn: true }); }
443
+ catch { /* The notice is best-effort; the job outcome and the drain still stand. */ }
444
+ },
445
+ });
446
+ registerBackgroundJobTools(pi, { registry: jobs, sessionId: (ctx) => ctx.sessionManager.getSessionId() ?? "", now, onChange: reportJobs });
447
+ // agent_settled reports the jobs still running so the runner can drain before
448
+ // it requests the orderly shutdown.
449
+ pi.on("agent_settled", () => reportJobs());
450
+ pi.on("session_shutdown", () => {
451
+ if (!outputDir) return;
452
+ const dir = outputDir;
453
+ outputDir = undefined;
454
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* A leftover temp directory is harmless. */ }
455
+ });
456
+ }
457
+
374
458
  const posixSessionTransport: SessionTransportFactory = {
375
459
  createRegistry(agentHome) { return SessionPresenceRegistry.create(agentHome); },
376
460
  createListener(registry: SessionPresenceRegistry, sessionId, onNotification) { return Object.assign(new ActiveSessionListener(registry, sessionId, onNotification), { closesRegistry: false }); },
@@ -378,7 +462,7 @@ const posixSessionTransport: SessionTransportFactory = {
378
462
  };
379
463
 
380
464
  const windowsSessionTransport: SessionTransportFactory = {
381
- createRegistry(agentHome, observeWindowsPhase) { return WindowsSessionPresenceRegistry.create(agentHome, observeWindowsPhase); },
465
+ createRegistry(agentHome, observeWindowsPhase, observeWindowsBootstrap) { return WindowsSessionPresenceRegistry.create(agentHome, observeWindowsPhase, observeWindowsBootstrap); },
382
466
  createListener(registry: WindowsSessionPresenceRegistry, sessionId, onNotification) { return Object.assign(new WindowsActiveSessionListener(registry, sessionId, onNotification), { closesRegistry: true }); },
383
467
  createClient(registry: WindowsSessionPresenceRegistry, sessionId) { return new WindowsActiveSessionClient(registry, sessionId); },
384
468
  };
@@ -408,7 +492,10 @@ function runtimeWriterProfile(task: TaskRecord): { writerModelId?: string; write
408
492
  }
409
493
 
410
494
  function taskDetails(task: TaskRecord): Record<string, unknown> {
411
- return { gentleAgents: { taskId: task.id, agent: task.agent, status: task.status, mode: task.mode, cwd: task.cwd } };
495
+ // Additive fields (label, turns, toolCalls, lastStep, error, model, thinking)
496
+ // feed the status card renderer; the model never sees details, so widening is
497
+ // display-only.
498
+ return { gentleAgents: { taskId: task.id, agent: task.agent, status: task.status, mode: task.mode, cwd: task.cwd, label: task.label, turns: task.turns, toolCalls: task.toolCalls, lastStep: task.lastStep, model: task.model, ...(task.thinking ? { thinking: task.thinking } : {}), ...(task.error ? { error: task.error } : {}) } };
412
499
  }
413
500
 
414
501
  export function describeTask(task: TaskRecord): string {
@@ -422,6 +509,162 @@ function finishedText(task: TaskRecord): string {
422
509
  return `Subagent ${task.agent} ${task.status}${task.error ? `: ${task.error}` : ""}${task.result ? `\n\nLast answer:\n${task.result}` : ""}`;
423
510
  }
424
511
 
512
+ // The status card speaks the Agents widget's visual language: the same glyph
513
+ // per state, and a card tone the reader can scan for — info while alive,
514
+ // success when done, error when the run ended without an answer, warning when
515
+ // the child is blocked on the parent.
516
+ const STATUS_CARD_TONE: Record<string, CardTone> = {
517
+ [TASK_STATUS.QUEUED]: CARD_TONE.INFO,
518
+ [TASK_STATUS.RUNNING]: CARD_TONE.INFO,
519
+ [TASK_STATUS.WAITING]: CARD_TONE.WARNING,
520
+ [TASK_STATUS.COMPLETED]: CARD_TONE.SUCCESS,
521
+ [TASK_STATUS.FAILED]: CARD_TONE.ERROR,
522
+ [TASK_STATUS.CANCELLED]: CARD_TONE.ERROR,
523
+ [TASK_STATUS.TIMED_OUT]: CARD_TONE.ERROR,
524
+ };
525
+ // The per-action identity from the design handoff (agent-tool-cards/04):
526
+ // each agent tool carries its own glyph and reads as a verb, so the transcript
527
+ // feels like working with agents rather than calling functions.
528
+ const ACTION_GLYPH: Record<string, string> = {
529
+ run: "→",
530
+ status: "◎",
531
+ result: "↩",
532
+ cancel: "⨯",
533
+ send_message: "✉",
534
+ reply: "✉",
535
+ continue: "↻",
536
+ list_tasks: "☰",
537
+ list_agents: "☰",
538
+ };
539
+ const ACTION_HEADING: Record<string, string> = {
540
+ run: "Delegating",
541
+ status: "Agent status",
542
+ result: "Agent answer",
543
+ cancel: "Stopping agent",
544
+ send_message: "Messaging agent",
545
+ reply: "Replying to agent",
546
+ continue: "Resuming agent",
547
+ list_tasks: "Agent tasks",
548
+ list_agents: "Agent roster",
549
+ };
550
+
551
+ // The state word as a scanable pill: uppercase, colored by the state's role.
552
+ function statusPill(status: string, theme: CardTheme): string {
553
+ const role = status === TASK_STATUS.COMPLETED ? "success"
554
+ : status === TASK_STATUS.WAITING ? "warning"
555
+ : (status === TASK_STATUS.FAILED || status === TASK_STATUS.CANCELLED || status === TASK_STATUS.TIMED_OUT) ? "error"
556
+ : "accent";
557
+ return theme.fg(role, status.replace("_", " ").toUpperCase());
558
+ }
559
+
560
+ // The agent identity palette from the design handoff (agent-tool-cards/04):
561
+ // agent cards wear the iris chrome — heading, glyph, frame and running pill —
562
+ // whatever the active accent is, so working with agents reads as its own
563
+ // mode. The palette is emitted as truecolor ANSI exactly like pi renders
564
+ // theme hex values; every other role stays theme-native, so body text,
565
+ // hints and the success/error states keep the user's theme.
566
+ const IRIS_FG = "\x1b[38;2;185;167;242m";
567
+ const IRIS_DEEP_FG = "\x1b[38;2;143;122;217m";
568
+ const IRIS_TINT_BG = "\x1b[48;2;26;21;38m";
569
+
570
+ // The float tint follows the card tone: info cards (live agent work) wear the
571
+ // iris tint; success, warning and error cards keep the theme's background.
572
+ function agentTheme(theme: CardTheme, tone: CardTone): CardTheme {
573
+ const tint = tone === CARD_TONE.INFO;
574
+ return {
575
+ fg: (color, text) => color === "accent" ? `${IRIS_FG}${text}\x1b[39m`
576
+ : color === "border" ? `${IRIS_DEEP_FG}${text}\x1b[39m`
577
+ : theme.fg(color, text),
578
+ ...(theme.bg ? { bg: (color, text) => tint && color === "toolSuccessBg" ? `${IRIS_TINT_BG}${text}\x1b[49m` : theme.bg!(color, text) } : {}),
579
+ };
580
+ }
581
+
582
+ // Card headings are one row: fold any line break a caller passes in before
583
+ // the usual control-character escaping.
584
+ function headingText(value: string): string {
585
+ return sanitizeTerminalText(value.replace(/[\r\n]+/g, " "));
586
+ }
587
+
588
+ // Structured task facts carried on the tool result; anything missing or of the
589
+ // wrong shape falls back to the plain preview, so older details and error
590
+ // results keep rendering.
591
+ interface StatusCardFacts {
592
+ taskId?: string;
593
+ agent?: string;
594
+ status?: string;
595
+ mode?: string;
596
+ cwd?: string;
597
+ label?: string;
598
+ turns?: number;
599
+ toolCalls?: number;
600
+ lastStep?: string;
601
+ error?: string;
602
+ model?: string;
603
+ thinking?: string;
604
+ }
605
+
606
+ function statusCardFacts(details: unknown): StatusCardFacts | undefined {
607
+ const raw = (details as { gentleAgents?: unknown } | undefined)?.gentleAgents;
608
+ if (typeof raw !== "object" || raw === null) return undefined;
609
+ const source = raw as Record<string, unknown>;
610
+ if (typeof source.taskId !== "string") return undefined;
611
+ const facts: StatusCardFacts = { taskId: source.taskId };
612
+ for (const key of ["agent", "status", "mode", "cwd", "label", "lastStep", "error", "model", "thinking"] as const) {
613
+ if (typeof source[key] === "string") facts[key] = source[key] as string;
614
+ }
615
+ for (const key of ["turns", "toolCalls"] as const) {
616
+ if (typeof source[key] === "number" && Number.isFinite(source[key])) facts[key] = source[key];
617
+ }
618
+ return facts;
619
+ }
620
+
621
+ // What the child runs on, beside the agent it runs as. The record stores the
622
+ // launch profile's model as `formatModelRef(undefined)` = "default" when no
623
+ // layer picked one, which is an inheritance, not a model name: say so.
624
+ function modelChip(model: string | undefined): string | undefined {
625
+ const named = model ? sanitizeTerminalText(model).trim() : "";
626
+ if (!named) return undefined;
627
+ return named === "default" ? "inherit" : named;
628
+ }
629
+
630
+ // One muted identity line: who, which task, and what the child runs on.
631
+ function subjectLine(chips: Array<string | undefined>): string | undefined {
632
+ const shown = chips.filter((chip): chip is string => typeof chip === "string" && chip !== "");
633
+ return shown.length > 0 ? shown.join(" · ") : undefined;
634
+ }
635
+
636
+ // A heading row carries identity, then the launch profile, then the key hint.
637
+ // The row is one line, so a narrow terminal sheds the profile from the end
638
+ // before it sheds the affordance the reader needs to open the card.
639
+ function fitSubject(
640
+ card: { title: string; tone: CardTone; glyph?: string },
641
+ hint: string | undefined,
642
+ size: number,
643
+ chips: Array<string | undefined>,
644
+ ): string | undefined {
645
+ const shown = chips.filter((chip): chip is string => typeof chip === "string" && chip !== "");
646
+ while (shown.length > 0 && !headingFits({ ...card, subtitle: subjectLine(shown), body: [] }, hint, size)) shown.pop();
647
+ return subjectLine(shown);
648
+ }
649
+
650
+ // One Gentle Shell card body for a task's live or final state, built from the
651
+ // details the execute path already records. Pure: facts in, body rows out.
652
+ // The state leads as a pill (RUNNING/OK/FAIL, colored by role); collapsed
653
+ // keeps pill, task label, and last step; expanded adds workspace and error.
654
+ function statusCardRows(facts: StatusCardFacts, theme: CardTheme, expanded: boolean): string[] {
655
+ const status = facts.status ?? "unknown";
656
+ const pill = statusPill(status, theme);
657
+ const head = [pill, facts.mode];
658
+ if (facts.turns !== undefined && facts.toolCalls !== undefined) head.push(`${facts.turns} turns · ${facts.toolCalls} tool calls`);
659
+ const headLine = head.filter((part) => part !== undefined).join(" · ");
660
+ const label = facts.label ? sanitizeTerminalText(facts.label) : undefined;
661
+ const cwd = facts.cwd ? `cwd ${sanitizeTerminalText(facts.cwd)}` : undefined;
662
+ const last = facts.lastStep ? `last: ${sanitizeTerminalText(facts.lastStep)}` : undefined;
663
+ const error = facts.error ? sanitizeTerminalText(facts.error) : undefined;
664
+ if (!expanded) return [headLine, ...(label ? [label] : []), ...(last ? [last] : [])];
665
+ return [headLine, ...(label ? [label] : []), ...(cwd ? [cwd] : []), ...(last ? [last] : []), ...(error ? [error] : [])];
666
+ }
667
+
425
668
  // pi's keybinding hint needs a live theme; outside one (tests, headless) the
426
669
  // plain words still tell the reader what the key does.
427
670
  function expandHint(expanded: boolean): string {
@@ -510,7 +753,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
510
753
  pi.on("tool_call", () => ({ block: true, reason: "Retired SDD child launch is not supported." }));
511
754
  return;
512
755
  }
513
- if (childIpc) registerChildMessaging(pi, childIpc);
756
+ if (childIpc) {
757
+ registerChildMessaging(pi, childIpc);
758
+ if (env[CHILD_JOBS_ENV] === "1") registerChildBackgroundJobs(pi, env, overrides, childIpc);
759
+ }
514
760
  registerMissingToolsCheck(pi, env);
515
761
  return;
516
762
  }
@@ -527,17 +773,67 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
527
773
  });
528
774
  return;
529
775
  }
530
- const collapseKey = agentsCollapseKey(env);
531
- const viewKey = agentsViewKey(env);
532
- const stopKey = agentsStopKey(env);
776
+ const keymaps = loadKeymaps(env).bindings;
777
+ const collapseKey = agentsCollapseKey(env, keymaps);
778
+ const viewKey = agentsViewKey(env, keymaps);
779
+ const stopKey = agentsStopKey(env, keymaps);
533
780
  const store = new TaskStore();
534
781
  // Attach before any live add/start; restore and unchanged updates are silent.
535
782
  // TaskStore contains bus listener failures so notifications cannot fail tools.
536
783
  const stopStatusNotifications = publishTaskStatusChanges(store, pi.events, () => performance.now());
537
784
  pi.on("session_shutdown", () => { stopStatusNotifications(); });
538
785
  const restoredTaskIds = new Set<string>();
786
+ // The latest resumed-session history restoration; list_tasks waits for it.
787
+ let sessionRestoration: Promise<void> = Promise.resolve();
539
788
  const tasksDir = historyDir(deps.home, agentHome);
540
789
  let ui: ExtensionContext["ui"] | undefined;
790
+ // The session that owns the Agents widget, so a click on an agent row opens its /gentle:agents view.
791
+ let widgetCtx: ExtensionContext | undefined;
792
+ // The catalog prices a fallback notice ("2.0x the price").
793
+ let modelRegistry: ExtensionContext["modelRegistry"] | undefined;
794
+ const announceFallback = (change: FallbackChange, parentSessionId: string | undefined, taskId?: string) => {
795
+ // Only the session that owns the run hears about it and records it.
796
+ if (parentSessionId !== undefined && activeSessionId() !== parentSessionId) return;
797
+ try { pi.appendEntry(MODEL_FALLBACK_ENTRY, { ...change, ...(taskId ? { taskId } : {}), at: deps.now() }); } catch { /* The switch matters more than its record. */ }
798
+ const prices = (model: { provider: string | undefined; id: string }) => (model.provider ? modelRegistry?.find(model.provider, model.id)?.cost : undefined);
799
+ ui?.notify(fallbackNotice(change, prices), "warning");
800
+ };
801
+ // One episode state per main session: a chain is walked once until a turn succeeds.
802
+ const orchestratorFallbacks = new Map<string, ReturnType<typeof createOrchestratorFallback>>();
803
+ const orchestratorFallbackFor = (ctx: ExtensionContext) => {
804
+ const sessionId = ctx.sessionManager.getSessionId() ?? "";
805
+ let fallback = orchestratorFallbacks.get(sessionId);
806
+ if (fallback) return fallback;
807
+ const find = (model: string) => {
808
+ const ref = parseModelRef(model);
809
+ return ref?.provider ? ctx.modelRegistry?.find(ref.provider, ref.id) : undefined;
810
+ };
811
+ fallback = createOrchestratorFallback({
812
+ chain: () => {
813
+ const configHome = gentlePiConfigHome(deps.env);
814
+ const resolution = resolveSessionProfile({ sessionId: ctx.sessionManager.getSessionId(), cwd: ctx.sessionManager.getCwd(), configHome, resolveWorktree: deps.resolveWorktree, env: deps.env });
815
+ return profileFallbackChain(configHome, resolution.kind === "explicit" ? resolution.name : resolution.profile?.name, "orchestrator");
816
+ },
817
+ current: () => (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined),
818
+ available: (model) => find(model) !== undefined,
819
+ setModel: async (model) => {
820
+ const found = find(model);
821
+ return found ? pi.setModel(found) : false;
822
+ },
823
+ setThinking: (level) => pi.setThinkingLevel(level),
824
+ // Unknown effort (an older host without the call) keeps each step's own effort only.
825
+ thinking: () => {
826
+ try { return typeof pi.getThinkingLevel === "function" ? pi.getThinkingLevel() as ThinkingLevel : undefined; }
827
+ catch { return undefined; }
828
+ },
829
+ announce: (change) => announceFallback(change, undefined),
830
+ resume: (message) => pi.sendUserMessage(message, { deliverAs: "followUp" }),
831
+ cooldown: sharedCooldown(),
832
+ now: () => deps.now(),
833
+ });
834
+ orchestratorFallbacks.set(sessionId, fallback);
835
+ return fallback;
836
+ };
541
837
  let host: { requestRender(): void } | undefined;
542
838
  let sidebarTui: TUI | undefined;
543
839
  const visualHome = gentlePiConfigHome(env);
@@ -722,6 +1018,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
722
1018
  type SessionTransport = { generation: number; sessionId: string; sessionManager: ExtensionContext["sessionManager"]; client: SessionTransportClient; listener: SessionTransportListener; registry: SessionTransportRegistry; close(): Promise<void> };
723
1019
  let transportGeneration = 0;
724
1020
  let activeSessionTransport: SessionTransport | undefined;
1021
+ // A session whose first startup failed gets exactly one later re-arm attempt.
1022
+ let transportRearm: { sessionManager: ExtensionContext["sessionManager"]; sessionId: string; ctx: ExtensionContext } | undefined;
725
1023
  const pendingTransportStartups = new Set<Promise<void>>();
726
1024
  const validTransportSessionId = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value);
727
1025
  const closeSessionTransport = async (transport: SessionTransport | undefined) => {
@@ -733,16 +1031,22 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
733
1031
  operation.then(() => { pendingTransportStartups.delete(operation); }, () => { pendingTransportStartups.delete(operation); });
734
1032
  return operation;
735
1033
  };
736
- const startSessionTransport = (ctx: ExtensionContext) => {
1034
+ const startSessionTransport = (ctx: ExtensionContext, rearm = false) => {
737
1035
  const previous = activeSessionTransport;
738
1036
  const generation = ++transportGeneration;
739
1037
  const sessionManager = ctx.sessionManager;
740
1038
  activeSessionTransport = undefined;
1039
+ transportRearm = undefined;
741
1040
  const operation = (async () => {
742
1041
  let registry: SessionTransportRegistry | undefined;
743
1042
  let listener: SessionTransportListener | undefined;
744
1043
  let client: SessionTransportClient | undefined;
745
1044
  let closePromise: Promise<void> | undefined;
1045
+ let sessionId: string | undefined;
1046
+ let startupPhase: "registry" | "listener" = "registry";
1047
+ const phases = new WindowsSessionRegistryPhaseSequence();
1048
+ let bootstrap: WindowsSessionBootstrapDiagnosticCode | undefined;
1049
+ const observeBootstrap = (code: WindowsSessionBootstrapDiagnosticCode) => { if (bootstrap === undefined && isWindowsSessionBootstrapDiagnosticCode(code)) bootstrap = code; return undefined; };
746
1050
  const closeStartupTransport = () => {
747
1051
  if (closePromise) return closePromise;
748
1052
  closePromise = Promise.resolve().then(async () => {
@@ -756,17 +1060,18 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
756
1060
  };
757
1061
  try {
758
1062
  if (previous) trackTransportOperation(closeSessionTransport(previous));
759
- const sessionId = sessionManager.getSessionId();
1063
+ sessionId = sessionManager.getSessionId();
760
1064
  if (!validTransportSessionId(sessionId) || sessions !== sessionManager || generation !== transportGeneration) return;
761
- registry = await sessionTransport.createRegistry(agentHome);
1065
+ registry = await sessionTransport.createRegistry(agentHome, (event) => phases.observe(event), observeBootstrap);
762
1066
  if (sessions !== sessionManager || generation !== transportGeneration) {
763
1067
  await closeStartupTransport();
764
1068
  return;
765
1069
  }
1070
+ startupPhase = "listener";
766
1071
  listener = sessionTransport.createListener(registry, sessionId, async (notification) => {
767
1072
  const active = activeSessionTransport;
768
1073
  if (!active || active.generation !== generation || active.sessionManager !== sessionManager || active.sessionId !== sessionId || sessions !== sessionManager || activeSessionId() !== sessionId) throw new Error("stale session transport");
769
- 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 });
1074
+ 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);
770
1075
  });
771
1076
  client = sessionTransport.createClient(registry, sessionId);
772
1077
  if (sessions !== sessionManager || generation !== transportGeneration || activeSessionId() !== sessionId) {
@@ -790,15 +1095,35 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
790
1095
  publishActivityPrompt();
791
1096
  } catch {
792
1097
  if (activeSessionTransport?.generation === generation) activeSessionTransport = undefined;
1098
+ // Only fixed, validated observer fields cross the UI boundary. Never
1099
+ // interpolate the exception or report a retired session's failure.
1100
+ const current = () => sessions === sessionManager && generation === transportGeneration && validTransportSessionId(sessionId) && activeSessionId() === sessionId;
1101
+ if (current()) {
1102
+ const observation = phases.snapshot();
1103
+ const diagnostic = startupPhase === "registry" && observation.availability === "observed" && observation.firstFailurePhase !== null
1104
+ ? `phase=${observation.firstFailurePhase} class=${observation.firstFailureClass} code=${observation.firstFailureCode} lastStartupMarker=${observation.lastStartupMarker ?? "unavailable"}`
1105
+ : `phase=${startupPhase} diagnostics=unavailable`;
1106
+ try { ctx.ui.notify(`Session transport startup failed: ${diagnostic}${bootstrap ? ` bootstrap=${bootstrap}` : ""}.`, "warning"); } catch {}
1107
+ }
793
1108
  await closeStartupTransport();
1109
+ // Armed only after cleanup, so the re-arm never overlaps the failed helper.
1110
+ if (!rearm && current()) transportRearm = { sessionManager, sessionId: sessionId!, ctx };
794
1111
  }
795
1112
  })();
796
1113
  trackTransportOperation(operation);
797
1114
  return operation;
798
1115
  };
1116
+ // The single re-arm runs on a later session event of the same session while it
1117
+ // still has no transport; its own failure warns again and arms nothing.
1118
+ const rearmSessionTransport = (ctx: ExtensionContext | undefined) => {
1119
+ const pending = transportRearm;
1120
+ if (!pending || ctx?.sessionManager !== pending.sessionManager || sessions !== pending.sessionManager || activeSessionId() !== pending.sessionId || activeSessionTransport) return;
1121
+ void startSessionTransport(pending.ctx, true);
1122
+ };
799
1123
  const shutdownSessionTransport = async () => {
800
1124
  const active = activeSessionTransport;
801
1125
  activeSessionTransport = undefined;
1126
+ transportRearm = undefined;
802
1127
  transportGeneration++;
803
1128
  if (active) await closeSessionTransport(active);
804
1129
  while (pendingTransportStartups.size > 0) {
@@ -853,6 +1178,17 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
853
1178
  .catch(() => {});
854
1179
  };
855
1180
 
1181
+ // A launched task is written to disk immediately so abrupt parent process
1182
+ // termination (SIGKILL, host reboot, crash) leaves a durable record (#1741).
1183
+ // Pruning is deferred until final persistence in onFinish. saveTask keeps
1184
+ // one task's writes in call order, and a task that is already terminal is
1185
+ // skipped here so its onFinish record is the last one on disk.
1186
+ const persistLaunch = (id: string) => {
1187
+ const task = store.get(id);
1188
+ if (!task || isFinished(task.status)) return;
1189
+ void saveTask(tasksDir, task, store.thread(id)).catch(() => {});
1190
+ };
1191
+
856
1192
  // A background result used to be handed straight to the host as a followUp
857
1193
  // message, but the host only drains that queue when the parent agent stops
858
1194
  // calling tools entirely, so in a long orchestrator run the notification
@@ -966,17 +1302,21 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
966
1302
  // Idle wake-up state. Child content stored while the parent is idle owes a
967
1303
  // wake, and one wake covers everything stored before the run it starts.
968
1304
  // While a prompt is starting (a dispatched wake, or any prompt seen at
969
- // before_agent_start) no second wake is sent: two prompts racing through
1305
+ // input or before_agent_start) no second wake is sent: two prompts racing through
970
1306
  // Pi's asynchronous pre-run phase can both reach the agent, and the loser
971
1307
  // resets the winner's run state. A prompt that never starts a run (handled
972
1308
  // by an input handler, or rejected) emits no extension event, so the
973
- // starting state expires after PARENT_WAKE_GRACE_MS and an owed wake is
974
- // sent then; it never suppresses later wakes for longer than that.
1309
+ // starting state expires after PARENT_WAKE_GRACE_MS (INPUT_PROMPT_GRACE_MS
1310
+ // when marked at input) and an owed wake is sent then; it never suppresses later wakes for longer than that.
975
1311
  let wakeOwed = false;
976
1312
  let wakeQueued = false;
977
1313
  let promptStarting = false;
978
1314
  let cancelPromptGrace: (() => void) | undefined;
979
1315
  let cancelBoundaryFlush: (() => void) | undefined;
1316
+ let cancelHoldRecheck: (() => void) | undefined;
1317
+ // Completions sit in an opaque queue; this notes that one may be waiting.
1318
+ // It is cleared by the next flush that reaches a deliverable route.
1319
+ let completionsMaybePending = false;
980
1320
  // An idle parent has no turn boundary coming, so a failed idle delivery or
981
1321
  // wake is retried by one bounded timer that runs a full flush.
982
1322
  let cancelDeliveryRetry: (() => void) | undefined;
@@ -1016,6 +1356,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1016
1356
  // A parent that is busy without a run (compaction, or a prompt's pre-run
1017
1357
  // compaction) is not streaming, so steer + triggerTurn would also start a
1018
1358
  // direct turn. Its content stays queued ("hold") until a later boundary.
1359
+ //
1360
+ // Three sources use this one router: child completions, child messages
1361
+ // (queries and notifications), and incoming orchestrator session messages.
1362
+ // The route decision is also the single point where a receiver-side
1363
+ // admission policy for session messages (#1518) would plug in.
1019
1364
  type ParentRoute = "idle" | "run" | "hold";
1020
1365
  // Throws for a missing or stale parent context, so delivery fails closed.
1021
1366
  const parentRoute = (): ParentRoute => {
@@ -1034,14 +1379,36 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1034
1379
  cancelPromptGrace?.();
1035
1380
  cancelPromptGrace = undefined;
1036
1381
  };
1037
- const beginPromptStart = () => {
1382
+ const beginPromptStart = (graceMs = PARENT_WAKE_GRACE_MS) => {
1038
1383
  endPromptStart();
1039
1384
  promptStarting = true;
1040
1385
  cancelPromptGrace = deps.schedule(() => {
1041
1386
  cancelPromptGrace = undefined;
1042
1387
  promptStarting = false;
1043
1388
  requestWake();
1044
- }, PARENT_WAKE_GRACE_MS);
1389
+ }, graceMs);
1390
+ };
1391
+
1392
+ const hasHeldContent = (): boolean =>
1393
+ heldOrchestratorMessages.length > 0 || wakeOwed || completionsMaybePending || messages.pendingCount() > 0 || jobNotices.length > 0;
1394
+ const stopHoldRecheck = () => {
1395
+ cancelHoldRecheck?.();
1396
+ cancelHoldRecheck = undefined;
1397
+ };
1398
+ // Events (`agent_*`, `turn_end`, `session_compact*`, `session_tree`) are the
1399
+ // fast path that releases held content. They are not a guarantee: a busy
1400
+ // state without a run can end without any event (a cancelled `/tree`
1401
+ // summarization emits none) or be added to the host later. So while content
1402
+ // is held for a parent that is busy without a run, one re-check is armed;
1403
+ // it re-arms itself only while that state and the held content persist.
1404
+ // Nothing is armed when nothing is held, and an idle or running parent is
1405
+ // never polled.
1406
+ const armHoldRecheck = () => {
1407
+ if (cancelHoldRecheck || !hasHeldContent()) return;
1408
+ cancelHoldRecheck = deps.schedule(() => {
1409
+ cancelHoldRecheck = undefined;
1410
+ flushAll();
1411
+ }, HOLD_RECHECK_MS);
1045
1412
  };
1046
1413
 
1047
1414
  // Every wake requested during one synchronous delivery pass is coalesced
@@ -1058,6 +1425,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1058
1425
  try { route = parentRoute(); } catch { return; }
1059
1426
  // A run in progress already carries the stored content; a parent busy
1060
1427
  // without a run keeps the wake owed until a later boundary flush.
1428
+ if (route === "hold") armHoldRecheck();
1061
1429
  if (route !== "idle") return;
1062
1430
  wakeOwed = false;
1063
1431
  endDeliveryRetry();
@@ -1088,9 +1456,12 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1088
1456
  }
1089
1457
  };
1090
1458
 
1091
- const sendToParent = (message: Parameters<ExtensionAPI["sendMessage"]>[0], route: Exclude<ParentRoute, "hold">) => {
1459
+ // `runMode` is how a message joins a run in progress: child content steers
1460
+ // (see the #867 rationale above); an orchestrator session message is a
1461
+ // follow-up, so it never interrupts the turn the parent is working on.
1462
+ const sendToParent = (message: Parameters<ExtensionAPI["sendMessage"]>[0], route: Exclude<ParentRoute, "hold">, runMode: "steer" | "followUp" = "steer") => {
1092
1463
  if (route === "run") {
1093
- pi.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
1464
+ pi.sendMessage(message, { deliverAs: runMode, triggerTurn: true });
1094
1465
  return;
1095
1466
  }
1096
1467
  pi.sendMessage(message, { triggerTurn: false });
@@ -1105,6 +1476,35 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1105
1476
  sendToParent({ customType: AGENTS_RESULT_TYPE, content: completionText(task), display: true, details: taskDetails(task) }, route);
1106
1477
  };
1107
1478
 
1479
+ // Incoming orchestrator session messages. The transport has already
1480
+ // acknowledged the sender when the listener runs, so a message held for a
1481
+ // busy parent that is then dropped by a session change is lost, exactly like
1482
+ // pending child content. A stale or missing parent context throws instead,
1483
+ // so the sender learns that delivery failed.
1484
+ interface HeldOrchestratorMessage { message: Parameters<ExtensionAPI["sendMessage"]>[0]; recipientSessionId: string }
1485
+ let heldOrchestratorMessages: HeldOrchestratorMessage[] = [];
1486
+ const deliverOrchestratorMessage = (message: Parameters<ExtensionAPI["sendMessage"]>[0], recipientSessionId: string) => {
1487
+ const route = parentRoute();
1488
+ if (route === "hold") {
1489
+ heldOrchestratorMessages.push({ message, recipientSessionId });
1490
+ armHoldRecheck();
1491
+ return;
1492
+ }
1493
+ sendToParent(message, route, "followUp");
1494
+ };
1495
+ const flushOrchestratorMessages = () => {
1496
+ if (heldOrchestratorMessages.length === 0) return;
1497
+ const route = deliveryRoute(false);
1498
+ if (!route) return;
1499
+ const held = heldOrchestratorMessages;
1500
+ heldOrchestratorMessages = [];
1501
+ for (const { message, recipientSessionId } of held) {
1502
+ if (activeSessionId() !== recipientSessionId) continue;
1503
+ try { sendToParent(message, route, "followUp"); }
1504
+ catch { /* Best-effort delivery: at most once, even if forwarding fails. */ }
1505
+ }
1506
+ };
1507
+
1108
1508
  // A stale report must not re-enter the LLM conversation, but the parent is
1109
1509
  // told never to poll: it gets a compact model-facing notice naming the task,
1110
1510
  // and the human gets durable TUI-only content.
@@ -1133,7 +1533,12 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1133
1533
  const deliveryRoute = (rethrow: boolean): Exclude<ParentRoute, "hold"> | undefined => {
1134
1534
  try {
1135
1535
  const route = parentRoute();
1136
- return route === "hold" ? undefined : route;
1536
+ if (route === "hold") {
1537
+ armHoldRecheck();
1538
+ return undefined;
1539
+ }
1540
+ stopHoldRecheck();
1541
+ return route;
1137
1542
  } catch (error) {
1138
1543
  if (rethrow) throw error;
1139
1544
  return undefined;
@@ -1156,6 +1561,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1156
1561
  const flushCompletions = () => {
1157
1562
  const route = deliveryRoute(false);
1158
1563
  if (!route) return;
1564
+ completionsMaybePending = false;
1159
1565
  for (const entry of completions.takeDeliverable(deps.now())) {
1160
1566
  try {
1161
1567
  if (entry.stale) deliverStale(entry.task, entry.settledAt, route);
@@ -1165,6 +1571,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1165
1571
  // lose the completion: it waits for the next boundary instead, and
1166
1572
  // an idle parent, which has none coming, gets a bounded retry.
1167
1573
  completions.requeue(entry);
1574
+ // Still pending, so a later held-only re-check must see it.
1575
+ completionsMaybePending = true;
1168
1576
  if (route === "idle") armDeliveryRetry();
1169
1577
  }
1170
1578
  }
@@ -1195,6 +1603,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1195
1603
  };
1196
1604
 
1197
1605
  const flushAll = () => {
1606
+ flushOrchestratorMessages();
1198
1607
  flushMessages();
1199
1608
  flushCompletions();
1200
1609
  flushJobNotices();
@@ -1222,7 +1631,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1222
1631
  wakeVisibilityWarning = false;
1223
1632
  parentRunActive = false;
1224
1633
  wakeOwed = false;
1634
+ heldOrchestratorMessages = [];
1635
+ completionsMaybePending = false;
1225
1636
  endPromptStart();
1637
+ stopHoldRecheck();
1226
1638
  cancelBoundaryFlush?.();
1227
1639
  cancelBoundaryFlush = undefined;
1228
1640
  endDeliveryRetry();
@@ -1282,6 +1694,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1282
1694
  const settleCompletion = (task: TaskRecord) => {
1283
1695
  messages.invalidateTask(task.id);
1284
1696
  completions.enqueue(task, deps.now());
1697
+ completionsMaybePending = true;
1285
1698
  if (activeAgentRuns === 0) flushAll();
1286
1699
  };
1287
1700
 
@@ -1309,18 +1722,43 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1309
1722
  deliveryRetries = 0;
1310
1723
  endPromptStart();
1311
1724
  });
1312
- pi.on("agent_end", () => {
1725
+ // The last attempt's messages, kept until the run settles: Pi fires agent_end
1726
+ // on every failed attempt and decides on a retry afterwards.
1727
+ let lastRunMessages: readonly unknown[] = [];
1728
+ pi.on("agent_end", (event) => {
1313
1729
  activeAgentRuns = Math.max(0, activeAgentRuns - 1);
1314
1730
  flushAll();
1731
+ lastRunMessages = event?.messages ?? [];
1315
1732
  });
1316
- pi.on("agent_settled", () => {
1733
+ pi.on("agent_settled", (event, ctx) => {
1317
1734
  parentRunActive = false;
1318
1735
  endPromptStart();
1319
1736
  flushAll();
1737
+ const messages = lastRunMessages;
1738
+ lastRunMessages = [];
1739
+ // A child's own failures are handled by the parent's runner, never by the child.
1740
+ if (deps.env.GENTLE_PI_AGENTS_CHILD !== "1" && ctx) void orchestratorFallbackFor(ctx).onSettled(messages, { aborted: event?.aborted === true }).catch((error: unknown) => ui?.notify(`Model fallback failed: ${error instanceof Error ? error.message : String(error)}`, "error"));
1320
1741
  });
1321
1742
  pi.on("turn_end", () => flushAll());
1322
1743
  pi.on("session_compact", scheduleBoundaryFlush);
1323
1744
  pi.on("session_compact_failed", scheduleBoundaryFlush);
1745
+ pi.on("session_tree", scheduleBoundaryFlush);
1746
+ // A user prompt is "starting" from `input`, through input handlers, auth and
1747
+ // model checks, until `before_agent_start`, while the host still reports
1748
+ // idle. A wake dispatched in that window races the prompt into
1749
+ // Agent.prompt(): the user's prompt can be rejected as already processing.
1750
+ // The starting prompt carries the stored content itself, so no wake is
1751
+ // needed. An input another extension handles never starts a run and emits
1752
+ // no event, so this suppression expires quickly (INPUT_PROMPT_GRACE_MS) and
1753
+ // the owed wake then goes out; a pre-run phase longer than that only
1754
+ // re-opens the old window. A pre-prompt compaction makes the route "hold",
1755
+ // and `before_agent_start` re-arms the starting state. A start window that
1756
+ // is already open is never shortened: a dispatched wake reaches `input`
1757
+ // too, and its own PARENT_WAKE_GRACE_MS window must keep a second wake out.
1758
+ pi.on("input", (event) => {
1759
+ if (parentRunActive || promptStarting || event.streamingBehavior !== undefined) return;
1760
+ beginPromptStart(INPUT_PROMPT_GRACE_MS);
1761
+ });
1324
1762
 
1325
1763
  const runner = new AgentRunner(store, loadAgentsConfig({ cwd: process.cwd(), home: deps.home, agentHome }), deps, {
1326
1764
  askUser: (_taskId, ask, raw) => answerThroughUi(ui, ask, raw),
@@ -1348,6 +1786,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1348
1786
  if (outcome === "replied") messages.consumeQuery(taskId, requestId);
1349
1787
  else messages.expireQuery(taskId, requestId);
1350
1788
  },
1789
+ onFallback: (task, change) => announceFallback({ agent: task.agent, from: change.from, to: change.to, category: change.category, ...(change.launch ? { launch: true } : {}) }, task.parentSessionId, task.id),
1351
1790
  onSuccessfulMutation: (task, tool) => {
1352
1791
  // Same-clone registry attribution remains unchanged. A foreign task
1353
1792
  // uses a separately bound, live-grant path only for successful tool evidence.
@@ -1428,7 +1867,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1428
1867
  const details = (message.details as { gentleAgents?: { taskId?: unknown; agent?: unknown } } | undefined)?.gentleAgents;
1429
1868
  const taskId = typeof details?.taskId === "string" ? details.taskId : "unknown";
1430
1869
  const agent = typeof details?.agent === "string" ? details.agent : "Subagent";
1431
- const heading = `${sanitizeTerminalText(agent)} message · Task ${sanitizeTerminalText(taskId)}`;
1870
+ const heading = `${ACTION_GLYPH.send_message} ${sanitizeTerminalText(agent)} message · Task ${sanitizeTerminalText(taskId)}`;
1432
1871
  const body = sanitizeTerminalText(messageText(message.content));
1433
1872
  return new Text(`${theme.fg("customMessageLabel", heading)}\n${theme.fg("customMessageText", body)}`, options.outputPad, 0);
1434
1873
  });
@@ -1442,12 +1881,21 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1442
1881
  const details = (message.details as { gentleAgents?: { agent?: string; status?: string } } | undefined)?.gentleAgents;
1443
1882
  const content = message.content as string | Array<{ type: string; text?: string }>;
1444
1883
  const text = typeof content === "string" ? content : content.map((part) => (part.type === "text" ? (part.text ?? "") : "")).join("\n");
1445
- const body = options.expanded ? text.split("\n") : agentResultPreview(text).split("\n").filter((line) => line.trim() !== "");
1446
1884
  const tone = details?.status === "completed" ? CARD_TONE.SUCCESS : CARD_TONE.ERROR;
1447
1885
  const hint = expandHint(options.expanded);
1886
+ // The same answer card as the tool result: iris chrome, the state pill
1887
+ // on top, the answer below ("answer" keeps its name through the flow).
1888
+ const t = agentTheme(theme, tone);
1889
+ const facts = details?.status ? statusCardFacts({ gentleAgents: details }) : undefined;
1890
+ const chips = [details?.agent, modelChip(facts?.model), facts?.thinking ? sanitizeTerminalText(facts.thinking) : undefined];
1891
+ const answer = options.expanded ? text.split("\n") : agentResultPreview(text).split("\n").filter((line) => line.trim() !== "");
1892
+ const body = facts ? [statusCardRows(facts, t, false)[0], ...answer] : answer;
1448
1893
  return {
1449
1894
  render(width: number) {
1450
- return renderCard({ title: "Agent result", subtitle: details?.agent, body, tone, glyph: AGENTS_GLYPH }, theme, width, { expanded: options.expanded, previewRows: 3, hint });
1895
+ // Same one-line heading budget as the tool cards: the answer card's
1896
+ // inner columns are the style's, not the terminal's.
1897
+ const subtitle = fitSubject({ title: "Agent answer", tone, glyph: ACTION_GLYPH.result }, hint, panelInnerWidth(theme, width, tone), chips);
1898
+ return renderCard({ title: "Agent answer", subtitle, body, tone, glyph: ACTION_GLYPH.result }, t, width, { expanded: options.expanded, previewRows: 3, hint });
1451
1899
  },
1452
1900
  invalidate() {},
1453
1901
  };
@@ -1469,7 +1917,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1469
1917
  ];
1470
1918
  return {
1471
1919
  render(width: number) {
1472
- return renderCard({ title: "Stale agent result", subtitle: `${agent} · task ${taskId}`, body, tone: CARD_TONE.WARNING, glyph: AGENTS_GLYPH }, theme, width, { expanded: options.expanded, previewRows: 3, hint: expandHint(options.expanded) });
1920
+ return renderCard({ title: "Stale agent answer", subtitle: `${headingText(agent)} · task ${headingText(taskId)}`, body, tone: CARD_TONE.WARNING, glyph: ACTION_GLYPH.result }, agentTheme(theme, CARD_TONE.WARNING), width, { expanded: options.expanded, previewRows: 3, hint: expandHint(options.expanded) });
1473
1921
  },
1474
1922
  invalidate() {},
1475
1923
  };
@@ -1524,16 +1972,39 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1524
1972
  return confirmation;
1525
1973
  };
1526
1974
 
1975
+ // A task stored on disk that never reached a terminal state was in flight
1976
+ // when the parent process was abruptly terminated (kill -9, host reboot,
1977
+ // OOM). When loaded into a new process where it has no live runner, it is
1978
+ // reconciled into a terminal failed state and updated on disk (#1741).
1979
+ const reconcileStored = async (stored: StoredTask): Promise<StoredTask> => {
1980
+ if (isFinished(stored.task.status)) return stored;
1981
+ const reconciledTask: TaskRecord = {
1982
+ ...stored.task,
1983
+ status: TASK_STATUS.FAILED,
1984
+ error: stored.task.error ?? "interrupted: parent process terminated while task was in flight",
1985
+ lastStep: "interrupted",
1986
+ endedAt: stored.task.endedAt ?? deps.now(),
1987
+ };
1988
+ try { await saveTask(tasksDir, reconciledTask, stored.thread); } catch { /* best effort */ }
1989
+ return { task: reconciledTask, thread: stored.thread };
1990
+ };
1991
+
1527
1992
  // Tasks from earlier sessions come back from disk on demand.
1528
1993
  const resolveTask = async (id: string): Promise<TaskRecord | undefined> => {
1529
1994
  const live = store.get(id);
1530
- if (live) return live;
1995
+ if (live && !restoredTaskIds.has(id)) return live;
1531
1996
  const stored = await loadStoredTask(tasksDir, id);
1532
1997
  if (stored) {
1533
- restoredTaskIds.add(stored.task.id);
1534
- store.restore(stored.task, stored.thread);
1998
+ if (!isFinished(stored.task.status) && stored.task.parentSessionId !== activeSessionId()) {
1999
+ return undefined;
2000
+ }
2001
+ const reconciled = await reconcileStored(stored);
2002
+ restoredTaskIds.add(reconciled.task.id);
2003
+ store.restore(reconciled.task, reconciled.thread);
2004
+ store.update(reconciled.task.id, reconciled.task);
2005
+ return reconciled.task;
1535
2006
  }
1536
- return stored?.task;
2007
+ return live;
1537
2008
  };
1538
2009
 
1539
2010
  // A guessed id ("1") leads back to real ids instead of a dead end, so the
@@ -1564,8 +2035,12 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1564
2035
  // The session may have moved on while disk was read; a stale restore
1565
2036
  // must never land in the wrong session's store.
1566
2037
  if (ctx.sessionManager.getSessionId() !== sessionId) return;
1567
- for (const { task, thread } of history) {
1568
- if (task.parentSessionId !== sessionId) continue;
2038
+ // An in-flight record has no live runner here, so it is reconciled
2039
+ // before the widget or store can show it as still running (#1741).
2040
+ const own = history.filter(({ task }) => task.parentSessionId === sessionId && !store.get(task.id));
2041
+ const reconciled = await Promise.all(own.map(reconcileStored));
2042
+ if (ctx.sessionManager.getSessionId() !== sessionId) return;
2043
+ for (const { task, thread } of reconciled) {
1569
2044
  if (store.restore(task, thread)) restoredTaskIds.add(task.id);
1570
2045
  }
1571
2046
  } catch { /* Partial history is acceptable; the live session keeps running. */ }
@@ -1642,9 +2117,35 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1642
2117
  await writeFile(path, markdown, "utf8");
1643
2118
  return path;
1644
2119
  };
2120
+ // gentle-shell#626: herdr's pane busy while owned subagents of the active
2121
+ // session run, even when the parent itself settled around a background
2122
+ // child. Pure edge-triggered projection (lib/herdr-busy.ts), recomputed on
2123
+ // every summary notification and on the session lifecycle edges; the
2124
+ // consumer owns blocked-over-busy precedence, so no gating happens here.
2125
+ let emittedBusy: HerdrBusyEmitted;
2126
+ const refreshHerdrBusy = (): void => {
2127
+ const sessionId = activeSessionId();
2128
+ if (!sessionId) {
2129
+ // No active session owns work: never raise, and lower anything this
2130
+ // runtime already raised so busy never outlives its session.
2131
+ if (emittedBusy?.active) pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
2132
+ emittedBusy = { active: false };
2133
+ return;
2134
+ }
2135
+ const action = nextHerdrBusyAction(store.list(sessionId).filter((task) => ownedTaskIds.has(task.id)), emittedBusy);
2136
+ if (action.kind === "none") return;
2137
+ if (action.kind === "lower") pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
2138
+ else {
2139
+ if (action.kind === "lower-then-raise") pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
2140
+ pi.events.emit(HERDR_BUSY_CHANNEL, { active: true, label: action.label });
2141
+ }
2142
+ emittedBusy = action.kind === "lower" ? { active: false } : { active: true, label: action.label };
2143
+ };
2144
+
1645
2145
  // A status change is worth a frame right away; deltas inside a task are
1646
2146
  // coalesced so a chatty child cannot flood the terminal.
1647
2147
  store.subscribeSummary(() => {
2148
+ refreshHerdrBusy();
1648
2149
  publishActivity();
1649
2150
  if (sidebarTui) invalidateSidebar(sidebarTui);
1650
2151
  host?.requestRender();
@@ -1652,7 +2153,9 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1652
2153
  });
1653
2154
 
1654
2155
  const showWidget = (ctx: ExtensionContext) => {
2156
+ widgetCtx = ctx;
1655
2157
  ui = ctx.hasUI ? ctx.ui : undefined;
2158
+ modelRegistry = ctx.modelRegistry;
1656
2159
  sessions = ctx.sessionManager;
1657
2160
  agentsVisible = resolveVisualSettings({ gentlePiConfigHome: visualHome }).settings.visibility.agents;
1658
2161
  stopVisualUpdates?.();
@@ -1681,42 +2184,76 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1681
2184
 
1682
2185
  // One surface of the Agents card. The rail is natively scrollable, so it
1683
2186
  // lists every task; the above-editor widget keeps its row budget. Only the
1684
- // header row is the clickable collapse control, exactly like Todos.
1685
- const agentsCard = (tui: TUI, theme: Parameters<typeof renderAgentsCard>[1], rail: boolean): Component & { dispose(): void; digest(): string } => {
2187
+ // header row is the clickable collapse control, exactly like Todos; a click
2188
+ // on an agent row below it opens /gentle:agents.
2189
+ const agentsCard = (tui: TUI, theme: Parameters<typeof renderAgentsCard>[1], rail: boolean): Component & { dispose(): void; digest(): string; surface?: "panel"; summary?(): ReturnType<typeof agentsSummary>; alert?(width: number): string[]; open?(): void } => {
1686
2190
  let hovered = false;
2191
+ let hoveredRow: number | undefined;
1687
2192
  let headerRow = 0;
2193
+ const agentRows = new Set<number>();
2194
+ // The rows the card drew last, so a click past them (the card's spacer) opens nothing.
2195
+ let drawnRows = 0;
1688
2196
  const card: Component = {
1689
2197
  render(width: number) {
2198
+ drawnRows = 0;
2199
+ agentRows.clear();
1690
2200
  if (!agentsVisible) return [];
1691
2201
  const tasks = visibleTasks();
1692
2202
  const now = deps.now();
2203
+ // The fullscreen rail draws a panel section (header on row 0) that
2204
+ // stays as one idle row without tasks; above the editor it is a card.
2205
+ if (rail) {
2206
+ headerRow = 0;
2207
+ const rows = renderAgentsSection(tasks, theme, width, now, { collapsed, hovered, hoveredRow, onAgentRow: (row) => agentRows.add(row) });
2208
+ drawnRows = tasks.length === 0 ? 0 : rows.length;
2209
+ return rows;
2210
+ }
1693
2211
  headerRow = panelHeaderRow(theme, width, agentsCardTone(tasks, now));
1694
- const lines = renderAgentsCard(tasks, theme, width, now, { collapsed, collapseKey, maxRows: rail ? undefined : widgetRows(tui.terminal?.rows), viewKey, collapseControl: true, hovered });
1695
- return lines.length === 0 || rail ? lines : [...lines, ""];
2212
+ const lines = renderAgentsCard(tasks, theme, width, now, { collapsed, collapseKey, maxRows: widgetRows(tui.terminal?.rows), viewKey, collapseControl: true, hovered, hoveredRow, onAgentRow: (row) => agentRows.add(row) });
2213
+ drawnRows = tasks.length === 0 ? 0 : lines.length;
2214
+ return lines.length === 0 ? lines : [...lines, ""];
1696
2215
  },
1697
2216
  invalidate() {
1698
2217
  hovered = false;
2218
+ hoveredRow = undefined;
1699
2219
  },
1700
2220
  };
1701
2221
  const region = new NativePointerRegion(card, {
1702
2222
  onHover(event) {
1703
2223
  const next = event.y === headerRow;
1704
- if (next === hovered) return { handled: true };
2224
+ const nextRow = agentRows.has(event.y) ? event.y : undefined;
2225
+ if (next || nextRow !== undefined) setSidebarHover(tui, region, () => region.clearHover());
2226
+ else setSidebarHover(tui);
2227
+ if (next === hovered && nextRow === hoveredRow) return { handled: true };
1705
2228
  hovered = next;
2229
+ hoveredRow = nextRow;
1706
2230
  return { handled: true, render: true };
1707
2231
  },
1708
2232
  onLeave() {
1709
- if (!hovered) return;
2233
+ releaseSidebarHover(tui, region);
2234
+ if (!hovered && hoveredRow === undefined) return;
1710
2235
  hovered = false;
2236
+ hoveredRow = undefined;
1711
2237
  host?.requestRender();
1712
2238
  },
1713
2239
  onClick(event) {
1714
- if (event.button !== "left" || event.y !== headerRow) return undefined;
1715
- toggleCollapsed();
2240
+ if (event.button !== "left") return undefined;
2241
+ region.clearHover();
2242
+ if (event.y === headerRow) {
2243
+ toggleCollapsed();
2244
+ return { handled: true, render: true };
2245
+ }
2246
+ if (event.y < headerRow || event.y >= drawnRows || !widgetCtx) return undefined;
2247
+ void openOverlay(widgetCtx);
1716
2248
  return { handled: true, render: true };
1717
2249
  },
1718
2250
  });
1719
2251
  return {
2252
+ // The mobile work row folds this section; a tap on it opens /gentle:agents.
2253
+ ...(rail ? { open: () => { if (widgetCtx) void openOverlay(widgetCtx); } } : {}),
2254
+ // The panel editor draws the alert above its rule while the IDE chrome
2255
+ // hides the above-editor card (rail or mobile work row).
2256
+ ...(rail ? { surface: "panel" as const, summary: () => (agentsVisible ? agentsSummary(visibleTasks(), theme, deps.now()) : undefined), alert: (width: number) => (agentsVisible ? renderAgentsAlert(visibleTasks(), theme, width) : []), spend: () => agentsSpend(visibleTasks()) } : {}),
1720
2257
  // The rail memo repaints a part only when its digest moves: task
1721
2258
  // state, the local controls, and the elapsed clock (to the second)
1722
2259
  // only while a task is still running, so an idle or finished card
@@ -1724,7 +2261,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1724
2261
  digest: () => {
1725
2262
  const tasks = visibleTasks();
1726
2263
  const clock = tasks.some((task) => !isFinished(task.status)) ? Math.floor(deps.now() / 1000) : 0;
1727
- return JSON.stringify([agentsVisible, collapsed, hovered, tui.terminal?.rows, clock, tasks.map((task) => [task.id, task.status, task.tokens, task.cost, task.label, task.lastStep, task.error])]);
2264
+ return JSON.stringify([agentsVisible, collapsed, hovered, hoveredRow, tui.terminal?.rows, clock, tasks.map((task) => [task.id, task.status, task.tokens, task.cost, task.label, task.lastStep, task.error])]);
1728
2265
  },
1729
2266
  render: (width) => region.render(width),
1730
2267
  handleMouse: (event) => region.handleMouse(event),
@@ -1760,6 +2297,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1760
2297
  // bound session used to kill its own non-git writer mid-preparation because
1761
2298
  // admission still read only the pin/global layers). Slice 3b-ii: the same
1762
2299
  // read covers the frozen inherited profile and `follow` mode.
2300
+ requireSessionProfileAuthority(ctx.sessionManager);
1763
2301
  const profileConfigHome = gentlePiConfigHome(deps.env);
1764
2302
  const sessionProfile = resolveSessionProfile({
1765
2303
  sessionId: ctx.sessionManager.getSessionId(),
@@ -1781,6 +2319,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1781
2319
  admittedModel = `${catalogModel.provider}/${catalogModel.id}`;
1782
2320
  if (!current() || !await prepareBoundSessionRepository(originalManager, originalCwd, signal) || !current() || safeBootstrapDirectory(originalCwd) !== root || resolveSessionWorktree(originalCwd, originalCwd)?.root !== root) throw new Error("Writer repository preparation was unavailable or its session/target changed.");
1783
2321
  }
2322
+ requireSessionProfileAuthority(originalManager);
1784
2323
  const parentCwd = ctx.sessionManager.getCwd();
1785
2324
  // An explicit target is validated before any queue or session-dir writes.
1786
2325
  const parentIdentity = deps.resolveWorktree(parentCwd, parentCwd);
@@ -1827,6 +2366,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1827
2366
  // included; only `follow` reads the defaults of the target. The profile is
1828
2367
  // resolved here, at task-request creation, so queued and running children
1829
2368
  // keep the routing frozen into their requests even if the session rebinds.
2369
+ requireSessionProfileAuthority(originalManager);
1830
2370
  // The routing target this launch reads (#1064), reused to name the winning
1831
2371
  // layer (#2180) so both answers come from one resolution.
1832
2372
  const routingTarget = {
@@ -1859,7 +2399,9 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1859
2399
  // inheriting and a matched key never warns. Keys are checked against every
1860
2400
  // discovered agent, so a key naming another agent is never reported here.
1861
2401
  if (ctx.hasUI) {
1862
- const unmatched = unmatchedProfileKeys(config.modelProfiles, discoverAgents(roots(ctx)).agents);
2402
+ // Provider review roles are routed by key and never have an agent file.
2403
+ const known = [...PROVIDER_REVIEW_ROLES.map((name) => ({ name })), ...discoverAgents(roots(ctx)).agents];
2404
+ const unmatched = unmatchedProfileKeys(config.modelProfiles, known);
1863
2405
  const nearMisses = unmatched.filter((entry) => entry.suggestion === agent.name);
1864
2406
  if (nearMisses.length > 0) {
1865
2407
  ctx.ui.notify(nearMisses.map((entry) => `"${entry.key}" did not match any agent, did you mean ${agent.name}?`).join(" "), "warning");
@@ -1895,7 +2437,17 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1895
2437
  const parentWorktreeRoot = ctx.sessionManager.getCwd();
1896
2438
  const parentRepositoryIdentity = resolveCanonicalGitRepositoryIdentitySync(parentWorktreeRoot);
1897
2439
  const childEnv = { ...deps.env };
2440
+ delete childEnv[CHILD_TIER_ENV];
2441
+ const childModel = profile.model ?? ctx.model;
2442
+ if (profile.tier && childModel?.provider && childModel.id) {
2443
+ childEnv[CHILD_TIER_ENV] = JSON.stringify({ tier: profile.tier, model: `${childModel.provider}/${childModel.id}` });
2444
+ }
1898
2445
  if (foreign) for (const key of inheritedUnsafeGitEnvironmentKeys(childEnv)) delete childEnv[key];
2446
+ const extensions = childExtensionRequest(deps.env, deps.childExtensionPaths);
2447
+ if (profile.tier && !parseChildPackageInjection(deps.env)) {
2448
+ const fastPath = fileURLToPath(new URL("./gentle-fast.ts", import.meta.url));
2449
+ if (existsSync(fastPath)) extensions.extensionPaths = [...new Set([...(extensions.extensionPaths ?? []), fastPath])];
2450
+ }
1899
2451
  const request: TaskRequest = {
1900
2452
  agent,
1901
2453
  prompt,
@@ -1919,9 +2471,15 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1919
2471
  model: profile.model,
1920
2472
  ...(modelSource === undefined ? {} : { modelSource }),
1921
2473
  thinking: profile.thinking,
2474
+ ...(() => {
2475
+ // The chain of the profile this launch resolved, else the active profile's.
2476
+ const name = sessionProfile.kind === "explicit" ? sessionProfile.name : sessionProfile.profile?.name;
2477
+ const fallbacks = profileFallbackChain(profileConfigHome, name, agent.name);
2478
+ return fallbacks.length ? { fallbacks } : {};
2479
+ })(),
1922
2480
  sessionDir,
1923
2481
  resumeSessionPath: resume,
1924
- ...childExtensionRequest(deps.env, deps.childExtensionPaths),
2482
+ ...extensions,
1925
2483
  // A writer claims its surfaces in its canonical worktree root for its queued
1926
2484
  // and running lifetime; a continuation is a new task and claims them again.
1927
2485
  ...(isBoundedWriter(agent.name) && surfaces ? { writerSurfaces: surfaces, writerRoot: canonicalWriterRoot(target ?? parentWorktreeRoot, foreign ? resolveSessionWorktree : deps.resolveWorktree) } : {}),
@@ -1969,6 +2527,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1969
2527
  launched = true;
1970
2528
  const foreign = foreignRequests.get(request);
1971
2529
  if (foreign && launchedTaskId) foreignTasks.set(launchedTaskId, foreign);
2530
+ if (launchedTaskId) persistLaunch(launchedTaskId);
1972
2531
  },
1973
2532
  ...(observe ? { canCollectResponseObservations: metrics.valid, prepareResponseObservations: async () => {
1974
2533
  if (metrics.finished || owner !== metricsOwner || request.parentSessionId !== activeSessionId() || !runtimeMetricsEnvAllows(deps.env)) return false;
@@ -1983,8 +2542,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1983
2542
  const foreignRequest = foreignRequests.get(request);
1984
2543
  if (launched && foreignRequest) foreignTasks.set(task.id, foreignRequest);
1985
2544
  ownedTaskIds.add(task.id);
2545
+ persistLaunch(task.id);
1986
2546
  publishWork?.(task.id);
1987
2547
  publishActivityPrompt(); // Admission's summary notification precedes runtime ownership.
2548
+ refreshHerdrBusy(); // So does the busy raise: ownership lands after that notification.
1988
2549
  store.subscribe(task.id, () => { publishActivity(); requestRender(); });
1989
2550
  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));
1990
2551
  // A tool call aborted by the host (a human interrupting the turn, a timeout)
@@ -2025,28 +2586,152 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2025
2586
  };
2026
2587
 
2027
2588
  const tool = (name: string, description: string, parameters: Record<string, unknown>, execute: (params: Record<string, unknown>, ctx: ExtensionContext, signal?: AbortSignal) => Promise<ToolText>) => {
2589
+ const heading = ACTION_HEADING[name] ?? `agent ${name.replace(/_/g, " ")}`;
2590
+ const glyph = ACTION_GLYPH[name] ?? AGENTS_GLYPH;
2591
+ // The agent chip: the call shows who it works with, and what that child
2592
+ // runs on. Status-style calls only carry a task id, so the store resolves
2593
+ // the agent and its launch profile.
2594
+ const subject = (params: { agent?: string; task_id?: string }, launched?: { agentProfile?: boolean; agentModel?: string; agentEffort?: string }): { agent?: string; taskRef?: string; model?: string; effort?: string } => {
2595
+ const task = typeof params.task_id === "string" ? store.get(params.task_id) : undefined;
2596
+ const agent = typeof params.agent === "string" && params.agent.trim() ? headingText(params.agent)
2597
+ : task ? headingText(task.agent) || undefined
2598
+ : undefined;
2599
+ const taskRef = typeof params.task_id === "string" ? `task ${headingText(params.task_id)}` : undefined;
2600
+ // A launch has no task id at call time, so its profile arrives through
2601
+ // the shared row state once the result slot knows it. Once it speaks for
2602
+ // this call it wins whole: a continuation is a new task, so keeping the
2603
+ // predecessor's model — or its effort when the new one has none — would
2604
+ // name the wrong child.
2605
+ const fresh = launched?.agentProfile === true;
2606
+ const model = fresh ? launched?.agentModel : modelChip(task?.model);
2607
+ const effort = fresh ? launched?.agentEffort : task?.thinking ? headingText(task.thinking) : undefined;
2608
+ return { agent, taskRef, model, effort };
2609
+ };
2610
+ const agentToolContext = (context: CardRowContext & { expanded?: boolean; isError?: boolean; state?: { agentFailed?: boolean; agentProfile?: boolean; agentModel?: string; agentEffort?: string } } | undefined) => context ?? {};
2028
2611
  pi.registerTool({
2029
2612
  name: `${TOOL_PREFIX}${name}`,
2030
2613
  renderShell: "self",
2031
2614
  label: `Agent ${name.replace(/_/g, " ")}`,
2032
2615
  description,
2033
2616
  parameters: { type: "object", additionalProperties: false, ...parameters } as never,
2034
- renderCall(args, theme) {
2617
+ // The same tool-card protocol the orchestrator tools use: the call
2618
+ // draws the card heading and closes its own frame while the result
2619
+ // is pending; the result then continues the card (afterHeading) and
2620
+ // closes it — one continuous card in the user's card style, never a
2621
+ // bare title over a second frame.
2622
+ renderCall(args, theme, context) {
2035
2623
  // The result title belongs with the result body so a running poll
2036
2624
  // can hide both without changing the tool call or its model output.
2037
2625
  if (name === "result") return { render: () => [], invalidate() {} };
2038
- const params = args as { agent?: string; task_id?: string };
2039
- return new Text(theme.fg("toolTitle", `${AGENTS_GLYPH} agent ${name.replace(/_/g, " ")}${params.agent ? ` · ${params.agent}` : params.task_id ? ` · ${params.task_id}` : ""}`), 0, 0);
2626
+ return {
2627
+ render(width: number) {
2628
+ if (width <= 0) return [];
2629
+ const row = agentToolContext(context);
2630
+ // Resolved per frame: the store gains the task and its profile after
2631
+ // the call is first drawn, and the heading has to catch up.
2632
+ const { agent, taskRef, model, effort } = subject(args as { agent?: string; task_id?: string }, row.state);
2633
+ const chips = [agent, taskRef, model, effort];
2634
+ // The heading is this slot's, so a failure the result slot learns about
2635
+ // has to travel through the shared row state: a rejected call wears the
2636
+ // error frame instead of reading as a delegation still in flight. The
2637
+ // row context is a snapshot, so its own isError cannot be trusted here.
2638
+ const tone = row.isError || row.state?.agentFailed ? CARD_TONE.ERROR : CARD_TONE.INFO;
2639
+ const iris = agentTheme(theme, tone);
2640
+ const hint = expandHint(!!row.expanded);
2641
+ return floatRows(tone, iris, width, (inner) => ({
2642
+ head: [cardTop({ title: heading, subtitle: fitSubject({ title: heading, tone, glyph }, hint, inner, chips), body: [], tone, glyph }, iris, inner, hint)],
2643
+ ...(cardAwaitingResult(row) ? { body: [cardRunningLine(tone, iris, inner)], bottom: cardBottom(tone, iris, inner) } : {}),
2644
+ }));
2645
+ },
2646
+ invalidate() {},
2647
+ };
2040
2648
  },
2041
- renderResult(result, options, theme) {
2042
- const task = (result.details as { gentleAgents?: { status?: string; taskId?: string } } | undefined)?.gentleAgents;
2649
+ renderResult(result, options, theme, context) {
2650
+ const task = (result.details as { gentleAgents?: { status?: string; taskId?: string; agent?: string } } | undefined)?.gentleAgents;
2043
2651
  if (name === "result" && task?.status === TASK_STATUS.RUNNING) {
2044
2652
  return { render: () => [], invalidate() {} };
2045
2653
  }
2654
+ if (!options.isPartial) markCardResult(agentToolContext(context).state);
2655
+ // A host error (a throw before any details exist) counts like a
2656
+ // details error, so the result keeps the tone the call already shows —
2657
+ // and the call's snapshot needs the flag to wear it too.
2658
+ const row = agentToolContext(context);
2659
+ const failed = row.isError === true || (result.details as { error?: unknown } | undefined)?.error !== undefined;
2660
+ if (row.state !== undefined) {
2661
+ row.state.agentFailed = failed;
2662
+ }
2663
+ // Parsed for every tool: the answer and status cards lead with the
2664
+ // facts, and every card names the launch profile in its heading.
2665
+ const facts = statusCardFacts(result.details);
2666
+ if (row.state !== undefined) {
2667
+ // The call slot draws the heading, so what the child runs on has to
2668
+ // reach it the same way the failure does.
2669
+ row.state.agentModel = modelChip(facts?.model);
2670
+ row.state.agentEffort = facts?.thinking ? headingText(facts.thinking) : undefined;
2671
+ // From here the result speaks for this call's profile: the store's
2672
+ // task may be a different one (a continuation's predecessor).
2673
+ row.state.agentProfile = true;
2674
+ }
2046
2675
  const body = result.content.map((part) => (part.type === "text" ? part.text : "")).join("\n");
2047
- const visibleBody = options.expanded ? body : theme.fg("muted", agentResultPreview(body).split("\n")[0] ?? "");
2048
- const title = `${AGENTS_GLYPH} agent result${task?.taskId ? ` · ${sanitizeTerminalText(task.taskId)}` : ""}`;
2049
- return new Text(name === "result" ? `${theme.fg("toolTitle", title)}\n${visibleBody}` : visibleBody, 0, 0);
2676
+ let tone: CardTone = failed ? CARD_TONE.ERROR : CARD_TONE.INFO;
2677
+ // Status answers a real orchestration decision, so its task facts
2678
+ // lead the card; the answer card gets the state pill when the
2679
+ // result carries them. Anything without structured details (older
2680
+ // sessions, error results) falls back to the text preview.
2681
+ // Only the status and answer cards lead with the facts; every card
2682
+ // still names the launch profile in its heading.
2683
+ const cardFacts = name === "status" || name === "result" ? facts : undefined;
2684
+ if (cardFacts) tone = STATUS_CARD_TONE[cardFacts.status ?? ""] ?? tone;
2685
+ const iris = agentTheme(theme, tone);
2686
+ let rows: string[];
2687
+ if (cardFacts) {
2688
+ if (name === "status") {
2689
+ rows = statusCardRows(cardFacts, iris, options.expanded);
2690
+ } else {
2691
+ // The answer card: the state pill on top, the answer below.
2692
+ const pillRow = statusCardRows(cardFacts, iris, options.expanded)[0] ?? "";
2693
+ const answer = options.expanded ? body.split("\n") : agentResultPreview(body).split("\n").filter((line) => line.trim() !== "");
2694
+ rows = [pillRow, ...answer];
2695
+ }
2696
+ } else if (options.expanded) {
2697
+ rows = failed ? [statusPill(TASK_STATUS.FAILED, iris), ...body.split("\n")] : body.split("\n");
2698
+ } else {
2699
+ // The collapsed preview leads with the meaningful content: the
2700
+ // answer for finished tasks, the state line for anything else.
2701
+ const preview = agentResultPreview(body).split("\n").filter((line) => line.trim() !== "");
2702
+ // Without facts there is no status to name, but a failure still has
2703
+ // to lead: the pill is the card's one scanable state channel.
2704
+ rows = failed ? [statusPill(TASK_STATUS.FAILED, iris), ...preview] : preview;
2705
+ }
2706
+ // The result tool hides its call, so the result draws the heading
2707
+ // itself; every other tool continues the call's card. Either way the
2708
+ // heading names the agent and what it runs on.
2709
+ const ownHeading = name === "result";
2710
+ // A collapsed status card keeps state, label and last step on one
2711
+ // row each, so a narrow terminal clips them instead of wrapping the
2712
+ // last step out of the three-row preview.
2713
+ const fitRows = !options.expanded && name === "status" && facts !== undefined;
2714
+ const ownChips = ownHeading
2715
+ ? [
2716
+ facts?.agent ? headingText(facts.agent) : facts ? `task ${headingText(facts.taskId)}` : undefined,
2717
+ modelChip(facts?.model),
2718
+ facts?.thinking ? headingText(facts.thinking) : undefined,
2719
+ ]
2720
+ : [];
2721
+ return {
2722
+ render(width: number) {
2723
+ if (width <= 0) return [];
2724
+ const hint = expandHint(options.expanded);
2725
+ return floatRows(tone, iris, width, (inner) => ({
2726
+ ...(ownHeading ? {
2727
+ head: [cardTop({ title: heading, subtitle: fitSubject({ title: heading, tone, glyph }, hint, inner, ownChips), body: [], tone, glyph }, iris, inner, hint)],
2728
+ } : { afterHeading: true }),
2729
+ body: cardBodyRows(fitRows ? rows.map((row) => truncateToWidth(row, cardInnerWidth(inner), "…")) : rows, tone, iris, inner, { expanded: options.expanded, previewRows: ownHeading ? 3 : undefined }),
2730
+ bottom: cardBottom(tone, iris, inner),
2731
+ }));
2732
+ },
2733
+ invalidate() {},
2734
+ };
2050
2735
  },
2051
2736
  async execute(_id, params, signal, _onUpdate, ctx) {
2052
2737
  return execute(params as Record<string, unknown>, ctx, signal);
@@ -2057,19 +2742,19 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2057
2742
  pi.registerTool({
2058
2743
  name: "orchestrator_session_id",
2059
2744
  label: "Orchestrator session ID",
2060
- description: "Return this host session's stable routing ID, Initial alias (FIRST TASK), Current alias (CURRENT TASK), and separate human Session name. Explicit subjects update Current even when named; Initial stays the first declared branch topic, unknown for legacy history. Publishing state.work with an explicit topic and no subject also refreshes Current from that topic; keep work.topic current when the task changes. Before delegation or cross-session coordination, declare a short recognizable subject here. 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. Use a concise non-sensitive label, not a prompt. Progress is published automatically from the todo list; publish state here only for objective, decisions, blockers, or work, never just to report progress. 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.",
2745
+ 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.",
2061
2746
  ...orchestratorToolRenderers("session", expandHint),
2062
2747
  parameters: { type: "object", additionalProperties: false, properties: {
2063
- subject: { type: "string", maxLength: 120, description: "Optional short task subject; updates task aliases independently of human names. Also names an unnamed Pi session." },
2748
+ subject: { type: "string", maxLength: 120, description: "Short task subject; updates aliases independently of human names and names unnamed Pi sessions." },
2064
2749
  state: { anyOf: [{ type: "null" }, { type: "object", additionalProperties: false, properties: {
2065
2750
  objective: { type: "string" }, progress: { type: "string" }, decisions: { type: "string" }, blockers: { type: "string" },
2066
2751
  work: { type: "object", additionalProperties: false,
2067
- description: "Optional historical, non-authoritative classification; topic requires area. Text plus work JSON fits 2048 UTF-8 bytes. Exact duplicate tags/refs are rejected; no ref resolution or routing.",
2752
+ 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.",
2068
2753
  properties: {
2069
2754
  ...workDescriptorSchema.properties,
2070
2755
  tasks: { type: "object", maxProperties: 8, propertyNames: { type: "string", maxLength: 256 },
2071
2756
  additionalProperties: workDescriptorSchema,
2072
- description: "Exact actual owner-declared task IDs, at most 256 UTF-8 bytes; controls, surrogates and __proto__/prototype/constructor rejected. Root-only; nonempty tasks alone are valid. Replacement omitting tasks clears annotations." },
2757
+ description: "Exact owner-declared task IDs, max 256 UTF-8 bytes; no controls, surrogates or __proto__/prototype/constructor. Root-only; nonempty tasks alone valid; replacement without tasks clears annotations." },
2073
2758
  },
2074
2759
  },
2075
2760
  } }] },
@@ -2157,15 +2842,15 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2157
2842
  name: "orchestrator_list",
2158
2843
  label: "List orchestrators",
2159
2844
  ...orchestratorToolRenderers("list", expandHint),
2160
- description: "List other sessions advertised by the trusted local profile. Optional filter searches only published classified work with bounded, non-exhaustive coverage, no authority and unknown reachability. Omit filter for the existing session list.",
2845
+ 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.",
2161
2846
  parameters: Type.Object({
2162
- recipient_session_id: Type.Optional(Type.String({ description: "Exact routing ID of the peer to inspect." })),
2163
- cursor: Type.Optional(Type.String({ description: "Opaque catalog continuation from that peer; requires recipient_session_id." })),
2847
+ recipient_session_id: Type.Optional(Type.String({ description: "Exact peer routing ID." })),
2848
+ cursor: Type.Optional(Type.String({ description: "Opaque peer catalog continuation; requires recipient_session_id." })),
2164
2849
  filter: Type.Optional(Type.Object({
2165
2850
  area: Type.Optional(Type.String()),
2166
2851
  topic: Type.Optional(Type.String({ description: "Requires area." })),
2167
2852
  tag: Type.Optional(Type.String()),
2168
- text: Type.Optional(Type.String({ description: "Literal label/descriptor search, never state prose or history." })),
2853
+ text: Type.Optional(Type.String({ description: "Literal label/descriptor search, not state prose or history." })),
2169
2854
  ref: Type.Optional(Type.Object({
2170
2855
  kind: Type.Union([Type.Literal("issue"), Type.Literal("pr"), Type.Literal("task")]),
2171
2856
  repository: Type.String({ description: "Exact public host/owner/repo scope." }),
@@ -2176,7 +2861,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2176
2861
  session_id: Type.String({ description: "Exact stable source owner session ID." }),
2177
2862
  task_id: Type.Optional(Type.String({ description: "Actual task ID on the current catalog page, not child session ID." })),
2178
2863
  }, { additionalProperties: false })),
2179
- }, { additionalProperties: false, description: "Explicit {} indexes classified work; criteria combine with AND." })),
2864
+ }, { additionalProperties: false, description: "{} indexes classified work; criteria combine with AND." })),
2180
2865
  }, { additionalProperties: false }),
2181
2866
  async execute(_id, _params, _signal, _onUpdate, ctx) {
2182
2867
  const params = _params as { recipient_session_id?: string; cursor?: string; filter?: unknown };
@@ -2200,7 +2885,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2200
2885
  return text(JSON.stringify(workSearch), { gentleAgents: { workSearch } });
2201
2886
  }
2202
2887
  const peers = discoverOrchestrators(agentHome, activations, Date.now(), params.recipient_session_id
2203
- ? { recipientSessionId: params.recipient_session_id, cursor: params.cursor } : undefined);
2888
+ ? { recipientSessionId: params.recipient_session_id, cursor: params.cursor, stateOnly: true } : { stateOnly: true });
2204
2889
  const repository = (fact?: RepositoryFact) => fact?.root
2205
2890
  ? `repository: ${fact.root} · clone: ${fact.cloneHash} · Git resolved at: ${fact.resolvedAt} (${fact.source})`
2206
2891
  : "repository: unknown";
@@ -2215,9 +2900,16 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2215
2900
  const note = params.recipient_session_id ? `\n owner-curated recorded state (not consent or owner reply; authority none): ${peer.state ? JSON.stringify(peer.state) : "unknown"}` : "";
2216
2901
  // A legacy peer never publishes its scope: say so instead of reporting an unknown.
2217
2902
  const legacy = peer.legacyLabel !== undefined;
2218
- return `- ${peer.sessionId}${context} · ${legacy ? "repository: not published" : repository(peer.scope?.host)} · metadata: ${legacy ? "legacy" : peer.freshness}${tasks}${registered}${gaps}${catalog}${note}${peer.omitted ? `\n (${peer.omitted} more tasks omitted)` : ""}`;
2903
+ // A peer doing classified work without ever publishing state cannot be
2904
+ // routed or coordinated with; the catalog says so explicitly (#2633).
2905
+ const unpublished = !legacy && peer.freshness === "recent" && !peer.state && !peer.statePublished
2906
+ ? " · work state: never published" : "";
2907
+ return `- ${peer.sessionId}${context} · ${legacy ? "repository: not published" : repository(peer.scope?.host)} · metadata: ${legacy ? "legacy" : peer.freshness}${tasks}${registered}${gaps}${catalog}${note}${unpublished}${peer.omitted ? `\n (${peer.omitted} more tasks omitted)` : ""}`;
2219
2908
  });
2220
- return peers.length === 0 ? text("No other sessions are currently advertised. Advertisements have unknown reachability and do not guarantee a live session.") : text(`Advertised sessions (reachability is unknown):\n${rows.join("\n")}`, { gentleAgents: { candidates: peers } });
2909
+ if (peers.length === 0) return text("No other sessions are currently advertised. Advertisements have unknown reachability and do not guarantee a live session.");
2910
+ const unlisted = peers.filter(peer => peer.freshness === "recent" && peer.legacyLabel === undefined && !peer.state && !peer.statePublished);
2911
+ const mandate = unlisted.length > 0 ? `\n${unlisted.length} of ${peers.length} advertised sessions have never published work state. Publication is mandatory for classified work: each owner session publishes state (objective, work.topic) at session start and again on every task-topic change via orchestrator_session_id.` : "";
2912
+ return text(`Advertised sessions (reachability is unknown):\n${rows.join("\n")}${mandate}`, { gentleAgents: { candidates: peers } });
2221
2913
  } catch (error) {
2222
2914
  // SessionPresenceError codes are a fixed enum with no record content,
2223
2915
  // so surfacing the reason is safe and keeps diagnosis possible.
@@ -2264,15 +2956,18 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2264
2956
  }
2265
2957
  if (recipient === undefined) {
2266
2958
  try {
2267
- const candidates = (await transport.listener.registry.listActivations(transport.sessionId)).filter((candidate) => candidate.sessionId !== transport.sessionId);
2959
+ const activations = (await transport.listener.registry.listActivations(transport.sessionId)).filter((candidate) => candidate.sessionId !== transport.sessionId);
2960
+ // A transport may report more than one activation for one session; the picker maps
2961
+ // the chosen label back to a single activation, so keep one entry per session ID.
2962
+ const candidates = [...new Map(activations.map((candidate) => [candidate.sessionId, candidate] as const)).values()];
2268
2963
  if (activeTransportFor(ctx) !== transport || signal?.aborted) return text("Message selection was cancelled.", { error: "cancelled" });
2269
2964
  if (candidates.length === 0) return text("No other sessions are currently advertised; message delivery is unavailable.", { error: "unavailable" });
2270
2965
  if (candidates.length === 1) {
2271
2966
  recipient = candidates[0].sessionId;
2272
2967
  activation = candidates[0];
2273
- } 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 })) } });
2274
- else {
2275
- const labels = candidates.map((candidate) => `Orchestrator ${candidate.sessionId}`);
2968
+ } else {
2969
+ const labels = recipientSelectionLabels(agentHome, candidates, activations);
2970
+ 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 })) } });
2276
2971
  const selected = await ctx.ui.select("Select recipient orchestrator", labels, { signal });
2277
2972
  if (selected === undefined || activeTransportFor(ctx) !== transport || signal?.aborted) return text("Message selection was cancelled.", { error: "cancelled" });
2278
2973
  const index = labels.indexOf(selected);
@@ -2326,6 +3021,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2326
3021
  },
2327
3022
  },
2328
3023
  async (params, ctx, signal) => {
3024
+ requireSessionProfileAuthority(ctx.sessionManager);
2329
3025
  const work = Object.hasOwn(params, "work") ? decodeWorkDescriptor(params.work) : undefined;
2330
3026
  const manager = ctx.sessionManager, sessionId = manager.getSessionId();
2331
3027
  if (typeof params.agent !== "string" || !params.agent.trim() || typeof params.task !== "string" || !params.task.trim() || (params.context !== undefined && typeof params.context !== "string") || (params.label !== undefined && typeof params.label !== "string")) throw new Error("Subagent dispatch requires a named agent, non-empty task and string context/label.");
@@ -2384,8 +3080,16 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2384
3080
  });
2385
3081
 
2386
3082
  tool("list_tasks", "List the subagent tasks of this session, newest first.", { properties: {} }, async (_params, ctx) => {
2387
- const tasks = store.list(ctx.sessionManager.getSessionId() ?? "");
2388
- return text(tasks.length === 0 ? "No subagent tasks in this session." : tasks.map(describeTask).join("\n"));
3083
+ await sessionRestoration;
3084
+ const sessionId = ctx.sessionManager.getSessionId() ?? "";
3085
+ const tasks = store.list(sessionId);
3086
+ for (const task of tasks) {
3087
+ if (!isFinished(task.status) && restoredTaskIds.has(task.id)) {
3088
+ await resolveTask(task.id);
3089
+ }
3090
+ }
3091
+ const reconciledTasks = store.list(sessionId);
3092
+ return text(reconciledTasks.length === 0 ? "No subagent tasks in this session." : reconciledTasks.map(describeTask).join("\n"));
2389
3093
  });
2390
3094
 
2391
3095
  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) => {
@@ -2411,6 +3115,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2411
3115
  "Resume a finished subagent task in its own session with a follow-up prompt.",
2412
3116
  { required: ["task_id", "prompt"], properties: { task_id: { type: "string" }, prompt: { type: "string" }, label: { type: "string", description: "Three to six words naming the follow-up." }, mode: { type: "string", enum: ["task", "background"] } } },
2413
3117
  async (params, ctx, signal) => {
3118
+ requireSessionProfileAuthority(ctx.sessionManager);
2414
3119
  if (Object.hasOwn(params, "sdd_change") || Object.hasOwn(params, "remediation") || Object.hasOwn(params, "research_selection")) return text("Error: retired SDD delegation is not supported.", { error: "retired SDD delegation" });
2415
3120
  const previous = await resolveTask(String(params.task_id));
2416
3121
  if (!previous) return unknownTask(params.task_id, ctx);
@@ -2437,7 +3142,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2437
3142
  }
2438
3143
 
2439
3144
  pi.registerCommand(JOBS_COMMAND_NAME, {
2440
- description: "Show background jobs: running first, newest first within each group; status, command, output tail; s stops the selected job.",
3145
+ 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.",
2441
3146
  handler: async (_args, ctx) => {
2442
3147
  if (!ctx.hasUI) return;
2443
3148
  if (ctx.mode !== "tui") {
@@ -2527,12 +3232,21 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2527
3232
  // resolveTask path for anything else.
2528
3233
  const sessionId = ctx.sessionManager.getSessionId();
2529
3234
  const preexisting = event.reason === "resume" || (event.reason === "startup" && ctx.sessionManager.getEntries().length > 0);
2530
- if (preexisting && sessionId) void restoreSessionHistory(ctx, sessionId);
3235
+ if (preexisting && sessionId) sessionRestoration = restoreSessionHistory(ctx, sessionId);
2531
3236
  try {
2532
3237
  presence = startPresence(ctx.sessionManager);
2533
3238
  resetActivityPublish();
2534
3239
  publishActivityPrompt();
2535
- } catch { presence = undefined; }
3240
+ } catch {
3241
+ presence = undefined;
3242
+ // Fixed text only: the failure may carry a profile path or session id.
3243
+ try { ctx.ui.notify("Session presence unavailable: phase=presence class=transport code=presence-cleared.", "warning"); } catch {}
3244
+ }
3245
+ // /reload and /resume recompute busy from live owned work only: a task
3246
+ // restored from disk never enters ownedTaskIds, so counting it would
3247
+ // report working for work this runtime no longer owns. An unchanged
3248
+ // label dedups; a session without owned running work lowers.
3249
+ refreshHerdrBusy();
2536
3250
  void startSessionTransport(ctx);
2537
3251
  // The desktop app's own pi process: publish live subagent state through
2538
3252
  // setWidget's RPC-mode string[] path. Plain headless RPC (no variable) and
@@ -2558,9 +3272,14 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2558
3272
  rpcActivityPublisher.start();
2559
3273
  }
2560
3274
  });
3275
+ pi.on("agent_start", (_event, ctx) => rearmSessionTransport(ctx));
3276
+ pi.on("turn_end", (_event, ctx) => rearmSessionTransport(ctx));
2561
3277
  pi.on("session_shutdown", async () => {
2562
3278
  completions.dropAll();
2563
3279
  messages.dropAll();
3280
+ // No stale busy may survive the runtime.
3281
+ if (emittedBusy?.active) pi.events.emit(HERDR_BUSY_CHANNEL, { active: false });
3282
+ emittedBusy = { active: false };
2564
3283
  // Jobs never outlive their session: a stopped job sends no notice.
2565
3284
  monitors.cancelAll();
2566
3285
  const jobsStopped = jobs.stopAll();