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
@@ -0,0 +1,515 @@
1
+ import { decodePrintableKey } from "./pi-tui-keys.ts";
2
+ import { isKeyRelease, matchesKey, truncateToWidth, visibleWidth, type EditorComponent } from "@earendil-works/pi-tui";
3
+
4
+ /**
5
+ * Native text-selection engine for GentlePromptEditor: shift+home / shift+end
6
+ * selection, alt+a select-all, and replace-on-key (backspace / delete /
7
+ * printable character) with reverse-video highlight and a bottom-rule hint.
8
+ * Ported from @exopro/pi-select-del so the petal prompt owns the feature
9
+ * natively — no factory composition, no cross-extension focus handoff.
10
+ *
11
+ * Behavior contract (ported from pi-select-del, with atomic paste replacement):
12
+ * - shift+home — anchor at the cursor, move to line start (held presses at
13
+ * the edge keep the selection; only a zero-width span collapses)
14
+ * - shift+end — anchor at the cursor, move to line end
15
+ * - alt+a — select all
16
+ * - backspace / delete / printable character or bracketed paste over an
17
+ * active selection — replace it in one atomic edit (undo restores text AND cursor)
18
+ * - any other key — collapse the selection first, then behave natively
19
+ *
20
+ * The engine drives the host editor's own internals (the EditorInternals
21
+ * surface every CustomEditor-derived editor exposes) and degrades to pure
22
+ * passthrough if that surface drifts: a pi upgrade can cost the selection
23
+ * features, never crash editing.
24
+ */
25
+
26
+ /** Cursor/anchor position in logical (line, col) editor coordinates. */
27
+ export interface Point {
28
+ line: number;
29
+ col: number;
30
+ }
31
+
32
+ /**
33
+ * Narrow view of the private Editor internals the engine relies on. Kept in
34
+ * one place so a pi upgrade only needs re-verifying against this interface.
35
+ */
36
+ export interface EditorInternals {
37
+ state: { lines: string[]; cursorLine: number; cursorCol: number };
38
+ paddingX: number;
39
+ scrollOffset: number;
40
+ renderedVisibleLineCount: number;
41
+ /** Layout width the last base render wrapped at; soft-optional — falsy falls back to manual width math. */
42
+ lastWidth: number;
43
+ tui: { requestRender(): void };
44
+ autocompleteState: "regular" | "force" | null;
45
+ lastAction: "kill" | "yank" | "type-word" | null;
46
+ pushUndoSnapshot(): void;
47
+ setCursorCol(col: number): void;
48
+ moveToLineStart(): void;
49
+ moveToLineEnd(): void;
50
+ exitHistoryBrowsing(): void;
51
+ cancelAutocomplete(): void;
52
+ updateAutocomplete(): void;
53
+ buildVisualLineMap(width: number): Array<{ logicalLine: number; startCol: number; length: number }>;
54
+ }
55
+
56
+ const INTERNAL_PROBE_MEMBERS = {
57
+ properties: [
58
+ "state",
59
+ "paddingX",
60
+ "scrollOffset",
61
+ "renderedVisibleLineCount",
62
+ "autocompleteState",
63
+ "lastAction",
64
+ "tui",
65
+ ],
66
+ functions: [
67
+ "pushUndoSnapshot",
68
+ "setCursorCol",
69
+ "moveToLineStart",
70
+ "moveToLineEnd",
71
+ "exitHistoryBrowsing",
72
+ "cancelAutocomplete",
73
+ "updateAutocomplete",
74
+ "buildVisualLineMap",
75
+ ],
76
+ } as const satisfies {
77
+ properties: readonly (keyof EditorInternals)[];
78
+ functions: readonly (keyof EditorInternals)[];
79
+ };
80
+
81
+ /**
82
+ * Members of `target` missing or malformed against the EditorInternals
83
+ * contract. Class-field trap: the properties are ES class fields (instance
84
+ * own-properties), invisible to any prototype probe — probe a real instance,
85
+ * never Editor.prototype or a subclass prototype.
86
+ */
87
+ export function missingEditorInternals(target: object): string[] {
88
+ const missing: string[] = [];
89
+ const view = target as Record<string, unknown>;
90
+ for (const name of INTERNAL_PROBE_MEMBERS.properties) {
91
+ if (view[name] === undefined) missing.push(name);
92
+ }
93
+ for (const name of INTERNAL_PROBE_MEMBERS.functions) {
94
+ if (typeof view[name] !== "function") missing.push(name);
95
+ }
96
+ return missing;
97
+ }
98
+
99
+ export function clamp(value: number, lo: number, hi: number): number {
100
+ return Math.max(lo, Math.min(hi, value));
101
+ }
102
+
103
+ /**
104
+ * Wrap the code-unit span [startCu, endCu) of a rendered editor row in reverse
105
+ * video. Positions are code-unit offsets into the row's PLAIN text (same unit
106
+ * the editor uses for cursorCol and visual-line map columns). The rendered row
107
+ * may already contain escape sequences (SGR colors, cursor markers); the walk
108
+ * passes those through untouched, keeping code-unit alignment. The span closes
109
+ * with SGR 27 (reverse off), not a full reset: row attributes set before the
110
+ * span must survive. A nested SGR reset re-arms reverse right after it.
111
+ */
112
+ export function withReverseSpan(row: string, startCu: number, endCu: number): string {
113
+ let out = "";
114
+ let cu = 0;
115
+ let i = 0;
116
+ let opened = false;
117
+ while (i < row.length) {
118
+ if (!opened && cu >= startCu) {
119
+ out += "\x1b[7m";
120
+ opened = true;
121
+ }
122
+ if (opened && cu >= endCu) {
123
+ return `${out}\x1b[27m${row.slice(i)}`;
124
+ }
125
+ if (row[i] === "\x1b") {
126
+ const seq = row.slice(i, i + escapeSequenceLength(row, i));
127
+ out += seq;
128
+ // A nested SGR reset (e.g. the cursor block's own, when the cursor
129
+ // sits inside the span) clears reverse for everything after it:
130
+ // re-arm reverse right after it.
131
+ if (opened && cu < endCu && isSgrReset(seq)) out += "\x1b[7m";
132
+ i += seq.length;
133
+ continue;
134
+ }
135
+ out += row[i];
136
+ i += 1;
137
+ cu += 1;
138
+ }
139
+ return opened ? `${out}\x1b[27m` : out;
140
+ }
141
+
142
+ /** Length of the escape sequence at s[i] (s[i] === ESC). Unterminated sequences end the row. */
143
+ export function escapeSequenceLength(s: string, i: number): number {
144
+ const next = s[i + 1];
145
+ if (next === "[") {
146
+ // CSI: parameter/intermediate bytes 0x20-0x3F, final byte 0x40-0x7E.
147
+ for (let j = i + 2; j < s.length; j++) {
148
+ const code = s.charCodeAt(j);
149
+ if (code >= 0x40 && code <= 0x7e) return j - i + 1;
150
+ }
151
+ return s.length - i;
152
+ }
153
+ if (next === "]" || next === "_") {
154
+ // OSC / APC (cursor markers are APC): terminated by BEL or ST (ESC \).
155
+ const bel = s.indexOf("\x07", i + 2);
156
+ const st = s.indexOf("\x1b\\", i + 2);
157
+ if (bel === -1 && st === -1) return s.length - i;
158
+ if (bel === -1) return st - i + 2;
159
+ if (st === -1) return bel - i + 1;
160
+ return Math.min(bel - i + 1, st - i + 2);
161
+ }
162
+ return 2;
163
+ }
164
+
165
+ /** True for SGR reset sequences: CSI ... m with an empty or all-zero parameter list. */
166
+ export function isSgrReset(seq: string): boolean {
167
+ const match = /^\x1b\[([\d;]*)m$/.exec(seq);
168
+ if (!match) return false;
169
+ const params = match[1];
170
+ if (params === "") return true;
171
+ return /^0+$/.test(params.split(";")[0]);
172
+ }
173
+
174
+ /**
175
+ * Selection engine driving a host editor through the EditorInternals cast.
176
+ * `handleInput` takes the host's native dispatch as a `native` callback so the
177
+ * host keeps its own key chain (Esc gates, autocomplete, history) intact:
178
+ * selection keys are handled here; everything else collapses the anchor first,
179
+ * then behaves natively.
180
+ */
181
+ const PASTE_START = "\x1b[200~";
182
+ const PASTE_END = "\x1b[201~";
183
+ const PASTE_END_TAIL_LENGTH = PASTE_END.length - 1;
184
+ /**
185
+ * Safety bound (UTF-8 bytes) for a bracketed-paste frame that has not yet
186
+ * seen its terminator. Checked only against a per-chunk byte count (never a
187
+ * full-buffer rescan), so it costs one Buffer.byteLength call per NEW chunk.
188
+ * Never applied once the terminator is found: a complete frame of any size,
189
+ * even one exceeding this bound, still reaches replaceSelectionWithPaste with
190
+ * one-step undo intact.
191
+ */
192
+ const MAX_INCOMPLETE_PASTE_BYTES = 16 * 1024 * 1024;
193
+
194
+ export class SelectionEngine {
195
+ /** Selection anchor in logical (line, col) coordinates; adapter-exposed state. */
196
+ anchor: Point | null = null;
197
+ /**
198
+ * Chunks of an in-progress bracketed-paste frame (undefined when none is
199
+ * open). Chunks are only ever appended, never re-concatenated, so buffering
200
+ * N chunks stays O(N) total; the full frame is joined once, at completion.
201
+ */
202
+ private pasteChunks: string[] | undefined;
203
+ /** Total code-unit length of `pasteChunks` before the chunk being processed; used to locate the terminator inside the joined frame. */
204
+ private pasteBufferedLength = 0;
205
+ /** Total UTF-8 byte length buffered so far while no terminator has been seen; compared against MAX_INCOMPLETE_PASTE_BYTES. */
206
+ private pasteBufferedBytes = 0;
207
+ /**
208
+ * Up to the last `PASTE_END_TAIL_LENGTH` characters buffered so far, carried
209
+ * forward so the terminator can be found even when split across chunk
210
+ * boundaries, without rescanning every previously buffered chunk.
211
+ */
212
+ private pasteTail = "";
213
+
214
+ /**
215
+ * Capability probe cache for the host internals: null until first use, then
216
+ * the (possibly empty) list of missing members, computed once on the first
217
+ * handleInput/render call. Any defect permanently DEGRADES the host to
218
+ * passthrough — selection features off, never a crash.
219
+ */
220
+ private internalDefects: string[] | null = null;
221
+
222
+ private readonly editor: EditorComponent;
223
+
224
+ constructor(editor: EditorComponent) {
225
+ this.editor = editor;
226
+ }
227
+
228
+ /** True once the probe found missing internals; computes and caches the probe on first call. */
229
+ get degraded(): boolean {
230
+ if (this.internalDefects === null) {
231
+ this.internalDefects = missingEditorInternals(this.editor);
232
+ }
233
+ return this.internalDefects.length > 0;
234
+ }
235
+
236
+ private get internals(): EditorInternals {
237
+ return this.editor as unknown as EditorInternals;
238
+ }
239
+
240
+ private get s(): EditorInternals["state"] {
241
+ return this.internals.state;
242
+ }
243
+
244
+ private cursor(): Point {
245
+ return { line: this.s.cursorLine, col: this.s.cursorCol };
246
+ }
247
+
248
+ private setCursor(p: Point): void {
249
+ this.s.cursorLine = p.line;
250
+ this.internals.setCursorCol(p.col);
251
+ }
252
+
253
+ /** Ordered (start, end) selection range, or null when no anchor is set. */
254
+ range(): [Point, Point] | null {
255
+ if (!this.anchor) return null;
256
+ const a = this.anchor;
257
+ const c = this.cursor();
258
+ const anchorFirst = a.line < c.line || (a.line === c.line && a.col < c.col);
259
+ return anchorFirst ? [a, c] : [c, a];
260
+ }
261
+
262
+ /** Number of characters covered by the active selection (0 when none). Counts line breaks a deletion would remove. */
263
+ selectionLength(): number {
264
+ const range = this.range();
265
+ if (!range) return 0;
266
+ const [start, end] = range;
267
+ const lines = this.s.lines;
268
+ if (start.line === end.line) return end.col - start.col;
269
+ let n = (lines[start.line] ?? "").length - start.col;
270
+ for (let i = start.line + 1; i < end.line; i++) n += (lines[i] ?? "").length;
271
+ return n + end.col + (end.line - start.line);
272
+ }
273
+
274
+ /**
275
+ * Selection dispatch in front of the native chain. Selection and replace
276
+ * keys are handled here; everything else collapses the anchor first, then
277
+ * behaves natively. Degraded hosts keep pure native key handling.
278
+ */
279
+ handleInput(data: string, native: (data: string) => void): void {
280
+ if (this.degraded) {
281
+ native(data);
282
+ return;
283
+ }
284
+ if (this.pasteChunks !== undefined || (this.anchor && data.startsWith(PASTE_START))) {
285
+ const priorLength = this.pasteBufferedLength;
286
+ const window = this.pasteTail + data;
287
+ const idx = window.indexOf(PASTE_END);
288
+ const chunks = (this.pasteChunks ??= []);
289
+ chunks.push(data);
290
+ this.pasteBufferedLength = priorLength + data.length;
291
+ if (idx < 0) {
292
+ this.pasteBufferedBytes += Buffer.byteLength(data, "utf8");
293
+ if (this.pasteBufferedBytes > MAX_INCOMPLETE_PASTE_BYTES) {
294
+ // Never seen a terminator and the buffered frame outgrew the safety
295
+ // bound: abandon it. The host editor started its own paste buffer at
296
+ // PASTE_START and is still waiting for PASTE_END, so forwarding the
297
+ // incomplete bytes to `native` could let it swallow later keystrokes
298
+ // — drop them instead of forwarding anything.
299
+ this.pasteChunks = undefined;
300
+ this.pasteBufferedLength = 0;
301
+ this.pasteBufferedBytes = 0;
302
+ this.pasteTail = "";
303
+ return;
304
+ }
305
+ this.pasteTail = window.slice(-PASTE_END_TAIL_LENGTH);
306
+ return;
307
+ }
308
+ const frameEnd = priorLength - this.pasteTail.length + idx + PASTE_END.length;
309
+ const buffered = chunks.join("");
310
+ const frame = buffered.slice(0, frameEnd);
311
+ const remaining = buffered.slice(frameEnd);
312
+ this.pasteChunks = undefined;
313
+ this.pasteBufferedLength = 0;
314
+ this.pasteBufferedBytes = 0;
315
+ this.pasteTail = "";
316
+ this.replaceSelectionWithPaste(frame, native);
317
+ if (remaining) this.handleInput(remaining, native);
318
+ return;
319
+ }
320
+ // Kitty flag 2 release byte strings still match their own key, so
321
+ // releases must be dropped before any matchesKey.
322
+ if (isKeyRelease(data)) return;
323
+ if (matchesKey(data, "shift+home")) {
324
+ this.selectToLineEdge(false);
325
+ return;
326
+ }
327
+ if (matchesKey(data, "shift+end")) {
328
+ this.selectToLineEdge(true);
329
+ return;
330
+ }
331
+ if (matchesKey(data, "alt+a")) {
332
+ this.selectAll();
333
+ return;
334
+ }
335
+
336
+ if (this.anchor) {
337
+ if (this.isReplaceKey(data)) {
338
+ const replaced = this.replaceSelection(data);
339
+ if (replaced) return;
340
+ // Selection collapsed to empty (anchor met cursor): native key behavior.
341
+ this.anchor = null;
342
+ native(data);
343
+ return;
344
+ }
345
+ // Movement, enter, history, kill/yank, app shortcuts: collapse first, then native behavior.
346
+ this.anchor = null;
347
+ }
348
+
349
+ native(data);
350
+ }
351
+
352
+ /** Let Pi normalize/register paste and take its one undo snapshot, then remove
353
+ * the selected text around the inserted text or marker in that transaction. */
354
+ private replaceSelectionWithPaste(frame: string, native: (data: string) => void): void {
355
+ const range = this.range();
356
+ this.anchor = null;
357
+ if (!range || frame === PASTE_START + PASTE_END) return native(frame);
358
+ const lines = this.s.lines;
359
+ const before = lines.join("\n");
360
+ const offset = (p: Point): number => lines.slice(0, p.line).reduce((n, line) => n + line.length + 1, 0) + p.col;
361
+ const [start, end] = range.map(offset);
362
+ if (start === end) return native(frame);
363
+ const cursor = offset(this.cursor());
364
+ native(frame);
365
+ const after = this.s.lines.join("\n");
366
+ const prefix = before.slice(0, cursor);
367
+ const suffix = before.slice(cursor);
368
+ // If Pi did not perform a plain insertion, retain its native result.
369
+ if (!after.startsWith(prefix) || !after.endsWith(suffix)) return;
370
+ const inserted = after.slice(prefix.length, after.length - suffix.length);
371
+ if (!inserted) return;
372
+ const result = before.slice(0, start) + inserted + before.slice(end);
373
+ this.s.lines = result.split("\n");
374
+ const caret = result.slice(0, start + inserted.length).split("\n");
375
+ this.s.cursorLine = caret.length - 1;
376
+ this.internals.setCursorCol(caret.at(-1)!.length);
377
+ this.internals.lastAction = null;
378
+ this.editor.onChange?.(this.editor.getText());
379
+ this.internals.tui.requestRender();
380
+ }
381
+
382
+ /** Keys whose native effect replaces a selection: backspace/delete (and shift variants) or a printable character. */
383
+ private isReplaceKey(data: string): boolean {
384
+ return (
385
+ matchesKey(data, "backspace") ||
386
+ matchesKey(data, "shift+backspace") ||
387
+ matchesKey(data, "delete") ||
388
+ matchesKey(data, "shift+delete") ||
389
+ this.insertsCharacter(data)
390
+ );
391
+ }
392
+
393
+ /**
394
+ * True when the input inserts a text character (Kitty/CSI-u and
395
+ * modify-other-keys aware, plus raw terminal bytes). The raw fallback
396
+ * accepts at most 4 UTF-16 code units with no control bytes; DEL and C1
397
+ * controls must not count as printable (the editor routes them to
398
+ * delete/other actions before its printable fallback, so re-submitting
399
+ * them after a splice would double-edit).
400
+ */
401
+ private insertsCharacter(data: string): boolean {
402
+ if (decodePrintableKey(data) !== undefined) return true;
403
+ if (data.length > 4) return false;
404
+ for (let i = 0; i < data.length; i++) {
405
+ const c = data.charCodeAt(i);
406
+ if (c < 32 || c === 127 || (c >= 0x80 && c <= 0x9f)) return false;
407
+ }
408
+ return true;
409
+ }
410
+
411
+ private selectToLineEdge(toEnd: boolean): void {
412
+ const before = this.cursor();
413
+ if (toEnd) this.internals.moveToLineEnd();
414
+ else this.internals.moveToLineStart();
415
+ this.internals.exitHistoryBrowsing();
416
+ // Repeated or held presses at the edge KEEP the selection: legacy
417
+ // terminals repeat the press byte-identically. Only a zero-width span
418
+ // (cursor landed exactly on the anchor) collapses.
419
+ this.anchor ??= before;
420
+ if (this.anchor.line === this.s.cursorLine && this.anchor.col === this.s.cursorCol) {
421
+ this.anchor = null;
422
+ }
423
+ if (this.internals.autocompleteState) this.internals.updateAutocomplete();
424
+ this.internals.tui.requestRender();
425
+ }
426
+
427
+ /** Select the entire editor text (alt+a). Cursor moves to the end of the last line. */
428
+ private selectAll(): void {
429
+ const lines = this.s.lines;
430
+ const lastLine = Math.max(0, lines.length - 1);
431
+ this.anchor = { line: 0, col: 0 };
432
+ this.s.cursorLine = lastLine;
433
+ this.internals.setCursorCol((lines[lastLine] ?? "").length);
434
+ this.internals.lastAction = null;
435
+ this.internals.exitHistoryBrowsing();
436
+ if (this.internals.autocompleteState) this.internals.cancelAutocomplete();
437
+ this.internals.tui.requestRender();
438
+ }
439
+
440
+ /**
441
+ * Replace the active selection in ONE atomic edit (delete, or delete +
442
+ * printable character): a single undo snapshot before any mutation, then
443
+ * one splice. Returns false when the span is empty; the caller falls back
444
+ * to native key behavior.
445
+ */
446
+ private replaceSelection(data: string): boolean {
447
+ const range = this.range();
448
+ if (!range) return false;
449
+ const [start, end] = range;
450
+ if (start.line === end.line && start.col === end.col) return false;
451
+ const resolved = decodePrintableKey(data) ?? (this.insertsCharacter(data) ? data : undefined);
452
+ const cp = resolved?.codePointAt(0) ?? 0;
453
+ const char = cp === 127 || (cp >= 0x80 && cp <= 0x9f) ? undefined : resolved;
454
+ const internals = this.internals;
455
+ const lines = internals.state.lines;
456
+ internals.pushUndoSnapshot();
457
+ const merged =
458
+ (lines[start.line] ?? "").slice(0, start.col) + (char ?? "") + (lines[end.line] ?? "").slice(end.col);
459
+ lines.splice(start.line, end.line - start.line + 1, merged);
460
+ this.anchor = null;
461
+ this.setCursor({ line: start.line, col: start.col + (char?.length ?? 0) });
462
+ internals.exitHistoryBrowsing();
463
+ internals.lastAction = null;
464
+ if (internals.autocompleteState) internals.cancelAutocomplete();
465
+ this.editor.onChange?.(this.editor.getText());
466
+ internals.tui.requestRender();
467
+ return true;
468
+ }
469
+
470
+ /**
471
+ * Render post-pass: wrap the selected span of each visible row in reverse
472
+ * video. `inset` is the number of columns the host render adds on EACH side
473
+ * before the editor's own content (0 for plain content rows, 1 for a
474
+ * one-column frame wall); `width` is the width the content was rendered at.
475
+ */
476
+ decorateRows(rows: string[], width: number, inset: number): string[] {
477
+ const range = this.range();
478
+ if (!range) return rows;
479
+ const internals = this.internals;
480
+ const [start, end] = range;
481
+ const contentWidth = Math.max(1, width - inset * 2 - internals.paddingX * 2);
482
+ const layoutWidth = internals.lastWidth || Math.max(1, contentWidth - (internals.paddingX ? 0 : 1));
483
+ const visual = internals.buildVisualLineMap(layoutWidth);
484
+ for (let r = 0; r < internals.renderedVisibleLineCount; r++) {
485
+ const vr = visual[internals.scrollOffset + r];
486
+ if (!vr || vr.logicalLine < start.line || vr.logicalLine > end.line) continue;
487
+ const from =
488
+ clamp(vr.logicalLine === start.line ? start.col - vr.startCol : 0, 0, vr.length) +
489
+ internals.paddingX +
490
+ inset;
491
+ const to =
492
+ clamp(vr.logicalLine === end.line ? end.col - vr.startCol : vr.length, 0, vr.length) +
493
+ internals.paddingX +
494
+ inset;
495
+ if (to <= from) continue;
496
+ const index = 1 + r; // rows[0] is the top border/rule in every layout
497
+ if (index < rows.length) rows[index] = withReverseSpan(rows[index] ?? "", from, to);
498
+ }
499
+ return rows;
500
+ }
501
+
502
+ /**
503
+ * Bottom-rule selection hint. `corner` re-attaches the host frame's right
504
+ * corner glyph after the label. Widths always add up: the rule is truncated
505
+ * to make exact room for label + corner.
506
+ */
507
+ decorateBottomRule(baseRow: string, width: number, corner: string): string {
508
+ const n = this.selectionLength();
509
+ if (n <= 0) return baseRow;
510
+ const label = ` ${n} char${n === 1 ? "" : "s"} selected - Del deletes - Alt+a select all `;
511
+ const labelWidth = visibleWidth(label);
512
+ if (labelWidth + visibleWidth(corner) + 1 >= width) return baseRow;
513
+ return `${truncateToWidth(baseRow, width - labelWidth - visibleWidth(corner), "")}${label}${corner}`;
514
+ }
515
+ }
@@ -7,6 +7,12 @@ import { resolveSessionWorktree, type WorktreeResolver } from "./session-worktre
7
7
  import { SessionChanges, readChangeSnapshot, sameSnapshot, textSnapshot, isSessionChangeEvidence,
8
8
  SESSION_CHANGE_ENTRY, SESSION_CHANGE_EVENT, SESSION_CHANGE_RELAY, type SessionChangeEvidence, type ChangeSnapshot } from "./session-changes.ts";
9
9
 
10
+ const foreignPublishers = new WeakMap<ExtensionAPI, (sessionId: string, evidence: SessionChangeEvidence) => void>();
11
+ /** Internal authenticated handoff from a successful child tool callback, never a model message or public event. */
12
+ export function publishForeignSessionChange(pi: ExtensionAPI, sessionId: string, evidence: SessionChangeEvidence): void {
13
+ foreignPublishers.get(pi)?.(sessionId, evidence);
14
+ }
15
+
10
16
  interface Pending { sessionId: string; inputPath: string; path: string; root: string; relativePath: string; before: ChangeSnapshot; toolName: string; evidence?: SessionChangeEvidence }
11
17
  const normalized = (text: string) => text.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
12
18
  const unknown = (): ChangeSnapshot => ({ kind: "unavailable", reason: "Tool snapshots could not be verified; diff unavailable." });
@@ -23,6 +29,9 @@ export function installSessionChangeCapture(pi: ExtensionAPI, env: NodeJS.Proces
23
29
  const notice = store.takeNotice();
24
30
  pi.events.emit(SESSION_CHANGE_EVENT, { sessionId: store.sessionId, ...(notice ? { notice } : {}) });
25
31
  };
32
+ foreignPublishers.set(pi, (sessionId, evidence) => {
33
+ if (!child && current?.sessionManager.getSessionId() === sessionId && isSessionChangeEvidence(evidence)) publish(evidence);
34
+ });
26
35
  pi.on("session_start", (_event, ctx) => {
27
36
  pending.clear(); current = ctx;
28
37
  store = new SessionChanges(ctx.sessionManager.getSessionId(), ctx.sessionManager.getEntries());
@@ -84,5 +93,5 @@ export function installSessionChangeCapture(pi: ExtensionAPI, env: NodeJS.Proces
84
93
  try { publish(item.evidence); } catch { /* Preserve the tool's outcome. */ }
85
94
  }
86
95
  });
87
- pi.on("session_shutdown", () => { pending.clear(); current = undefined; store = undefined; off(); });
96
+ pi.on("session_shutdown", () => { pending.clear(); current = undefined; store = undefined; foreignPublishers.delete(pi); off(); });
88
97
  }
@@ -0,0 +1,135 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export const MESSAGING_REASON_MIN_CHARACTERS = 8;
4
+ export const MESSAGING_REASON_MAX_UTF8_BYTES = 512;
5
+
6
+ const PREVIEW_CONTROL_CHARACTER = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
7
+
8
+ function escapePreviewText(value: string): string {
9
+ return Array.from(value, (character) => {
10
+ if (!PREVIEW_CONTROL_CHARACTER.test(character)) return character;
11
+ if (character === "\r") return "\\r";
12
+ if (character === "\n") return "\\n";
13
+ if (character === "\t") return "\\t";
14
+ return `\\u${character.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`;
15
+ }).join("");
16
+ }
17
+
18
+ export function normalizeMessagingReason(value: unknown): string {
19
+ if (typeof value !== "string") throw new Error("Cross-orchestrator communication requires a concrete reason of at least 8 trimmed characters and at most 512 UTF-8 bytes.");
20
+ const reason = value.trim();
21
+ if (Array.from(reason).length < MESSAGING_REASON_MIN_CHARACTERS || Buffer.byteLength(value, "utf8") > MESSAGING_REASON_MAX_UTF8_BYTES) {
22
+ throw new Error("Cross-orchestrator communication requires a concrete reason of at least 8 trimmed characters and at most 512 UTF-8 bytes.");
23
+ }
24
+ return reason;
25
+ }
26
+
27
+ /**
28
+ * Supported decision tokens for cross-orchestrator communication consent.
29
+ */
30
+ export const MESSAGING_CONSENT_DECISIONS = {
31
+ ALLOW_ONCE: "Allow once",
32
+ ALLOW_SESSION: "Allow for this session",
33
+ DENY: "Deny",
34
+ } as const;
35
+
36
+ export type MessagingConsentDecision =
37
+ (typeof MESSAGING_CONSENT_DECISIONS)[keyof typeof MESSAGING_CONSENT_DECISIONS];
38
+
39
+ /**
40
+ * Options for requesting human authorization before outbound cross-session communication.
41
+ */
42
+ export interface MessagingConsentOptions {
43
+ /** Outbound message payload. */
44
+ message: string;
45
+ /** Concrete caller-supplied reason explaining why this communication is needed. */
46
+ reason: string;
47
+ /** Optional abort signal for request cancellation. */
48
+ signal?: AbortSignal;
49
+ }
50
+
51
+ /**
52
+ * Ephemeral in-memory grant manager for cross-orchestrator communication.
53
+ * Permissions are scoped strictly to the live session identity and session manager instance.
54
+ */
55
+ export class SessionMessagingGrants {
56
+ private readonly grants = new Map<string, Set<string>>();
57
+ private manager?: ExtensionContext["sessionManager"];
58
+ private sessionId?: string;
59
+
60
+ /**
61
+ * Authorizes an outbound cross-orchestrator message to the given recipient.
62
+ * Prompts the user interactively when no session-level grant exists, and fails closed otherwise.
63
+ */
64
+ async authorize(
65
+ ctx: Pick<ExtensionContext, "sessionManager" | "hasUI" | "ui">,
66
+ recipient: string,
67
+ options: MessagingConsentOptions
68
+ ): Promise<void> {
69
+ const message = options.message;
70
+ if (typeof message !== "string" || Buffer.byteLength(message, "utf8") > 8192) throw new Error("Cross-orchestrator message is invalid.");
71
+ const reason = normalizeMessagingReason(options.reason);
72
+ const signal = options.signal;
73
+ if (signal?.aborted) throw new Error("Cross-orchestrator message authorization aborted.");
74
+ const id = ctx.sessionManager.getSessionId();
75
+ if (!id) throw new Error("Cross-orchestrator communication requires an active session identity.");
76
+ if (this.manager !== ctx.sessionManager || this.sessionId !== id) {
77
+ this.grants.clear();
78
+ this.manager = ctx.sessionManager;
79
+ this.sessionId = id;
80
+ }
81
+ if (!ctx.hasUI || typeof ctx.ui?.select !== "function") {
82
+ throw new Error("Cross-orchestrator communication requires interactive human consent before sending.");
83
+ }
84
+ if (this.grants.get(id)?.has(recipient)) return;
85
+
86
+ const previewMessage = escapePreviewText(message);
87
+ const isTruncated = message.length > 200;
88
+ const messageLabel = isTruncated
89
+ ? `Message (${message.length} chars, preview): ${escapePreviewText(message.slice(0, 197))}...`
90
+ : `Message: ${previewMessage}`;
91
+ const title = `Authorize cross-orchestrator message to ${escapePreviewText(recipient)}?\nReason: ${escapePreviewText(reason)}\n${messageLabel}`;
92
+
93
+ const selected = await ctx.ui.select(
94
+ title,
95
+ [
96
+ MESSAGING_CONSENT_DECISIONS.ALLOW_ONCE,
97
+ MESSAGING_CONSENT_DECISIONS.ALLOW_SESSION,
98
+ MESSAGING_CONSENT_DECISIONS.DENY,
99
+ ],
100
+ { signal }
101
+ );
102
+
103
+ if (signal?.aborted) throw new Error("Cross-orchestrator message authorization aborted.");
104
+ if (ctx.sessionManager !== this.manager || ctx.sessionManager.getSessionId() !== id) {
105
+ throw new Error("Session identity changed during authorization.");
106
+ }
107
+
108
+ if (selected === MESSAGING_CONSENT_DECISIONS.ALLOW_SESSION) {
109
+ const sessionGrants = this.grants.get(id) ?? new Set<string>();
110
+ sessionGrants.add(recipient);
111
+ this.grants.set(id, sessionGrants);
112
+ return;
113
+ }
114
+
115
+ if (selected === MESSAGING_CONSENT_DECISIONS.ALLOW_ONCE) {
116
+ return;
117
+ }
118
+
119
+ throw new Error("Cross-orchestrator communication denied by user.");
120
+ }
121
+
122
+ /**
123
+ * Checks whether a live session-level grant exists for the target recipient in the current session.
124
+ */
125
+ assertCurrent(ctx: Pick<ExtensionContext, "sessionManager">, recipient: string): boolean {
126
+ if (
127
+ ctx.sessionManager !== this.manager ||
128
+ !this.sessionId ||
129
+ ctx.sessionManager.getSessionId() !== this.sessionId
130
+ ) {
131
+ return false;
132
+ }
133
+ return this.grants.get(this.sessionId)?.has(recipient) ?? false;
134
+ }
135
+ }