dispach 0.1.2 → 0.1.3

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 (195) hide show
  1. package/README.md +134 -85
  2. package/dist/App-qfqvx9c7.js +11 -0
  3. package/dist/{App-b1yrwrcq.js.map → App-qfqvx9c7.js.map} +6 -7
  4. package/dist/ConfigEditor-apcnj4nj.js +6 -0
  5. package/dist/{ConfigEditor-n8hdw6r7.js.map → ConfigEditor-apcnj4nj.js.map} +2 -2
  6. package/dist/KeyProbe-ya5t3v3v.js +5 -0
  7. package/dist/{KeyProbe-9jjeze5r.js.map → KeyProbe-ya5t3v3v.js.map} +2 -2
  8. package/dist/Picker-b7mn0mjg.js +5 -0
  9. package/dist/{Picker-hfeh1g6m.js.map → Picker-b7mn0mjg.js.map} +1 -1
  10. package/dist/SessionPicker-vacfwczg.js +5 -0
  11. package/dist/{SessionPicker-zyqkg4dn.js.map → SessionPicker-vacfwczg.js.map} +2 -2
  12. package/dist/SkillBrowser-66ntwaa9.js +5 -0
  13. package/dist/{SkillBrowser-3qdp8080.js.map → SkillBrowser-66ntwaa9.js.map} +1 -1
  14. package/dist/WizardApp-123998yh.js +5 -0
  15. package/dist/{WizardApp-vzpbydy3.js.map → WizardApp-123998yh.js.map} +3 -3
  16. package/dist/agents.d.ts +19 -3
  17. package/dist/agents.d.ts.map +1 -1
  18. package/dist/channels-q4fwqq87.js +31 -0
  19. package/dist/channels-q4fwqq87.js.map +10 -0
  20. package/dist/channels.d.ts +26 -0
  21. package/dist/channels.d.ts.map +1 -0
  22. package/dist/client.js +10 -10
  23. package/dist/client.js.map +3 -3
  24. package/dist/config-64q4mgxc.js +24 -0
  25. package/dist/{config-g7za9x13.js.map → config-64q4mgxc.js.map} +2 -2
  26. package/dist/{credential-npr6z8c8.js → credential-2sj7vsmw.js} +5 -5
  27. package/dist/{credential-npr6z8c8.js.map → credential-2sj7vsmw.js.map} +1 -1
  28. package/dist/daemon.d.ts.map +1 -1
  29. package/dist/index-0k3w2mxf.js +6 -0
  30. package/dist/{index-hwpvhaza.js.map → index-0k3w2mxf.js.map} +1 -1
  31. package/dist/index-1s81qstp.js +6 -0
  32. package/dist/{index-v8e92nfw.js.map → index-1s81qstp.js.map} +1 -1
  33. package/dist/index-2rycma8x.js +12 -0
  34. package/dist/{index-258d8bzg.js.map → index-2rycma8x.js.map} +4 -3
  35. package/dist/index-2zye08c4.js +6 -0
  36. package/dist/{index-vgc3y3rm.js.map → index-2zye08c4.js.map} +2 -2
  37. package/dist/{index-gme2egyq.js → index-3km1jwh7.js} +4 -4
  38. package/dist/{index-gme2egyq.js.map → index-3km1jwh7.js.map} +1 -1
  39. package/dist/index-3mtgcvkq.js +429 -0
  40. package/dist/index-3mtgcvkq.js.map +11 -0
  41. package/dist/index-4knb5vjm.js +90 -0
  42. package/dist/index-4knb5vjm.js.map +13 -0
  43. package/dist/{index-3g3ny01d.js → index-5nwwekk0.js} +4 -4
  44. package/dist/{index-3g3ny01d.js.map → index-5nwwekk0.js.map} +1 -1
  45. package/dist/index-5rm7dwq4.js +6 -0
  46. package/dist/index-5rm7dwq4.js.map +11 -0
  47. package/dist/index-79epttpm.js +6 -0
  48. package/dist/index-79epttpm.js.map +10 -0
  49. package/dist/{index-4cf6v9nb.js → index-7yk1zvds.js} +4 -4
  50. package/dist/{index-4cf6v9nb.js.map → index-7yk1zvds.js.map} +1 -1
  51. package/dist/index-81gb4ey4.js +6 -0
  52. package/dist/{index-4z7axw4r.js.map → index-81gb4ey4.js.map} +1 -1
  53. package/dist/index-8a5d8sfe.js +6 -0
  54. package/dist/{index-0d93hyfc.js.map → index-8a5d8sfe.js.map} +1 -1
  55. package/dist/index-a21zyy54.js +6 -0
  56. package/dist/index-a21zyy54.js.map +9 -0
  57. package/dist/index-b6da6c16.js +92 -0
  58. package/dist/index-b6da6c16.js.map +15 -0
  59. package/dist/index-byxrc961.js +903 -0
  60. package/dist/{index-tv4yv7d2.js.map → index-byxrc961.js.map} +16 -15
  61. package/dist/{index-ammv5st7.js → index-cgfg6t5a.js} +6 -6
  62. package/dist/{index-ammv5st7.js.map → index-cgfg6t5a.js.map} +1 -1
  63. package/dist/{index-s9mbq7h6.js → index-ehzwdnc3.js} +4 -4
  64. package/dist/{index-s9mbq7h6.js.map → index-ehzwdnc3.js.map} +1 -1
  65. package/dist/index-fzmmhmk2.js +7 -0
  66. package/dist/index-fzmmhmk2.js.map +11 -0
  67. package/dist/index-g3pk0kc0.js +6 -0
  68. package/dist/{index-9r0wyj6w.js.map → index-g3pk0kc0.js.map} +2 -2
  69. package/dist/index-h828nk24.js +153 -0
  70. package/dist/index-h828nk24.js.map +20 -0
  71. package/dist/{index-02dn6m2j.js → index-jq999vcw.js} +5 -5
  72. package/dist/{index-02dn6m2j.js.map → index-jq999vcw.js.map} +2 -2
  73. package/dist/index-k2aq5bg0.js +9 -0
  74. package/dist/{index-6p999cx4.js.map → index-k2aq5bg0.js.map} +4 -6
  75. package/dist/{index-cqqb6gaq.js → index-k3y8y3wj.js} +5 -5
  76. package/dist/{index-cqqb6gaq.js.map → index-k3y8y3wj.js.map} +1 -1
  77. package/dist/index-k59wwdgz.js +9 -0
  78. package/dist/{index-ff514z3y.js.map → index-k59wwdgz.js.map} +3 -5
  79. package/dist/index-nmnnwa02.js +6 -0
  80. package/dist/{index-6q4wf8e3.js.map → index-nmnnwa02.js.map} +1 -1
  81. package/dist/index-nn3tk25c.js +6 -0
  82. package/dist/{index-d4x6yvqh.js.map → index-nn3tk25c.js.map} +3 -4
  83. package/dist/index-q0hxh57v.js +126 -0
  84. package/dist/index-q0hxh57v.js.map +14 -0
  85. package/dist/index-srmhk9g5.js +11 -0
  86. package/dist/index-srmhk9g5.js.map +11 -0
  87. package/dist/index-swtyfhha.js +6 -0
  88. package/dist/{index-fex44816.js.map → index-swtyfhha.js.map} +2 -2
  89. package/dist/index-whq42sat.js +6 -0
  90. package/dist/{index-h9mw7b9d.js.map → index-whq42sat.js.map} +1 -1
  91. package/dist/{index-j7gyr5nx.js → index-wzsmh5j0.js} +7 -7
  92. package/dist/{index-j7gyr5nx.js.map → index-wzsmh5j0.js.map} +1 -1
  93. package/dist/{index-j55s3ehk.js → index-x7v1zq89.js} +7 -7
  94. package/dist/{index-j55s3ehk.js.map → index-x7v1zq89.js.map} +2 -2
  95. package/dist/index-xhzmv4dh.js +66 -0
  96. package/dist/index-xhzmv4dh.js.map +12 -0
  97. package/dist/index-xmv47vs0.js +6 -0
  98. package/dist/{index-gz9x25tz.js.map → index-xmv47vs0.js.map} +2 -2
  99. package/dist/index-y4c32wn7.js +6 -0
  100. package/dist/{index-qdbq8crg.js.map → index-y4c32wn7.js.map} +2 -2
  101. package/dist/index-yjcdp72k.js +6 -0
  102. package/dist/{index-tf71ap9v.js.map → index-yjcdp72k.js.map} +1 -1
  103. package/dist/index-zn24991r.js +6 -0
  104. package/dist/index-zn24991r.js.map +10 -0
  105. package/dist/index.js +374 -443
  106. package/dist/index.js.map +23 -27
  107. package/dist/init.d.ts.map +1 -1
  108. package/dist/lib/channel-actions.d.ts +103 -0
  109. package/dist/lib/channel-actions.d.ts.map +1 -0
  110. package/dist/lib/chat-frame.d.ts +12 -1
  111. package/dist/lib/chat-frame.d.ts.map +1 -1
  112. package/dist/lib/commands.d.ts +13 -0
  113. package/dist/lib/commands.d.ts.map +1 -1
  114. package/dist/lib/const.d.ts +1 -1
  115. package/dist/lib/host-actions.d.ts +121 -0
  116. package/dist/lib/host-actions.d.ts.map +1 -0
  117. package/dist/lib/init-flow.d.ts +32 -0
  118. package/dist/lib/init-flow.d.ts.map +1 -1
  119. package/dist/lib/init-whatsapp.d.ts +52 -0
  120. package/dist/lib/init-whatsapp.d.ts.map +1 -0
  121. package/dist/lib/plugin-install.d.ts +120 -0
  122. package/dist/lib/plugin-install.d.ts.map +1 -0
  123. package/dist/lib/providers.d.ts.map +1 -1
  124. package/dist/lib/provision.d.ts.map +1 -1
  125. package/dist/lib/readme-table.d.ts +15 -0
  126. package/dist/lib/readme-table.d.ts.map +1 -0
  127. package/dist/lib/sandbox.d.ts +15 -0
  128. package/dist/lib/sandbox.d.ts.map +1 -1
  129. package/dist/lib/schema.d.ts +34 -1
  130. package/dist/lib/schema.d.ts.map +1 -1
  131. package/dist/lib/subcommand.d.ts.map +1 -1
  132. package/dist/lib/web-url.d.ts +15 -0
  133. package/dist/lib/web-url.d.ts.map +1 -0
  134. package/dist/lib/wizard.d.ts.map +1 -1
  135. package/dist/memory.d.ts.map +1 -1
  136. package/dist/model.d.ts.map +1 -1
  137. package/dist/plugins.d.ts +27 -8
  138. package/dist/plugins.d.ts.map +1 -1
  139. package/dist/restart.d.ts +21 -0
  140. package/dist/restart.d.ts.map +1 -0
  141. package/dist/run.d.ts.map +1 -1
  142. package/dist/schedules.d.ts.map +1 -1
  143. package/dist/serve.d.ts.map +1 -1
  144. package/dist/sessions.d.ts.map +1 -1
  145. package/dist/skills.d.ts.map +1 -1
  146. package/dist/status.d.ts +16 -0
  147. package/dist/status.d.ts.map +1 -0
  148. package/dist/tools.d.ts.map +1 -1
  149. package/dist/validate.d.ts.map +1 -1
  150. package/dist/web-923c7f5e.js +14 -0
  151. package/dist/{web-vkb16r62.js.map → web-923c7f5e.js.map} +3 -3
  152. package/dist/web.d.ts +2 -13
  153. package/dist/web.d.ts.map +1 -1
  154. package/dist/workspace.d.ts.map +1 -1
  155. package/dist/wrapper-0w9b3my0.js +11 -0
  156. package/dist/wrapper-0w9b3my0.js.map +23 -0
  157. package/package.json +6 -3
  158. package/dist/App-b1yrwrcq.js +0 -11
  159. package/dist/ConfigEditor-n8hdw6r7.js +0 -6
  160. package/dist/KeyProbe-9jjeze5r.js +0 -5
  161. package/dist/Picker-hfeh1g6m.js +0 -5
  162. package/dist/SessionPicker-zyqkg4dn.js +0 -5
  163. package/dist/SkillBrowser-3qdp8080.js +0 -5
  164. package/dist/WizardApp-vzpbydy3.js +0 -5
  165. package/dist/config-g7za9x13.js +0 -24
  166. package/dist/index-0d93hyfc.js +0 -6
  167. package/dist/index-1c5113t4.js +0 -66
  168. package/dist/index-1c5113t4.js.map +0 -12
  169. package/dist/index-258d8bzg.js +0 -12
  170. package/dist/index-4z7axw4r.js +0 -6
  171. package/dist/index-6p999cx4.js +0 -9
  172. package/dist/index-6q4wf8e3.js +0 -6
  173. package/dist/index-9r0wyj6w.js +0 -6
  174. package/dist/index-d4x6yvqh.js +0 -6
  175. package/dist/index-fecm8xe7.js +0 -77
  176. package/dist/index-fecm8xe7.js.map +0 -12
  177. package/dist/index-fex44816.js +0 -6
  178. package/dist/index-ff514z3y.js +0 -14
  179. package/dist/index-gz9x25tz.js +0 -6
  180. package/dist/index-h9mw7b9d.js +0 -6
  181. package/dist/index-hwpvhaza.js +0 -6
  182. package/dist/index-mtn0g9vc.js +0 -7
  183. package/dist/index-mtn0g9vc.js.map +0 -11
  184. package/dist/index-qdbq8crg.js +0 -6
  185. package/dist/index-tf71ap9v.js +0 -6
  186. package/dist/index-ttwyrdjs.js +0 -427
  187. package/dist/index-ttwyrdjs.js.map +0 -11
  188. package/dist/index-tv4yv7d2.js +0 -903
  189. package/dist/index-ty24n0jh.js +0 -167
  190. package/dist/index-ty24n0jh.js.map +0 -19
  191. package/dist/index-v8e92nfw.js +0 -6
  192. package/dist/index-vgc3y3rm.js +0 -6
  193. package/dist/index-whaw4b18.js +0 -6
  194. package/dist/index-whaw4b18.js.map +0 -10
  195. package/dist/web-vkb16r62.js +0 -14
@@ -1,12 +1,10 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/exit.ts", "../src/lib/keyboard.ts", "../src/lib/output.ts"],
3
+ "sources": ["../src/lib/exit.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * One way out of the process.\n *\n * Two failure modes this exists to prevent, both of which the previous CLI had:\n *\n * **A hidden cursor and a terminal left in raw mode.** Ink hides the cursor and puts stdin in raw\n * mode. `process.exit()` from anywhere else — an error path, a signal, an uncaught rejection —\n * skips React's cleanup, and the shell you get back does not echo what you type. Recovering needs\n * `stty sane`, and nothing tells you that. So the restore is registered on `process.on(\"exit\")`\n * as well as run explicitly: whatever route the process takes out, the terminal is handed back.\n *\n * **Truncated output.** `process.stdout.write` to a *pipe* is asynchronous, and `process.exit()`\n * discards whatever has not flushed — so a `sessions … | head` invocation could lose its last lines,\n * intermittently and only when piped. Measured: 10 MB written and then exited immediately arrives as\n * **65,536 bytes**, one pipe buffer.\n *\n * The rule used to be \"set `process.exitCode` and let the event loop drain\", and that rule assumed the\n * loop *can* drain. It cannot. A command that boots a runtime leaves a keep-alive TLS socket to the\n * tool provider in Node's global `fetch` pool — `backend.composio.dev:443`, opened by the\n * post-readiness refresh — and that socket is ref'd, with no public API to close it. Measured: the\n * process was still alive **180 seconds** after `/exit`, and the `tools` command had to be killed at 30 s.\n * `^C` appeared to work only because SIGINT is deliberately unhandled here, so the default action kills\n * the process. a `tools --json | jq` invocation would have waited forever.\n *\n * So the rule is now: run the teardowns, drain the output *properly*, then leave. Both halves are\n * load-bearing — draining without leaving is the hang above, and leaving without draining is the\n * truncation above.\n */\n\nimport {\n DISABLE_ENHANCED_KEYS,\n EXIT_FAILURE,\n EXIT_SIGTERM,\n LEAVE_ALT_SCREEN,\n RESET_STYLE,\n SHOW_CURSOR,\n} from \"#lib/const\"\nimport { DISABLE_MOUSE } from \"#lib/mouse\"\nimport type { TerminalHandles } from \"#lib/schema\"\n\n/**\n * The real streams. Spelled out rather than passing `process` itself, which has no `in`/`out` —\n * that mistake typechecked against the structural type and threw only at runtime, inside the one\n * function whose entire job is to run when things have already gone wrong.\n */\nfunction processHandles(): TerminalHandles {\n return { out: process.stdout, in: process.stdin }\n}\n\ntype Teardown = () => void | Promise<void>\n\nconst teardowns: Teardown[] = []\nlet guardsInstalled = false\nlet restored = false\nlet dirty = false\nlet altScreen = false\nlet mouse = false\nlet enhancedKeys = false\nlet signalsClaimed = false\n\n/**\n * Declare that the terminal has been put into a state that needs undoing — raw mode, a hidden\n * cursor, alternate styling. Only the rich path does this.\n *\n * Without the flag, the restore would fire on *every* exit, including the plain path, which puts a\n * cursor-and-style reset at the end of output that is otherwise pure text. That breaks the property\n * plain mode exists for: `--plain` at a terminal has to produce exactly what a pipe produces.\n */\nexport function markTerminalDirty(): void {\n dirty = true\n}\n\n/**\n * Declare that the alternate screen buffer has been entered, so the restore swaps back out of it.\n *\n * Separate from `markTerminalDirty` rather than folded into it, because the two are not the same\n * claim: every rich surface dirties the terminal, and only the ones that *take* it need swapping\n * back. Folding them together would write the leave sequence after every wizard and every chat\n * session, and a `1049l` sent to a terminal that never entered the buffer clears the screen the\n * output was just written to — the plain path's parity rule, broken in the least debuggable way.\n *\n * Setting this and never entering is therefore worse than the reverse. The host that writes\n * `ENTER_ALT_SCREEN` calls this in the same statement.\n */\nexport function markAltScreen(): void {\n dirty = true\n altScreen = true\n}\n\n/**\n * The session asked the terminal to report the mouse, so the terminal has to be told to stop.\n *\n * Separate from `markAltScreen` because only the chat reads mouse reports. A surface that enabled\n * tracking without claiming every report would have them typed into it as text, which is what Ink does\n * with one — so the flag follows whoever handles them rather than whoever took the screen.\n *\n * Left on, the shell that gets the terminal back emits a report on every click and scroll, into a prompt\n * that has no idea what they are. That is the failure worth being loud about: it outlives the process.\n */\nexport function markMouse(): void {\n dirty = true\n mouse = true\n}\n\n/**\n * Ink negotiated the kitty keyboard protocol, so the terminal has to be told to stop reporting that way.\n *\n * Ink pops it itself on unmount and around a suspend — this exists for the path it cannot cover, which is\n * the same one `markMouse` exists for: a signal. `SIGTERM` is the only route a service manager uses, and\n * a terminal left in the protocol hands the next shell `CSI u` for every Ctrl chord, which reads as a\n * broken keyboard and outlives the process.\n *\n * Set by the render sites rather than derived, because whether the protocol was actually *pushed* depends\n * on the terminal answering a query 200 ms after mount — so the honest flag is \"we asked\", and popping a\n * protocol that was never pushed is a no-op on every terminal.\n */\nexport function markEnhancedKeys(): void {\n dirty = true\n enhancedKeys = true\n}\n\n/**\n * Run before the process ends. Registration order is preserved and reversed on the way out, so a\n * later-registered resource is released before the thing it depends on.\n */\nexport function onExit(teardown: Teardown): void {\n teardowns.push(teardown)\n}\n\n/**\n * Take ownership of SIGTERM, for a command whose shutdown *is* the point.\n *\n * The default guard answers SIGTERM with `finishNow(EXIT_SIGTERM)`, which is right for a command\n * that was interrupted: 143 is the shell convention and the work was not finished. It is wrong for\n * `serve`, where a signal is the ordinary and expected way to stop — the work was to stay up, and\n * being asked to stop is the successful end of it, not a failure.\n *\n * That distinction is not cosmetic once a service manager is involved. The generated service\n * definition restarts only on a crash, precisely so a misconfiguration stops once instead of\n * looping forever; a graceful stop reported as 143 is indistinguishable from that misconfiguration,\n * so the supervisor would refuse to bring the agent back.\n *\n * The caller must resolve its own wait on the signal and return an exit code normally. Everything\n * registered with `onExit` still runs, because `finish` awaits the teardowns either way.\n */\nexport function claimSignals(): void {\n signalsClaimed = true\n}\n\n/**\n * Synchronous by necessity — `process.on(\"exit\")` cannot await. Idempotent, because it runs both\n * explicitly and from the exit hook.\n */\nexport function restoreTerminal(handles: TerminalHandles = processHandles()): void {\n if (restored || !dirty) return\n restored = true\n if (handles.in.isTTY === true && handles.in.setRawMode !== undefined) {\n handles.in.setRawMode(false)\n }\n if (handles.out.isTTY !== true) return\n // Style and cursor first, buffer swap second. A reset applies to the buffer that is current when\n // it arrives, so resetting after the swap leaves the app's last colour on the shell's screen and\n // dutifully resets the one being thrown away.\n handles.out.write(`${RESET_STYLE}${SHOW_CURSOR}`)\n // Before the buffer swap, for the same reason the style reset is: the request was made against this\n // buffer and the shell must not be left with a terminal that reports clicks at it.\n if (mouse) handles.out.write(DISABLE_MOUSE)\n // Before the buffer swap for the same reason, and after the mouse for no reason but stable ordering\n // — a test asserts the sequence, and an order nothing pins is an order that drifts.\n //\n // This is usually the *second* pop: Ink pops on unmount, and on both the normal and the signal path\n // the unmount teardown has already run by the time this fires. Kept anyway, because the path it exists\n // for is the one where teardowns do not run at all — a hard crash — and a terminal left reporting\n // `CSI u` for every Ctrl chord outlives the process. Seen in a capture as `[<u[<u`.\n //\n // The cost is stated rather than hidden. A pop on an empty stack is ignored, so standalone this is\n // harmless; nested inside *another* application that pushed its own flags, the extra pop takes that\n // application's entry instead. That trade is accepted for a top-level CLI and would be the wrong one\n // for a library.\n if (enhancedKeys) handles.out.write(DISABLE_ENHANCED_KEYS)\n if (altScreen) handles.out.write(LEAVE_ALT_SCREEN)\n}\n\n/** Test seam. Nothing in `src/` outside this module calls it. */\nexport function resetForTests(\n options: {\n readonly dirty?: boolean\n readonly altScreen?: boolean\n readonly mouse?: boolean\n readonly enhancedKeys?: boolean\n } = {},\n): void {\n teardowns.length = 0\n restored = false\n dirty = options.dirty ?? true\n altScreen = options.altScreen ?? false\n mouse = options.mouse ?? false\n enhancedKeys = options.enhancedKeys ?? false\n signalsClaimed = false\n}\n\n/** Enough of a stream to wait on. Spelled out so a test can supply one without a pipe. */\ninterface Drainable {\n write(chunk: string, callback: () => void): unknown\n readonly writableEnded?: boolean\n readonly destroyed?: boolean\n}\n\n/**\n * Wait until everything written to stdout has actually reached the operating system.\n *\n * This used to test `writableNeedDrain` and await a `drain` event, which is a weaker claim than it\n * reads as: the flag is only true once the buffer is *over* the high-water mark, so a modest pending\n * write to a pipe reported nothing to wait for and the function named \"flush\" returned immediately.\n * That was survivable while the process went on to idle until the loop emptied, and is not survivable\n * now that it exits on purpose.\n *\n * A zero-length write is the receipt. `Writable` invokes callbacks in write order once the underlying\n * write completes, so a chunk queued behind everything else calls back only after everything else has\n * gone out. Measured against a pipe with a sleeping reader: 10 MB exits complete, where an immediate\n * `process.exit` delivered 65,536 bytes.\n *\n * **The wait is deliberately unbounded.** A timeout would trade a silent truncation for a bounded exit,\n * and with a slow reader — `| less`, a terminal being scrolled — truncation is the worse of the two. A\n * closed reader is not the hazard it looks like: the callback still fires, carrying `EPIPE`.\n *\n * Also awaited between turns, where the point is different: a long session feeding a slow reader\n * accumulates unwritten output in memory, and this bounds that to one turn's worth.\n */\nexport async function flushOutput(stream: Drainable = process.stdout): Promise<void> {\n // Nothing to wait for, and writing would throw. Checked rather than caught, because a throw here\n // lands inside the function whose whole job is to run when things are already ending.\n if (stream.writableEnded === true || stream.destroyed === true) return\n await new Promise<void>((resolve) => {\n stream.write(\"\", () => resolve())\n })\n}\n\nasync function runTeardowns(): Promise<void> {\n for (const teardown of [...teardowns].reverse()) {\n try {\n await teardown()\n } catch (error) {\n // A failing teardown must not mask the exit code that brought us here, and must not\n // stop the remaining teardowns — the terminal restore is one of them.\n process.stderr.write(\n `warning: cleanup failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n }\n }\n teardowns.length = 0\n}\n\n/**\n * Everything that has to happen before the process ends: teardowns, the terminal, the exit code, and\n * the output.\n *\n * Sets `process.exitCode` rather than exiting, so a caller that has its own reason to stay alive can.\n * Nothing in `src/` is such a caller any more — the entry point uses `finishNow` — but the split is\n * what makes this testable: a `finish` that exited would take the test runner with it.\n */\nexport async function finish(code: number): Promise<void> {\n await runTeardowns()\n restoreTerminal()\n process.exitCode = code\n await flushOutput()\n}\n\n/**\n * Finish, and then actually leave.\n *\n * The ordinary way out, not the exceptional one. It was written for a signal or a crash — \"where\n * waiting for the loop to drain would mean hanging\" — on the assumption that the ordinary path could\n * wait. It cannot: the module docstring records the measurement, a keep-alive socket in the global\n * `fetch` pool that outlived the process by three minutes.\n *\n * Safe to call here and nowhere earlier, because `finish` has already awaited the teardowns and the\n * output. Anything still holding the loop open at this point is a resource with no owner, and waiting\n * on one is what the hang was.\n */\nexport async function finishNow(code: number): Promise<never> {\n await finish(code)\n process.exit(code)\n}\n\n/**\n * Guards for the ways a process dies without being asked to.\n *\n * `SIGINT` is deliberately **not** handled here. During a turn it means \"cancel this turn\", not\n * \"exit\" — the chat path owns it, and a guard that exited would break the contract Phase 1\n * established and measured.\n */\nexport function installGuards(): void {\n if (guardsInstalled) return\n guardsInstalled = true\n\n // Last line of defence. Runs even when something calls process.exit directly.\n process.on(\"exit\", () => restoreTerminal())\n\n process.on(\"SIGTERM\", () => {\n // Yield to a command that owns its own shutdown. Without this the two handlers raced and\n // the hard exit won: `serve`'s graceful path started, `process.exit(143)` landed first, and\n // `runtime.stop()` never completed — so the outbox was not flushed, the database was not\n // closed, and the child processes `exec` backgrounds were never reaped. Invisible at a\n // terminal, because ctrl-C sends SIGINT and this guard deliberately ignores that one.\n if (signalsClaimed) return\n void finishNow(EXIT_SIGTERM)\n })\n\n const crash = (label: string) => (error: unknown) => {\n restoreTerminal()\n const message = error instanceof Error ? (error.stack ?? error.message) : String(error)\n // Loud and non-zero. An unexpected failure that exits 0 is the thing hard rule 8 forbids.\n process.stderr.write(`\\n${label}: ${message}\\n`)\n void finishNow(EXIT_FAILURE)\n }\n process.on(\"uncaughtException\", crash(\"uncaught exception\"))\n process.on(\"unhandledRejection\", crash(\"unhandled rejection\"))\n}\n",
6
- "/**\n * Whether this process asks the terminal for enhanced keys, and what it asks for.\n *\n * ## Why there is anything to ask for\n *\n * Ink 7.1 ships a complete kitty-keyboard-protocol parser — `parse-keypress.js` decodes `CSI u`, and\n * `Key` carries `super`, `hyper`, `home` and `end` — and **none of it runs unless a caller opts in**:\n *\n * initKittyKeyboard() {\n * // Protocol is opt-in: if kittyKeyboard is not specified, do nothing\n * if (!this.options.kittyKeyboard) return\n *\n * That single `return` is why `⌥r` typed `®` into the message instead of unfolding the reasoning block,\n * and why `cmd+←` word-moved instead of jumping to the start of the line: without the protocol, `⌥`\n * depends on a terminal setting that is off by default in Warp, and `super` cannot be expressed by any\n * legacy escape sequence at all — Ink's legacy branch folds it into `meta` (`modifier & 10`, bit 8 being\n * super and bit 2 alt), so the two chords become the same keystroke.\n *\n * ## Why both flags\n *\n * `disambiguateEscapeCodes` alone fixes the letter chords: `⌥r` arrives as `CSI 114;3u`, which Ink reports\n * as `input \"r\"` with `meta` set — exactly the shape `keymap.ts` already matched, which is why turning\n * this on required no change to a single binding. It is **not** enough for `cmd+←`: an arrow with a\n * modifier comes back as `CSI 1;9D`, and Ink's kitty branch for special keys (`kittySpecialKeyRe`)\n * *requires* the `:eventType` field, so without `reportEventTypes` the sequence falls through to the\n * legacy path and the super bit is folded away again.\n *\n * The cost of that second flag is stated where it is paid: Ink passes `eventType` through untouched and\n * filters nothing, so `keymap.ts` drops `release` or every enhanced chord fires twice.\n *\n * ## Why `enabled` rather than `auto`, measured\n *\n * `auto` is the careful-looking option: Ink writes `CSI ? u`, waits **200 ms**, and enables only if the\n * terminal answers. It was the first choice here and it loses the race. In a real Warp session the reply\n * arrived *after* the window closed — visible in `keys` as `bytes 1b 5b 3f 30 75` resolving to an insert,\n * because Ink strips the answer only while it is still listening. So the protocol stayed **off** on a\n * terminal that plainly supports it, and every option-letter chord went on depending on Warp's\n * *Left/Right Option Key is Meta* setting, which is off by default. That is the reported bug, one layer\n * down from where it looked like it was.\n *\n * `enabled` pushes `CSI > flags u` without asking. The cost is bounded by how terminals treat private-mode\n * sequences they do not know — they discard them — and the pop on the way out is the same shape. It is\n * also no longer load-bearing: `lib/csi.ts` reads modifiers off the bytes, so a terminal that ignores the\n * push still gets working cmd chords. The protocol now buys the *letter* chords, and losing it silently\n * costs those rather than everything.\n *\n * The override stays for the case neither argument covers: a terminal that accepts the push and then\n * implements it badly. The reference CLI carries the same hatch (`CLAUDE_CODE_DISABLE_MOUSE`), and a\n * switch nobody can reach is not a hatch.\n */\n\nimport { readEnv } from \"#lib/env\"\n/**\n * The render options fragment, shaped structurally rather than imported from Ink.\n *\n * Declared here for the same reason `KeyState` is declared in `lib/types.ts` rather than imported: this\n * module sits on a path every command touches, and Ink costs ~170-210 ms to load under Node — more than\n * the entire runtime of `validate --json`. TypeScript checks it structurally against `RenderOptions` at\n * each call site, so a drift in Ink's own type is still a compile error.\n */\nimport { markEnhancedKeys } from \"#lib/exit\"\n\nexport interface KeyboardOptions {\n readonly kittyKeyboard?: {\n readonly mode: \"auto\" | \"enabled\" | \"disabled\"\n /**\n * The property is readonly; the array is not, because Ink's own `flags` is a mutable\n * `KittyFlagName[]` and under `exactOptionalPropertyTypes` a `readonly` array does not satisfy\n * it. Nothing is shared as a result — `keyboardOptions` builds a fresh array on every call, which\n * is what makes the mutable type harmless rather than a hole.\n */\n readonly flags: (\"disambiguateEscapeCodes\" | \"reportEventTypes\")[]\n }\n}\n\n/**\n * One answer for every surface that mounts Ink, and the teardown registered with it.\n *\n * Every one of them reads keys, so a per-surface decision would mean the chat honoured `cmd+←` and the\n * settings editor did not — and the *next* surface would forget entirely. `inSession` on `CommandSpec` is\n * the same shape: derived once so a new caller cannot drift.\n *\n * It marks rather than merely returning, which is why it is not called `keyboardOptions`: asking for the\n * protocol and arranging to withdraw it are one decision, and six call sites each remembering to do the\n * second is six chances to leave a terminal reporting `CSI u` at somebody's shell. Ink withdraws it on\n * unmount by itself; the mark covers the signal path, which is the one Ink cannot see.\n */\nexport function negotiateKeyboard(disabled?: boolean): KeyboardOptions {\n // `??` rather than a default parameter: a default fires on an explicitly passed `undefined` too, and\n // this repo has already lost a debugging round to that (`load(dir, undefined)` used the runner it was\n // meant to omit). Written this way, \"no opinion\" and \"not passed\" are deliberately the same case.\n if (disabled ?? readEnv().noEnhancedKeys) return {}\n markEnhancedKeys()\n return {\n kittyKeyboard: {\n // Not \"auto\" — see above. Ink's 200 ms detection window loses the race in Warp, measured.\n mode: \"enabled\",\n flags: [\"disambiguateEscapeCodes\", \"reportEventTypes\"],\n },\n }\n}\n",
7
- "/**\n * How output is rendered, resolved once per process.\n *\n * This mirrors the reasoning behind decision 3.5, which forbids the tool dialect from changing with\n * the model: behaviour that shifts silently with the environment cannot be reasoned about. So the\n * resolution is total and ordered, and it returns *why* it chose — the reason is printable, which is\n * what turns \"it wasn't interactive and I don't know why\" into a question with an answer.\n *\n * Measured, not assumed: importing Ink and React costs ~65 ms under Bun and ~170-210 ms under Node,\n * against a ~70 ms total runtime for `validate --json`. Nothing on a non-rich path may import them,\n * which is why this returns a mode rather than a renderer.\n */\n\nimport { readEnv } from \"#lib/env\"\nimport type { ModeDecision, ModeInputs } from \"#lib/schema\"\n\n/**\n * Total and ordered. Every branch is reachable and every input is consulted, so no combination of\n * flags and environment lands somewhere undocumented.\n */\nexport function resolveMode(inputs: ModeInputs): ModeDecision {\n if (inputs.json) return { mode: \"json\", because: \"--json was passed\" }\n if (inputs.plain) return { mode: \"plain\", because: \"--plain was passed\" }\n\n // A one-shot is a scripting affordance. Its output must not depend on whether a human happened\n // to be at a terminal, or `--input` would mean two different things in a shell script and in a\n // shell.\n if (inputs.oneShot) return { mode: \"plain\", because: \"--input is always plain\" }\n\n if (!inputs.stdoutIsTTY) return { mode: \"plain\", because: \"stdout is not a terminal\" }\n // A live transcript with no way to type into it is a worse plain renderer, not a better one.\n if (!inputs.stdinIsTTY) return { mode: \"plain\", because: \"stdin is not a terminal\" }\n\n if (inputs.env.noColor) return { mode: \"plain\", because: \"NO_COLOR is set\" }\n if (inputs.env.dumbTerminal) return { mode: \"plain\", because: \"TERM is dumb\" }\n // CI logs are files that happen to scroll. Cursor movement in one is noise forever.\n if (inputs.env.ci) return { mode: \"plain\", because: \"CI is set\" }\n\n return { mode: \"rich\", because: \"stdout and stdin are both terminals\" }\n}\n\n/**\n * Deliberately not consulted: `FORCE_COLOR`. It says how much colour a stream can carry, not\n * whether a human is watching, and honouring it here would turn a CI job that wanted coloured logs\n * into one driving a cursor around a file. Ink's own colour depth still respects it.\n */\nexport function resolveModeFromProcess(flags: {\n readonly json: boolean\n readonly plain: boolean\n readonly oneShot: boolean\n}): ModeDecision {\n return resolveMode({\n ...flags,\n stdinIsTTY: process.stdin.isTTY === true,\n stdoutIsTTY: process.stdout.isTTY === true,\n env: readEnv(),\n })\n}\n"
5
+ "/**\n * One way out of the process.\n *\n * Two failure modes this exists to prevent, both of which the previous CLI had:\n *\n * **A hidden cursor and a terminal left in raw mode.** Ink hides the cursor and puts stdin in raw\n * mode. `process.exit()` from anywhere else — an error path, a signal, an uncaught rejection —\n * skips React's cleanup, and the shell you get back does not echo what you type. Recovering needs\n * `stty sane`, and nothing tells you that. So the restore is registered on `process.on(\"exit\")`\n * as well as run explicitly: whatever route the process takes out, the terminal is handed back.\n *\n * **Truncated output.** `process.stdout.write` to a *pipe* is asynchronous, and `process.exit()`\n * discards whatever has not flushed — so a `sessions … | head` invocation could lose its last lines,\n * intermittently and only when piped. Measured: 10 MB written and then exited immediately arrives as\n * **65,536 bytes**, one pipe buffer.\n *\n * The rule used to be \"set `process.exitCode` and let the event loop drain\", and that rule assumed the\n * loop *can* drain. It cannot. A command that boots a runtime leaves a keep-alive TLS socket to the\n * tool provider in Node's global `fetch` pool — `backend.composio.dev:443`, opened by the\n * post-readiness refresh — and that socket is ref'd, with no public API to close it. Measured: the\n * process was still alive **180 seconds** after `/exit`, and the `tools` command had to be killed at 30 s.\n * `^C` appeared to work only because SIGINT is deliberately unhandled here, so the default action kills\n * the process. a `tools --json | jq` invocation would have waited forever.\n *\n * So the rule is now: run the teardowns, drain the output *properly*, then leave. Both halves are\n * load-bearing — draining without leaving is the hang above, and leaving without draining is the\n * truncation above.\n */\n\nimport {\n DISABLE_ENHANCED_KEYS,\n EXIT_FAILURE,\n EXIT_SIGTERM,\n LEAVE_ALT_SCREEN,\n RESET_STYLE,\n SHOW_CURSOR,\n} from \"#lib/const\"\nimport { DISABLE_MOUSE } from \"#lib/mouse\"\nimport type { TerminalHandles } from \"#lib/schema\"\n\n/**\n * The real streams. Spelled out rather than passing `process` itself, which has no `in`/`out` —\n * that mistake typechecked against the structural type and threw only at runtime, inside the one\n * function whose entire job is to run when things have already gone wrong.\n */\nfunction processHandles(): TerminalHandles {\n return { out: process.stdout, in: process.stdin }\n}\n\ntype Teardown = () => void | Promise<void>\n\nconst teardowns: Teardown[] = []\nlet guardsInstalled = false\nlet restored = false\nlet dirty = false\nlet altScreen = false\nlet mouse = false\nlet enhancedKeys = false\nlet signalsClaimed = false\n\n/**\n * Declare that the terminal has been put into a state that needs undoing — raw mode, a hidden\n * cursor, alternate styling. Only the rich path does this.\n *\n * Without the flag, the restore would fire on *every* exit, including the plain path, which puts a\n * cursor-and-style reset at the end of output that is otherwise pure text. That breaks the property\n * plain mode exists for: `--plain` at a terminal has to produce exactly what a pipe produces.\n */\nexport function markTerminalDirty(): void {\n dirty = true\n}\n\n/**\n * Declare that the alternate screen buffer has been entered, so the restore swaps back out of it.\n *\n * Separate from `markTerminalDirty` rather than folded into it, because the two are not the same\n * claim: every rich surface dirties the terminal, and only the ones that *take* it need swapping\n * back. Folding them together would write the leave sequence after every wizard and every chat\n * session, and a `1049l` sent to a terminal that never entered the buffer clears the screen the\n * output was just written to — the plain path's parity rule, broken in the least debuggable way.\n *\n * Setting this and never entering is therefore worse than the reverse. The host that writes\n * `ENTER_ALT_SCREEN` calls this in the same statement.\n */\nexport function markAltScreen(): void {\n dirty = true\n altScreen = true\n}\n\n/**\n * The session asked the terminal to report the mouse, so the terminal has to be told to stop.\n *\n * Separate from `markAltScreen` because only the chat reads mouse reports. A surface that enabled\n * tracking without claiming every report would have them typed into it as text, which is what Ink does\n * with one — so the flag follows whoever handles them rather than whoever took the screen.\n *\n * Left on, the shell that gets the terminal back emits a report on every click and scroll, into a prompt\n * that has no idea what they are. That is the failure worth being loud about: it outlives the process.\n */\nexport function markMouse(): void {\n dirty = true\n mouse = true\n}\n\n/**\n * Ink negotiated the kitty keyboard protocol, so the terminal has to be told to stop reporting that way.\n *\n * Ink pops it itself on unmount and around a suspend — this exists for the path it cannot cover, which is\n * the same one `markMouse` exists for: a signal. `SIGTERM` is the only route a service manager uses, and\n * a terminal left in the protocol hands the next shell `CSI u` for every Ctrl chord, which reads as a\n * broken keyboard and outlives the process.\n *\n * Set by the render sites rather than derived, because whether the protocol was actually *pushed* depends\n * on the terminal answering a query 200 ms after mount — so the honest flag is \"we asked\", and popping a\n * protocol that was never pushed is a no-op on every terminal.\n */\nexport function markEnhancedKeys(): void {\n dirty = true\n enhancedKeys = true\n}\n\n/**\n * Run before the process ends. Registration order is preserved and reversed on the way out, so a\n * later-registered resource is released before the thing it depends on.\n */\nexport function onExit(teardown: Teardown): void {\n teardowns.push(teardown)\n}\n\n/**\n * Take ownership of SIGTERM, for a command whose shutdown *is* the point.\n *\n * The default guard answers SIGTERM with `finishNow(EXIT_SIGTERM)`, which is right for a command\n * that was interrupted: 143 is the shell convention and the work was not finished. It is wrong for\n * `serve`, where a signal is the ordinary and expected way to stop — the work was to stay up, and\n * being asked to stop is the successful end of it, not a failure.\n *\n * That distinction is not cosmetic once a service manager is involved. The generated service\n * definition restarts only on a crash, precisely so a misconfiguration stops once instead of\n * looping forever; a graceful stop reported as 143 is indistinguishable from that misconfiguration,\n * so the supervisor would refuse to bring the agent back.\n *\n * The caller must resolve its own wait on the signal and return an exit code normally. Everything\n * registered with `onExit` still runs, because `finish` awaits the teardowns either way.\n */\nexport function claimSignals(): void {\n signalsClaimed = true\n}\n\n/**\n * Synchronous by necessity — `process.on(\"exit\")` cannot await. Idempotent, because it runs both\n * explicitly and from the exit hook.\n */\nexport function restoreTerminal(handles: TerminalHandles = processHandles()): void {\n if (restored || !dirty) return\n restored = true\n if (handles.in.isTTY === true && handles.in.setRawMode !== undefined) {\n handles.in.setRawMode(false)\n }\n if (handles.out.isTTY !== true) return\n // Style and cursor first, buffer swap second. A reset applies to the buffer that is current when\n // it arrives, so resetting after the swap leaves the app's last colour on the shell's screen and\n // dutifully resets the one being thrown away.\n handles.out.write(`${RESET_STYLE}${SHOW_CURSOR}`)\n // Before the buffer swap, for the same reason the style reset is: the request was made against this\n // buffer and the shell must not be left with a terminal that reports clicks at it.\n if (mouse) handles.out.write(DISABLE_MOUSE)\n // Before the buffer swap for the same reason, and after the mouse for no reason but stable ordering\n // — a test asserts the sequence, and an order nothing pins is an order that drifts.\n //\n // This is usually the *second* pop: Ink pops on unmount, and on both the normal and the signal path\n // the unmount teardown has already run by the time this fires. Kept anyway, because the path it exists\n // for is the one where teardowns do not run at all — a hard crash — and a terminal left reporting\n // `CSI u` for every Ctrl chord outlives the process. Seen in a capture as `[<u[<u`.\n //\n // The cost is stated rather than hidden. A pop on an empty stack is ignored, so standalone this is\n // harmless; nested inside *another* application that pushed its own flags, the extra pop takes that\n // application's entry instead. That trade is accepted for a top-level CLI and would be the wrong one\n // for a library.\n if (enhancedKeys) handles.out.write(DISABLE_ENHANCED_KEYS)\n if (altScreen) handles.out.write(LEAVE_ALT_SCREEN)\n}\n\n/** Test seam. Nothing in `src/` outside this module calls it. */\nexport function resetForTests(\n options: {\n readonly dirty?: boolean\n readonly altScreen?: boolean\n readonly mouse?: boolean\n readonly enhancedKeys?: boolean\n } = {},\n): void {\n teardowns.length = 0\n restored = false\n dirty = options.dirty ?? true\n altScreen = options.altScreen ?? false\n mouse = options.mouse ?? false\n enhancedKeys = options.enhancedKeys ?? false\n signalsClaimed = false\n}\n\n/** Enough of a stream to wait on. Spelled out so a test can supply one without a pipe. */\ninterface Drainable {\n write(chunk: string, callback: () => void): unknown\n readonly writableEnded?: boolean\n readonly destroyed?: boolean\n}\n\n/**\n * Wait until everything written to stdout has actually reached the operating system.\n *\n * This used to test `writableNeedDrain` and await a `drain` event, which is a weaker claim than it\n * reads as: the flag is only true once the buffer is *over* the high-water mark, so a modest pending\n * write to a pipe reported nothing to wait for and the function named \"flush\" returned immediately.\n * That was survivable while the process went on to idle until the loop emptied, and is not survivable\n * now that it exits on purpose.\n *\n * A zero-length write is the receipt. `Writable` invokes callbacks in write order once the underlying\n * write completes, so a chunk queued behind everything else calls back only after everything else has\n * gone out. Measured against a pipe with a sleeping reader: 10 MB exits complete, where an immediate\n * `process.exit` delivered 65,536 bytes.\n *\n * **The wait is deliberately unbounded.** A timeout would trade a silent truncation for a bounded exit,\n * and with a slow reader — `| less`, a terminal being scrolled — truncation is the worse of the two. A\n * closed reader is not the hazard it looks like: the callback still fires, carrying `EPIPE`.\n *\n * Also awaited between turns, where the point is different: a long session feeding a slow reader\n * accumulates unwritten output in memory, and this bounds that to one turn's worth.\n */\nexport async function flushOutput(stream: Drainable = process.stdout): Promise<void> {\n // Nothing to wait for, and writing would throw. Checked rather than caught, because a throw here\n // lands inside the function whose whole job is to run when things are already ending.\n if (stream.writableEnded === true || stream.destroyed === true) return\n await new Promise<void>((resolve) => {\n stream.write(\"\", () => resolve())\n })\n}\n\nasync function runTeardowns(): Promise<void> {\n for (const teardown of [...teardowns].reverse()) {\n try {\n await teardown()\n } catch (error) {\n // A failing teardown must not mask the exit code that brought us here, and must not\n // stop the remaining teardowns — the terminal restore is one of them.\n process.stderr.write(\n `warning: cleanup failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n }\n }\n teardowns.length = 0\n}\n\n/**\n * Everything that has to happen before the process ends: teardowns, the terminal, the exit code, and\n * the output.\n *\n * Sets `process.exitCode` rather than exiting, so a caller that has its own reason to stay alive can.\n * Nothing in `src/` is such a caller any more — the entry point uses `finishNow` — but the split is\n * what makes this testable: a `finish` that exited would take the test runner with it.\n */\nexport async function finish(code: number): Promise<void> {\n await runTeardowns()\n restoreTerminal()\n process.exitCode = code\n await flushOutput()\n}\n\n/**\n * Finish, and then actually leave.\n *\n * The ordinary way out, not the exceptional one. It was written for a signal or a crash — \"where\n * waiting for the loop to drain would mean hanging\" — on the assumption that the ordinary path could\n * wait. It cannot: the module docstring records the measurement, a keep-alive socket in the global\n * `fetch` pool that outlived the process by three minutes.\n *\n * Safe to call here and nowhere earlier, because `finish` has already awaited the teardowns and the\n * output. Anything still holding the loop open at this point is a resource with no owner, and waiting\n * on one is what the hang was.\n */\nexport async function finishNow(code: number): Promise<never> {\n await finish(code)\n process.exit(code)\n}\n\n/**\n * Guards for the ways a process dies without being asked to.\n *\n * `SIGINT` is deliberately **not** handled here. During a turn it means \"cancel this turn\", not\n * \"exit\" — the chat path owns it, and a guard that exited would break the contract Phase 1\n * established and measured.\n */\nexport function installGuards(): void {\n if (guardsInstalled) return\n guardsInstalled = true\n\n // Last line of defence. Runs even when something calls process.exit directly.\n process.on(\"exit\", () => restoreTerminal())\n\n process.on(\"SIGTERM\", () => {\n // Yield to a command that owns its own shutdown. Without this the two handlers raced and\n // the hard exit won: `serve`'s graceful path started, `process.exit(143)` landed first, and\n // `runtime.stop()` never completed — so the outbox was not flushed, the database was not\n // closed, and the child processes `exec` backgrounds were never reaped. Invisible at a\n // terminal, because ctrl-C sends SIGINT and this guard deliberately ignores that one.\n if (signalsClaimed) return\n void finishNow(EXIT_SIGTERM)\n })\n\n const crash = (label: string) => (error: unknown) => {\n restoreTerminal()\n const message = error instanceof Error ? (error.stack ?? error.message) : String(error)\n // Loud and non-zero. An unexpected failure that exits 0 is the thing hard rule 8 forbids.\n process.stderr.write(`\\n${label}: ${message}\\n`)\n void finishNow(EXIT_FAILURE)\n }\n process.on(\"uncaughtException\", crash(\"uncaught exception\"))\n process.on(\"unhandledRejection\", crash(\"unhandled rejection\"))\n}\n"
8
6
  ],
9
- "mappings": ";0HA6CA,SAAS,CAAc,EAAoB,CACvC,MAAO,CAAE,IAAK,QAAQ,OAAQ,GAAI,QAAQ,KAAM,EAKpD,IAAM,EAAwB,CAAC,EAC3B,EAAkB,GAClB,EAAW,GACX,EAAQ,GACR,EAAY,GACZ,EAAQ,GACR,EAAe,GACf,EAAiB,GAUd,SAAS,EAAiB,EAAS,CACtC,EAAQ,GAeL,SAAS,EAAa,EAAS,CAClC,EAAQ,GACR,EAAY,GAaT,SAAS,EAAS,EAAS,CAC9B,EAAQ,GACR,EAAQ,GAeL,SAAS,CAAgB,EAAS,CACrC,EAAQ,GACR,EAAe,GAOZ,SAAS,CAAM,CAAC,EAA0B,CAC7C,EAAU,KAAK,CAAQ,EAmBpB,SAAS,EAAY,EAAS,CACjC,EAAiB,GAOd,SAAS,CAAe,CAAC,EAA2B,EAAe,EAAS,CAC/E,GAAI,GAAY,CAAC,EAAO,OAExB,GADA,EAAW,GACP,EAAQ,GAAG,QAAU,IAAQ,EAAQ,GAAG,aAAe,OACvD,EAAQ,GAAG,WAAW,EAAK,EAE/B,GAAI,EAAQ,IAAI,QAAU,GAAM,OAOhC,GAHA,EAAQ,IAAI,MAAM,GAAG,KAAc,IAAa,EAG5C,EAAO,EAAQ,IAAI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kB,GAGlB,QAAQ,GAAG,OAAQ,IAAM,GAAgB,CAAC,EAE1C,QAAQ,GAAG,UAAW,IAAM,CAMxB,GAAI,EAAgB,OACf,GAAU,EAAY,EAC9B,EAED,IAAM,EAAQ,CAAC,IAAkB,CAAC,IAAmB,CACjD,GAAgB,EAChB,IAAM,EAAU,aAAiB,MAAS,EAAM,OAAS,EAAM,QAAW,OAAO,CAAK,EAEtF,QAAQ,OAAO,MAAM;AAAA,EAAK,MAAU;AAAA,CAAW,EAC1C,GAAU,CAAY,GAE/B,QAAQ,GAAG,oBAAqB,EAAM,oBAAoB,CAAC,EAC3D,QAAQ,GAAG,qBAAsB,EAAM,qBAAqB,CAAC",
8
+ "debugId": "0F7325DCACA7341764756E2164756E21",
11
9
  "names": []
12
10
  }
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var y=[[4352,4447],[11904,12350],[12353,13311],[13312,19903],[19968,40959],[40960,42191],[43360,43391],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65280,65376],[65504,65510],[127744,128591],[128640,128767],[129280,129535],[129648,129791],[131072,196605],[196608,262141]],w=[[768,879],[1155,1161],[1425,1469],[1552,1562],[1611,1631],[1648,1648],[1750,1756],[2304,2307],[2362,2362],[3633,3633],[3636,3642],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[65279,65279]];function m(n,t){for(let[f,e]of t){if(n<f)return!1;if(n<=e)return!0}return!1}function W(n){if(n<32||n>=127&&n<160)return 0;if(m(n,w))return 0;if(m(n,y))return 2;return 1}function g(n){return n.map((t)=>W(t.codePointAt(0)??0))}var T=" ".repeat(8);function vn(n,t){let f=n.replaceAll("\t",T),e=[...f],s=g(e),b=(x,u)=>{let r=0;for(let l=x;l<u;l+=1)r+=s[l]??0;return r};if(t<=0||b(0,e.length)<=t)return[{text:f,lead:0,from:0,to:e.length}];let o=0;while(o<e.length&&(e[o]===" "||e[o]===" "))o+=1;if(o>0){let x=e.slice(o).join("");if(o>=t)return vn(x,t).map((r)=>({...r,from:r.from+o,to:r.to+o}));let u=" ".repeat(o);return vn(x,t-o).map((r)=>({text:`${u}${r.text}`,lead:r.lead+o,from:r.from+o,to:r.to+o}))}let h=[],d=0,i=0,p=(x)=>{h.push({text:e.slice(d,x).join(""),lead:0,from:d,to:x})},a=0;while(a<=e.length){let x=a;while(x<e.length&&e[x]!==" ")x+=1;let u=b(a,x);if(u>t){if(i>0)p(a===d?a:a-1),d=a,i=0;let r=a;while(b(r,x)>t){let l=r,c=0;while(l<x&&c+(s[l]??0)<=t)c+=s[l]??0,l+=1;if(l===r)l=r+1;d=r,p(l),r=l,d=r}d=r,i=b(r,x)}else if(i>0&&i+1+u>t)p(a-1),d=a,i=u;else i=i===0?u:i+1+u;if(x>=e.length)break;a=x+1}return p(e.length),h}function A(n,t){return vn(n,t).map((f)=>f.text)}function Fo(n,t){let f=0;for(let[e,s]of[...n].entries()){if(e>=t)break;f+=s==="\t"?8:1}return f}function sr(n,t){return n.split(`
3
- `).flatMap((f)=>A(f,t))}function ir(n,t,f){if(n===""||f<=0)return{lines:[],rows:0,hidden:0};let e=sr(n,t);if(e.length<=f)return{lines:e,rows:e.length,hidden:0};return{lines:e.slice(e.length-f),rows:f+1,hidden:e.length-f}}
4
- export{vn,Fo,sr,ir};
2
+ var y=[[4352,4447],[11904,12350],[12353,13311],[13312,19903],[19968,40959],[40960,42191],[43360,43391],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65280,65376],[65504,65510],[127744,128591],[128640,128767],[129280,129535],[129648,129791],[131072,196605],[196608,262141]],w=[[768,879],[1155,1161],[1425,1469],[1552,1562],[1611,1631],[1648,1648],[1750,1756],[2304,2307],[2362,2362],[3633,3633],[3636,3642],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[65279,65279]];function m(n,t){for(let[f,e]of t){if(n<f)return!1;if(n<=e)return!0}return!1}function W(n){if(n<32||n>=127&&n<160)return 0;if(m(n,w))return 0;if(m(n,y))return 2;return 1}function g(n){return n.map((t)=>W(t.codePointAt(0)??0))}var T=" ".repeat(8);function jt(n,t){let f=n.replaceAll("\t",T),e=[...f],s=g(e),b=(x,u)=>{let r=0;for(let l=x;l<u;l+=1)r+=s[l]??0;return r};if(t<=0||b(0,e.length)<=t)return[{text:f,lead:0,from:0,to:e.length}];let o=0;while(o<e.length&&(e[o]===" "||e[o]===" "))o+=1;if(o>0){let x=e.slice(o).join("");if(o>=t)return jt(x,t).map((r)=>({...r,from:r.from+o,to:r.to+o}));let u=" ".repeat(o);return jt(x,t-o).map((r)=>({text:`${u}${r.text}`,lead:r.lead+o,from:r.from+o,to:r.to+o}))}let h=[],d=0,i=0,p=(x)=>{h.push({text:e.slice(d,x).join(""),lead:0,from:d,to:x})},a=0;while(a<=e.length){let x=a;while(x<e.length&&e[x]!==" ")x+=1;let u=b(a,x);if(u>t){if(i>0)p(a===d?a:a-1),d=a,i=0;let r=a;while(b(r,x)>t){let l=r,c=0;while(l<x&&c+(s[l]??0)<=t)c+=s[l]??0,l+=1;if(l===r)l=r+1;d=r,p(l),r=l,d=r}d=r,i=b(r,x)}else if(i>0&&i+1+u>t)p(a-1),d=a,i=u;else i=i===0?u:i+1+u;if(x>=e.length)break;a=x+1}return p(e.length),h}function A(n,t){return jt(n,t).map((f)=>f.text)}function pi(n,t){let f=0;for(let[e,s]of[...n].entries()){if(e>=t)break;f+=s==="\t"?8:1}return f}function Un(n,t){return n.split(`
3
+ `).flatMap((f)=>A(f,t))}function _t(n,t,f){if(n===""||f<=0)return{lines:[],rows:0,hidden:0};let e=Un(n,t);if(e.length<=f)return{lines:e,rows:e.length,hidden:0};return{lines:e.slice(e.length-f),rows:f+1,hidden:e.length-f}}
4
+ export{jt,pi,Un,_t};
5
5
 
6
- //# debugId=1C4BBE684410C70264756E2164756E21
7
- //# sourceMappingURL=index-cqqb6gaq.js.map
6
+ //# debugId=31C3259F7C30B16B64756E2164756E21
7
+ //# sourceMappingURL=index-k3y8y3wj.js.map
@@ -6,6 +6,6 @@
6
6
  "/**\n * Breaking text into the rows a fixed-width window will draw.\n *\n * ## One wrapping, ours\n *\n * This module used to count rows the way a terminal does — divide the character count by the width — and\n * hand the text to Ink to wrap. Those are two different answers to one question, and the difference is not\n * academic: Ink breaks at spaces, so 240 characters at 80 columns is **four** rows to Ink and three to a\n * division. Every cap built on the division was therefore one row short of what appeared on screen, which\n * on the alternate buffer is a frame taller than the terminal.\n *\n * So the rule is that whoever owns a bounded window wraps the text itself and renders each row with\n * `wrap=\"truncate\"`. The count is then the count, by construction, and a frame test asserts it against a\n * real render rather than trusting the arithmetic.\n *\n * Tabs are expanded to spaces on the way through. A tab's width is the terminal's business and not ours,\n * so a row containing one cannot be measured — expanding it is the only way the number we counted is the\n * number drawn. It changes bytes, never meaning, which is the line decision 4.27 draws.\n */\n\nconst TAB_WIDTH = 8\nconst TAB = \" \".repeat(TAB_WIDTH)\n\nimport { cellWidths } from \"#lib/width\"\n\n/**\n * One drawn row, and which source characters it drew.\n *\n * The offsets exist because a row's text is **not** a slice of its line. Breaking at a space consumes\n * the space, a word longer than the window is cut, and a hanging indent is re-applied to rows that never\n * contained it — so \"which row is source offset 41 on, and at what column\" cannot be recovered from the\n * strings afterwards. Anything that draws a caret over wrapped text needs exactly that, and computing it\n * a second time from the finished rows is how a cursor ends up a column out on the lines that wrapped.\n */\nexport interface WrappedRow {\n /** Exactly what is painted, the re-applied indent included. */\n readonly text: string\n /** Columns of `text` that are indent. A caret never lands to the left of this. */\n readonly lead: number\n /** Source code-point offset of this row's first drawn character. */\n readonly from: number\n /** One past this row's last drawn character. A break at a space leaves a gap before the next `from`. */\n readonly to: number\n}\n\n/**\n * One logical line, broken at spaces to fit `columns`, with the source offsets kept.\n *\n * A word longer than the whole width is cut rather than allowed to overflow — a URL or a base64 blob is\n * the normal case for that, and there is nowhere better to break it. Returns one row for an empty line,\n * because a blank line in a reply is a blank row on screen and dropping it would close up paragraphs the\n * model deliberately separated.\n */\nexport function wrapRows(line: string, columns: number): readonly WrappedRow[] {\n // Tabs are expanded before anything is measured, so offsets are into the *expanded* line. A caller\n // placing a caret has to expand its own column the same way, which `expandColumn` is for.\n const flat = line.replaceAll(\"\\t\", TAB)\n const all = [...flat]\n // Widths per cell, computed once. Every measurement below is a sum over this rather than a count of\n // code points: an emoji is one code point and two columns, so counting made `\"👍\".repeat(10)` measure\n // ten and draw twenty. Offsets stay in code points, because that is what a caller slices with.\n const w = cellWidths(all)\n const span = (from: number, to: number): number => {\n let total = 0\n for (let at = from; at < to; at += 1) total += w[at] ?? 0\n return total\n }\n if (columns <= 0 || span(0, all.length) <= columns) {\n return [{ text: flat, lead: 0, from: 0, to: all.length }]\n }\n\n // Leading whitespace is structure, and splitting on spaces destroys it.\n //\n // Found live: `/help`'s output indents each entry by two spaces, and every line short enough to fit kept\n // them while every line that wrapped lost them — so one list came out at two different indents depending\n // on how long each summary happened to be. Held aside here and re-applied to every row, which also gives\n // a wrapped indented block a hanging indent rather than a ragged left edge.\n let indent = 0\n while (indent < all.length && (all[indent] === \" \" || all[indent] === \"\\u00a0\")) indent += 1\n if (indent > 0) {\n const body = all.slice(indent).join(\"\")\n // An indent as wide as the window is dropped rather than honoured: keeping it would leave no room\n // for the text, and shrinking the width to fit it recurses forever. The recursion terminates either\n // way, because `body` cannot begin with a space.\n if (indent >= columns) {\n return wrapRows(body, columns).map((row) => ({\n ...row,\n from: row.from + indent,\n to: row.to + indent,\n }))\n }\n const pad = \" \".repeat(indent)\n return wrapRows(body, columns - indent).map((row) => ({\n text: `${pad}${row.text}`,\n lead: row.lead + indent,\n from: row.from + indent,\n to: row.to + indent,\n }))\n }\n\n const rows: WrappedRow[] = []\n // `at` is where the pending row starts in the source; `width` is how much of it is drawn so far.\n let at = 0\n let width = 0\n const push = (to: number) => {\n rows.push({ text: all.slice(at, to).join(\"\"), lead: 0, from: at, to })\n }\n let cursor = 0\n while (cursor <= all.length) {\n // The next word, and the single space that introduced it. A run of spaces is not collapsed —\n // only the one space a break consumes is, which is what keeps the offsets honest.\n let end = cursor\n while (end < all.length && all[end] !== \" \") end += 1\n const word = span(cursor, end)\n\n if (word > columns) {\n // Longer than any row can hold. Flush what is pending, then cut it into full rows.\n if (width > 0) {\n push(cursor === at ? cursor : cursor - 1)\n at = cursor\n width = 0\n }\n let take = cursor\n while (span(take, end) > columns) {\n // Advance by *columns*, not by cells. A cut that would land inside a double-width\n // character stops before it, which is why the row can come out one column short: half an\n // emoji is not a thing a terminal can draw, and drawing it anyway is how a row overflows.\n let stop = take\n let filled = 0\n while (stop < end && filled + (w[stop] ?? 0) <= columns) {\n filled += w[stop] ?? 0\n stop += 1\n }\n // A single character wider than the whole window would otherwise loop forever taking\n // nothing. Emit it alone and overflow by one column, which is the only option left.\n if (stop === take) stop = take + 1\n at = take\n push(stop)\n take = stop\n at = take\n }\n at = take\n width = span(take, end)\n } else if (width > 0 && width + 1 + word > columns) {\n // Does not fit beside what is already on this row. The space before it is the break and is\n // drawn by neither row, which is why `to` and the next `from` are not the same number.\n push(cursor - 1)\n at = cursor\n width = word\n } else {\n width = width === 0 ? word : width + 1 + word\n }\n\n if (end >= all.length) break\n cursor = end + 1\n }\n push(all.length)\n return rows\n}\n\nfunction wrapLine(line: string, columns: number): readonly string[] {\n return wrapRows(line, columns).map((row) => row.text)\n}\n\n/** A code-point column in `line` translated into the tab-expanded coordinates `wrapRows` reports. */\nexport function expandColumn(line: string, column: number): number {\n let out = 0\n for (const [at, ch] of [...line].entries()) {\n if (at >= column) break\n out += ch === \"\\t\" ? TAB_WIDTH : 1\n }\n return out\n}\n\n/** Every row `text` occupies at `columns`, newlines respected and long lines broken. */\nexport function wrapText(text: string, columns: number): readonly string[] {\n return text.split(\"\\n\").flatMap((line) => wrapLine(line, columns))\n}\n\n/**\n * The live pane: the rows to draw, how tall that makes it, and how much was dropped.\n *\n * Height-capped on purpose. Ink erases and redraws its whole dynamic tree per frame, so an uncapped pane\n * means redrawing the entire reply on every token — a cost that grows with the length of the answer,\n * precisely when the terminal is busiest. The newest rows are the ones kept, because they are what the\n * reader is looking at, and nothing is lost: the finished reply joins the transcript at `turn.end`.\n *\n * All three numbers from one wrap, because they were computed separately and disagreed. The component\n * needs the rows and the dropped count; the chat frame needs the height to subtract from the terminal\n * *before* the pane renders. Deriving them apart meant the notice's own row was counted by one caller and\n * not the other, which is a layout one row taller than the screen.\n */\nexport interface LivePane {\n /** What to draw, newest last. Already wrapped, so each is one row. */\n readonly lines: readonly string[]\n /** Rows the pane occupies, the \"… n hidden\" notice included. Zero when there is nothing to show. */\n readonly rows: number\n /** Rows dropped off the top. Non-zero is exactly the condition for drawing the notice. */\n readonly hidden: number\n}\n\nexport function livePane(text: string, columns: number, maxRows: number): LivePane {\n if (text === \"\" || maxRows <= 0) return { lines: [], rows: 0, hidden: 0 }\n const all = wrapText(text, columns)\n if (all.length <= maxRows) return { lines: all, rows: all.length, hidden: 0 }\n // The extra row is the notice itself.\n return {\n lines: all.slice(all.length - maxRows),\n rows: maxRows + 1,\n hidden: all.length - maxRows,\n }\n}\n"
7
7
  ],
8
8
  "mappings": ";AA4BA,IAAM,EAA+C,CACjD,CAAC,KAAQ,IAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,MAAQ,KAAM,EACf,CAAC,OAAS,MAAO,EACjB,CAAC,OAAS,MAAO,EACjB,CAAC,OAAS,MAAO,EACjB,CAAC,OAAS,MAAO,EACjB,CAAC,OAAS,MAAO,EACjB,CAAC,OAAS,MAAO,CACrB,EAGM,EAA+C,CACjD,CAAC,IAAQ,GAAM,EACf,CAAC,KAAQ,IAAM,EACf,CAAC,KAAQ,IA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rc961.js";import{LA,ko}from"./index-yjcdp72k.js";import{dt,Ct,Ye}from"./index-srmhk9g5.js";import{g,B,l,c}from"./index-wzsmh5j0.js";function GA(n){if(n===void 0||n===null)return"(not set)";if(typeof n==="string")return n===""?'""':n;if(typeof n==="boolean"||typeof n==="number")return String(n);return JSON.stringify(n)}function m(n){return n.split(/[.[]/)[0]??n}function Co(n,e){let t=[`${e}`,""],i=new Map;for(let r of n){let a=m(r.setting.path);i.set(a,[...i.get(a)??[],r])}let o=!0;for(let[r,a]of i){t.push(B(r,o)),o=!1;for(let s of a){let d=s.setting.agentListed?"":" · yours only",h=s.setting.via===void 0?"":` · set with \`${s.setting.via}\``,y=s.setting.confirm===void 0?"":" · asks first";t.push(g([{label:s.setting.path,value:GA(s.value)}]),c(`${s.setting.means}${d}${h}${y}`,4))}}return t.push("","A change takes effect the next time the agent starts. `yours only` marks a field the agent is","refused: what it may do is its to ask for, where it writes and who may reach it are yours."),t.join(`
3
+ `)}function Bo(n,e){return[g([{label:n.path,value:GA(e)}]),c(n.means,4),...n.toAgent===void 0?[]:[c(`to the agent: ${n.toAgent}`,4)]].join(`
4
+ `)}function fo(n,e){if(n.confirm===void 0)return;if(n.path==="tools.untrusted.onMutate"&&String(e).toLowerCase()!=="allow")return;return n.confirm}function Eo(n){let e=[g([{label:"set",value:`${n.path} = ${GA(n.after)}`},{label:"was",value:n.before===void 0?"(not set)":GA(n.before)},{label:"file",value:n.file}])];if(n.reflowed)e.push("",l("the block could not be edited in place, so the file was re-serialised — it is valid, and comments may have moved"));if(n.running!==void 0)e.push("",l(`this agent is running (pid ${n.running.pid}, ${n.running.mode}) and holds its settings for its lifetime — the change applies after ${n.restartHint}`));for(let t of n.pending)e.push(l(`${t.name} is not set — ${t.why}`)),e.push(l(`fill it in with \`config env <agent> ${t.name}\``));return e.join(`
5
+ `)}function po(){return AA.filter((n)=>n.via===void 0&&!/[[<]/.test(n.path)).map((n)=>n.path)}function FA(n){if(typeof n!=="object"||n===null)return[];let e=n,t=[],i=(s,d)=>{if(typeof s==="string"&&s!=="")t.push({name:s,why:d})},o=f(e.model);for(let s of["main","selector","compactor"]){let d=f(o?.[s]);i(d?.apiKeyEnv,"the manifest will not load until it is set")}if(Array.isArray(e.channels))for(let s of e.channels){let d=f(s);if(d===void 0||d.enabled===!1)continue;i(d.tokenEnv,`the ${String(d.id??d.type??"channel")} channel is read at boot, so the agent will not start until it is set`)}let r=f(e.server);if(r?.enabled===!0)i(r.tokenEnv,"the HTTP API would accept unauthenticated requests. This does not stop the agent starting");let a=f(f(e.tools)?.providers);for(let[s,d]of Object.entries(a??{}))i(f(d)?.apiKeyEnv,`the ${s} provider's tools will not work until it is set`);return t}function f(n){if(typeof n!=="object"||n===null||Array.isArray(n))return;return n}function an(n,e){return n.filter((t)=>e[t.name]===void 0||e[t.name]==="")}function u(n,e){let t=[],i=new Map;for(let o of n){if(o.setting.via!==void 0||/[[<]/.test(o.setting.path))continue;let r=o.setting.path.split(".")[0]??o.setting.path;i.set(r,[...i.get(r)??[],o])}for(let[o,r]of i){t.push({kind:"heading",label:o});for(let a of r)t.push({kind:"setting",setting:a.setting,value:a.value})}if(e.channels.length>0){t.push({kind:"heading",label:"who may reach it"});for(let o of e.channels)t.push({kind:"allow",channelId:o.id,channelType:o.type,handles:o.allowFrom})}if(e.secrets.length>0){t.push({kind:"heading",label:"secrets — written to the .env, never shown"});for(let o of e.secrets)t.push({kind:"secret",name:o.name,why:o.why,present:e.present(o.name)})}return t}import{readFileSync as p}from"node:fs";function gn(n){let e=p(n,"utf8");return AA.map((t)=>{if(t.path==="channels[].allowFrom"){let i=de(e,["channels"]);if(!Array.isArray(i))return{setting:t,value:void 0};let o={};for(let r of i){if(typeof r!=="object"||r===null)continue;let a=r;if(typeof a.id!=="string")continue;o[a.id]=a.allowFrom??[]}return{setting:t,value:Object.keys(o).length===0?void 0:o}}if(t.path==="tools.providers.<id>.writeRoots"){let i=de(e,["tools","providers"]);if(typeof i!=="object"||i===null||Array.isArray(i))return{setting:t,value:void 0};let o={};for(let[r,a]of Object.entries(i)){if(typeof a!=="object"||a===null)continue;let s=a.writeRoots;if(s!==void 0)o[r]=s}return{setting:t,value:Object.keys(o).length===0?void 0:o}}return{setting:t,value:de(e,t.path.split("."))}})}function lA(n){let e=p(n,"utf8"),t=eA(e),i=LA(n),o=de(e,["channels"]);return u(gn(n),{channels:(Array.isArray(o)?o:[]).filter((r)=>typeof r==="object"&&r!==null&&!Array.isArray(r)).map((r)=>({id:String(r.id??""),type:String(r.type??""),allowFrom:Array.isArray(r.allowFrom)?r.allowFrom.map(String):[]})).filter((r)=>r.id!==""),secrets:FA(t),present:(r)=>ko(i,r)})}async function tt(n,e,t){switch(e.kind){case"setting":{if(t.trim()==="")throw new A({code:"cli_config_value_missing",message:`No value given for ${e.setting.path}.`,hint:'A bare word, a number, a list as ["a", "b"], or a map as {k: v}.',field:"value"});return(await dt(n,e.setting.path,t)).note}case"allow":{let i=t.trim()===""?[]:t.trim().split(/\s+/);return(await Ct(n,e.channelId,i)).note}case"secret":return Ye(n,e.name,t).note;case"heading":return""}}
6
+ export{GA,Co,Bo,fo,Eo,po,FA,an,gn,lA,tt};
7
+
8
+ //# debugId=5A8C72646CCB097564756E2164756E21
9
+ //# sourceMappingURL=index-k59wwdgz.js.map
@@ -1,13 +1,11 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/config-apply.ts", "../src/lib/dotenv-edit.ts", "../src/lib/config-view.ts", "../src/lib/config-rows.ts"],
3
+ "sources": ["../src/lib/config-view.ts", "../src/lib/config-rows.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * The three writes `config` performs, separated from how any surface prints them.\n *\n * The plain actions and the editor both go through here, which is the same argument the phase made one\n * level down: `editManifest` is the only thing that writes `agent.yaml` because three writers meant the\n * guarantee depended on which caller you were. Two *callers* of that writer would have the same problem\n * one step up — the editor validating a handle differently from `config allow`, or writing a secret\n * without tightening the file's mode.\n *\n * Each function does the effect and returns a sentence. Refusals throw `HarnessError`, so a caller that\n * prints to a terminal and a caller that shows a line in a frame both get the same words.\n */\n\nimport { chmodSync, existsSync, readFileSync, statSync, writeFileSync } from \"node:fs\"\nimport { dirname, join } from \"node:path\"\nimport { editManifest, HarnessError, manifestValueAt, parseSettingValue } from \"@dispach/core\"\nimport { upsertEnv } from \"#lib/dotenv-edit\"\nimport { telegramHandle } from \"#lib/init-flow\"\n\nexport interface Applied {\n /** One line saying what happened, for whichever surface asked. */\n readonly note: string\n /** The source editor could not place the path, so the document was re-serialised. */\n readonly reflowed: boolean\n /** What was there before, so a caller can offer the undo. */\n readonly before: unknown\n}\n\n/** The `.env` beside a manifest. */\nexport function envPathOf(manifestPath: string): string {\n return join(dirname(manifestPath), \".env\")\n}\n\nexport async function applySet(manifestPath: string, path: string, raw: string): Promise<Applied> {\n const value = parseSettingValue(raw)\n const result = await editManifest({ file: manifestPath, path: path.split(\".\"), value })\n return {\n note: `${path} is now ${describe(value)}`,\n reflowed: result.reflowed,\n before: result.before,\n }\n}\n\n/**\n * Add, remove or replace a channel's inbound allowlist.\n *\n * `handles` is the whole list, because the whole list is what gets written: the field lives inside a\n * sequence entry and the source editor matches `key:` at an indent, so one entry's key is not\n * addressable. Every handle is checked against the service that issues it first — an impossible one\n * matches nobody, and the only symptom is a bot that is connected, healthy and silently refusing the\n * person it was set up for.\n */\nexport async function applyAllow(\n manifestPath: string,\n channelId: string,\n handles: readonly string[],\n): Promise<Applied> {\n const source = readFileSync(manifestPath, \"utf8\")\n const channels = manifestValueAt(source, [\"channels\"])\n if (!Array.isArray(channels)) {\n throw new HarnessError({\n code: \"cli_config_no_channels\",\n message: \"This agent has no channels, so there is nobody to allow.\",\n hint: \"`config set <agent> channels '[{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]'` declares one first.\",\n })\n }\n\n const entries = channels.filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n const at = entries.findIndex((entry) => String(entry.id ?? \"\") === channelId)\n if (at === -1) {\n throw new HarnessError({\n code: \"cli_config_channel_unknown\",\n message: `No channel with id \"${channelId}\".`,\n hint: `Declared: ${entries.map((entry) => String(entry.id ?? \"\")).join(\", \")}.`,\n field: \"channel\",\n })\n }\n\n const target = entries[at] as Record<string, unknown>\n const checked = handles.map((handle) => checkedHandle(handle, String(target.type ?? \"\")))\n const unique = [...new Set(checked)]\n const before = Array.isArray(target.allowFrom) ? target.allowFrom.map(String) : []\n\n const result = await editManifest({\n file: manifestPath,\n path: [\"channels\"],\n value: entries.map((entry, index) =>\n index === at ? { ...entry, allowFrom: unique } : entry,\n ),\n })\n return {\n note:\n unique.length === 0\n ? `${channelId} now allows nobody, which refuses every message`\n : `${channelId} now allows ${unique.join(\", \")}`,\n reflowed: result.reflowed,\n before,\n }\n}\n\n/**\n * Put a value in the `.env` beside the manifest, at 0600.\n *\n * Written 0600 whichever way the file arrived: under a service manager this is the *only* path\n * credentials take — launchd hands a job almost no environment and a plist carries none on purpose — so\n * tightening it is right even when this command did not create it. `writeFileSync`'s mode applies only\n * when it creates the file, which is why the check afterwards is not redundant.\n */\nexport function applySecret(manifestPath: string, name: string, value: string): Applied {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new HarnessError({\n code: \"cli_config_env_name_invalid\",\n message: `\"${name}\" is not an environment variable name.`,\n hint: \"Letters, digits and underscores, not starting with a digit — MODEL_API_KEY, TELEGRAM_BOT_TOKEN.\",\n field: \"name\",\n })\n }\n if (value === \"\") {\n throw new HarnessError({\n code: \"cli_config_env_empty\",\n message: `An empty value for ${name} would not start the agent.`,\n hint: \"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.\",\n })\n }\n\n const path = envPathOf(manifestPath)\n const before = existsSync(path) ? readFileSync(path, \"utf8\") : \"\"\n const upsert = upsertEnv(before, name, value)\n writeFileSync(path, upsert.text, { encoding: \"utf8\", mode: 0o600 })\n const loose = (statSync(path).mode & 0o077) !== 0\n if (loose) chmodSync(path, 0o600)\n\n return {\n note: `${name} ${upsert.replaced ? \"replaced\" : \"written\"} in ${path}${loose ? \" (tightened to 0600)\" : \"\"}`,\n reflowed: false,\n before: undefined,\n }\n}\n\n/**\n * A handle, validated against the service that issues it.\n *\n * Telegram's rule is shared with `init` rather than restated, because a check only one surface performs\n * is a check the two disagree about. An unknown channel type passes through: guessing at another\n * service's identifier format would refuse handles that are perfectly valid.\n */\nexport function checkedHandle(raw: string, type: string): string {\n const given = raw.trim()\n if (given === \"\") {\n throw new HarnessError({\n code: \"cli_config_handle_missing\",\n message: \"No handle given.\",\n hint: \"On Telegram that is the username, not the display name.\",\n field: \"handle\",\n })\n }\n if (type !== \"telegram\") return given\n const checked = telegramHandle(given)\n if (!checked.ok) {\n throw new HarnessError({\n code: \"cli_config_handle_invalid\",\n message: `\"${given}\" ${checked.reason}`,\n hint: \"A handle that cannot exist matches nobody, and the only symptom is the bot silently refusing every message from the person it was set up for.\",\n field: \"handle\",\n })\n }\n return checked.value\n}\n\n/** A value as a short phrase, for a one-line note. */\nfunction describe(value: unknown): string {\n if (value === \"\") return \"empty\"\n if (typeof value === \"string\") return value\n return JSON.stringify(value)\n}\n",
6
- "/**\n * Setting one variable in a `.env` without disturbing the rest of it. Pure: text in, text out.\n *\n * The same argument as `yaml-edit.ts`, for the same file's neighbour. A generated `.env` carries\n * comments naming what each variable is for and where to get it, and rewriting the file from a parsed\n * map would drop every one of them — which matters more here than in the manifest, because this is the\n * file somebody opens six months later wondering which dashboard a key came from.\n *\n * Deliberately not a `.env` *parser*: reading one is `parseDotEnv` in core, and a second implementation\n * of that would be two things that have to agree about quoting. This only ever finds a line and\n * replaces it, so the two meet at exactly one place — how a value is quoted on the way out, which is\n * written to be read back by that parser and asserted against it in the tests.\n */\n\n/** Whether a value needs quoting to survive `parseDotEnv`, and the quoted form if so. */\nexport function renderEnvValue(value: string): string {\n // Unquoted values stop at ` #`, and a leading quote character would be eaten as an opening quote.\n // Everything else round-trips bare, which keeps a generated file readable.\n const needsQuotes =\n value === \"\" ||\n /^[\"']/.test(value) ||\n /\\s/.test(value) ||\n value.includes(\"#\") ||\n value !== value.trim()\n if (!needsQuotes) return value\n const escaped = value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\")\n return `\"${escaped}\"`\n}\n\nexport interface EnvUpsert {\n readonly text: string\n /** True when the variable was already there and its line was replaced. */\n readonly replaced: boolean\n}\n\n/**\n * Set `name` to `value`, replacing an existing assignment in place or appending a new one.\n *\n * Replacing **in place** rather than appending is what stops the file growing a second, shadowing\n * assignment on every edit — `parseDotEnv` takes the last one, so an append-only writer would leave a\n * file whose earlier lines are lies. A commented-out assignment is left alone: it is documentation,\n * and uncommenting it would resurrect a value somebody deliberately disabled.\n */\nexport function upsertEnv(source: string, name: string, value: string): EnvUpsert {\n const assignment = `${name}=${renderEnvValue(value)}`\n const lines = source.split(\"\\n\")\n // `export FOO=` counts, because `parseDotEnv` reads it. A `#` first does not.\n const pattern = new RegExp(`^\\\\s*(?:export\\\\s+)?${name}\\\\s*=`)\n const at = lines.findIndex((line) => pattern.test(line))\n\n if (at !== -1) {\n const existing = lines[at] ?? \"\"\n // The `export ` prefix is preserved: it is there because something sources this file rather\n // than reading it, and dropping it would break that quietly.\n const prefix = /^\\s*export\\s+/.exec(existing)?.[0] ?? \"\"\n return {\n text: [...lines.slice(0, at), `${prefix}${assignment}`, ...lines.slice(at + 1)].join(\n \"\\n\",\n ),\n replaced: true,\n }\n }\n\n // Appended with exactly one trailing newline, whatever the file ended with. A `.env` that gains a\n // blank line on every edit is a file that looks edited by a machine, which it is, but it should not\n // look careless about it.\n const body = source.replace(/\\n+$/, \"\")\n return { text: body === \"\" ? `${assignment}\\n` : `${body}\\n${assignment}\\n`, replaced: false }\n}\n",
7
5
  "/**\n * What `config` prints, and what a person has to confirm. Pure, so both are asserted as strings.\n *\n * The policy lives here rather than in the command for the same reason `remove-plan.ts` does: this\n * surface can disable the write gate and open a bind address to the network, and \"which edits need a\n * confirmation\" is exactly the thing that must be checkable without performing one.\n *\n * ## Why the person's policy is not the agent's\n *\n * Decision 11.29: *enabling a capability answers \"what may I do\"; a write root, an allowlist and a\n * bind address answer \"who and where\", and those are the person's by definition.* The agent's floor\n * exists because an agent that could widen its own inbound gate could be **talked into** widening it\n * by the very message it is reading — `config_set` sits in `policy.allow` on a real manifest, so the\n * write gate would not stop that. A person typing at a terminal is not that threat, and refusing them\n * is what left the fields reserved for them with the worst ergonomics in the system.\n *\n * So nothing here is floored. Two edits are confirmed, both from decision 4.50, and only those two:\n * a confirmation that fires on `limits.maxSteps` is one nobody reads by the time it fires on the\n * write gate.\n */\n\nimport { SETTINGS, type Setting } from \"@dispach/core\"\nimport type { EditorRow } from \"#lib/config-editor\"\nimport { bullet, indent, keyValue, section } from \"#lib/render\"\n\n/** A setting with whatever the manifest currently has in it. */\nexport interface SettingValue {\n readonly setting: Setting\n /** Plain JS, or `undefined` when the field is absent from the file. */\n readonly value: unknown\n}\n\n/**\n * How a value appears in a listing.\n *\n * Lists and maps as JSON rather than flattened YAML, which is the lesson from `config_read`: collapsing\n * a block's newlines rendered `[type: telegram id: tg tokenEnv: …]`, one run-on string where the reader\n * needed fields. A sequence of maps went through `String(entry)` and wrote `[object Object]` — the same\n * defect, three times, in three renderers.\n */\nexport function showValue(value: unknown): string {\n if (value === undefined || value === null) return \"(not set)\"\n if (typeof value === \"string\") return value === \"\" ? '\"\"' : value\n if (typeof value === \"boolean\" || typeof value === \"number\") return String(value)\n return JSON.stringify(value)\n}\n\n/** The top-level key a path belongs under, for grouping. */\nfunction group(path: string): string {\n return path.split(/[.[]/)[0] ?? path\n}\n\n/**\n * The whole catalogue, grouped by the block it lives in, each row carrying who owns it.\n *\n * Grouped by manifest block rather than by owner, because the question a reader arrives with is \"what\n * can I change about tools\" far more often than \"what is mine versus the agent's\" — and the ownership\n * still shows on every row that is not the default.\n */\nexport function renderSettings(rows: readonly SettingValue[], file: string): string {\n const out: string[] = [`${file}`, \"\"]\n\n // Collected by block rather than emitted in catalogue order. Printing a heading whenever the block\n // *changes* looks equivalent and is not: the person-only rows sit at the end of the catalogue, so a\n // real listing came out with `server` and `tools` as two sections each, reading as though there\n // were two of them. Grouping here rather than reordering the catalogue keeps the render correct\n // whatever order the rows arrive in, which is the property worth having.\n const blocks = new Map<string, SettingValue[]>()\n for (const row of rows) {\n const block = group(row.setting.path)\n blocks.set(block, [...(blocks.get(block) ?? []), row])\n }\n\n let first = true\n for (const [block, members] of blocks) {\n out.push(section(block, first))\n first = false\n for (const row of members) {\n const owner = row.setting.agentListed ? \"\" : \" · yours only\"\n const via = row.setting.via === undefined ? \"\" : ` · set with \\`${row.setting.via}\\``\n const guard = row.setting.confirm === undefined ? \"\" : \" · asks first\"\n out.push(\n keyValue([{ label: row.setting.path, value: showValue(row.value) }]),\n indent(`${row.setting.means}${owner}${via}${guard}`, 4),\n )\n }\n }\n out.push(\n \"\",\n \"A change takes effect the next time the agent starts. `yours only` marks a field the agent is\",\n \"refused: what it may do is its to ask for, where it writes and who may reach it are yours.\",\n )\n return out.join(\"\\n\")\n}\n\n/** One field, for `config get`. */\nexport function renderOne(setting: Setting, value: unknown): string {\n return [\n keyValue([{ label: setting.path, value: showValue(value) }]),\n indent(setting.means, 4),\n ...(setting.toAgent === undefined ? [] : [indent(`to the agent: ${setting.toAgent}`, 4)]),\n ].join(\"\\n\")\n}\n\n/**\n * What a confirmation says before a guard-weakening edit, or `undefined` when none is needed.\n *\n * The value matters, not only the path: `onMutate: confirm` tightens the gate and `allow` removes it,\n * and asking about both would teach people to agree to the one that matters. Same asymmetry the agent's\n * floor has, where `confirm` is settable and `allow` is refused.\n */\nexport function confirmationFor(setting: Setting, value: unknown): string | undefined {\n if (setting.confirm === undefined) return undefined\n if (setting.path === \"tools.untrusted.onMutate\" && String(value).toLowerCase() !== \"allow\") {\n return undefined\n }\n return setting.confirm\n}\n\n/**\n * The report after a successful set.\n *\n * `reflowed` is surfaced rather than swallowed: the file is correct and its comments have moved, which\n * is a surprise better heard from the command than found later in a diff.\n */\nexport function renderChange(input: {\n readonly path: string\n readonly before: unknown\n readonly after: unknown\n readonly file: string\n readonly reflowed: boolean\n /** A live process holding this agent, if there is one. */\n readonly running?: { readonly pid: number; readonly mode: string }\n /**\n * Env variables this edit has *newly* made load-bearing and that are not set.\n *\n * Newly, not \"all of them\": a note about tokens printed on every `limits.maxSteps` change is a note\n * nobody reads by the time it matters — the same reasoning that makes `config_set` report a pending\n * secret only for a write that could have introduced one. What is already missing is `config list`'s\n * to report, because that is the command whose job is the overview.\n */\n readonly pending: readonly EnvNeed[]\n readonly restartHint: string\n}): string {\n const out: string[] = [\n keyValue([\n { label: \"set\", value: `${input.path} = ${showValue(input.after)}` },\n {\n label: \"was\",\n value: input.before === undefined ? \"(not set)\" : showValue(input.before),\n },\n { label: \"file\", value: input.file },\n ]),\n ]\n if (input.reflowed) {\n out.push(\n \"\",\n bullet(\n \"the block could not be edited in place, so the file was re-serialised — it is valid, and comments may have moved\",\n ),\n )\n }\n if (input.running !== undefined) {\n // Never a refusal. Fixing a misconfiguration while it is running and broken is the main use of\n // this command, so the state it would refuse in is the state somebody is trying to get out of.\n out.push(\n \"\",\n bullet(\n `this agent is running (pid ${input.running.pid}, ${input.running.mode}) and holds its settings for its lifetime — the change applies after ${input.restartHint}`,\n ),\n )\n }\n for (const need of input.pending) {\n out.push(bullet(`${need.name} is not set — ${need.why}`))\n out.push(bullet(`fill it in with \\`config env <agent> ${need.name}\\``))\n }\n return out.join(\"\\n\")\n}\n\n/** Every setting with a real dotted path, in catalogue order. `config set`'s accepted list. */\nexport function settablePaths(): readonly string[] {\n return SETTINGS.filter((entry) => entry.via === undefined && !/[[<]/.test(entry.path)).map(\n (entry) => entry.path,\n )\n}\n\n/** An env variable this manifest depends on, and what actually happens without it. */\nexport interface EnvNeed {\n readonly name: string\n /** The real consequence, which differs per source and is not interchangeable. */\n readonly why: string\n}\n\n/**\n * The env variables a manifest depends on, each with the consequence of it being unset.\n *\n * One message for all of them was wrong, and a live run showed it: the API token variable reported as\n * \"read at boot — the agent will refuse to start until it is filled in\", printed for an agent with\n * `server.enabled: false` that starts perfectly well. Three sources, three different outcomes:\n *\n * - `model.<role>.apiKeyEnv` — a **load failure**. `validateApiKeyEnv` refuses the manifest outright.\n * - an enabled channel's `tokenEnv` — a **boot failure**, because the factory reads it inside\n * `Runtime.create`. A channel with `enabled: false` is never constructed, so it needs nothing.\n * - `server.tokenEnv` — **no failure at all**. The API serves unauthenticated and the banner says so,\n * which is worth telling somebody and is not the same sentence as \"will not start\".\n * - a provider's `apiKeyEnv` — that provider's tools do not work; the agent runs.\n *\n * A disabled block contributes nothing. Claiming a dependency that does not exist is worse than\n * claiming none, because it is the kind of warning that teaches people to ignore this line.\n */\nexport function envNeeds(document: unknown): readonly EnvNeed[] {\n if (typeof document !== \"object\" || document === null) return []\n const doc = document as Record<string, unknown>\n const needs: EnvNeed[] = []\n const add = (name: unknown, why: string) => {\n if (typeof name === \"string\" && name !== \"\") needs.push({ name, why })\n }\n\n const model = asRecord(doc.model)\n for (const role of [\"main\", \"selector\", \"compactor\"]) {\n const config = asRecord(model?.[role])\n add(config?.apiKeyEnv, \"the manifest will not load until it is set\")\n }\n\n if (Array.isArray(doc.channels)) {\n for (const entry of doc.channels) {\n const channel = asRecord(entry)\n if (channel === undefined || channel.enabled === false) continue\n add(\n channel.tokenEnv,\n `the ${String(channel.id ?? channel.type ?? \"channel\")} channel is read at boot, so the agent will not start until it is set`,\n )\n }\n }\n\n const server = asRecord(doc.server)\n if (server?.enabled === true) {\n add(\n server.tokenEnv,\n \"the HTTP API would accept unauthenticated requests. This does not stop the agent starting\",\n )\n }\n\n const providers = asRecord(asRecord(doc.tools)?.providers)\n for (const [id, config] of Object.entries(providers ?? {})) {\n add(asRecord(config)?.apiKeyEnv, `the ${id} provider's tools will not work until it is set`)\n }\n\n return needs\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined\n return value as Record<string, unknown>\n}\n\n/** Those of `needs` the environment does not supply. */\nexport function unmet(\n needs: readonly EnvNeed[],\n env: Readonly<Record<string, string | undefined>>,\n): readonly EnvNeed[] {\n return needs.filter((need) => env[need.name] === undefined || env[need.name] === \"\")\n}\n\n/**\n * The editor's rows for a manifest: every setting, one `allowFrom` per channel, and every secret.\n *\n * Here rather than in the component because it is the whole shape of the surface and it is pure — what\n * appears, in what order, under which heading — and because both hosts build it the same way.\n *\n * The two catalogue rows that are not dotted paths are *replaced* by their expansions rather than shown\n * beside them: `channels[].allowFrom` becomes one row per declared channel, and\n * `tools.providers.<id>.writeRoots` is left as a listing-only row, because writing it means naming a\n * provider and the editor has no way to ask which. A row nobody can act on would be the dead end this\n * surface exists to remove, so it is not offered at all — `config list` still shows it.\n */\nexport function editorRows(\n settings: readonly SettingValue[],\n input: {\n readonly channels: readonly {\n readonly id: string\n readonly type: string\n readonly allowFrom: readonly string[]\n }[]\n readonly secrets: readonly EnvNeed[]\n readonly present: (name: string) => boolean\n },\n): readonly EditorRow[] {\n const out: EditorRow[] = []\n\n // Collected by block, not emitted when the block *changes* — the same distinction `renderSettings`\n // records above, which this renderer had never been given. The two are not equivalent: the\n // person-only rows sit at the end of the catalogue, so `server.host` and `server.tokenEnv` were\n // already a second `server` section here, and inserting any row between `server.port` and them\n // made it visible. `schedules` was that row. Grouping keeps the render correct whatever order the\n // catalogue arrives in, which is the property worth having and the reason not to fix it by\n // reordering the table.\n const blocks = new Map<string, SettingValue[]>()\n for (const row of settings) {\n if (row.setting.via !== undefined || /[[<]/.test(row.setting.path)) continue\n const key = row.setting.path.split(\".\")[0] ?? row.setting.path\n blocks.set(key, [...(blocks.get(key) ?? []), row])\n }\n for (const [label, members] of blocks) {\n out.push({ kind: \"heading\", label })\n for (const row of members) {\n out.push({ kind: \"setting\", setting: row.setting, value: row.value })\n }\n }\n\n if (input.channels.length > 0) {\n out.push({ kind: \"heading\", label: \"who may reach it\" })\n for (const channel of input.channels) {\n out.push({\n kind: \"allow\",\n channelId: channel.id,\n channelType: channel.type,\n handles: channel.allowFrom,\n })\n }\n }\n\n if (input.secrets.length > 0) {\n out.push({ kind: \"heading\", label: \"secrets — written to the .env, never shown\" })\n for (const need of input.secrets) {\n out.push({\n kind: \"secret\",\n name: need.name,\n why: need.why,\n present: input.present(need.name),\n })\n }\n }\n\n return out\n}\n",
8
6
  "/**\n * What the config editor shows, and what one confirmed row does. Reads files; no Ink.\n *\n * Its own module because **both hosts import it statically** — `config.ts` for the standalone editor and\n * `App.tsx` for the pane — while `index.ts` imports `config.ts` *dynamically* to keep Ink off the\n * startup path. A module reached both ways makes `bun build --splitting` emit its exports twice and the\n * binary refuses to parse, and `bun test` sails straight through it because tests import source. So the\n * shared half lives where nothing has to be lazy about it.\n */\n\nimport { readFileSync } from \"node:fs\"\nimport { HarnessError, manifestDocument, manifestValueAt, SETTINGS } from \"@dispach/core\"\nimport { applyAllow, applySecret, applySet } from \"#lib/config-apply\"\nimport type { EditorRow } from \"#lib/config-editor\"\nimport { agentEnv, isSet } from \"#lib/config-env\"\nimport { editorRows, envNeeds, type SettingValue } from \"#lib/config-view\"\n\n/**\n * Every setting with whatever the file currently holds.\n *\n * Two rows do not have a readable dotted path — `allowFrom` lives inside a list entry and `writeRoots`\n * inside a provider — so they are gathered by walking the block instead. Shown rather than omitted: a\n * field missing from a listing reads as \"no such concept\", which is the same reasoning that puts a\n * `none` row in slot 2 instead of leaving the line out.\n */\nexport function currentValues(manifestPath: string): readonly SettingValue[] {\n const source = readFileSync(manifestPath, \"utf8\")\n return SETTINGS.map((setting) => {\n if (setting.path === \"channels[].allowFrom\") {\n const channels = manifestValueAt(source, [\"channels\"])\n if (!Array.isArray(channels)) return { setting, value: undefined }\n const byId: Record<string, unknown> = {}\n for (const entry of channels) {\n if (typeof entry !== \"object\" || entry === null) continue\n const row = entry as { id?: unknown; allowFrom?: unknown }\n if (typeof row.id !== \"string\") continue\n byId[row.id] = row.allowFrom ?? []\n }\n return { setting, value: Object.keys(byId).length === 0 ? undefined : byId }\n }\n if (setting.path === \"tools.providers.<id>.writeRoots\") {\n const providers = manifestValueAt(source, [\"tools\", \"providers\"])\n if (typeof providers !== \"object\" || providers === null || Array.isArray(providers)) {\n return { setting, value: undefined }\n }\n const roots: Record<string, unknown> = {}\n for (const [id, config] of Object.entries(providers as Record<string, unknown>)) {\n if (typeof config !== \"object\" || config === null) continue\n const found = (config as { writeRoots?: unknown }).writeRoots\n if (found !== undefined) roots[id] = found\n }\n return { setting, value: Object.keys(roots).length === 0 ? undefined : roots }\n }\n return { setting, value: manifestValueAt(source, setting.path.split(\".\")) }\n })\n}\n\n/**\n * The rows the editor shows, read fresh from the manifest and its `.env`.\n *\n * Exported because both hosts build them: this command mounts the editor standalone, and the chat opens\n * it as a pane. Two builders would drift on the first row either one grew.\n */\nexport function editorRowsFor(manifestPath: string): readonly EditorRow[] {\n const source = readFileSync(manifestPath, \"utf8\")\n const document = manifestDocument(source)\n const env = agentEnv(manifestPath)\n const channels = manifestValueAt(source, [\"channels\"])\n\n return editorRows(currentValues(manifestPath), {\n channels: (Array.isArray(channels) ? channels : [])\n .filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n .map((entry) => ({\n id: String(entry.id ?? \"\"),\n type: String(entry.type ?? \"\"),\n allowFrom: Array.isArray(entry.allowFrom) ? entry.allowFrom.map(String) : [],\n }))\n .filter((entry) => entry.id !== \"\"),\n secrets: envNeeds(document),\n // The agent's layered environment, not this process's — `ambientEnv` alone never adds the file\n // beside the manifest, which made a row read `(not set)` right after somebody set it.\n present: (name: string) => isSet(env, name),\n })\n}\n\n/**\n * Perform one row's edit. The editor's only asynchronous part, and the plain commands' path too.\n *\n * A blank buffer means different things per row and each is the useful reading: no handles is \"allow\n * nobody\", which is a real thing to want; an empty *setting* would be a value nobody typed on purpose;\n * and an empty secret is refused by `applySecret`, because a variable set to nothing fails the load\n * exactly as a missing one does.\n */\nexport async function applyEditorRow(\n manifestPath: string,\n row: EditorRow,\n raw: string,\n): Promise<string> {\n switch (row.kind) {\n case \"setting\": {\n if (raw.trim() === \"\") {\n throw new HarnessError({\n code: \"cli_config_value_missing\",\n message: `No value given for ${row.setting.path}.`,\n hint: 'A bare word, a number, a list as [\"a\", \"b\"], or a map as {k: v}.',\n field: \"value\",\n })\n }\n return (await applySet(manifestPath, row.setting.path, raw)).note\n }\n case \"allow\": {\n const handles = raw.trim() === \"\" ? [] : raw.trim().split(/\\s+/)\n return (await applyAllow(manifestPath, row.channelId, handles)).note\n }\n case \"secret\":\n return applySecret(manifestPath, row.name, raw).note\n case \"heading\":\n return \"\"\n }\n}\n"
9
7
  ],
10
- "mappings": ";sKAaA,oBAAS,gBAAW,kBAAY,cAAc,mBAAU,gBACxD,kBAAS,UAAS,kBCCX,SAAS,CAAc,CAAC,EAAuB,CASlD,GAAI,EALA,IAAU,IACV,QAAQ,KAAK,CAAK,GAClB,KAAK,KAAK,CAAK,GACf,EAAM,SAAS,GAAG,GAClB,IAAU,EAAM,KAAK,GACP,OAAO,EAOzB,MAAO,IANS,EACX,QAAQ,MAAO,MAAM,EACrB,QAAQ,KAAM,MAAK,EACnB,QAAQ,MAAO,KAAK,EACpB,QAAQ,MAAO,KAAK,EACpB,QAAQ,MAAO,KAAK,KAkBtB,SAAS,CAAS,CAAC,EAAgB,EAAc,EAA0B,CAC9E,IAAM,EAAa,GAAG,KAAQ,EAAe,CAAK,IAC5C,EAAQ,EAAO,MAAM;AAAA,CAAI,EAEzB,EAAU,IAAI,OAAO,uBAAuB,QAAW,EACvD,EAAK,EAAM,UAAU,CAAC,IAAS,EAAQ,KAAK,CAAI,CAAC,EAEvD,GAAI,IAAO,GAAI,CACX,IAAM,EAAW,EAAM,IAAO,GAGxB,EAAS,gBAAgB,KAAK,CAAQ,I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AG,GAAG,IACjE,KACK,QAAS,CACV,IAAM,EAAU,EAAI,KAAK,IAAM,GAAK,CAAC,EAAI,EAAI,KAAK,EAAE,MAAM,KAAK,EAC/D,OAAQ,MAAM,GAAW,EAAc,EAAI,UAAW,CAAO,GAAG,IACpE,KACK,SACD,OAAO,GAAY,EAAc,EAAI,KAAM,CAAG,EAAE,SAC/C,UACD,MAAO",
9
+ "debugId": "5A8C72646CCB097564756E2164756E21",
12
10
  "names": []
13
11
  }
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import{o,I}from"./index-nn3tk25c.js";import{Jt}from"./index-jq999vcw.js";import{Box as f,Text as i}from"ink";import{jsx as d,jsxs as l}from"react/jsx-runtime";function xt({label:u,editor:p,placeholder:e,error:r,secret:a,columns:t,maxRows:n}){return l(f,{flexDirection:"column",children:[d(i,{children:u}),d(Jt,{editor:p,gutter:I.prompt,...e===void 0?{}:{placeholder:e},...a===!0?{secret:!0}:{},...t===void 0?{}:{columns:t},...n===void 0?{}:{maxRows:n}}),r===void 0?null:l(i,{color:o.error,children:[I.error,r]})]})}
3
+ export{xt};
4
+
5
+ //# debugId=851F8383AD6A5EE364756E2164756E21
6
+ //# sourceMappingURL=index-nmnnwa02.js.map
@@ -5,6 +5,6 @@
5
5
  "/**\n * A labelled text input for wizard questions: label, caret, LineCursor, optional error line.\n *\n * The editing itself lives upstream — the screen root routes keys through `keyToIntent` into\n * `applyIntent` and hands the resulting `EditorState` down — so every editing nicety the chat\n * input has (^A/^E, ^W, code-point cursor) works here without a second implementation.\n */\n\nimport { Box, Text } from \"ink\"\nimport { LineCursor } from \"#components/LineCursor\"\nimport { GLYPH, THEME } from \"#lib/theme\"\nimport type { EditorState } from \"#lib/types\"\n\nexport interface TextFieldProps {\n readonly label: string\n readonly editor: EditorState\n /** The question's default, shown dim when the buffer is empty; enter accepts it. */\n readonly placeholder?: string\n /** A validation failure, rendered beneath in the error colour. Cleared upstream on edit. */\n readonly error?: string\n /** Mask the value as it is typed. Passed straight through to the cursor. */\n readonly secret?: boolean\n /**\n * Columns available for the value. **Not optional in practice.**\n *\n * `LineCursor`'s own docstring says it: omitted, nothing wraps and a line wider than whatever draws\n * this is truncated by Ink at a width nobody chose. This component never passed it, and in the\n * settings editor — which draws the field into an unbordered column — a value longer than the\n * terminal was clipped at the right edge with the caret *past* the clip. You could not see what you\n * were typing, and `tools.pinned` is 92 characters in a generated manifest, so it was the first long\n * value anybody opened.\n *\n * **The wizard was not affected, and checking that mattered**: its bordered frame gives the `<Text>`\n * a bounded width, so Ink wrapped it anyway. Measured, after the assumption that it must be broken\n * too — the guard that would have \"proved\" it passed with the fix reverted. It is passed there now\n * regardless, because whoever owns a bounded window should wrap the text itself rather than leave it\n * to whatever happens to enclose it, and because `maxRows` genuinely bounds the height.\n */\n readonly columns?: number\n /** Rows the value may take before the view scrolls to follow the cursor. */\n readonly maxRows?: number\n}\n\nexport function TextField({\n label,\n editor,\n placeholder,\n error,\n secret,\n columns,\n maxRows,\n}: TextFieldProps) {\n return (\n <Box flexDirection=\"column\">\n <Text>{label}</Text>\n {/*\n * The prompt glyph is the cursor's `gutter` rather than a sibling `<Text>`. Two reasons, and\n * the second is not optional: it keeps a wrapped or multi-line value in one column, and\n * `LineCursor` renders a `<Box>`, which inside a `<Text>` produces an empty frame — no error,\n * nothing on screen. A frame test caught that; nothing else would have.\n */}\n <LineCursor\n editor={editor}\n gutter={GLYPH.prompt}\n {...(placeholder === undefined ? {} : { placeholder })}\n {...(secret === true ? { secret: true } : {})}\n {...(columns === undefined ? {} : { columns })}\n {...(maxRows === undefined ? {} : { maxRows })}\n />\n {error === undefined ? null : (\n <Text color={THEME.error}>\n {GLYPH.error}\n {error}\n </Text>\n )}\n </Box>\n )\n}\n"
6
6
  ],
7
7
  "mappings": ";yEAQA,cAAS,UAAK,8DAmCP,SAAS,EAAS,EACrB,QACA,SACA,cACA,QACA,SACA,UACA,WACe,CACf,OACI,EAsBE,EAtBF,CAAK,cAAc,SAAnB,SAsBE,CArBE,EAAe,EAAf,UAAO,EAAQ,EAOf,EAAC,GAAD,CACI,OAAQ,EACR,OAAQ,EAAM,UACT,IAAgB,OAAY,CAAC,EAAI,CAAE,aAAY,KAC/C,IAAW,GAAO,CAAE,OAAQ,EAAK,EAAI,CAAC,KACtC,IAAY,OAAY,CAAC,EAAI,CAAE,SAAQ,KACvC,IAAY,OAAY,CAAC,EAAI,CAAE,SAAQ,EAChD,EACC,IAAU,OAAY,KACnB,EAGE,EAHF,CAAM,MAAO,EAAM,MAAnB,SAGE,CAFG,EAAM,MACN,GACH,GAER",
8
- "debugId": "F7AC4B15F45FF29764756E2164756E21",
8
+ "debugId": "851F8383AD6A5EE364756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ var o={accent:"magenta",muted:"gray",success:"green",warning:"yellow",error:"red",info:"blue",emphasis:"cyan",selection:"blue",border:"gray",borderActive:"magenta",brand:"magenta"},Mi={idle:o.success,thinking:o.warning,streaming:o.accent,working:o.info,cancelling:o.emphasis},ki={user:o.accent,assistant:void 0,reasoning:o.muted,note:o.muted,error:o.error,tool:o.info,banner:void 0},Oi={user:"› ",assistant:"",reasoning:" ",note:"· ",error:"✖ ",tool:" · ",banner:""},I={prompt:"› ",pointer:"❯ ",bullet:"· ",error:"✖ ",dot:"● ",check:"✓ ",ellipsis:"…",create:"+ ",checked:"◉ ",unchecked:"◯ "},Io=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],Ni=80,ce="round";var Di="\x1B[?1000h\x1B[?1002h\x1B[?1006h",bi="\x1B[?1006l\x1B[?1002l\x1B[?1000l";var d=/(?:^|\u001B)\[<(\d+);(\d+);(\d+)([Mm])/g,u=/(?:^|\u001B)\[M[\s\S]{3}/g;function Si(t){if(!t.includes("[<")&&!t.includes("[M"))return;let r=0,s=!1,i,a,c=!1;for(let e of t.matchAll(d)){s=!0;let n=Number(e[1]);if(n===64){r-=3;continue}if(n===65){r+=3;continue}i={column:Math.max(0,Number(e[2])-1),row:Math.max(0,Number(e[3])-1)},a=e[4]==="m"?"release":(n&32)!==0?"drag":"press",c=(n&4)!==0}for(let e of t.matchAll(u)){s=!0;let n=(e[0].codePointAt(e[0].length-3)??32)-32;if(n===64)r-=3;else if(n===65)r+=3}if(!s)return;return{rows:r,...i===void 0?{}:{at:i},...a===void 0?{}:{kind:a},...c?{shift:c}:{}}}
3
+ export{Di,bi,Si,o,Mi,ki,Oi,I,Io,Ni,ce};
4
+
5
+ //# debugId=10FDE3DF81F1F59C64756E2164756E21
6
+ //# sourceMappingURL=index-nn3tk25c.js.map
@@ -1,12 +1,11 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/theme.ts", "../src/lib/rows.ts", "../src/lib/mouse.ts"],
3
+ "sources": ["../src/lib/theme.ts", "../src/lib/mouse.ts"],
4
4
  "sourcesContent": [
5
5
  "/**\n * The one home for appearance: colour tokens, glyphs, and the maps components render from.\n *\n * `lib/const.ts` keeps *behavioural* numbers (row caps, history limits, control sequences); this\n * module holds everything a person would touch to change how the CLI looks. Splitting the two\n * extends the \"no magic value inline\" rule rather than weakening it — one home each, and a\n * component containing a literal colour name is a review failure.\n *\n * Tokens are plain Ink colour names (16-colour safe; Ink's chalk layer maps them per terminal),\n * which keeps this module PURE-listable. `brand` is the single deliberate exception and says why. `NO_COLOR` needs no handling here: the mode resolution\n * forces plain output before Ink ever loads, and chalk independently honours it anyway.\n *\n * This is deliberately a single built-in token set, not a theming system — decision 11.12\n * reverses Phase 2.5's \"themes\" non-goal in the narrowest possible sense. User-configurable\n * themes stay a non-goal.\n */\n\nimport type { TranscriptRole, TurnStatus } from \"#lib/types\"\n\nexport interface Theme {\n /** The one accent, used sparingly: caret, selection cursor, user lines, banner border. */\n readonly accent: string\n /** Hints, notes, reasoning, breadcrumbs. */\n readonly muted: string\n readonly success: string\n readonly warning: string\n readonly error: string\n /** Tool rows and tool-running status. */\n readonly info: string\n /** Cancelling — the one transitional state worth its own colour. */\n readonly emphasis: string\n /**\n * The background a selected run is painted on.\n *\n * A background rather than `inverse`, which is what the caret uses. Inverse swaps foreground and\n * background, so on a coloured run it produces a different colour per role and reads as three\n * highlights rather than one selection — and where a selection contains the caret the two inversions\n * cancel and the caret disappears inside it. A solid background composes instead of fighting.\n */\n readonly selection: string\n /** Non-focal boxes: cards, frames. */\n readonly border: string\n /** The focused box: the input line, the banner. */\n readonly borderActive: string\n /**\n * The wordmark, and only the wordmark.\n *\n * The one token that is a hex triplet rather than an Ink colour name, chosen by the owner. Every other\n * token is 16-colour safe on purpose — a name lets chalk pick whatever the terminal actually has — and\n * this is the deliberate exception, because a brand mark is the one element whose *exact* colour is the\n * point. Chalk downsamples it per terminal rather than failing: on a 256-colour terminal it lands on the\n * nearest cube entry, on a 16-colour one on bright green, which is the right neighbour. `NO_COLOR` is\n * handled before Ink loads at all, by the mode resolution.\n *\n * Not reused anywhere else. A second consumer would make it an accent, and the accent already exists.\n */\n readonly brand: string\n}\n\nexport const THEME: Theme = {\n accent: \"magenta\",\n muted: \"gray\",\n success: \"green\",\n warning: \"yellow\",\n error: \"red\",\n info: \"blue\",\n emphasis: \"cyan\",\n // 16-colour safe like every token but `brand`: chalk maps it to whatever the terminal has, and a\n // named colour survives a 16-colour terminal where a hex triplet would be approximated.\n selection: \"blue\",\n border: \"gray\",\n borderActive: \"magenta\",\n brand: \"magenta\",\n}\n\n/** Status-dot colours, previously inlined in StatusBar. */\nexport const STATUS_COLOR: Record<TurnStatus, string> = {\n idle: THEME.success,\n thinking: THEME.warning,\n streaming: THEME.accent,\n working: THEME.info,\n cancelling: THEME.emphasis,\n}\n\n/** Transcript role colours, previously inlined in Transcript. `undefined` = terminal default. */\nexport const ROLE_COLOR: Record<TranscriptRole, string | undefined> = {\n user: THEME.accent,\n assistant: undefined,\n reasoning: THEME.muted,\n note: THEME.muted,\n error: THEME.error,\n tool: THEME.info,\n banner: undefined,\n}\n\n/**\n * What each role puts before its text, and re-applies as a hanging indent on every row after the first.\n *\n * That second half is why `reasoning` is **two columns** rather than the `\\u00b7 reasoning \\u00b7 ` it used to be.\n * A prefix is an indent, so the longest block in the transcript was also the narrowest — 86 columns of a\n * 100-column terminal, on the one item that is routinely forty rows long. The label moved to a header row\n * of its own, where it costs one row once instead of fourteen columns per row.\n */\nexport const ROLE_PREFIX: Record<TranscriptRole, string> = {\n user: \"› \",\n assistant: \"\",\n reasoning: \" \",\n note: \"· \",\n error: \"✖ \",\n tool: \" · \",\n banner: \"\",\n}\n\n/** The glyph vocabulary. Components compose these; none defines its own. */\nexport const GLYPH = {\n prompt: \"› \",\n pointer: \"❯ \",\n bullet: \"· \",\n error: \"✖ \",\n dot: \"● \",\n check: \"✓ \",\n ellipsis: \"…\",\n create: \"+ \",\n /** Multi-select boxes. Two glyphs so a ticked row reads as ticked without colour. */\n checked: \"◉ \",\n unchecked: \"◯ \",\n} as const\n\n/** Braille spinner. Ten glyphs in a const, not a dependency — decision 11.10 holds. */\nexport const SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"] as const\nexport const SPINNER_INTERVAL_MS = 80\n\n/** cli-boxes ships inside Ink 7; rounded is the house border. Zero new dependencies. */\nexport const BORDER_STYLE = \"round\" as const\n",
6
- "/**\n * Laying a catalogue row out in a fixed number of columns. Pure, so the layout is testable as strings.\n *\n * ## Why this is not a component's problem\n *\n * The first version put the name, the size and the whole description in one `<Text>` and let Ink wrap.\n * Every row longer than the terminal became two or three lines, the checkbox column stopped lining up,\n * and a list of forty skills was unreadable. Wrapping is not a styling detail in a list — it destroys the\n * one property a list has, which is that a row is a row.\n *\n * So the width arithmetic lives here, in one place, as functions over numbers and strings: pad the name to\n * a column, pad the meta to a column, give the description whatever is left, and **truncate every field\n * before it can wrap**. `Text` also carries `wrap=\"truncate\"` as a backstop, but a backstop is not a\n * layout — the columns have to add up, or the description gets cut at a width nobody chose.\n */\n\n/** Terminal columns below which the description is dropped rather than shown as three characters. */\nconst NARROW = 60\n/** The name column, wide enough for `create-architectural-decision-record` to be recognisable. */\nconst NAME_MIN = 18\nconst NAME_MAX = 34\n/** `12.3k · 15 scripts` is the widest realistic meta string. */\nconst META = 18\n/** Checkbox plus pointer, both two characters. */\nconst GUTTER = 4\nconst GAP = 2\n\n/** `2284` → `2.3k`. A row is scanned, not audited, and five digits of precision cost a column. */\nexport function compactTokens(tokens: number): string {\n if (tokens < 1000) return String(tokens)\n const thousands = tokens / 1000\n return thousands < 10 ? `${thousands.toFixed(1)}k` : `${Math.round(thousands)}k`\n}\n\nexport function metaOf(tokens: number, scripts: number, installed: boolean): string {\n if (installed) return \"installed\"\n const size = compactTokens(tokens)\n return scripts === 0 ? size : `${size} · ${scripts} script${scripts === 1 ? \"\" : \"s\"}`\n}\n\n/** Cut to `width`, with an ellipsis when anything was lost. Never returns more than `width`. */\nexport function clip(text: string, width: number): string {\n if (width <= 0) return \"\"\n const flat = text.replace(/\\s+/g, \" \").trim()\n if (flat.length <= width) return flat\n if (width === 1) return \"…\"\n return `${flat.slice(0, width - 1)}…`\n}\n\nexport interface RowColumns {\n readonly name: number\n readonly meta: number\n readonly description: number\n}\n\n/**\n * How wide each column is at a given terminal width.\n *\n * The name column flexes with the longest name actually present rather than being fixed: a catalogue of\n * short names should not leave a third of the row empty, and one long name should not push the\n * description off the screen. Clamped at both ends for both reasons.\n */\nexport function columnsFor(\n width: number,\n longestName: number,\n options: { readonly nameMax?: number } = {},\n): RowColumns {\n // Overridden by the plain path, whose names carry a `source/` prefix and which has no cursor to keep\n // near them. Passing a wider name column *without* going through this function is what pushed every\n // piped row twelve characters over the width it was laid out for.\n let name = Math.max(NAME_MIN, Math.min(options.nameMax ?? NAME_MAX, longestName))\n let meta = META\n\n // The name and meta columns shrink before anything else does. Without this the *fixed* part of the row\n // could exceed the terminal on its own — at 40 columns with a 34-character name it came to 60, so every\n // row wrapped no matter what the description did, which is the bug this module exists to remove.\n const chrome = GUTTER + GAP\n if (chrome + name + meta > width) meta = Math.max(6, width - chrome - name)\n if (chrome + name + meta > width) name = Math.max(6, width - chrome - meta)\n\n const description = width - (chrome + name + meta + GAP)\n // Below the threshold the description is dropped entirely. Three characters of a sentence is worse than\n // none: it takes the same column and carries no information.\n if (width < NARROW || description < 24) return { name, meta, description: 0 }\n return { name, meta, description }\n}\n\n/**\n * One row, exactly `width` characters wide or less, in three aligned columns.\n *\n * Returned as one string rather than as fields, because alignment is the whole point and a caller that\n * assembled the parts could get the padding wrong. Colour is applied by the component *around* this — the\n * arithmetic must not know about escape codes, which do not occupy columns and would break every count.\n */\nexport function layoutRow(\n input: {\n readonly name: string\n readonly meta: string\n readonly description: string\n },\n columns: RowColumns,\n): { readonly name: string; readonly meta: string; readonly description: string } {\n return {\n name: clip(input.name, columns.name).padEnd(columns.name),\n meta: clip(input.meta, columns.meta).padEnd(columns.meta),\n description: columns.description === 0 ? \"\" : clip(input.description, columns.description),\n }\n}\n\n/** A heading, drawn as a rule so groups separate without costing a blank line each. */\nexport function headingRule(label: string, width: number): string {\n const text = clip(label, Math.max(0, width - 8))\n const filled = text.length + 3\n return `${text} ${\"─\".repeat(Math.max(0, Math.min(width, 80) - filled))}`\n}\n\n/**\n * Which slice of a longer list to show.\n *\n * Shared by the catalogue list and the input box, which want the same rule for the same reason: both\n * are taller than their allowance and both have a position that must stay visible. It lives here rather\n * than in either component because the second caller is what proved it was layout arithmetic and not a\n * detail of one screen.\n *\n * Originally: Keeps the cursor inside the window rather than paging, because a cursor that jumps a\n * whole viewport loses the reader's place.\n */\nexport function viewport(\n total: number,\n index: number,\n window: number,\n): { readonly from: number; readonly to: number } {\n if (total <= window) return { from: 0, to: total }\n const half = Math.floor(window / 2)\n const from = Math.min(Math.max(0, index - half), total - window)\n return { from, to: from + window }\n}\n",
7
6
  "/**\n * Wheel scrolling on the alternate screen. Pure, so a mouse report is arithmetic rather than a guess.\n *\n * ## Why this needs a guard rather than only a parser\n *\n * Ink does not know about mouse reports. Measured against a real pty with tracking on: a wheel notch\n * arrived as the literal text `ESC[<64;10;5M`, fell through the keymap to the insert branch, and was typed\n * into the message — twice, because two notches are two reports. So recognising a report is not an\n * optimisation here; every report a terminal can send has to be claimed, wheel and click alike, or the\n * feature's cost is garbage in somebody's message.\n *\n * A chunk can carry several reports. A fast scroll sends one per notch and the runtime coalesces them, so\n * the count matters: honouring one report per chunk makes a flick of the wheel move a single row and reads\n * as the wheel not working.\n *\n * ## The trade this makes, stated\n *\n * Tracking is what stops the terminal handling the mouse itself, so **drag-selecting text with the mouse\n * stops working while a session is mounted**. Every terminal worth naming lets you hold shift to bypass\n * tracking and select natively, which is why the key list says so rather than leaving it to be discovered.\n *\n * Two encodings are recognised. SGR (`ESC [ < b ; x ; y M`) is what we ask for and what any terminal from\n * the last decade replies with; X10 (`ESC [ M` and three raw bytes) is the fallback a terminal that ignored\n * the SGR request will use, and its bytes are frequently above 127 — so leaving it unclaimed would put\n * unprintable characters into a message on exactly the terminals least able to say why.\n */\n\n/**\n * Button tracking, drag tracking, and SGR encoding.\n *\n * 1000 reports press and release and is the least that reports the wheel at all. **1002 adds motion while a\n * button is held**, and without it a drag is not reported — which is why selecting text was not merely\n * disabled but unreachable: the events never arrived. 1003 (motion with no button) is deliberately absent,\n * because it makes the terminal send a report for every pixel of idle pointer movement and nothing here\n * wants hover.\n *\n * Set low-to-high and reset high-to-low, so a terminal that only understands some of them is left in a\n * state we asked for rather than a partial one.\n */\nexport const ENABLE_MOUSE = \"\\u001B[?1000h\\u001B[?1002h\\u001B[?1006h\"\n/** Reversed on the way out, so a terminal is left handling its own mouse again. */\nexport const DISABLE_MOUSE = \"\\u001B[?1006l\\u001B[?1002l\\u001B[?1000l\"\n\n/**\n * Rows one notch of the wheel moves.\n *\n * Three, which is the line-scroll every desktop uses. One row per notch is technically a scroll and feels\n * like the wheel is broken; a whole page per notch overshoots what somebody is looking for.\n */\nexport const WHEEL_ROWS = 3\n\n/** Wheel-up and wheel-down in SGR's button numbering. 64 is the wheel bit plus button 0. */\nconst WHEEL_UP = 64\nconst WHEEL_DOWN = 65\n\n/** Motion bit — set on every report mode 1002 sends while a button is held. */\nconst MOTION = 32\n/** Shift bit, so shift-clicking can extend a selection rather than starting a new one. */\nconst SHIFT = 4\n\n/**\n * The escape prefix is **optional**, and that is not laxness.\n *\n * Ink strips one leading `ESC` from the chunk before a handler sees it (`use-input.js:97`), so the first\n * report in a chunk arrives bare and every one after it keeps its escape. Requiring the prefix therefore\n * matched none of them, which is exactly how the first version of this let a wheel notch through: measured\n * against a real pty, the composer read `abc[<64;10;5M[<64;10;5M`.\n *\n * Anchored rather than left floating: a bare report is only recognised at the very start of the chunk,\n * which is the one position Ink's stripping can produce. A message that happens to contain the same text\n * in the middle of a sentence is still a message.\n */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: the escape byte is the thing being matched\nconst SGR = /(?:^|\\u001B)\\[<(\\d+);(\\d+);(\\d+)([Mm])/g\n// biome-ignore lint/suspicious/noControlCharactersInRegex: the escape byte is the thing being matched\nconst X10 = /(?:^|\\u001B)\\[M[\\s\\S]{3}/g\n\n/** Which gesture a report describes. */\nexport type MouseKind = \"wheel\" | \"press\" | \"drag\" | \"release\"\n\n/** Where a report happened, in **zero-based** screen cells. */\nexport interface MousePoint {\n readonly column: number\n readonly row: number\n}\n\nexport interface MouseInput {\n /**\n * Rows to move: negative up, positive down, zero for a report that is not the wheel.\n *\n * Zero is *not* \"no report\" — a click is a report with no scroll in it, and it still has to be\n * swallowed. The `undefined` return is what means \"no report\".\n */\n readonly rows: number\n /**\n * The last gesture in the chunk, and where it happened. `undefined` when nothing positional was in it.\n *\n * The *last* rather than every one, because a drag arrives as a stream of motion reports and only the\n * newest position matters — a selection follows the pointer, it does not retrace it. The wheel is the\n * exception and is summed instead, which is why `rows` is separate: a flick coalesces several notches\n * into one chunk and honouring only the last would move a single row.\n */\n readonly at?: MousePoint\n readonly kind?: MouseKind\n /** Held modifiers, from SGR's button bits. Shift is what extends a selection from a click. */\n readonly shift?: boolean\n}\n\n/**\n * What a chunk of input means to the mouse, or `undefined` if it holds no mouse report at all.\n *\n * Returning `undefined` rather than a zero is what keeps a keystroke a keystroke: every other branch of\n * the keymap runs only when this says nothing.\n */\nexport function mouseInput(input: string): MouseInput | undefined {\n // Cheap prefilter. Every report contains one of these two, and almost no keystroke does.\n if (!input.includes(\"[<\") && !input.includes(\"[M\")) return undefined\n let rows = 0\n let seen = false\n let at: MousePoint | undefined\n let kind: MouseKind | undefined\n let shift = false\n for (const match of input.matchAll(SGR)) {\n seen = true\n const button = Number(match[1])\n if (button === WHEEL_UP) {\n rows -= WHEEL_ROWS\n continue\n }\n if (button === WHEEL_DOWN) {\n rows += WHEEL_ROWS\n continue\n }\n // SGR reports 1-based cells; everything downstream indexes from zero, so the conversion happens\n // once, here, rather than at each of the callers that would each have to remember it.\n at = { column: Math.max(0, Number(match[2]) - 1), row: Math.max(0, Number(match[3]) - 1) }\n // `m` is a release whatever the button bits say. Motion is bit 5 (32); the low two bits are the\n // button, and only the left one starts a selection.\n kind = match[4] === \"m\" ? \"release\" : (button & MOTION) !== 0 ? \"drag\" : \"press\"\n shift = (button & SHIFT) !== 0\n }\n for (const match of input.matchAll(X10)) {\n seen = true\n // X10 offsets every field by 32, so the wheel's 64 and 65 arrive as 96 and 97.\n // Three fields follow `[M`, and the escape before it is optional — so the button is found\n // from the end of the match rather than at a fixed offset.\n const button = (match[0].codePointAt(match[0].length - 3) ?? 32) - 32\n if (button === WHEEL_UP) rows -= WHEEL_ROWS\n else if (button === WHEEL_DOWN) rows += WHEEL_ROWS\n }\n if (!seen) return undefined\n return {\n rows,\n ...(at === undefined ? {} : { at }),\n ...(kind === undefined ? {} : { kind }),\n ...(shift ? { shift } : {}),\n }\n}\n"
8
7
  ],
9
- "mappings": ";AA2DO,IAAM,EAAe,CACxB,OAAQ,UACR,MAAO,OACP,QAAS,QACT,QAAS,SACT,MAAO,MACP,KAAM,OACN,SAAU,OAGV,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