gentle-pi 3.6.0 → 4.0.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 (320) hide show
  1. package/README.md +37 -6
  2. package/assets/agents/gentle-ai-explore.md +4 -4
  3. package/assets/agents/gentle-ai-verify.md +6 -4
  4. package/assets/agents/gentle-ai-worker.md +7 -9
  5. package/assets/orchestrator-delegation.md +40 -41
  6. package/assets/orchestrator-memory.md +1 -22
  7. package/assets/orchestrator-skills.md +1 -1
  8. package/assets/orchestrator.md +12 -24
  9. package/assets/support/strict-tdd-verify.md +4 -266
  10. package/assets/support/strict-tdd.md +8 -360
  11. package/bin/gentle-shell.mjs +254 -29
  12. package/docs/delegated-verification.md +26 -1
  13. package/docs/gentle-agents-activity.md +24 -0
  14. package/docs/gentle-shell.md +95 -30
  15. package/docs/native-authority-architecture.md +2 -2
  16. package/docs/prompt-history.md +280 -0
  17. package/docs/readme-reference.md +117 -235
  18. package/docs/telemetry.md +1 -1
  19. package/docs/yolo-mode.md +86 -0
  20. package/extensions/child-context.ts +26 -0
  21. package/extensions/child-safety.ts +23 -0
  22. package/extensions/gentle-agents.ts +509 -275
  23. package/extensions/gentle-ai.ts +781 -683
  24. package/extensions/gentle-shell.ts +1375 -88
  25. package/extensions/gentle-stats.ts +101 -0
  26. package/extensions/gentle-todo.ts +18 -7
  27. package/extensions/history/atomic-write.ts +38 -0
  28. package/extensions/history/hide-prompts.ts +183 -0
  29. package/extensions/history/index.ts +1419 -0
  30. package/extensions/history/load-shared-history.ts +39 -0
  31. package/extensions/history/selector-helpers.ts +538 -0
  32. package/extensions/history/session-scan.ts +233 -0
  33. package/extensions/history/store.ts +1119 -0
  34. package/extensions/nan-provider.ts +6 -0
  35. package/extensions/quiet-tools.ts +179 -87
  36. package/extensions/resume-hint.ts +60 -0
  37. package/extensions/skill-registry.ts +16 -12
  38. package/extensions/startup-banner.ts +60 -31
  39. package/lib/agent-assets.ts +604 -0
  40. package/lib/agent-profile-pin.ts +12 -0
  41. package/lib/agents-message-delivery.ts +181 -0
  42. package/lib/agents-protocol.ts +60 -0
  43. package/lib/agents-runner.ts +105 -98
  44. package/lib/agents-view.ts +26 -3
  45. package/lib/agents-widget.ts +16 -9
  46. package/lib/append-system-prompt.ts +21 -0
  47. package/lib/bounded-writer-admission.ts +147 -0
  48. package/lib/card-style-policy.ts +60 -0
  49. package/lib/child-context-files.ts +166 -0
  50. package/lib/codemode-renderer.ts +185 -0
  51. package/lib/command-palette-catalog.ts +3 -9
  52. package/lib/command-palette.ts +25 -14
  53. package/lib/destructive-command-guard.ts +144 -0
  54. package/lib/foreign-target-grants.ts +32 -0
  55. package/lib/gentle-ai-elapsed-store.ts +87 -0
  56. package/lib/gentle-ai-renderer.ts +196 -39
  57. package/lib/gentle-shell-launcher.ts +24 -13
  58. package/lib/gentle-shell-resume-hint.ts +176 -0
  59. package/lib/history-capture-policy.ts +95 -0
  60. package/lib/model-routing-authority.ts +5 -1
  61. package/lib/nan-provider.ts +227 -0
  62. package/lib/native-review-cli.ts +53 -108
  63. package/lib/odd-phase-inference.ts +231 -0
  64. package/lib/odd-phase.ts +141 -0
  65. package/lib/overlay-repaint.ts +26 -0
  66. package/lib/pi-tui-keys.ts +53 -0
  67. package/lib/review-candidate-view-owner.ts +67 -17
  68. package/lib/review-candidate-view.ts +112 -25
  69. package/lib/review-reminder-receipt.ts +48 -8
  70. package/lib/review-risk-assessment.ts +156 -11
  71. package/lib/review-sidebar-state.ts +223 -0
  72. package/lib/selection-engine.ts +515 -0
  73. package/lib/session-change-capture.ts +10 -1
  74. package/lib/session-messaging-grants.ts +135 -0
  75. package/lib/session-worktree-registry.ts +14 -2
  76. package/lib/shell-bar.ts +179 -24
  77. package/lib/shell-card.ts +287 -18
  78. package/lib/shell-changes-view.ts +2 -1
  79. package/lib/shell-prompt.ts +102 -6
  80. package/lib/shell-sidebar-layout.ts +78 -14
  81. package/lib/shell-sidebar.ts +15 -1
  82. package/lib/shell-todo.ts +23 -13
  83. package/lib/shell-usage-view.ts +9 -4
  84. package/lib/shell-usage.ts +66 -10
  85. package/lib/stats-collector.ts +381 -0
  86. package/lib/stats-view.ts +431 -0
  87. package/lib/theme-customization.ts +52 -0
  88. package/lib/vim-editor-adapter.ts +379 -0
  89. package/lib/vim-normal-engine.ts +154 -0
  90. package/lib/vim-operator-engine.ts +416 -0
  91. package/lib/vim-policy.ts +49 -0
  92. package/lib/vim-visual-engine.ts +107 -0
  93. package/lib/visual-customization-policy.ts +108 -0
  94. package/lib/visual-customize-view.ts +330 -0
  95. package/lib/visual-profiles.ts +228 -0
  96. package/lib/yolo-session-policy.ts +240 -0
  97. package/package.json +20 -8
  98. package/runtime/gentle-shell-launcher.mjs +23 -12
  99. package/runtime/gentle-shell-resume-hint.mjs +177 -0
  100. package/runtime/native-review-cli.mjs +53 -108
  101. package/runtime/review-risk-assessment.mjs +154 -9
  102. package/scripts/build-runtime-modules.mjs +1 -0
  103. package/scripts/gentle-ai-installer.mjs +14 -13
  104. package/scripts/mirror-odd-routing.mjs +2 -2
  105. package/scripts/run-test-suite.mjs +76 -0
  106. package/scripts/test-packed-runner.mjs +31 -14
  107. package/scripts/verify-package-files.mjs +11 -22
  108. package/skills/branch-pr/SKILL.md +24 -52
  109. package/skills/chained-pr/SKILL.md +31 -15
  110. package/skills/chained-pr/references/chaining-details.md +31 -20
  111. package/skills/gentle-ai/SKILL.md +9 -15
  112. package/skills/issue-creation/SKILL.md +8 -2
  113. package/skills/issue-creation/references/delegated-workflow-actions.md +19 -0
  114. package/skills/work-unit-commits/SKILL.md +4 -3
  115. package/tests/agent-profiles.test.ts +18 -0
  116. package/tests/agents-fake-child.ts +2 -2
  117. package/tests/agents-message-delivery.test.ts +106 -0
  118. package/tests/agents-protocol.test.ts +40 -0
  119. package/tests/agents-runner.test.ts +400 -89
  120. package/tests/agents-view-thread-identity.test.ts +169 -0
  121. package/tests/agents-view.test.ts +8 -2
  122. package/tests/agents-widget.test.ts +154 -15
  123. package/tests/append-system-prompt-route.test.ts +160 -0
  124. package/tests/append-system-prompt.test.ts +46 -0
  125. package/tests/artifact-language.test.ts +19 -213
  126. package/tests/ask-user-question.test.ts +44 -1
  127. package/tests/asset-installation-runtime.test.ts +5 -16
  128. package/tests/autonomous-guard.test.ts +69 -1
  129. package/tests/bounded-writer-admission.test.ts +95 -0
  130. package/tests/branch-pr-skill.test.ts +43 -0
  131. package/tests/card-style-policy.test.ts +55 -0
  132. package/tests/chained-pr-skill.test.ts +124 -0
  133. package/tests/child-context-files.test.ts +255 -0
  134. package/tests/child-safety.test.ts +82 -0
  135. package/tests/codemode-rendering.test.ts +491 -0
  136. package/tests/command-palette.test.ts +39 -3
  137. package/tests/delegated-key-learnings-contract.test.ts +0 -76
  138. package/tests/destructive-command-guard.test.ts +84 -0
  139. package/tests/devbinary/native-review-parity.devtest.ts +170 -2
  140. package/tests/devbinary/non-git-subagent-bootstrap.devtest.ts +193 -0
  141. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +7 -0
  142. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +3 -0
  143. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T08-00-00-000Z_ddd.jsonl +2 -0
  144. package/tests/fixtures/stats/sessions/--work-alpha--/2026-09-30T09-00-00-000Z_eee.jsonl +3 -0
  145. package/tests/fixtures/stats/sessions/--work-alpha--/run-1/session.jsonl +2 -0
  146. package/tests/fixtures/stats/sessions/--work-beta--/2026-09-01T12-00-00-000Z_ccc.jsonl +2 -0
  147. package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-28T10-00-00-000Z_aaa.jsonl +2 -0
  148. package/tests/fixtures/stats/user-pi/sessions/--work-alpha--/2026-09-29T23-00-00-000Z_bbb.jsonl +4 -0
  149. package/tests/fixtures/stats/user-pi/sessions/--work-gamma--/2026-09-20T09-00-00-000Z_fff.jsonl +3 -0
  150. package/tests/foreign-target-grants.test.ts +58 -0
  151. package/tests/generic-agent-tools.test.ts +54 -0
  152. package/tests/gentle-agents.test.ts +1411 -256
  153. package/tests/gentle-ai-binary.test.ts +3 -3
  154. package/tests/gentle-ai-elapsed-store.test.ts +68 -0
  155. package/tests/gentle-ai-installer.test.ts +68 -54
  156. package/tests/gentle-ai-renderer.test.ts +487 -8
  157. package/tests/gentle-ai.test.ts +288 -65
  158. package/tests/gentle-card-text.ts +2 -1
  159. package/tests/gentle-shell-bin.test.ts +651 -114
  160. package/tests/gentle-shell-launcher.test.ts +99 -52
  161. package/tests/gentle-shell-resume-hint.test.ts +270 -0
  162. package/tests/gentle-shell.test.ts +3839 -187
  163. package/tests/gentle-stats.test.ts +152 -0
  164. package/tests/gentle-theme.test.ts +4 -1
  165. package/tests/gentle-todo.test.ts +80 -8
  166. package/tests/history-atomic-write.test.ts +57 -0
  167. package/tests/history-capture-policy.test.ts +102 -0
  168. package/tests/history-command-registration.test.ts +164 -0
  169. package/tests/history-dedupe-entries.test.ts +123 -0
  170. package/tests/history-delete-backfill.test.ts +190 -0
  171. package/tests/history-delete-confirm.test.ts +460 -0
  172. package/tests/history-dispatch.test.ts +180 -0
  173. package/tests/history-drain-hidden.test.ts +110 -0
  174. package/tests/history-drain-order.test.ts +98 -0
  175. package/tests/history-expanded-globals.test.ts +62 -0
  176. package/tests/history-gc.test.ts +832 -0
  177. package/tests/history-header-layout.test.ts +265 -0
  178. package/tests/history-hide-prompts.test.ts +275 -0
  179. package/tests/history-lazy-windowing.test.ts +508 -0
  180. package/tests/history-legacy-migrate-v2.test.ts +297 -0
  181. package/tests/history-load-shared-history.test.ts +53 -0
  182. package/tests/history-max-results-cap.test.ts +76 -0
  183. package/tests/history-multi-reader.test.ts +203 -0
  184. package/tests/history-off-path.test.ts +170 -0
  185. package/tests/history-openflow-integration.test.ts +173 -0
  186. package/tests/history-overlay-margin.test.ts +326 -0
  187. package/tests/history-preview-layout.test.ts +93 -0
  188. package/tests/history-registry.test.ts +143 -0
  189. package/tests/history-scope-delete.test.ts +411 -0
  190. package/tests/history-search-caret-keys.test.ts +142 -0
  191. package/tests/history-seed-bootstrap.test.ts +170 -0
  192. package/tests/history-seed-regen.test.ts +129 -0
  193. package/tests/history-selector-windowing.test.ts +94 -0
  194. package/tests/history-session-scan-directory.test.ts +87 -0
  195. package/tests/history-session-scan-extract.test.ts +583 -0
  196. package/tests/history-session-writer.test.ts +351 -0
  197. package/tests/history-store-paths.test.ts +79 -0
  198. package/tests/history-tombstone-exact.test.ts +139 -0
  199. package/tests/history-wheel-mouse.test.ts +242 -0
  200. package/tests/inprocess-reviewer.test.ts +29 -19
  201. package/tests/issue-creation-skill.test.ts +61 -0
  202. package/tests/model-routing-authority.test.ts +16 -0
  203. package/tests/nan-provider.test.ts +471 -0
  204. package/tests/native-review-capability-contract.test.ts +13 -1
  205. package/tests/native-review-cli.test.ts +6 -120
  206. package/tests/native-review-parity-runtime.test.ts +100 -3
  207. package/tests/odd-integration.test.ts +67 -0
  208. package/tests/odd-phase-inference.test.ts +213 -0
  209. package/tests/odd-phase-loader.test.ts +253 -0
  210. package/tests/odd-phase.test.ts +307 -0
  211. package/tests/odd-routing-canonical-ratchet.test.ts +11 -6
  212. package/tests/odd-routing-contract.test.ts +86 -35
  213. package/tests/orchestrator-budget.test.ts +14 -39
  214. package/tests/orchestrator-rdd-ownership.test.ts +3 -3
  215. package/tests/overlay-repaint.test.ts +74 -0
  216. package/tests/package-manifest.test.ts +252 -115
  217. package/tests/packed-runner-owned-path.test.ts +46 -0
  218. package/tests/persona-single-channel.test.ts +6 -6
  219. package/tests/provider-defect-handoff.test.ts +3 -11
  220. package/tests/quiet-bash-runtime.test.ts +76 -0
  221. package/tests/quiet-tool-rendering.test.ts +409 -184
  222. package/tests/rdd-aware-verification-contract.test.ts +76 -1
  223. package/tests/rdd-status-line.test.ts +9 -4
  224. package/tests/resume-hint-extension.test.ts +122 -0
  225. package/tests/review-agent-end-preflight.test.ts +176 -12
  226. package/tests/review-candidate-owner-retry.test.ts +22 -1
  227. package/tests/review-candidate-view.test.ts +298 -0
  228. package/tests/review-contract-prompt.test.ts +108 -43
  229. package/tests/review-controller-lock-status.test.ts +0 -1
  230. package/tests/review-controller-native-routing.test.ts +611 -5
  231. package/tests/review-controller-workspace-root.test.ts +163 -4
  232. package/tests/review-host-relay-routing.test.ts +338 -2
  233. package/tests/review-integration-v2-forward.test.ts +200 -0
  234. package/tests/review-ledger-contract.test.ts +10 -34
  235. package/tests/review-reminder-receipt.test.ts +47 -1
  236. package/tests/review-risk-assessment.test.ts +498 -6
  237. package/tests/review-sidebar-state.test.ts +402 -0
  238. package/tests/run-test-suite.test.ts +124 -0
  239. package/tests/runtime-harness.mjs +145 -786
  240. package/tests/runtime-metrics-children.test.ts +16 -23
  241. package/tests/selection-engine.test.ts +421 -0
  242. package/tests/session-change-capture.test.ts +12 -1
  243. package/tests/session-messaging-grants.test.ts +255 -0
  244. package/tests/session-worktree-registry.test.ts +77 -0
  245. package/tests/shell-bar.test.ts +382 -1
  246. package/tests/shell-card.test.ts +353 -1
  247. package/tests/shell-changes-view.test.ts +52 -0
  248. package/tests/shell-prompt.test.ts +94 -2
  249. package/tests/shell-sidebar-layout.test.ts +325 -21
  250. package/tests/shell-sidebar-scroll-benchmark.test.ts +255 -0
  251. package/tests/shell-todo.test.ts +87 -1
  252. package/tests/shell-usage-view.test.ts +27 -0
  253. package/tests/shell-usage.test.ts +73 -0
  254. package/tests/skill-registry.test.ts +50 -1
  255. package/tests/startup-banner.test.ts +130 -2
  256. package/tests/stats-collector.test.ts +195 -0
  257. package/tests/stats-view.test.ts +202 -0
  258. package/tests/telemetry-trigger.test.ts +81 -20
  259. package/tests/theme-customization.test.ts +72 -0
  260. package/tests/vim-editor-adapter-host-resolution.test.ts +37 -0
  261. package/tests/vim-editor-adapter.test.ts +804 -0
  262. package/tests/vim-normal-engine.test.ts +101 -0
  263. package/tests/vim-operator-engine.test.ts +215 -0
  264. package/tests/vim-policy.test.ts +19 -0
  265. package/tests/vim-visual-engine.test.ts +52 -0
  266. package/tests/visual-customization-policy.test.ts +110 -0
  267. package/tests/visual-customize-view.test.ts +418 -0
  268. package/tests/visual-profiles.test.ts +87 -0
  269. package/tests/yolo-customize.test.ts +256 -0
  270. package/tests/yolo-mode-runtime.test.ts +161 -0
  271. package/tests/yolo-mode.test.ts +261 -0
  272. package/tests/yolo-session-policy.test.ts +59 -0
  273. package/themes/Gentle.json +2 -1
  274. package/themes/Gentleman-Cute.json +2 -1
  275. package/themes/Gentleman-Sexy.json +2 -1
  276. package/assets/agents/sdd-apply.md +0 -159
  277. package/assets/agents/sdd-archive.md +0 -228
  278. package/assets/agents/sdd-design.md +0 -49
  279. package/assets/agents/sdd-explore.md +0 -48
  280. package/assets/agents/sdd-init.md +0 -56
  281. package/assets/agents/sdd-onboard.md +0 -52
  282. package/assets/agents/sdd-proposal.md +0 -64
  283. package/assets/agents/sdd-remediate.md +0 -37
  284. package/assets/agents/sdd-research.md +0 -49
  285. package/assets/agents/sdd-spec.md +0 -192
  286. package/assets/agents/sdd-status.md +0 -54
  287. package/assets/agents/sdd-tasks.md +0 -108
  288. package/assets/agents/sdd-verify.md +0 -124
  289. package/assets/chains/sdd-full.chain.md +0 -83
  290. package/assets/chains/sdd-plan.chain.md +0 -56
  291. package/assets/chains/sdd-verify.chain.md +0 -43
  292. package/assets/sdd-orchestrator-workflow.md +0 -319
  293. package/assets/support/sdd-status-contract.md +0 -77
  294. package/docs/assets/diagrams/sdd-cycle.svg +0 -14
  295. package/extensions/sdd-init.ts +0 -816
  296. package/lib/openspec-deltas.ts +0 -156
  297. package/lib/sdd-preflight.ts +0 -1066
  298. package/lib/sdd-research-capabilities.ts +0 -94
  299. package/lib/sdd-status.ts +0 -26
  300. package/tests/fixtures/legacy/sdd-research-v2.5.0.md +0 -54
  301. package/tests/fixtures/native-review-cli/v2.1.3/bind-sdd.json +0 -25
  302. package/tests/fixtures/v0.10.7/assets/agents/sdd-apply.md +0 -132
  303. package/tests/openspec-deltas.test.ts +0 -209
  304. package/tests/sdd-agent-tools.test.ts +0 -156
  305. package/tests/sdd-archive-replay.test.ts +0 -82
  306. package/tests/sdd-classical-continuation.test.ts +0 -74
  307. package/tests/sdd-execution-routing-contract.test.ts +0 -44
  308. package/tests/sdd-managed-runtime-settlement.test.ts +0 -155
  309. package/tests/sdd-native-managed-uptake.test.ts +0 -243
  310. package/tests/sdd-no-attempts-contract.test.ts +0 -15
  311. package/tests/sdd-odd-integration.test.ts +0 -33
  312. package/tests/sdd-optional-research.test.ts +0 -124
  313. package/tests/sdd-planning-routing-contract.test.ts +0 -45
  314. package/tests/sdd-preflight-rpc-input.test.ts +0 -125
  315. package/tests/sdd-preflight.test.ts +0 -541
  316. package/tests/sdd-research-capabilities.test.ts +0 -114
  317. package/tests/sdd-research-live.test.ts +0 -241
  318. package/tests/sdd-selection-transport.test.ts +0 -653
  319. package/tests/sdd-status.test.ts +0 -9
  320. package/tests/sdd-task-truth.test.ts +0 -43
@@ -1,12 +1,14 @@
1
1
  import { isSessionChangeEvidence, type SessionChangeEvidence } from "./session-changes.ts";
2
+ import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
2
5
  import type { Duplex, Readable, Writable } from "node:stream";
3
6
  import { stripVTControlCharacters } from "node:util";
4
- import { RESEARCH_SELECTION_ENV } from "./sdd-research-capabilities.ts";
5
7
  import { withoutInteractiveHost } from "./rpc-host.ts";
6
8
  import { AGENT_MODE, formatModelRef, type AgentDefinition, type AgentMode, type ModelRef } from "./agents-config.ts";
7
9
  import { CHILD_QUERY_MAX_INFLIGHT, CHILD_QUERY_TIMEOUT_MS, parseChildFrame, validChildMessage, validChildQueryId } from "./agents-messaging.ts";
8
10
  import { ParentStandingReviewPermissionBroker } from "./review-session-standing-permission-ipc.ts";
9
- import { isFinished, normalizeRpcEvent, TASK_EVENT, TASK_STATUS, taskLabel, type AskRequest, type ChildResponseObservation, type TaskRecord, type TaskStore } from "./agents-protocol.ts";
11
+ import { isFinished, normalizeRpcEvent, ToolArgumentProgress, TASK_EVENT, TASK_STATUS, taskLabel, type AskRequest, type ChildResponseObservation, type TaskRecord, type TaskStore } from "./agents-protocol.ts";
10
12
 
11
13
  // Gentle Agents runner. Every subagent is its own `pi --mode rpc` process:
12
14
  // the host never runs subagent work on the TUI thread. It writes JSON
@@ -53,6 +55,7 @@ export interface RunnerDeps {
53
55
  now(): number;
54
56
  schedule(fn: () => void, ms: number): () => void;
55
57
  pi: PiCommand;
58
+ resolvePi?(): PiCommand;
56
59
  process?: ProcessControl;
57
60
  }
58
61
 
@@ -73,6 +76,7 @@ export interface AskAnswer {
73
76
  export interface TaskQuery {
74
77
  taskId: string;
75
78
  requestId: string;
79
+ message: string;
76
80
  }
77
81
 
78
82
  export const MAX_CHILD_RESPONSE_OBSERVATIONS = 128;
@@ -104,51 +108,12 @@ export interface RunnerHooks {
104
108
  // Accepts a child notification only while the originating parent session is active.
105
109
  onNotification?(task: TaskRecord, message: string): boolean | void;
106
110
  onQuery?(task: TaskRecord, requestId: string, message: string): boolean | void;
111
+ onQuerySettled?(taskId: string, requestId: string, outcome: "replied" | "expired"): void;
107
112
  // Parent-only observation of a paired successful filesystem tool, not prose.
108
113
  onSuccessfulMutation?(task: TaskRecord, tool: { toolName: "write" | "edit"; toolCallId: string; path: string; evidence?: SessionChangeEvidence }): void | Promise<void>;
109
114
  }
110
115
 
111
- export interface RemediationHarnessPlan { command?: string; naReason?: string }
112
- export interface RemediationRollbackPlan { boundary: string; command: string }
113
- export interface RemediationScope { cwd: string; editPaths: string[]; commands: string[]; allowedEditRoots: string[] }
114
- export interface RemediationPlan {
115
- editPaths?: string[];
116
- cwd: string;
117
- commands: string[];
118
- runtimeHarness: RemediationHarnessPlan;
119
- rollback: RemediationRollbackPlan;
120
- }
121
- const concrete = (value: unknown): value is string => typeof value === "string" && value.trim() === value && value.length > 3 && value.length <= 4096 && !/[\0\r\n]/.test(value);
122
- export function parseRemediationPlan(value: unknown, cwd: string): RemediationPlan {
123
- const plan = value as RemediationPlan;
124
- if (!plan || plan.cwd !== cwd || !Array.isArray(plan.commands) || plan.commands.length < 1 || plan.commands.length > 16 || !plan.commands.every(concrete) ||
125
- !concrete(plan.rollback?.boundary) || !concrete(plan.rollback?.command) || !plan.runtimeHarness ||
126
- !(concrete(plan.runtimeHarness.command) && plan.runtimeHarness.naReason === undefined || plan.runtimeHarness.command === undefined && concrete(plan.runtimeHarness.naReason) && plan.runtimeHarness.naReason.length >= 20 && /because/i.test(plan.runtimeHarness.naReason))) throw new TypeError("Invalid remediation evidence plan");
127
- return structuredClone(plan);
128
- }
129
- export const plannedCommands = (plan: RemediationPlan) => [...plan.commands, ...(plan.runtimeHarness.command ? [plan.runtimeHarness.command] : []), plan.rollback.command];
130
- // Launch-local scope only; task history is not an attempt authority.
131
- export interface RemediationContext {
132
- failedEvidenceRevision: string;
133
- plan: RemediationPlan;
134
- scope: RemediationScope;
135
- }
136
-
137
- export interface SddChangeSelection {
138
- changeName: string;
139
- workspaceRoot: string;
140
- phase: "apply" | "verify" | "archive" | "remediate";
141
- failedEvidenceRevision?: string;
142
- }
143
-
144
- export const SDD_CHANGE_FLAG = "--gentle-sdd-change";
145
-
146
- export const REMEDIATION_PLAN_ENV = "GENTLE_PI_SDD_REMEDIATION_PLAN";
147
-
148
116
  export interface TaskRequest {
149
- remediationIntent?: unknown;
150
- sddRemediation?: RemediationContext;
151
- sddPreflightContext?: string;
152
117
  agent: AgentDefinition;
153
118
  prompt: string;
154
119
  label: string | undefined;
@@ -161,11 +126,11 @@ export interface TaskRequest {
161
126
  sessionDir: string;
162
127
  resumeSessionPath: string | undefined;
163
128
  env: NodeJS.ProcessEnv;
164
- // A launch-local SDD identity. It is never prompt text or shared state.
165
- sddChange?: SddChangeSelection;
166
129
  // Untrusted narrowing intent; paths come only from matching host provenance.
167
- researchSelection?: unknown;
168
130
  extensionPaths?: string[];
131
+ // Synchronous admission recheck at dequeue, before any OS spawn. Throws fail
132
+ // only this task; unlike onLaunch, it must never persist Changes evidence.
133
+ beforeSpawn?: () => void;
169
134
  // Captures the originating session; invoked only after successful OS spawn.
170
135
  onLaunch?: () => void;
171
136
  /** Default off. Parent owns policy before opting into bounded local buffering,
@@ -221,6 +186,8 @@ interface LiveTask {
221
186
  processGroup: number | undefined;
222
187
  terminal: { status: TaskRecord["status"]; error: string | null } | undefined;
223
188
  childExit: number | null | undefined;
189
+ childExitSignal?: string | null;
190
+ instructionsTransportDir?: string;
224
191
  cleanupDeadlineAt: number | undefined;
225
192
  quarantined: boolean;
226
193
  nextId: number;
@@ -233,6 +200,7 @@ interface LiveTask {
233
200
  // live work, so the watchdog gives it the tool ceiling instead of the idle
234
201
  // silence budget. Keyed by call id, holding the announced tool name.
235
202
  inFlightTools: Map<string, string>;
203
+ argumentProgress: ToolArgumentProgress;
236
204
  // Bounded ring buffer of the child's raw stderr output, capped to the last
237
205
  // STDERR_TAIL_MAX characters. Only surfaced on the stall and pre-settle exit
238
206
  // terminal paths, never on completed, cancelled, or other failure reasons.
@@ -240,6 +208,11 @@ interface LiveTask {
240
208
  }
241
209
 
242
210
  const STDERR_TAIL_MAX = 512;
211
+ const DIR_MODE = 0o700;
212
+ const FILE_MODE = 0o600;
213
+ // UTF-8 bytes, not characters: argv size is what kills the child on macOS.
214
+ export const MAX_INLINE_INSTRUCTIONS_BYTES = 1000;
215
+ const MAX_TRANSPORT_PREFIX_CHARS = 64;
243
216
  const CHILD_MARKER = "GENTLE_PI_AGENTS_CHILD";
244
217
  const IPC_MARKER = "GENTLE_PI_AGENTS_OWNED_IPC";
245
218
  const PARENT_NOTIFICATION_TOOL = "subagent_parent_message";
@@ -274,31 +247,40 @@ function queryRejection(error: unknown): string {
274
247
  return "parent rejected query";
275
248
  }
276
249
 
250
+ export function formatChildExit(code: number | null | undefined, signal?: string | null): string {
251
+ if (typeof code === "number") return `code ${code}`;
252
+ if (signal) return `signal ${signal}`;
253
+ return `code ${code ?? "unknown"}`;
254
+ }
255
+
277
256
  const hostProcess: ProcessControl = { platform: process.platform, kill: (pid, signal) => process.kill(pid, signal) };
278
257
 
279
- export function childArguments(request: TaskRequest): string[] {
258
+ export function childArguments(request: TaskRequest, instructionsPath?: string): string[] {
280
259
  const args = ["--mode", "rpc", "--session-dir", request.sessionDir];
281
260
  for (const path of request.extensionPaths ?? []) args.push("--extension", path);
282
- if (request.sddChange) args.push(SDD_CHANGE_FLAG, JSON.stringify(request.sddChange));
283
261
  if (request.resumeSessionPath) args.push("--session", request.resumeSessionPath);
284
262
  if (request.model) args.push("--model", request.thinking ? `${formatModelRef(request.model)}:${request.thinking}` : formatModelRef(request.model));
285
263
  else if (request.thinking) args.push("--thinking", request.thinking);
286
- const tools = request.agent.tools.length > 0 || request.agent.name === "sdd-research" ? [...new Set([...request.agent.tools, PARENT_NOTIFICATION_TOOL])] : DEFAULT_TOOLS;
264
+ const tools = request.agent.tools.length > 0 ? [...new Set([...request.agent.tools, PARENT_NOTIFICATION_TOOL])] : DEFAULT_TOOLS;
287
265
  if (tools.length > 0) args.push("--tools", tools.join(","));
288
- if (request.agent.instructions.length > 0) args.push("--append-system-prompt", request.agent.instructions);
266
+ if (instructionsPath) {
267
+ args.push("--append-system-prompt", instructionsPath);
268
+ } else if (request.agent.instructions.length > 0) {
269
+ args.push("--append-system-prompt", request.agent.instructions);
270
+ }
289
271
  return args;
290
272
  }
291
273
 
292
- // The child is the same pi that is running us: node plus its cli entry.
274
+ // Reuse the running pi entry while it exists; upgrades may remove it.
293
275
  // GENTLE_PI_AGENTS_PI overrides it with a command line.
294
- export function piCommand(proc: ProcessLike = process): PiCommand {
276
+ export function piCommand(proc: ProcessLike = process, exists: (path: string) => boolean = existsSync): PiCommand {
295
277
  const override = proc.env.GENTLE_PI_AGENTS_PI?.trim();
296
278
  if (override) {
297
279
  const [command, ...args] = override.split(/\s+/);
298
280
  return { command, args };
299
281
  }
300
282
  const entry = proc.argv[1];
301
- if (entry && /(^|[\\/])cli\.js$/.test(entry)) return { command: proc.execPath, args: [entry] };
283
+ if (entry && /(^|[\\/])cli\.js$/.test(entry) && exists(entry)) return { command: proc.execPath, args: [entry] };
302
284
  return { command: "pi", args: [] };
303
285
  }
304
286
 
@@ -329,8 +311,7 @@ export class JsonLines {
329
311
  }
330
312
 
331
313
  export function promptText(request: TaskRequest): string {
332
- const prompt = request.context ? `${request.prompt}\n\n## Context\n${request.context}` : request.prompt;
333
- return request.sddRemediation ? `${prompt}\n\n## Human-authorized remediation plan\nExecute only these exact commands in the selected cwd; report actual results without claiming native verification.\n${JSON.stringify(request.sddRemediation.plan)}\nFailed evidence: ${request.sddRemediation.failedEvidenceRevision}` : prompt;
314
+ return request.context ? `${request.prompt}\n\n## Context\n${request.context}` : request.prompt;
334
315
  }
335
316
 
336
317
  export class AgentRunner {
@@ -360,7 +341,6 @@ export class AgentRunner {
360
341
  const task: TaskRecord = {
361
342
  id: `${now.toString(36)}-${this.counter.toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
362
343
  agent: request.agent.name,
363
- ...(request.sddPreflightContext ? { sddPreflightContext: request.sddPreflightContext } : {}),
364
344
  mode: request.mode,
365
345
  prompt: request.prompt,
366
346
  label: taskLabel(request.prompt, request.label),
@@ -387,23 +367,8 @@ export class AgentRunner {
387
367
  }
388
368
 
389
369
  run(request: TaskRequest): TaskRecord {
390
- // Admission already confirmed the canonical cwd and human edit scope.
391
- // Check this runner's queue/live slots before scheduling any launch: history
392
- // is not a lock, and quarantined children still own their live slot.
393
- if (request.sddRemediation) {
394
- const active = [...this.queue.map(entry => entry.task), ...[...this.live.keys()].map(id => this.store.get(id))];
395
- if (active.some(task => task?.agent === "sdd-remediate" && task.cwd === request.cwd)) {
396
- throw new Error("Remediation already queued or running in this worktree; wait for confirmed cleanup or cancel the active task before requesting fresh authorization");
397
- }
398
- }
399
370
  const task = this.createTask(request);
400
- // A caller can retain and mutate its request after dispatch. Preserve only
401
- // the identity selected at construction for this child launch.
402
- const launchRequest = {
403
- ...request,
404
- sddChange: request.sddChange && { ...request.sddChange },
405
- };
406
- this.queue.push({ task, request: launchRequest });
371
+ this.queue.push({ task, request });
407
372
  queueMicrotask(() => this.pump());
408
373
  return task;
409
374
  }
@@ -442,6 +407,7 @@ export class AgentRunner {
442
407
  if (live.queries.get(requestId) === query) {
443
408
  query.cancel();
444
409
  live.queries.delete(requestId);
410
+ this.hooks.onQuerySettled?.(id, requestId, "replied");
445
411
  }
446
412
  return accepted;
447
413
  }
@@ -489,6 +455,12 @@ export class AgentRunner {
489
455
  // A child that cannot start (missing pi, bad cwd) fails only its task:
490
456
  // spawn exceptions and process errors settle without uncaught host errors.
491
457
  private launch(id: string, request: TaskRequest): void {
458
+ try { request.beforeSpawn?.(); }
459
+ catch (error) {
460
+ this.store.update(id, { status: TASK_STATUS.RUNNING, startedAt: this.deps.now(), lastStep: "starting" });
461
+ this.finish(id, TASK_STATUS.FAILED, `could not start pi: ${error instanceof Error ? error.message : String(error)}`);
462
+ return;
463
+ }
492
464
  const detached = this.processControl.platform !== "win32";
493
465
  const hasParentPermissionChannel = request.authorizeParentStandingReviewPermission !== undefined;
494
466
  const permissionChannelStdio = this.processControl.platform === "win32" ? "overlapped" : "pipe";
@@ -498,28 +470,51 @@ export class AgentRunner {
498
470
  // one (`lib/rpc-host.ts`).
499
471
  const env = withoutInteractiveHost({
500
472
  ...request.env,
501
- ...(request.extensionPaths ? { [RESEARCH_SELECTION_ENV]: JSON.stringify(request.researchSelection ?? null) } : {}),
502
473
  [CHILD_MARKER]: "1",
503
474
  [IPC_MARKER]: `${this.deps.now()}-${Math.random().toString(36).slice(2)}`,
504
475
  ...(hasParentPermissionChannel ? { GENTLE_PI_AGENTS_PARENT_PERMISSION_FD: "3" } : {}),
505
476
  });
506
- delete env[REMEDIATION_PLAN_ENV];
507
- if (request.sddRemediation) env[REMEDIATION_PLAN_ENV] = JSON.stringify({ plan: request.sddRemediation.plan, scope: request.sddRemediation.scope, selection: request.sddChange });
477
+ // Do not forward stale legacy child selection or authorization.
478
+ delete env.GENTLE_PI_SDD_REMEDIATION_PLAN;
479
+ delete env.GENTLE_PI_RESEARCH_SELECTION;
480
+ let instructionsTransportDir: string | undefined;
481
+ let instructionsTransportPath: string | undefined;
482
+ if (Buffer.byteLength(request.agent.instructions, "utf8") > MAX_INLINE_INSTRUCTIONS_BYTES) {
483
+ try {
484
+ const prefix = (request.agent.name || "instructions").replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, MAX_TRANSPORT_PREFIX_CHARS);
485
+ instructionsTransportDir = mkdtempSync(join(tmpdir(), `gentle-pi-subagent-${prefix}-`));
486
+ try { chmodSync(instructionsTransportDir, DIR_MODE); } catch { /* best effort */ }
487
+ instructionsTransportPath = join(instructionsTransportDir, "instructions.md");
488
+ writeFileSync(instructionsTransportPath, request.agent.instructions, { mode: FILE_MODE, encoding: "utf8" });
489
+ try { chmodSync(instructionsTransportPath, FILE_MODE); } catch { /* best effort */ }
490
+ } catch (error) {
491
+ if (instructionsTransportDir) {
492
+ try { rmSync(instructionsTransportDir, { recursive: true, force: true }); } catch { /* best effort */ }
493
+ }
494
+ this.store.update(id, { status: TASK_STATUS.RUNNING, startedAt: this.deps.now(), lastStep: "starting" });
495
+ this.finish(id, TASK_STATUS.FAILED, `could not write agent instructions: ${error instanceof Error ? error.message : String(error)}`);
496
+ return;
497
+ }
498
+ }
508
499
  let child: ChildLike;
509
500
  try {
510
- child = this.deps.spawn(this.deps.pi.command, [...this.deps.pi.args, ...childArguments(request)], {
501
+ const pi = this.deps.resolvePi?.() ?? this.deps.pi;
502
+ child = this.deps.spawn(pi.command, [...pi.args, ...childArguments(request, instructionsTransportPath)], {
511
503
  cwd: request.cwd,
512
504
  env,
513
505
  detached,
514
506
  stdio: hasParentPermissionChannel ? ["pipe", "pipe", "pipe", permissionChannelStdio, "ipc"] : ["pipe", "pipe", "pipe", "ipc"],
515
507
  });
516
508
  } catch (error) {
509
+ if (instructionsTransportDir) {
510
+ try { rmSync(instructionsTransportDir, { recursive: true, force: true }); } catch { /* best effort */ }
511
+ }
517
512
  this.store.update(id, { status: TASK_STATUS.RUNNING, startedAt: this.deps.now(), lastStep: "starting" });
518
513
  this.finish(id, TASK_STATUS.FAILED, `could not start pi: ${error instanceof Error ? error.message : String(error)}`);
519
514
  return;
520
515
  }
521
516
  const processGroup = detached && typeof child.pid === "number" && child.pid > 0 ? child.pid : undefined;
522
- const live: LiveTask = { child, sawRunEvent: false, mutationStarts: new Map(), inFlightTools: new Map(), pending: new Map(), queries: new Map(), replies: new Map(), cancelStall: () => {}, cancelGrace: () => {}, processGroup, terminal: undefined, childExit: undefined, cleanupDeadlineAt: undefined, quarantined: false, nextId: 0, ipcClosed: false, acknowledgedIpcIds: new Set(), acknowledgedIpcOrder: [], stderrTail: "" };
517
+ const live: LiveTask = { child, sawRunEvent: false, mutationStarts: new Map(), inFlightTools: new Map(), argumentProgress: new ToolArgumentProgress(), pending: new Map(), queries: new Map(), replies: new Map(), cancelStall: () => {}, cancelGrace: () => {}, processGroup, terminal: undefined, childExit: undefined, childExitSignal: undefined, instructionsTransportDir, cleanupDeadlineAt: undefined, quarantined: false, nextId: 0, ipcClosed: false, acknowledgedIpcIds: new Set(), acknowledgedIpcOrder: [], stderrTail: "" };
523
518
  if (request.prepareResponseObservations) {
524
519
  let ready = false;
525
520
  live.observationPreparation = () => ready;
@@ -561,11 +556,7 @@ export class AgentRunner {
561
556
  const tail = live.stderrTail + chunk;
562
557
  live.stderrTail = tail.length > STDERR_TAIL_MAX ? tail.slice(-STDERR_TAIL_MAX) : tail;
563
558
  });
564
- child.on("exit", (code) => this.exited(id, code));
565
- if (request.sddRemediation && child.pid === undefined) {
566
- this.childError(id, new Error("remediation child has no process ID"));
567
- return;
568
- }
559
+ child.on("exit", (code, signal) => this.exited(id, code, signal));
569
560
  void this.send(id, { type: "get_state" }).then((response) => {
570
561
  const data = response.data as { sessionFile?: unknown; model?: { provider?: unknown; id?: unknown } | null; thinkingLevel?: unknown } | undefined;
571
562
  if (response.success !== true || live.terminal || this.live.get(id) !== live || !data) return;
@@ -604,8 +595,8 @@ export class AgentRunner {
604
595
 
605
596
  // An idle child is bounded by the silence budget; a child whose announced
606
597
  // tool call is still running is live work and bounded by the longer tool
607
- // ceiling. The budget is chosen from the state at arm time, and every RPC
608
- // object re-arms, so a finished tool call returns the task to idle silence.
598
+ // ceiling. These are renewable silence budgets, not total duration limits.
599
+ // A finished tool call returns the task to idle silence.
609
600
  private armStall(id: string, live: LiveTask): void {
610
601
  live.cancelStall();
611
602
  const tool = live.inFlightTools.values().next().value;
@@ -659,12 +650,12 @@ export class AgentRunner {
659
650
  try {
660
651
  if (live.queries.has(parsed.frame.id)) rejectQuery("duplicate query request");
661
652
  if (live.queries.size >= CHILD_QUERY_MAX_INFLIGHT) rejectQuery("too many pending parent queries");
662
- query = { replying: false, cancel: this.deps.schedule(() => this.expireQuery(live, parsed.frame!.id), CHILD_QUERY_TIMEOUT_MS) };
653
+ query = { replying: false, cancel: this.deps.schedule(() => this.expireQuery(id, live, parsed.frame!.id), CHILD_QUERY_TIMEOUT_MS) };
663
654
  live.queries.set(parsed.frame.id, query);
664
655
  if (!this.hooks.onQuery) rejectQuery("task parent cannot accept queries");
665
656
  if (this.hooks.onQuery(task, parsed.frame.id, parsed.frame.message) === false) rejectQuery("task parent is not the active host session");
666
657
  if (task.mode === AGENT_MODE.TASK && !this.firstQueries.has(id)) {
667
- const first = { taskId: id, requestId: parsed.frame.id };
658
+ const first = { taskId: id, requestId: parsed.frame.id, message: parsed.frame.message };
668
659
  this.firstQueries.set(id, first);
669
660
  for (const resolve of this.queryWaiters.get(id) ?? []) resolve(first);
670
661
  this.queryWaiters.delete(id);
@@ -678,10 +669,11 @@ export class AgentRunner {
678
669
  }
679
670
  }
680
671
 
681
- private expireQuery(live: LiveTask, id: string): void {
672
+ private expireQuery(taskId: string, live: LiveTask, id: string): void {
682
673
  const query = live.queries.get(id);
683
674
  if (!query) return;
684
675
  live.queries.delete(id);
676
+ this.hooks.onQuerySettled?.(taskId, id, "expired");
685
677
  if (query.replying) this.settleReply(live, id, false);
686
678
  else this.sendQueryError(live, id, "parent query timed out");
687
679
  }
@@ -773,7 +765,12 @@ export class AgentRunner {
773
765
  // renews the watchdog here, so fire-and-forget UI traffic that normalizes
774
766
  // to nothing cannot keep a child that never started its run alive forever
775
767
  // (#1034); the pre-existing timer stays armed until real progress arrives.
776
- const progress = events.length > 0;
768
+ const argumentProgress = live.argumentProgress.observe(raw);
769
+ if (argumentProgress) {
770
+ live.sawRunEvent = true;
771
+ this.store.update(id, { lastStep: "generating tool arguments", lastActivityAt: this.deps.now() });
772
+ }
773
+ const progress = events.length > 0 || argumentProgress;
777
774
  for (const event of events) {
778
775
  if (event.type === TASK_EVENT.RESPONSE_OBSERVATION) {
779
776
  const buffer = live.observations;
@@ -897,6 +894,7 @@ export class AgentRunner {
897
894
  if (this.deps.now() >= (live.cleanupDeadlineAt ?? 0)) {
898
895
  live.cancelGrace();
899
896
  live.quarantined = true;
897
+ this.cleanupLive(live);
900
898
  this.finish(id, TASK_STATUS.FAILED, `process cleanup unconfirmed after ${GROUP_CONFIRM_DEADLINE_MS}ms; capacity quarantined`, live);
901
899
  return;
902
900
  }
@@ -921,12 +919,24 @@ export class AgentRunner {
921
919
  if (this.deps.now() >= (live.cleanupDeadlineAt ?? 0)) {
922
920
  live.cancelGrace();
923
921
  live.quarantined = true;
922
+ this.cleanupLive(live);
924
923
  this.finish(id, TASK_STATUS.FAILED, `child exit unconfirmed after ${GROUP_CONFIRM_DEADLINE_MS}ms; capacity quarantined`, live);
925
924
  return;
926
925
  }
927
926
  live.cancelGrace = this.deps.schedule(() => this.confirmGroupExit(id, live), GROUP_CONFIRM_MS);
928
927
  }
929
928
 
929
+ private cleanupLive(live: LiveTask): void {
930
+ live.permissionBroker?.close();
931
+ this.closeIpc(live);
932
+ live.cancelStall();
933
+ live.cancelGrace();
934
+ if (live.instructionsTransportDir) {
935
+ try { rmSync(live.instructionsTransportDir, { recursive: true, force: true }); } catch { /* best effort */ }
936
+ live.instructionsTransportDir = undefined;
937
+ }
938
+ }
939
+
930
940
  private childError(id: string, error: Error): void {
931
941
  const live = this.live.get(id);
932
942
  if (!live) return;
@@ -936,30 +946,26 @@ export class AgentRunner {
936
946
  this.requestStop(id, TASK_STATUS.FAILED, `pi process error: ${error.message}`);
937
947
  return;
938
948
  }
939
- live.permissionBroker?.close();
940
- this.closeIpc(live);
941
- live.cancelStall();
942
- live.cancelGrace();
949
+ this.cleanupLive(live);
943
950
  this.live.delete(id);
944
951
  this.finish(id, TASK_STATUS.FAILED, `could not start pi: ${error.message}`, live);
945
952
  }
946
953
 
947
- private exited(id: string, code: number | null): void {
954
+ private exited(id: string, code: number | null, signal?: NodeJS.Signals | string | null): void {
948
955
  const live = this.live.get(id);
949
956
  if (!live) return;
950
957
  live.childExit = code;
958
+ live.childExitSignal = signal ?? null;
959
+ const exitDesc = formatChildExit(code, signal);
951
960
  if (this.groupExists(live)) {
952
- if (!live.terminal) this.requestStop(id, TASK_STATUS.FAILED, `pi exited with code ${code ?? "unknown"} before agent_settled${this.stderrSuffix(live)}`);
961
+ if (!live.terminal) this.requestStop(id, TASK_STATUS.FAILED, `pi exited with ${exitDesc} before agent_settled${this.stderrSuffix(live)}`);
953
962
  return;
954
963
  }
955
964
  this.completeExit(id, live);
956
965
  }
957
966
 
958
967
  private completeExit(id: string, live: LiveTask): void {
959
- live.permissionBroker?.close();
960
- this.closeIpc(live);
961
- live.cancelStall();
962
- live.cancelGrace();
968
+ this.cleanupLive(live);
963
969
  this.live.delete(id);
964
970
  // Quarantine already notified completion, but its retained slot is now free.
965
971
  if (live.quarantined) {
@@ -967,7 +973,8 @@ export class AgentRunner {
967
973
  return;
968
974
  }
969
975
  const terminal = live.terminal;
970
- this.finish(id, terminal ? terminal.status : TASK_STATUS.FAILED, terminal ? terminal.error : `pi exited with code ${live.childExit ?? "unknown"} before agent_settled${this.stderrSuffix(live)}`, live);
976
+ const exitDesc = formatChildExit(live.childExit, live.childExitSignal);
977
+ this.finish(id, terminal ? terminal.status : TASK_STATUS.FAILED, terminal ? terminal.error : `pi exited with ${exitDesc} before agent_settled${this.stderrSuffix(live)}`, live);
971
978
  }
972
979
 
973
980
  private finish(id: string, status: TaskRecord["status"], error: string | null, live?: LiveTask): void {
@@ -5,7 +5,7 @@ import { emptyThread, isFinished, TASK_STATUS, type TaskRecord, type TaskStore,
5
5
  import { renderThreadItem, type AgentsThreadTheme } from "./agents-thread-view.ts";
6
6
  import { formatElapsed } from "./agents-widget.ts";
7
7
  import { createNativePointerScope, type NativePointerRegion } from "./native-pointer-region.ts";
8
- import { formatTokens } from "./shell-bar.ts";
8
+ import { formatCost, formatTokens } from "./shell-bar.ts";
9
9
  import { PresenceCursor, readActivity, type Header, type Target } from "./orchestrator-presence.ts";
10
10
 
11
11
  // Gentle Agents overlay: tasks on the left, the selected task's thread on
@@ -128,8 +128,22 @@ function fit(text: string, width: number): string {
128
128
  return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
129
129
  }
130
130
 
131
+ // Deep equality over presence thread items: validated JSON payloads, so only
132
+ // plain objects, arrays, strings, booleans, and null appear. Used to keep the
133
+ // prior item object (and its WeakMap render cache entry) when polled content
134
+ // is render-equivalent at the same position.
135
+ function sameItemValue(a: unknown, b: unknown): boolean {
136
+ if (a === b) return true;
137
+ if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
138
+ const left = a as Record<string, unknown>;
139
+ const right = b as Record<string, unknown>;
140
+ const keys = Object.keys(left);
141
+ if (keys.length !== Object.keys(right).length) return false;
142
+ return keys.every((key) => Object.hasOwn(right, key) && sameItemValue(left[key], right[key]));
143
+ }
144
+
131
145
  export function taskHeader(task: TaskRecord, now: number): string {
132
- const parts = [task.agent, task.status, task.model, task.tokens > 0 ? formatTokens(task.tokens) : "", task.cost > 0 ? `$${task.cost.toFixed(2)}` : "", task.startedAt === null ? "" : formatElapsed((task.endedAt ?? now) - task.startedAt)];
146
+ const parts = [task.agent, task.status, task.model, task.tokens > 0 ? formatTokens(task.tokens) : "", task.cost > 0 ? formatCost(task.cost) : "", task.startedAt === null ? "" : formatElapsed((task.endedAt ?? now) - task.startedAt)];
133
147
  return parts.filter((part) => part.length > 0).join(" · ");
134
148
  }
135
149
 
@@ -197,8 +211,17 @@ export class AgentsView {
197
211
  const task: TaskRecord = { ...summary, id: `peer:${id}:${summary.id}`, parentSessionId: id,
198
212
  status: summary.status as TaskRecord["status"], mode: "background", prompt: "", cwd: "",
199
213
  thinking: undefined, sessionPath: null, error: null, result: null, lastStep: "", turns: 0, toolCalls: 0, tokens: 0, cost: 0 };
214
+ const prior = this.remoteThreads.get(task.id);
200
215
  threads.set(task.id, { ...emptyThread(), ...thread,
201
- items: thread.items.map((item) => item.kind === "tool" ? { ...item, args: {} } : item) as ThreadItem[] });
216
+ items: thread.items.map((item, index) => {
217
+ // Sanitize before equality: presence tool items carry no invocation
218
+ // args, so compare against the stored sanitized form.
219
+ const sanitized = item.kind === "tool" ? { ...item, args: {} } : item;
220
+ const previous = prior?.items[index];
221
+ // Reuse the prior object when content is render-equivalent so the
222
+ // WeakMap render cache hits; any delta keeps a fresh identity.
223
+ return previous !== undefined && sameItemValue(previous, sanitized) ? previous : sanitized;
224
+ }) as ThreadItem[] });
202
225
  return task;
203
226
  });
204
227
  groups.push({ id, sessionId: id, label: `${header.label}${unavailable ? " · unavailable" : ""}`, tasks });
@@ -1,7 +1,7 @@
1
1
  import { visibleWidth } from "@earendil-works/pi-tui";
2
2
  import { isFinished, TASK_STATUS, type TaskRecord, type TaskStatus } from "./agents-protocol.ts";
3
- import { formatTokens } from "./shell-bar.ts";
4
- import { CARD_TONE, cardInnerWidth, renderCard, type CardTheme, type CardTone } from "./shell-card.ts";
3
+ import { formatCost, formatTokens } from "./shell-bar.ts";
4
+ import { CARD_TONE, panelExtraRows, panelInnerWidth, renderCard, type CardTheme, type CardTone } from "./shell-card.ts";
5
5
 
6
6
  // Gentle Agents widget: the card above the editor. Reads task records only
7
7
  // (status, prompt, counters, timestamps), so drawing it costs nothing per
@@ -136,10 +136,12 @@ function startOrder(a: TaskRecord, b: TaskRecord): number {
136
136
  }
137
137
 
138
138
  // When the card overflows, questions and running work keep their rows first;
139
- // what stays visible is still drawn in start order.
140
- function visibleRows(shown: readonly TaskRecord[], maxRows: number | undefined): { listed: TaskRecord[]; hidden: number } {
139
+ // what stays visible is still drawn in start order. Float chrome can leave
140
+ // only one body row: spend it on the overflow count instead of exceeding the
141
+ // budget. Neon retains its existing minimum of one task plus overflow.
142
+ function visibleRows(shown: readonly TaskRecord[], maxRows: number | undefined, allowOverflowOnly = false): { listed: TaskRecord[]; hidden: number } {
141
143
  if (maxRows === undefined || shown.length <= maxRows) return { listed: [...shown], hidden: 0 };
142
- const kept = Math.max(1, maxRows - 1);
144
+ const kept = allowOverflowOnly && maxRows === 1 ? 0 : Math.max(1, maxRows - 1);
143
145
  const listed = [...shown]
144
146
  .sort((a, b) => SHOW_PRIORITY[a.status] - SHOW_PRIORITY[b.status] || startOrder(a, b))
145
147
  .slice(0, kept)
@@ -185,7 +187,7 @@ function metaFields(task: TaskRecord, now: number): MetaFields {
185
187
  return {
186
188
  exec: executionLabel(task),
187
189
  tokens: task.tokens > 0 ? formatTokens(task.tokens) : "",
188
- cost: task.cost > 0 ? `$${task.cost.toFixed(2)}` : "",
190
+ cost: task.cost > 0 ? formatCost(task.cost) : "",
189
191
  elapsed: elapsed(task, now),
190
192
  };
191
193
  }
@@ -298,8 +300,13 @@ function batchElapsed(tasks: readonly TaskRecord[], now: number): string | undef
298
300
  export function renderAgentsCard(tasks: readonly TaskRecord[], theme: CardTheme, width: number, now: number, options: AgentsWidgetOptions): string[] {
299
301
  const shown = widgetTasks(tasks, now);
300
302
  if (shown.length === 0) return [];
301
- const cols = columns(shown, cardInnerWidth(width), now);
302
- const { listed, hidden } = options.collapsed ? { listed: [shown[0]], hidden: 0 } : visibleRows(shown, options.maxRows);
303
+ const cols = columns(shown, panelInnerWidth(theme, width, tone(shown)), now);
304
+ // The float panel spends two more rows on padding above its header and the
305
+ // separator below it, so it gives them back from the task budget to stay as
306
+ // tall as the frame.
307
+ const extraRows = panelExtraRows(theme, width, tone(shown));
308
+ const maxRows = options.maxRows === undefined ? undefined : options.maxRows - extraRows;
309
+ const { listed, hidden } = options.collapsed ? { listed: [shown[0]], hidden: 0 } : visibleRows(shown, maxRows, extraRows > 0);
303
310
  const hint = options.collapsed && options.collapseKey ? `${options.collapseKey} expand` : shown.length > 1 ? batchElapsed(shown, now) : undefined;
304
311
  const body = listed.flatMap((task) => row(task, theme, cols, now, options.maxRows === undefined));
305
312
  if (hidden > 0) body.push(overflowRow(hidden, theme, options.viewKey));
@@ -307,6 +314,6 @@ export function renderAgentsCard(tasks: readonly TaskRecord[], theme: CardTheme,
307
314
  { title: "Agents", subtitle: counts(shown), body, tone: tone(shown), glyph: AGENTS_GLYPH },
308
315
  theme,
309
316
  width,
310
- { expanded: true, hint },
317
+ { expanded: true, hint, panel: true },
311
318
  );
312
319
  }
@@ -0,0 +1,21 @@
1
+ // gentle-shell#1485: pi-claude-bridge only forwards the structured
2
+ // systemPromptOptions parts of before_agent_start, dropping any
3
+ // handler-returned replacement systemPrompt. Extensions mutate
4
+ // options.appendSystemPrompt instead so the harness reaches every provider.
5
+ export interface AppendableSystemPromptOptions {
6
+ appendSystemPrompt: string;
7
+ }
8
+
9
+ // Safe to call more than once with the same options object and the same
10
+ // text: a text already present is a no-op, so a handler that runs more than
11
+ // once against the same systemPromptOptions never duplicates its own block.
12
+ export function appendSystemPromptOnce(
13
+ options: AppendableSystemPromptOptions | null | undefined,
14
+ text: string,
15
+ ): void {
16
+ const normalized = text.replace(/^\n+/, "");
17
+ if (!options || !normalized) return;
18
+ const current = options.appendSystemPrompt ?? "";
19
+ if (current.includes(normalized)) return;
20
+ options.appendSystemPrompt = current ? `${current}\n\n${normalized}` : normalized;
21
+ }