gentle-pi 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/README.md +55 -44
  2. package/assets/agents/gentle-ai-explore.md +3 -3
  3. package/assets/agents/gentle-ai-verify.md +20 -6
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/agents/jd-judge-a.md +1 -3
  6. package/assets/agents/jd-judge-b.md +1 -3
  7. package/assets/agents/review-readability.md +1 -5
  8. package/assets/agents/review-reliability.md +1 -5
  9. package/assets/agents/review-resilience.md +1 -5
  10. package/assets/agents/review-risk.md +1 -5
  11. package/assets/design-canvas/canvas-api.js +45 -0
  12. package/assets/design-canvas/canvas-boards.js +456 -0
  13. package/assets/design-canvas/canvas-boot.js +217 -0
  14. package/assets/design-canvas/canvas-checks.js +491 -0
  15. package/assets/design-canvas/canvas-comments.js +315 -0
  16. package/assets/design-canvas/canvas-compare.js +159 -0
  17. package/assets/design-canvas/canvas-events.js +75 -0
  18. package/assets/design-canvas/canvas-export.js +393 -0
  19. package/assets/design-canvas/canvas-focus.js +203 -0
  20. package/assets/design-canvas/canvas-handoffs.js +150 -0
  21. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  22. package/assets/design-canvas/canvas-i18n.js +108 -0
  23. package/assets/design-canvas/canvas-layout.js +526 -0
  24. package/assets/design-canvas/canvas-menu.js +213 -0
  25. package/assets/design-canvas/canvas-messages.js +86 -0
  26. package/assets/design-canvas/canvas-minimap.js +163 -0
  27. package/assets/design-canvas/canvas-parts.js +401 -0
  28. package/assets/design-canvas/canvas-popover.js +234 -0
  29. package/assets/design-canvas/canvas-rail.js +348 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +164 -0
  32. package/assets/design-canvas/canvas-tokens.js +674 -0
  33. package/assets/design-canvas/canvas-ui.js +24 -0
  34. package/assets/design-canvas/canvas-view.js +184 -0
  35. package/assets/design-canvas/canvas.css +746 -15
  36. package/assets/design-canvas/canvas.js +2 -1506
  37. package/assets/design-canvas/index.html +117 -36
  38. package/assets/design-canvas/inspector.js +546 -16
  39. package/assets/install-wizard/wizard.js +5 -1
  40. package/assets/migrations/agent-body-history.json +24 -0
  41. package/assets/orchestrator-delegation-reference.md +8 -14
  42. package/assets/orchestrator-delegation.md +4 -4
  43. package/assets/orchestrator-full-delegation-card.md +4 -5
  44. package/assets/orchestrator-full-delegation.md +8 -8
  45. package/assets/orchestrator-memory.md +2 -2
  46. package/assets/orchestrator-prompts.md +1 -1
  47. package/assets/orchestrator-quota-recovery.md +5 -0
  48. package/assets/orchestrator-skills.md +13 -12
  49. package/assets/orchestrator-tracking.md +10 -14
  50. package/assets/orchestrator-verification.md +10 -8
  51. package/assets/orchestrator-writer.md +4 -4
  52. package/assets/orchestrator.md +18 -22
  53. package/bin/gentle-shell.mjs +128 -9
  54. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  55. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  60. package/docs/assets/brand/sponsor-banner.svg +60 -0
  61. package/docs/bundled-install.md +14 -6
  62. package/docs/delegated-verification.md +18 -2
  63. package/docs/desktop-rpc.md +1253 -0
  64. package/docs/gentle-agents-activity.md +26 -0
  65. package/docs/gentle-shell.md +39 -16
  66. package/docs/install-wizard.md +30 -21
  67. package/docs/odd-preparation-continuity.md +24 -0
  68. package/docs/permission-modes.md +9 -1
  69. package/docs/prompt-budget.md +12 -0
  70. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  71. package/docs/readme-reference.md +76 -24
  72. package/docs/review-coordinator.md +29 -9
  73. package/docs/review-delivery-preflight.md +22 -0
  74. package/docs/work-continuity.md +11 -1
  75. package/extensions/ask-user-question.ts +2 -2
  76. package/extensions/child-context.ts +21 -7
  77. package/extensions/gentle-agents.ts +234 -33
  78. package/extensions/gentle-ai.ts +576 -135
  79. package/extensions/gentle-design.ts +69 -3
  80. package/extensions/gentle-desktop-rpc.ts +143 -0
  81. package/extensions/gentle-guide.ts +3 -0
  82. package/extensions/gentle-shell.ts +105 -52
  83. package/extensions/gentle-todo.ts +48 -25
  84. package/extensions/skill-registry.ts +248 -223
  85. package/lib/agent-assets.ts +30 -6
  86. package/lib/agent-tool-overlay.ts +117 -0
  87. package/lib/agents-config.ts +47 -6
  88. package/lib/agents-message-delivery.ts +17 -0
  89. package/lib/agents-messaging.ts +8 -2
  90. package/lib/agents-protocol.ts +15 -0
  91. package/lib/agents-report-cap.ts +115 -0
  92. package/lib/agents-runner.ts +91 -6
  93. package/lib/agents-session-transport.ts +17 -1
  94. package/lib/background-jobs-tools.ts +9 -4
  95. package/lib/bounded-writer-admission.ts +184 -31
  96. package/lib/child-context-files.ts +21 -6
  97. package/lib/codemode-renderer.ts +1 -0
  98. package/lib/delivery-conflict-markers.ts +349 -0
  99. package/lib/design-canvas-assets.ts +36 -0
  100. package/lib/design-canvas-server.ts +241 -23
  101. package/lib/design-comments.ts +94 -4
  102. package/lib/design-handoffs.ts +2 -1
  103. package/lib/design-layout.ts +125 -0
  104. package/lib/design-parts.ts +281 -0
  105. package/lib/design-system-tokens.ts +111 -0
  106. package/lib/desktop-agents-service.ts +294 -0
  107. package/lib/desktop-design-service.ts +233 -0
  108. package/lib/desktop-jobs-service.ts +263 -0
  109. package/lib/desktop-rpc-agents.ts +294 -0
  110. package/lib/desktop-rpc-config.ts +731 -0
  111. package/lib/desktop-rpc-design.ts +138 -0
  112. package/lib/desktop-rpc-jobs.ts +181 -0
  113. package/lib/desktop-rpc-permissions.ts +177 -0
  114. package/lib/desktop-rpc-profiles.ts +196 -0
  115. package/lib/desktop-rpc-usage.ts +229 -0
  116. package/lib/desktop-rpc.ts +225 -0
  117. package/lib/desktop-usage-service.ts +310 -0
  118. package/lib/destructive-command-guard.ts +188 -13
  119. package/lib/gentle-ai-renderer.ts +13 -1
  120. package/lib/gentle-design.ts +201 -14
  121. package/lib/gentle-shell-bundled.ts +100 -9
  122. package/lib/hidden-tools.ts +35 -0
  123. package/lib/inprocess-reviewer.ts +96 -12
  124. package/lib/model-fallback-policy.ts +9 -0
  125. package/lib/model-routing-authority.ts +9 -0
  126. package/lib/nan-provider.ts +42 -28
  127. package/lib/native-review-cli.ts +79 -4
  128. package/lib/orchestrator-discovery.ts +39 -2
  129. package/lib/reply-language-anchor.ts +27 -2
  130. package/lib/request-context-placement.ts +53 -0
  131. package/lib/review-candidate-view.ts +11 -1
  132. package/lib/review-continuation-registry.ts +17 -0
  133. package/lib/review-coordinator.ts +252 -8
  134. package/lib/review-delivery-preflight.ts +85 -0
  135. package/lib/review-host-relay.ts +5 -1
  136. package/lib/review-integration-v2.ts +56 -3
  137. package/lib/reviewer-stream.ts +87 -0
  138. package/lib/shell-prompt.ts +16 -3
  139. package/lib/shell-usage.ts +10 -0
  140. package/lib/vim-editor-adapter.ts +9 -2
  141. package/lib/writer-batch-admission.ts +55 -0
  142. package/lib/yolo-session-policy.ts +6 -1
  143. package/package.json +2 -2
  144. package/prompts/skill-creation.md +1 -10
  145. package/runtime/design-canvas-assets.mjs +37 -0
  146. package/runtime/gentle-shell-bundled.mjs +100 -9
  147. package/runtime/native-review-cli.mjs +79 -4
  148. package/runtime/review-integration-v2.mjs +56 -3
  149. package/scripts/bootstrap.cmd +2 -2
  150. package/scripts/bootstrap.sh +41 -4
  151. package/scripts/build-full-delegation-card.mjs +4 -0
  152. package/scripts/build-runtime-modules.mjs +1 -0
  153. package/scripts/gentle-ai-installer.mjs +10 -10
  154. package/scripts/gentle-ai-proxy.mjs +1 -1
  155. package/scripts/installer-downloads.mjs +34 -8
  156. package/scripts/installer-preflight.mjs +28 -17
  157. package/scripts/installer-probes.mjs +25 -5
  158. package/scripts/installer-server.mjs +38 -9
  159. package/scripts/installer-windows.mjs +2 -2
  160. package/scripts/pi-update.mjs +166 -27
  161. package/scripts/prepare-verifier.mjs +107 -0
  162. package/scripts/update-agent-body-history.mjs +55 -8
  163. package/scripts/verify-package-files.mjs +40 -19
  164. package/skills/branch-pr/SKILL.md +16 -16
  165. package/skills/comment-writer/SKILL.md +1 -1
  166. package/skills/design/SKILL.md +6 -6
  167. package/skills/gentle-ai/SKILL.md +5 -5
  168. package/skills/judgment-day/SKILL.md +2 -2
  169. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  170. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  171. package/skills/skill-improver/SKILL.md +2 -2
  172. package/skills/skill-registry/SKILL.md +11 -13
  173. package/skills/tui-design/SKILL.md +1 -1
  174. package/skills/work-unit-commits/SKILL.md +5 -5
  175. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  176. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  177. package/tests/agent-tool-overlay.test.ts +89 -0
  178. package/tests/agents-config.test.ts +10 -1
  179. package/tests/agents-message-delivery.test.ts +36 -0
  180. package/tests/agents-queries.test.ts +144 -4
  181. package/tests/agents-report-cap.test.ts +126 -0
  182. package/tests/agents-runner.test.ts +37 -1
  183. package/tests/agents-session-transport.test.ts +34 -0
  184. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  185. package/tests/append-system-prompt-route.test.ts +10 -2
  186. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  187. package/tests/artifact-language.test.ts +1 -1
  188. package/tests/ask-user-question.test.ts +2 -1
  189. package/tests/audit-leftovers-contract.test.ts +51 -0
  190. package/tests/bounded-stop-contract.test.ts +9 -1
  191. package/tests/branch-pr-skill.test.ts +10 -1
  192. package/tests/bundled-install.test.ts +1 -1
  193. package/tests/child-context-files.test.ts +64 -8
  194. package/tests/child-skills-catalog.test.ts +56 -0
  195. package/tests/codemode-rendering.test.ts +4 -1
  196. package/tests/delegate-for-reason-contract.test.ts +30 -8
  197. package/tests/delivery-conflict-markers.test.ts +348 -0
  198. package/tests/design-canvas-all-sizes.test.ts +631 -0
  199. package/tests/design-canvas-allowlist.test.ts +32 -0
  200. package/tests/design-canvas-assets.test.ts +11 -878
  201. package/tests/design-canvas-boards.test.ts +77 -0
  202. package/tests/design-canvas-checks.test.ts +655 -0
  203. package/tests/design-canvas-compare.test.ts +79 -0
  204. package/tests/design-canvas-events.test.ts +59 -0
  205. package/tests/design-canvas-export.test.ts +1168 -0
  206. package/tests/design-canvas-focus.test.ts +113 -0
  207. package/tests/design-canvas-handoffs.test.ts +59 -0
  208. package/tests/design-canvas-i18n-review.test.ts +513 -0
  209. package/tests/design-canvas-i18n-views.test.ts +259 -0
  210. package/tests/design-canvas-i18n.test.ts +526 -0
  211. package/tests/design-canvas-inspector.test.ts +937 -0
  212. package/tests/design-canvas-layout.test.ts +1222 -0
  213. package/tests/design-canvas-minimap.test.ts +413 -0
  214. package/tests/design-canvas-modules.test.ts +90 -0
  215. package/tests/design-canvas-parts.test.ts +721 -0
  216. package/tests/design-canvas-rail.test.ts +799 -0
  217. package/tests/design-canvas-server.test.ts +855 -17
  218. package/tests/design-canvas-sizes.test.ts +548 -0
  219. package/tests/design-canvas-store.test.ts +180 -0
  220. package/tests/design-canvas-tokens.test.ts +965 -0
  221. package/tests/design-canvas-view.test.ts +299 -0
  222. package/tests/design-comments.test.ts +201 -1
  223. package/tests/design-handoffs.test.ts +20 -0
  224. package/tests/design-layout.test.ts +100 -0
  225. package/tests/design-parts.test.ts +260 -0
  226. package/tests/design-system-tokens.test.ts +215 -0
  227. package/tests/desktop-rpc-agents.test.ts +893 -0
  228. package/tests/desktop-rpc-config.test.ts +1452 -0
  229. package/tests/desktop-rpc-design.test.ts +662 -0
  230. package/tests/desktop-rpc-jobs.test.ts +796 -0
  231. package/tests/desktop-rpc-permissions.test.ts +311 -0
  232. package/tests/desktop-rpc-profiles.test.ts +140 -0
  233. package/tests/desktop-rpc-safety.test.ts +119 -0
  234. package/tests/desktop-rpc-usage.test.ts +697 -0
  235. package/tests/desktop-rpc.test.ts +252 -0
  236. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  237. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  238. package/tests/engram-safety.test.ts +111 -0
  239. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  240. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  241. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
  242. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  243. package/tests/full-delegation-closure.test.ts +29 -0
  244. package/tests/gentle-agents.test.ts +329 -4
  245. package/tests/gentle-ai-binary.test.ts +1 -1
  246. package/tests/gentle-ai-child-guards.test.ts +1 -0
  247. package/tests/gentle-ai-installer.test.ts +52 -51
  248. package/tests/gentle-ai-renderer.test.ts +36 -2
  249. package/tests/gentle-ai.test.ts +121 -6
  250. package/tests/gentle-design.test.ts +365 -1
  251. package/tests/gentle-shell-bundled.test.ts +91 -5
  252. package/tests/gentle-shell-launcher.test.ts +1 -1
  253. package/tests/gentle-shell.test.ts +118 -87
  254. package/tests/gentle-todo.test.ts +32 -9
  255. package/tests/hidden-tools.test.ts +188 -0
  256. package/tests/independent-recovery-delivery.test.ts +19 -5
  257. package/tests/inprocess-reviewer.test.ts +73 -0
  258. package/tests/install-wizard.test.ts +27 -1
  259. package/tests/installer-downloads.test.ts +30 -1
  260. package/tests/installer-posix-bootstrap.test.ts +114 -13
  261. package/tests/installer-preflight.test.ts +49 -1
  262. package/tests/installer-probes.test.ts +146 -0
  263. package/tests/installer-server.test.ts +203 -4
  264. package/tests/installer-windows-bootstrap.test.ts +19 -1
  265. package/tests/judgment-day-severity-admission.test.ts +46 -0
  266. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  267. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  268. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  269. package/tests/model-fallback-policy.test.ts +26 -7
  270. package/tests/nan-provider-runtime.test.ts +17 -3
  271. package/tests/nan-provider.test.ts +111 -56
  272. package/tests/native-review-capability-contract.test.ts +11 -1
  273. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  274. package/tests/native-review-parity.test.ts +24 -5
  275. package/tests/native-review-refusal-identity.test.ts +25 -0
  276. package/tests/no-self-pause-contract.test.ts +11 -3
  277. package/tests/odd-integration.test.ts +11 -3
  278. package/tests/odd-routing-contract.test.ts +80 -28
  279. package/tests/orchestrator-budget.test.ts +30 -5
  280. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  281. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  282. package/tests/orchestrator-discovery.test.ts +28 -0
  283. package/tests/orchestrator-prompt-budget.test.ts +11 -2
  284. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  285. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  286. package/tests/orchestrator-work-search.test.ts +4 -2
  287. package/tests/package-files.test.ts +25 -1
  288. package/tests/package-manifest.test.ts +11 -10
  289. package/tests/parallel-reason-contract.test.ts +6 -3
  290. package/tests/permission-allowlist.test.ts +200 -30
  291. package/tests/persona-neutral-voseo.test.ts +4 -4
  292. package/tests/persona-reply-language.test.ts +1 -1
  293. package/tests/persona-single-channel.test.ts +13 -5
  294. package/tests/pi-update-launcher.test.ts +17 -7
  295. package/tests/pi-update-source.test.ts +113 -6
  296. package/tests/pi-update.test.ts +294 -19
  297. package/tests/pnpm-workspace-policy.test.ts +47 -0
  298. package/tests/primary-context-files.test.ts +233 -0
  299. package/tests/primary-context-three-files.test.ts +174 -0
  300. package/tests/provider-defect-handoff.test.ts +9 -2
  301. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  302. package/tests/rdd-status-line.test.ts +94 -1
  303. package/tests/reply-language-anchor-placement.test.ts +184 -0
  304. package/tests/reply-language-anchor.test.ts +17 -1
  305. package/tests/request-context-append-only.test.ts +218 -0
  306. package/tests/request-context-placement.test.ts +148 -0
  307. package/tests/review-agent-end-preflight.test.ts +79 -1
  308. package/tests/review-candidate-view.test.ts +65 -0
  309. package/tests/review-continuation-registry.test.ts +31 -0
  310. package/tests/review-contract-prompt.test.ts +1 -1
  311. package/tests/review-controller.test.ts +2 -1
  312. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  313. package/tests/review-coordinator-findings.test.ts +206 -0
  314. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  315. package/tests/review-coordinator.test.ts +271 -4
  316. package/tests/review-delivery-preflight.test.ts +462 -0
  317. package/tests/review-due-compaction.test.ts +31 -0
  318. package/tests/review-due-public-boundary.test.ts +26 -0
  319. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  320. package/tests/review-json-arguments.test.ts +41 -2
  321. package/tests/review-ledger-contract.test.ts +19 -40
  322. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  323. package/tests/review-one-call-findings.test.ts +131 -0
  324. package/tests/review-one-call-followups.test.ts +308 -0
  325. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  326. package/tests/review-one-call.test.ts +452 -0
  327. package/tests/review-relay-transport-agent.test.ts +28 -1
  328. package/tests/review-reviewer-evidence.test.ts +41 -1
  329. package/tests/review-risk-assessment.test.ts +52 -5
  330. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  331. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  332. package/tests/review-tool-prose-budget.test.ts +1 -0
  333. package/tests/reviewer-stream.test.ts +149 -0
  334. package/tests/session-profile-extension.test.ts +2 -2
  335. package/tests/shell-prompt.test.ts +17 -0
  336. package/tests/shell-usage.test.ts +59 -10
  337. package/tests/skill-contradictions-contract.test.ts +122 -0
  338. package/tests/skill-registry-watcher.test.ts +216 -2
  339. package/tests/skill-registry.test.ts +929 -306
  340. package/tests/support/design-canvas-dom.ts +369 -0
  341. package/tests/support/review-coordinator-runtime.ts +212 -17
  342. package/tests/task-size-routing-contract.test.ts +42 -11
  343. package/tests/test-strength-contract.test.ts +2 -1
  344. package/tests/todo-request-append-only.test.ts +214 -0
  345. package/tests/tool-batching-contract.test.ts +3 -1
  346. package/tests/update-agent-body-history.test.ts +138 -0
  347. package/tests/verification-tiers-contract.test.ts +229 -0
  348. package/tests/verifier-preparation.test.ts +229 -0
  349. package/tests/verify-agent-contract.test.ts +20 -2
  350. package/tests/verify-first-launch-contract.test.ts +87 -11
  351. package/tests/vim-editor-adapter.test.ts +2 -2
  352. package/tests/work-continuity-contract.test.ts +54 -11
  353. package/tests/writer-admission-messages.test.ts +232 -0
  354. package/tests/writer-batch-admission.test.ts +66 -0
  355. package/tests/writer-edit-surface-scope.test.ts +52 -20
  356. package/tests/writer-feature-document-admission.test.ts +184 -0
  357. package/tests/yolo-mode.test.ts +39 -0
  358. package/skills/_shared/review-ledger-contract.md +0 -106
  359. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  360. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  361. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  362. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  363. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -56,7 +56,12 @@ function gentlePiAgentHome(): string {
56
56
  }
57
57
 
58
58
 
59
- interface ManagedAssetsManifest {
59
+ /**
60
+ * What `readManagedAssetsManifestResult` reports, and the shape the installer
61
+ * writes. Exported so the Desktop config projection can name the type it filters
62
+ * without redefining it.
63
+ */
64
+ export interface ManagedAssetsManifest {
60
65
  schemaVersion: number;
61
66
  assets: Record<string, string>;
62
67
  }
@@ -64,7 +69,6 @@ interface ManagedAssetsManifest {
64
69
  interface LegacyManagedAssetsManifest extends ManagedAssetsManifest {
65
70
  packageVersion: string;
66
71
  }
67
-
68
72
  interface ManagedAssetsLockOwner {
69
73
  schemaVersion: 1;
70
74
  token: string;
@@ -88,7 +92,27 @@ function emptyManagedAssetsManifest(): ManagedAssetsManifest {
88
92
  }
89
93
 
90
94
  function readManagedAssetsManifest(path: string): ManagedAssetsManifest {
91
- if (!existsSync(path)) return emptyManagedAssetsManifest();
95
+ const read = readManagedAssetsManifestResult(path);
96
+ return read.status === "valid" ? read.manifest : emptyManagedAssetsManifest();
97
+ }
98
+
99
+ /** Where the installer keeps its ownership manifest for one agent home. */
100
+ export function managedAssetsManifestPath(agentHome: string): string {
101
+ return join(agentHome, "gentle-ai", MANAGED_ASSETS_MANIFEST);
102
+ }
103
+
104
+ /**
105
+ * Read-side status of the manifest, kept apart from the installer's forgiving
106
+ * reader so a caller can report an absent file separately from one this version
107
+ * cannot understand. It never writes and never repairs the file.
108
+ */
109
+ export type ManagedAssetsManifestReadResult =
110
+ | { status: "missing" }
111
+ | { status: "invalid" }
112
+ | { status: "valid"; manifest: ManagedAssetsManifest };
113
+
114
+ export function readManagedAssetsManifestResult(path: string): ManagedAssetsManifestReadResult {
115
+ if (!existsSync(path)) return { status: "missing" };
92
116
  try {
93
117
  const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
94
118
  if (
@@ -96,16 +120,16 @@ function readManagedAssetsManifest(path: string): ManagedAssetsManifest {
96
120
  parsed.schemaVersion !== MANAGED_ASSETS_SCHEMA_VERSION ||
97
121
  !isRecord(parsed.assets)
98
122
  ) {
99
- return emptyManagedAssetsManifest();
123
+ return { status: "invalid" };
100
124
  }
101
125
  const assets = Object.fromEntries(
102
126
  Object.entries(parsed.assets).filter(
103
127
  (entry): entry is [string, string] => typeof entry[1] === "string",
104
128
  ),
105
129
  );
106
- return { schemaVersion: MANAGED_ASSETS_SCHEMA_VERSION, assets };
130
+ return { status: "valid", manifest: { schemaVersion: MANAGED_ASSETS_SCHEMA_VERSION, assets } };
107
131
  } catch {
108
- return emptyManagedAssetsManifest();
132
+ return { status: "invalid" };
109
133
  }
110
134
  }
111
135
 
@@ -0,0 +1,117 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ // Gentle AI agent tool overlay: a load-time layer that adds/removes subagent
5
+ // tools without editing the package-owned agent files. Mirrors the routing
6
+ // layer (`models.json`): applied at load, never written back, so package
7
+ // ownership and upgrade behavior stay untouched (gentle-shell#3133).
8
+ //
9
+ // Sources merge low -> high (higher wins on a per-tool conflict):
10
+ // 1. extension drop-ins under `<configHome>/agent-overlays.d/*.json`
11
+ // 2. global `<configHome>/tools.json`
12
+ // 3. project `<cwd>/.pi/gentle-ai/tools.json`
13
+
14
+ export interface ToolOverlayEntry {
15
+ add: string[];
16
+ remove: string[];
17
+ }
18
+
19
+ export interface ToolOverlayResult {
20
+ entries: Record<string, ToolOverlayEntry>;
21
+ notices: string[];
22
+ }
23
+
24
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
25
+ return typeof value === "object" && value !== null && !Array.isArray(value);
26
+ }
27
+
28
+ function isStringArray(value: unknown): value is string[] {
29
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
30
+ }
31
+
32
+ function readOverlayFile(path: string, notices: string[]): Record<string, ToolOverlayEntry> | undefined {
33
+ let parsed: unknown;
34
+ try {
35
+ parsed = JSON.parse(readFileSync(path, "utf8")) as unknown;
36
+ } catch {
37
+ notices.push(`ignored invalid tool overlay ${path}`);
38
+ return undefined;
39
+ }
40
+ if (!isPlainObject(parsed)) {
41
+ notices.push(`ignored invalid tool overlay ${path}`);
42
+ return undefined;
43
+ }
44
+ const entries: Record<string, ToolOverlayEntry> = {};
45
+ for (const [name, value] of Object.entries(parsed)) {
46
+ if (!isPlainObject(value)) {
47
+ notices.push(`ignored invalid entry for "${name}" in ${path}`);
48
+ continue;
49
+ }
50
+ const add = value.add;
51
+ const remove = value.remove;
52
+ if ((add !== undefined && !isStringArray(add)) || (remove !== undefined && !isStringArray(remove))) {
53
+ notices.push(`ignored invalid entry for "${name}" in ${path}`);
54
+ continue;
55
+ }
56
+ entries[name] = {
57
+ add: isStringArray(add) ? add : [],
58
+ remove: isStringArray(remove) ? remove : [],
59
+ };
60
+ }
61
+ return entries;
62
+ }
63
+
64
+ export function loadToolOverlays(configHome: string, cwd: string): ToolOverlayResult {
65
+ const notices: string[] = [];
66
+ const addByAgent = new Map<string, Set<string>>();
67
+ const removeByAgent = new Map<string, Set<string>>();
68
+
69
+ const sources: Array<Record<string, ToolOverlayEntry> | undefined> = [];
70
+
71
+ const dropInDir = join(configHome, "agent-overlays.d");
72
+ if (existsSync(dropInDir)) {
73
+ for (const file of readdirSync(dropInDir).filter((entry) => entry.endsWith(".json")).sort()) {
74
+ sources.push(readOverlayFile(join(dropInDir, file), notices));
75
+ }
76
+ }
77
+
78
+ const globalPath = join(configHome, "tools.json");
79
+ if (existsSync(globalPath)) sources.push(readOverlayFile(globalPath, notices));
80
+
81
+ const projectPath = join(cwd, ".pi", "gentle-ai", "tools.json");
82
+ if (existsSync(projectPath)) sources.push(readOverlayFile(projectPath, notices));
83
+
84
+ for (const entries of sources) {
85
+ if (entries === undefined) continue;
86
+ for (const [name, entry] of Object.entries(entries)) {
87
+ const addSet = addByAgent.get(name) ?? new Set<string>();
88
+ const removeSet = removeByAgent.get(name) ?? new Set<string>();
89
+ for (const tool of entry.add) {
90
+ addSet.add(tool);
91
+ removeSet.delete(tool);
92
+ }
93
+ for (const tool of entry.remove) {
94
+ removeSet.add(tool);
95
+ addSet.delete(tool);
96
+ }
97
+ addByAgent.set(name, addSet);
98
+ removeByAgent.set(name, removeSet);
99
+ }
100
+ }
101
+
102
+ const entries: Record<string, ToolOverlayEntry> = {};
103
+ for (const name of new Set([...addByAgent.keys(), ...removeByAgent.keys()])) {
104
+ entries[name] = {
105
+ add: [...(addByAgent.get(name) ?? new Set<string>())],
106
+ remove: [...(removeByAgent.get(name) ?? new Set<string>())],
107
+ };
108
+ }
109
+
110
+ return { entries, notices };
111
+ }
112
+
113
+ export function applyToolOverlay(tools: string[], overlay: ToolOverlayEntry | undefined): string[] {
114
+ if (overlay === undefined) return tools;
115
+ const removeSet = new Set(overlay.remove);
116
+ return [...new Set([...tools, ...overlay.add])].filter((tool) => !removeSet.has(tool));
117
+ }
@@ -1,6 +1,9 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
+ import { gentlePiConfigHome } from "./agent-home.ts";
4
+ import { applyToolOverlay, loadToolOverlays } from "./agent-tool-overlay.ts";
3
5
  import type { AgentProfilesFile } from "./agent-profiles.ts";
6
+ import { DEFAULT_REPORT_MAX_BYTES } from "./agents-report-cap.ts";
4
7
  import { THINKING_LEVELS as ROUTING_THINKING_LEVELS, isServiceTier, type AgentModelConfig, type ServiceTier, type ThinkingLevel as RoutingThinkingLevel } from "./model-routing-authority.ts";
5
8
 
6
9
  // Gentle Agents configuration. Agent definitions are markdown files with YAML
@@ -75,6 +78,8 @@ export interface AgentsConfig {
75
78
  toolStallTimeoutMs: number;
76
79
  maxConcurrency: number;
77
80
  historyMaxTasks: number;
81
+ /** UTF-8 bytes of a child report delivered into the parent's context (`report_max_bytes`); subagent_result always returns the full text. */
82
+ reportMaxBytes: number;
78
83
  }
79
84
 
80
85
  export interface ProfileSources {
@@ -93,11 +98,13 @@ export interface DiscoveryRoots {
93
98
  cwd: string;
94
99
  home: string;
95
100
  agentHome?: string;
101
+ configHome?: string;
96
102
  }
97
103
 
98
104
  export interface DiscoveryResult {
99
105
  agents: AgentDefinition[];
100
106
  errors: string[];
107
+ notices: string[];
101
108
  }
102
109
 
103
110
  export type FrontmatterValue = string | string[];
@@ -222,6 +229,7 @@ export function agentDirectories(roots: DiscoveryRoots): Array<{ dir: string; sc
222
229
  }
223
230
 
224
231
  export function discoverAgents(roots: DiscoveryRoots): DiscoveryResult {
232
+ const overlays = loadToolOverlays(roots.configHome ?? gentlePiConfigHome(), roots.cwd);
225
233
  const agents = new Map<string, AgentDefinition>();
226
234
  const errors: string[] = [];
227
235
  for (const { dir, scope } of agentDirectories(roots)) {
@@ -230,10 +238,16 @@ export function discoverAgents(roots: DiscoveryRoots): DiscoveryResult {
230
238
  const filePath = join(dir, file);
231
239
  const parsed = parseAgentDefinition(readFileSync(filePath, "utf8"), filePath, scope);
232
240
  if ("error" in parsed) errors.push(`${filePath}: ${parsed.error}`);
233
- else agents.set(parsed.name, parsed);
241
+ else {
242
+ const tools = applyToolOverlay(parsed.tools, overlays.entries[parsed.name]);
243
+ agents.set(parsed.name, { ...parsed, tools });
244
+ }
234
245
  }
235
246
  }
236
- return { agents: [...agents.values()].sort((a, b) => a.name.localeCompare(b.name)), errors };
247
+ for (const name of Object.keys(overlays.entries).filter((name) => !agents.has(name))) {
248
+ overlays.notices.push(`overlay names unknown agent "${name}"`);
249
+ }
250
+ return { agents: [...agents.values()].sort((a, b) => a.name.localeCompare(b.name)), errors, notices: overlays.notices };
237
251
  }
238
252
 
239
253
  type RawConfig = Record<string, unknown> | undefined;
@@ -283,21 +297,48 @@ export function parseAgentsConfig(global: RawConfig, project: RawConfig): Agents
283
297
  toolStallTimeoutMs: Math.max(positiveInteger(merged.tool_stall_timeout_ms, DEFAULT_TOOL_STALL_TIMEOUT_MS), stallTimeoutMs),
284
298
  maxConcurrency: positiveInteger(merged.max_concurrency, DEFAULT_MAX_CONCURRENCY),
285
299
  historyMaxTasks: positiveInteger(merged.history_max_tasks, DEFAULT_HISTORY_MAX_TASKS),
300
+ reportMaxBytes: positiveInteger(merged.report_max_bytes, DEFAULT_REPORT_MAX_BYTES),
286
301
  };
287
302
  }
288
303
 
289
304
  function readJson(path: string): RawConfig {
290
- if (!existsSync(path)) return undefined;
305
+ const read = readSubagentsFileResult(path);
306
+ return read.status === "valid" ? read.value : undefined;
307
+ }
308
+
309
+ /** The two stores `subagents.json` is assembled from, global first. */
310
+ export function subagentsConfigPaths(roots: DiscoveryRoots): { global: string; project: string } {
311
+ return {
312
+ global: join(profileRoot(roots), "subagents.json"),
313
+ project: join(roots.cwd, ".pi", "subagents.json"),
314
+ };
315
+ }
316
+
317
+ /**
318
+ * Read-side status of one `subagents.json`, kept apart from `loadAgentsConfig`'s
319
+ * forgiving merge so a caller can report a missing layer separately from a
320
+ * malformed one. It never writes and never repairs the file.
321
+ */
322
+ export type SubagentsFileReadResult =
323
+ | { status: "missing" }
324
+ | { status: "invalid" }
325
+ | { status: "valid"; value: Record<string, unknown> };
326
+
327
+ export function readSubagentsFileResult(path: string): SubagentsFileReadResult {
328
+ if (!existsSync(path)) return { status: "missing" };
291
329
  try {
292
330
  const parsed = JSON.parse(readFileSync(path, "utf8")) as unknown;
293
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : undefined;
331
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
332
+ ? { status: "valid", value: parsed as Record<string, unknown> }
333
+ : { status: "invalid" };
294
334
  } catch {
295
- return undefined;
335
+ return { status: "invalid" };
296
336
  }
297
337
  }
298
338
 
299
339
  export function loadAgentsConfig(roots: DiscoveryRoots): AgentsConfig {
300
- return parseAgentsConfig(readJson(join(profileRoot(roots), "subagents.json")), readJson(join(roots.cwd, ".pi", "subagents.json")));
340
+ const paths = subagentsConfigPaths(roots);
341
+ return parseAgentsConfig(readJson(paths.global), readJson(paths.project));
301
342
  }
302
343
 
303
344
  export function withPinnedModelProfiles(
@@ -13,6 +13,8 @@
13
13
  // idle using `deliverAs: "steer"`.
14
14
 
15
15
  export const STALE_NOTIFICATION_MS = 90_000;
16
+ /** Appended to a query that expired before the parent's turn boundary. */
17
+ export const EXPIRED_QUERY_LINE = "This query expired before it reached you; a reply is delivered to the task as a message.";
16
18
 
17
19
  export type AgentMessageKind = "notification" | "query";
18
20
 
@@ -50,6 +52,10 @@ export interface AgentMessageQueue {
50
52
  /** Mark a query as expired (timed out or errored). Prevents delivery. */
51
53
  expireQuery(taskId: string, requestId: string): void;
52
54
 
55
+ /** A query that timed out: one the parent never saw is still delivered once,
56
+ * marked expired, so a late reply can reach the task; otherwise like expireQuery. */
57
+ markQueryExpired(taskId: string, requestId: string): void;
58
+
53
59
  /** Invalidate all pending messages (notifications and queries) for a settled or cancelled task. */
54
60
  invalidateTask(taskId: string): void;
55
61
 
@@ -139,6 +145,17 @@ export function createAgentMessageQueue(): AgentMessageQueue {
139
145
  pending = pending.filter((msg) => !(msg.kind === "query" && msg.taskId === taskId && msg.requestId === requestId));
140
146
  },
141
147
 
148
+ markQueryExpired(taskId, requestId) {
149
+ const queued = pending.find((msg) => msg.kind === "query" && msg.taskId === taskId && msg.requestId === requestId);
150
+ if (!queued) {
151
+ expiredQueries.add(queryKey(taskId, requestId));
152
+ return;
153
+ }
154
+ if (queued.details.gentleAgents && (queued.details.gentleAgents as { expired?: boolean }).expired) return;
155
+ queued.content = `${queued.content}\n${EXPIRED_QUERY_LINE}`;
156
+ queued.details = { gentleAgents: { ...(queued.details.gentleAgents as Record<string, unknown>), expired: true } };
157
+ },
158
+
142
159
  invalidateTask(taskId) {
143
160
  invalidatedTasks.add(taskId);
144
161
  pending = pending.filter((msg) => msg.taskId !== taskId);
@@ -4,7 +4,13 @@ export const CHILD_QUERY_ERROR_MAX_BYTES = 256;
4
4
  export const CHILD_MESSAGE_MAX_INFLIGHT = 8;
5
5
  export const CHILD_MESSAGE_TIMEOUT_MS = 2_000;
6
6
  export const CHILD_QUERY_MAX_INFLIGHT = 4;
7
- export const CHILD_QUERY_TIMEOUT_MS = 30_000;
7
+ // A busy parent answers after its current model call and tool batch, which
8
+ // routinely takes one to two minutes. The child's query is an in-flight tool
9
+ // call meanwhile, so the stall watchdog applies its tool ceiling, not idle silence.
10
+ export const CHILD_QUERY_TIMEOUT_MS = 120_000;
11
+ // What the child reads when the deadline passes; both the child's own deadline
12
+ // and the runner's reply frame use it, so it must fit CHILD_QUERY_ERROR_MAX_BYTES.
13
+ export const CHILD_QUERY_TIMEOUT_ERROR = "Parent query timed out: the parent did not answer in time. A late answer may still arrive as a message; continue with work that does not depend on it and state the open question in your report.";
8
14
 
9
15
  export interface NotificationFrame {
10
16
  id: string;
@@ -182,7 +188,7 @@ export class ChildMessenger {
182
188
  if (!validChildMessage(message)) return Promise.reject(new Error("query is not well-formed UTF-16 or exceeds 8KiB"));
183
189
  if (this.queries.size >= CHILD_QUERY_MAX_INFLIGHT) return Promise.reject(new Error("too many pending parent queries"));
184
190
  if (this.nextQueryId >= Number.MAX_SAFE_INTEGER) return Promise.reject(new Error("parent query correlation exhausted"));
185
- return this.send(this.queries, `q${++this.nextQueryId}`, "query", message, CHILD_QUERY_TIMEOUT_MS, "parent query timed out");
191
+ return this.send(this.queries, `q${++this.nextQueryId}`, "query", message, CHILD_QUERY_TIMEOUT_MS, CHILD_QUERY_TIMEOUT_ERROR);
186
192
  }
187
193
 
188
194
  close(reason = "parent notification channel closed"): void {
@@ -126,6 +126,19 @@ export interface TaskThread {
126
126
  limits: ThreadLimits;
127
127
  }
128
128
 
129
+ /**
130
+ * Per-helper token breakdown accumulated from the final-assistant observations
131
+ * the runner delivers at completion. Absent while a task is in flight: the
132
+ * runner only releases that breakdown once the run settled.
133
+ */
134
+ export interface TaskUsage {
135
+ input: number;
136
+ output: number;
137
+ cacheRead: number;
138
+ cacheWrite: number;
139
+ reasoning: number;
140
+ }
141
+
129
142
  export interface TaskRecord {
130
143
  /** Retained legacy payload, never interpreted or replayed as launch authority. */
131
144
  sddRemediation?: unknown;
@@ -159,6 +172,8 @@ export interface TaskRecord {
159
172
  toolCalls: number;
160
173
  tokens: number;
161
174
  cost: number;
175
+ /** Final-assistant token breakdown, recorded by the owner at completion. */
176
+ usage?: TaskUsage;
162
177
  }
163
178
 
164
179
  export interface TaskSummary {
@@ -0,0 +1,115 @@
1
+ // Gentle Agents report cap (P9b).
2
+ //
3
+ // A finished child's report is pushed into the parent's conversation (the
4
+ // background completion message, or the task-mode subagent_run and
5
+ // subagent_continue result) and stays there for the rest of the session.
6
+ // This module bounds that delivered copy only: the stored task result, the
7
+ // task file, and subagent_result keep the full text. Under the cap the report
8
+ // is returned unchanged, so every path stays byte-identical.
9
+
10
+ export const DEFAULT_REPORT_MAX_BYTES = 16_384;
11
+ /** A cut moves to a line boundary when one lies within this many bytes of it (see lineWindowBytes). */
12
+ export const REPORT_LINE_WINDOW_BYTES = 512;
13
+ /** Over the cap, the last bytes of the report (at most this many) follow the truncation line. */
14
+ export const REPORT_TAIL_BYTES = 2_048;
15
+
16
+ /** The line-boundary search window for a cut of `budget` bytes: at most 512, and at most a quarter of the budget, so a small cap cannot shrink a cut to a few bytes. */
17
+ export const lineWindowBytes = (budget: number): number => Math.min(REPORT_LINE_WINDOW_BYTES, budget >> 2);
18
+
19
+ export interface CappedReport {
20
+ text: string;
21
+ truncated: boolean;
22
+ reportBytes: number;
23
+ deliveredBytes: number;
24
+ }
25
+
26
+ const encoder = new TextEncoder();
27
+ const utf8Bytes = (value: string): number => encoder.encode(value).length;
28
+
29
+ // Byte length of one code point as TextEncoder writes it; a lone surrogate
30
+ // becomes U+FFFD (3 bytes), and a pair is one 4-byte code point.
31
+ function codePointBytes(codePoint: number): number {
32
+ if (codePoint < 0x80) return 1;
33
+ if (codePoint < 0x800) return 2;
34
+ if (codePoint < 0x10000) return 3;
35
+ return 4;
36
+ }
37
+
38
+ /** The longest prefix of `value` whose UTF-8 encoding fits `maxBytes`, never splitting a code point or a surrogate pair. */
39
+ export function utf8Head(value: string, maxBytes: number): string {
40
+ let bytes = 0;
41
+ let end = 0;
42
+ for (const char of value) {
43
+ const size = codePointBytes(char.codePointAt(0)!);
44
+ if (bytes + size > maxBytes) break;
45
+ bytes += size;
46
+ end += char.length;
47
+ }
48
+ return value.slice(0, end);
49
+ }
50
+
51
+ /** The longest suffix of `value` whose UTF-8 encoding fits `maxBytes`, never splitting a code point or a surrogate pair. */
52
+ export function utf8Tail(value: string, maxBytes: number): string {
53
+ let bytes = 0;
54
+ let start = value.length;
55
+ while (start > 0) {
56
+ const low = value.charCodeAt(start - 1);
57
+ const pair = start >= 2 && low >= 0xdc00 && low <= 0xdfff && value.charCodeAt(start - 2) >= 0xd800 && value.charCodeAt(start - 2) <= 0xdbff;
58
+ const size = pair ? 4 : codePointBytes(low);
59
+ if (bytes + size > maxBytes) break;
60
+ bytes += size;
61
+ start -= pair ? 2 : 1;
62
+ }
63
+ return value.slice(start);
64
+ }
65
+
66
+ // Agents whose whole answer must be one JSON document: the Judgment Day roles (`jd-*`) and the review lens
67
+ // roles (`review-*`). The same rule as STRICT_JSON_PREFIX in the delegation contract test, which keeps the
68
+ // closing-block instruction out of these agents.
69
+ const STRICT_JSON_AGENT = /^(jd-|review-)/;
70
+ export const isStrictJsonAgent = (agent: string): boolean => STRICT_JSON_AGENT.test(agent);
71
+
72
+ // One valid JSON object or array after trimming, optionally inside one fenced block: cutting it would
73
+ // deliver invalid JSON, so it is never truncated.
74
+ function singleJsonDocument(report: string): boolean {
75
+ const body = report.trim().replace(/^```[\w-]*\n([\s\S]*)\n```$/, "$1").trim();
76
+ if (!/^[[{]/.test(body)) return false;
77
+ try { JSON.parse(body); return true; } catch { return false; }
78
+ }
79
+
80
+ // The head: up to `maxBytes`, moved back to the last line break when one lies in the final window.
81
+ function head(source: string, maxBytes: number): string {
82
+ const cut = utf8Head(source, maxBytes);
83
+ const newline = cut.lastIndexOf("\n");
84
+ return newline >= 0 && utf8Bytes(cut.slice(newline)) <= lineWindowBytes(maxBytes) ? cut.slice(0, newline) : cut;
85
+ }
86
+
87
+ // The tail: the last REPORT_TAIL_BYTES at most, starting after the first line break in the opening window
88
+ // when there is one, otherwise at a code point boundary. The text is not inspected beyond line breaks.
89
+ function tail(source: string): string {
90
+ const cut = utf8Tail(source, REPORT_TAIL_BYTES);
91
+ const newline = cut.indexOf("\n");
92
+ return newline >= 0 && utf8Bytes(cut.slice(0, newline + 1)) <= lineWindowBytes(REPORT_TAIL_BYTES) ? cut.slice(newline + 1) : cut;
93
+ }
94
+
95
+ /** Bound the report delivered into the parent's context: its head, a truncation line, then the end of the report. The full text stays available through subagent_result. */
96
+ export function capReport(report: string, maxBytes: number, taskId: string, agent = ""): CappedReport {
97
+ const reportBytes = utf8Bytes(report);
98
+ const whole = { text: report, truncated: false, reportBytes, deliveredBytes: reportBytes };
99
+ if (reportBytes <= maxBytes || isStrictJsonAgent(agent) || singleJsonDocument(report)) return whole;
100
+ const first = head(report, maxBytes);
101
+ const firstBytes = utf8Bytes(first);
102
+ // What the head leaves out fits the tail allowance: deliver everything, so head and tail never overlap.
103
+ if (reportBytes - firstBytes <= REPORT_TAIL_BYTES) return whole;
104
+ const last = tail(report);
105
+ const lastBytes = utf8Bytes(last);
106
+ const notice = `Report truncated: the first ${firstBytes} and the last ${lastBytes} of ${reportBytes} bytes were delivered. Call subagent_result with task_id ${taskId} for the full text.`;
107
+ return { text: `${first}\n\n${notice}\n\n${last}`, truncated: true, reportBytes, deliveredBytes: firstBytes + lastBytes };
108
+ }
109
+
110
+ /** Additive details for the UI: the existing fields stay as they are, and nothing is added under the cap. */
111
+ export function withReportCap(details: Record<string, unknown>, capped: CappedReport): Record<string, unknown> {
112
+ if (!capped.truncated) return details;
113
+ const agents = (details.gentleAgents ?? {}) as Record<string, unknown>;
114
+ return { ...details, gentleAgents: { ...agents, reportTruncated: true, reportBytes: capped.reportBytes, reportDeliveredBytes: capped.deliveredBytes } };
115
+ }