dispach 0.2.0 → 0.2.1

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 (167) hide show
  1. package/README.md +58 -18
  2. package/dist/APEv2Parser-9wqew3zv.js +5 -0
  3. package/dist/{APEv2Parser-jdp5yp24.js.map → APEv2Parser-9wqew3zv.js.map} +1 -1
  4. package/dist/{AiffParser-n65syezh.js → AiffParser-tbx3xkmk.js} +3 -3
  5. package/dist/{AiffParser-n65syezh.js.map → AiffParser-tbx3xkmk.js.map} +1 -1
  6. package/dist/App-hjn867nc.js +11 -0
  7. package/dist/{App-pmqmzsb3.js.map → App-hjn867nc.js.map} +1 -1
  8. package/dist/{AsfParser-da1fqvxz.js → AsfParser-d784ak3y.js} +3 -3
  9. package/dist/{AsfParser-da1fqvxz.js.map → AsfParser-d784ak3y.js.map} +1 -1
  10. package/dist/{ConfigEditor-4nqbeejh.js → ConfigEditor-g7eb2wsm.js} +3 -3
  11. package/dist/{ConfigEditor-4nqbeejh.js.map → ConfigEditor-g7eb2wsm.js.map} +1 -1
  12. package/dist/{DsdiffParser-gk95sj7t.js → DsdiffParser-vxnfx80c.js} +2 -2
  13. package/dist/{DsfParser-b0enevjw.js → DsfParser-0xsh0zzk.js} +3 -3
  14. package/dist/{DsfParser-b0enevjw.js.map → DsfParser-0xsh0zzk.js.map} +1 -1
  15. package/dist/FlacParser-bf8y3e0w.js +5 -0
  16. package/dist/{KeyProbe-rspsxpsr.js → KeyProbe-w8c37s9q.js} +3 -3
  17. package/dist/{KeyProbe-rspsxpsr.js.map → KeyProbe-w8c37s9q.js.map} +1 -1
  18. package/dist/{MP4Parser-ph7rv2fn.js → MP4Parser-tq7r7wd4.js} +3 -3
  19. package/dist/{MP4Parser-ph7rv2fn.js.map → MP4Parser-tq7r7wd4.js.map} +1 -1
  20. package/dist/{MatroskaParser-fjk1mpct.js → MatroskaParser-a79gsmzb.js} +3 -3
  21. package/dist/{MatroskaParser-fjk1mpct.js.map → MatroskaParser-a79gsmzb.js.map} +1 -1
  22. package/dist/{MpegParser-vp7cj8ts.js → MpegParser-zs61b3wq.js} +3 -3
  23. package/dist/{MpegParser-vp7cj8ts.js.map → MpegParser-zs61b3wq.js.map} +1 -1
  24. package/dist/{MusepackParser-v22gft1f.js → MusepackParser-bp8dm6nz.js} +3 -3
  25. package/dist/{MusepackParser-v22gft1f.js.map → MusepackParser-bp8dm6nz.js.map} +1 -1
  26. package/dist/{OggParser-as1m8xsa.js → OggParser-7pxr1sn9.js} +3 -3
  27. package/dist/{OggParser-as1m8xsa.js.map → OggParser-7pxr1sn9.js.map} +1 -1
  28. package/dist/{Picker-jkmd5xnx.js → Picker-b09hr4tk.js} +3 -3
  29. package/dist/{Picker-jkmd5xnx.js.map → Picker-b09hr4tk.js.map} +1 -1
  30. package/dist/{SessionPicker-3712ke3k.js → SessionPicker-wtfxwdxg.js} +3 -3
  31. package/dist/{SessionPicker-3712ke3k.js.map → SessionPicker-wtfxwdxg.js.map} +1 -1
  32. package/dist/{SkillBrowser-qhsyszt4.js → SkillBrowser-p9ht63c7.js} +3 -3
  33. package/dist/{SkillBrowser-qhsyszt4.js.map → SkillBrowser-p9ht63c7.js.map} +1 -1
  34. package/dist/{WavPackParser-b4qqavzg.js → WavPackParser-gpf3r92t.js} +3 -3
  35. package/dist/{WavPackParser-b4qqavzg.js.map → WavPackParser-gpf3r92t.js.map} +1 -1
  36. package/dist/{WaveParser-fqs1h38f.js → WaveParser-3kcak550.js} +3 -3
  37. package/dist/{WaveParser-fqs1h38f.js.map → WaveParser-3kcak550.js.map} +1 -1
  38. package/dist/WizardApp-494018sk.js +5 -0
  39. package/dist/{WizardApp-qrq36nv8.js.map → WizardApp-494018sk.js.map} +1 -1
  40. package/dist/{channels-gf31stv7.js → channels-yhdvxxrb.js} +14 -14
  41. package/dist/{channels-gf31stv7.js.map → channels-yhdvxxrb.js.map} +1 -1
  42. package/dist/config-g0ybmm4t.js +24 -0
  43. package/dist/{config-z2cd0c5f.js.map → config-g0ybmm4t.js.map} +1 -1
  44. package/dist/credential-pkme1sfe.js +19 -0
  45. package/dist/{credential-h0wmsjsw.js.map → credential-pkme1sfe.js.map} +1 -1
  46. package/dist/{index-dwxmy0kx.js → index-0mz7wpbw.js} +6 -6
  47. package/dist/{index-dwxmy0kx.js.map → index-0mz7wpbw.js.map} +1 -1
  48. package/dist/{index-fcqy46mh.js → index-0pddq849.js} +25 -25
  49. package/dist/{index-fcqy46mh.js.map → index-0pddq849.js.map} +1 -1
  50. package/dist/{index-2yj11ykt.js → index-1f1erzfx.js} +4 -4
  51. package/dist/{index-2yj11ykt.js.map → index-1f1erzfx.js.map} +1 -1
  52. package/dist/{index-1h9pqnec.js → index-26ejkp8q.js} +189 -189
  53. package/dist/{index-1h9pqnec.js.map → index-26ejkp8q.js.map} +7 -7
  54. package/dist/{index-ccpq4k6r.js → index-307qmvb0.js} +25 -25
  55. package/dist/{index-ccpq4k6r.js.map → index-307qmvb0.js.map} +1 -1
  56. package/dist/index-3b3h8kyh.js +5 -0
  57. package/dist/{index-3mvenfbg.js.map → index-3b3h8kyh.js.map} +1 -1
  58. package/dist/{index-0p9p6fvc.js → index-3fgq1acj.js} +10 -10
  59. package/dist/{index-0p9p6fvc.js.map → index-3fgq1acj.js.map} +3 -3
  60. package/dist/{index-dh2g58s1.js → index-4emtktc0.js} +3 -3
  61. package/dist/{index-dh2g58s1.js.map → index-4emtktc0.js.map} +1 -1
  62. package/dist/{index-026q0y3a.js → index-4t3p7vm9.js} +4 -4
  63. package/dist/{index-026q0y3a.js.map → index-4t3p7vm9.js.map} +1 -1
  64. package/dist/{index-t5d8ey5t.js → index-5m9wydxb.js} +4 -4
  65. package/dist/{index-t5d8ey5t.js.map → index-5m9wydxb.js.map} +1 -1
  66. package/dist/{index-g1d06ct5.js → index-633eqxry.js} +7 -7
  67. package/dist/{index-g1d06ct5.js.map → index-633eqxry.js.map} +1 -1
  68. package/dist/index-6r9h7ftn.js +308 -0
  69. package/dist/index-6r9h7ftn.js.map +21 -0
  70. package/dist/{index-kktaw552.js → index-7gsbzvnc.js} +2 -2
  71. package/dist/{index-z88f35vs.js → index-94k4mh6s.js} +13 -13
  72. package/dist/{index-z88f35vs.js.map → index-94k4mh6s.js.map} +3 -3
  73. package/dist/index-9dmgk6d3.js +5 -0
  74. package/dist/{index-tny7c703.js.map → index-9dmgk6d3.js.map} +1 -1
  75. package/dist/index-9qv87rq7.js +9 -0
  76. package/dist/{index-s4a28ctb.js.map → index-9qv87rq7.js.map} +1 -1
  77. package/dist/{index-k2q76dhw.js → index-a6mtqkth.js} +6 -6
  78. package/dist/{index-k2q76dhw.js.map → index-a6mtqkth.js.map} +1 -1
  79. package/dist/{index-0m0x1454.js → index-ac2wzspd.js} +4 -4
  80. package/dist/{index-0m0x1454.js.map → index-ac2wzspd.js.map} +1 -1
  81. package/dist/{index-wxmqyv4c.js → index-ad5c9t83.js} +4 -4
  82. package/dist/{index-wxmqyv4c.js.map → index-ad5c9t83.js.map} +1 -1
  83. package/dist/{index-b7qc21s7.js → index-akv6e7ge.js} +6 -6
  84. package/dist/{index-b7qc21s7.js.map → index-akv6e7ge.js.map} +1 -1
  85. package/dist/{index-v271gbaz.js → index-ec101x93.js} +4 -4
  86. package/dist/{index-v271gbaz.js.map → index-ec101x93.js.map} +1 -1
  87. package/dist/{index-rhv6gqpt.js → index-f056wkb4.js} +4 -4
  88. package/dist/{index-rhv6gqpt.js.map → index-f056wkb4.js.map} +1 -1
  89. package/dist/{index-c2qjdz4q.js → index-gqaa06yh.js} +8 -8
  90. package/dist/{index-c2qjdz4q.js.map → index-gqaa06yh.js.map} +1 -1
  91. package/dist/{index-rfa0ztab.js → index-j20k6k0m.js} +4 -4
  92. package/dist/{index-rfa0ztab.js.map → index-j20k6k0m.js.map} +1 -1
  93. package/dist/{index-2pzgta33.js → index-jh2az41t.js} +4 -4
  94. package/dist/{index-2pzgta33.js.map → index-jh2az41t.js.map} +1 -1
  95. package/dist/{index-gace5ac7.js → index-mn34kj95.js} +4 -4
  96. package/dist/{index-gace5ac7.js.map → index-mn34kj95.js.map} +1 -1
  97. package/dist/{index-rvq7t636.js → index-myg5enf5.js} +2 -2
  98. package/dist/{index-s78sq9g1.js → index-pdsey1ab.js} +45 -45
  99. package/dist/{index-s78sq9g1.js.map → index-pdsey1ab.js.map} +1 -1
  100. package/dist/{index-jmnjcw61.js → index-psk6q25h.js} +4 -4
  101. package/dist/{index-jmnjcw61.js.map → index-psk6q25h.js.map} +1 -1
  102. package/dist/{index-3s2q0m64.js → index-q8b1fc3k.js} +4 -4
  103. package/dist/{index-3s2q0m64.js.map → index-q8b1fc3k.js.map} +1 -1
  104. package/dist/{index-g8n8rhtr.js → index-qh82wtpa.js} +3 -3
  105. package/dist/{index-g8n8rhtr.js.map → index-qh82wtpa.js.map} +1 -1
  106. package/dist/{index-gqbny9gy.js → index-s2tzq27a.js} +6 -6
  107. package/dist/{index-gqbny9gy.js.map → index-s2tzq27a.js.map} +1 -1
  108. package/dist/{index-1wxw30j1.js → index-s57ztjhq.js} +35 -35
  109. package/dist/index-s57ztjhq.js.map +13 -0
  110. package/dist/{index-jv7egrh2.js → index-skkddg44.js} +4 -4
  111. package/dist/{index-jv7egrh2.js.map → index-skkddg44.js.map} +1 -1
  112. package/dist/{index-9m6b14b4.js → index-thmq816c.js} +4 -4
  113. package/dist/{index-9m6b14b4.js.map → index-thmq816c.js.map} +1 -1
  114. package/dist/{index-es4bgkbh.js → index-trx9xb59.js} +6 -6
  115. package/dist/{index-es4bgkbh.js.map → index-trx9xb59.js.map} +1 -1
  116. package/dist/{index-60jxyzbe.js → index-twcgf73h.js} +4 -4
  117. package/dist/{index-60jxyzbe.js.map → index-twcgf73h.js.map} +1 -1
  118. package/dist/index-vw2hf4d8.js +6 -0
  119. package/dist/{index-v6taf4vn.js.map → index-vw2hf4d8.js.map} +1 -1
  120. package/dist/{index-m5rmhcez.js → index-w97gprre.js} +4 -4
  121. package/dist/{index-m5rmhcez.js.map → index-w97gprre.js.map} +1 -1
  122. package/dist/index-wk6andxq.js +5 -0
  123. package/dist/{index-ak304afj.js.map → index-wk6andxq.js.map} +1 -1
  124. package/dist/index-x9z2xnct.js +11 -0
  125. package/dist/{index-5nprb9px.js.map → index-x9z2xnct.js.map} +1 -1
  126. package/dist/index-xa9crtzq.js +6 -0
  127. package/dist/{index-qe3ybzh6.js.map → index-xa9crtzq.js.map} +1 -1
  128. package/dist/{index-0v2gw4mk.js → index-y34s71qe.js} +3 -3
  129. package/dist/{index-0v2gw4mk.js.map → index-y34s71qe.js.map} +1 -1
  130. package/dist/{index-y6r1k2yd.js → index-ye2yb3xf.js} +7 -7
  131. package/dist/{index-y6r1k2yd.js.map → index-ye2yb3xf.js.map} +1 -1
  132. package/dist/{index-y605a1rj.js → index-z0dgxd7d.js} +10 -10
  133. package/dist/{index-y605a1rj.js.map → index-z0dgxd7d.js.map} +2 -2
  134. package/dist/{index-m01mb74d.js → index-zg89tq04.js} +4 -4
  135. package/dist/{index-m01mb74d.js.map → index-zg89tq04.js.map} +1 -1
  136. package/dist/{index-dgrwpzz9.js → index-zjphh8ch.js} +4 -4
  137. package/dist/{index-dgrwpzz9.js.map → index-zjphh8ch.js.map} +1 -1
  138. package/dist/index.js +172 -172
  139. package/dist/index.js.map +4 -4
  140. package/dist/transcript.d.ts.map +1 -1
  141. package/dist/web-f6869dy2.js +14 -0
  142. package/dist/{web-stkkwyka.js.map → web-f6869dy2.js.map} +1 -1
  143. package/dist/wrapper-52c0vacs.js +5 -0
  144. package/dist/{wrapper-bwxbqa53.js.map → wrapper-52c0vacs.js.map} +1 -1
  145. package/package.json +2 -2
  146. package/dist/APEv2Parser-jdp5yp24.js +0 -5
  147. package/dist/App-pmqmzsb3.js +0 -11
  148. package/dist/FlacParser-6jwner07.js +0 -5
  149. package/dist/WizardApp-qrq36nv8.js +0 -5
  150. package/dist/config-z2cd0c5f.js +0 -24
  151. package/dist/credential-h0wmsjsw.js +0 -19
  152. package/dist/index-1wxw30j1.js.map +0 -13
  153. package/dist/index-358nsn9t.js +0 -65
  154. package/dist/index-358nsn9t.js.map +0 -21
  155. package/dist/index-3mvenfbg.js +0 -5
  156. package/dist/index-5nprb9px.js +0 -11
  157. package/dist/index-ak304afj.js +0 -5
  158. package/dist/index-qe3ybzh6.js +0 -6
  159. package/dist/index-s4a28ctb.js +0 -9
  160. package/dist/index-tny7c703.js +0 -5
  161. package/dist/index-v6taf4vn.js +0 -6
  162. package/dist/web-stkkwyka.js +0 -14
  163. package/dist/wrapper-bwxbqa53.js +0 -5
  164. /package/dist/{DsdiffParser-gk95sj7t.js.map → DsdiffParser-vxnfx80c.js.map} +0 -0
  165. /package/dist/{FlacParser-6jwner07.js.map → FlacParser-bf8y3e0w.js.map} +0 -0
  166. /package/dist/{index-kktaw552.js.map → index-7gsbzvnc.js.map} +0 -0
  167. /package/dist/{index-rvq7t636.js.map → index-myg5enf5.js.map} +0 -0
@@ -4,9 +4,9 @@
4
4
  "sourcesContent": [
5
5
  "/**\n * What you can type at a running prompt, as data.\n *\n * The outer CLI's help is generated from `COMMANDS`, so a flag the parser honours cannot be missing\n * from `--help`. The in-session help had no such link: it was a string in a component, and the two\n * drifted in both directions — `/help` was advertised by the banner and unhandled on the plain path,\n * where it was sent to the model as a prompt, while five working key chords went undocumented.\n *\n * So the same discipline applies here. One table drives dispatch *and* the help text, which closes\n * the drift for commands. Key bindings cannot be generated the same way, because they live in a\n * function rather than a table — `keyToIntent` decides what `^C` means from whether a turn is in\n * flight. The loop is closed by tests instead: every documented chord is walked through the real\n * `keyToIntent`, and every chord it honours is required to appear here.\n *\n * Pure, and free of Ink: both renderers dispatch through this, which is what keeps `--plain` and the\n * rich path from answering the same keystroke differently.\n */\n\nimport { nearest } from \"@dispach/core\"\nimport { keyValue } from \"#lib/render\"\n\nexport type SessionCommandKind =\n | \"help\"\n | \"status\"\n | \"context\"\n | \"restart\"\n | \"new\"\n | \"tools\"\n | \"reset\"\n | \"exit\"\n\nexport interface SessionCommandSpec {\n readonly kind: SessionCommandKind\n readonly word: string\n /** Accepted and not advertised individually; they appear beside the canonical word. */\n readonly aliases: readonly string[]\n readonly summary: string\n}\n\nexport const SESSION_COMMANDS: readonly SessionCommandSpec[] = [\n { kind: \"help\", word: \"/help\", aliases: [], summary: \"this list\" },\n {\n // The human twin of context slot 2. Until this existed, the *model* was told its model,\n // window, channels, server and permissions on every turn — and the person at the prompt\n // had no way to see any of it. An agent that knows more about the runtime than its operator\n // does is the same asymmetry, pointed the other way, that slot 2 was added to fix.\n kind: \"status\",\n word: \"/status\",\n aliases: [],\n summary: \"model, channels, server, store — what this agent is and what is actually running\",\n },\n {\n // The status line has carried `ctx 61%` since Phase 7A and has never said what the denominator\n // is — it is not the window, and two of its three terms are invisible from outside the\n // assembler. This is where they are written down.\n kind: \"context\",\n word: \"/context\",\n aliases: [],\n summary:\n \"what is in the prompt right now, per slot, and what the percentage is a percentage of\",\n },\n {\n kind: \"restart\",\n word: \"/restart\",\n aliases: [],\n summary:\n \"restart the agent, for any configuration changes to take effect (memory files on disk are untouched)\",\n },\n {\n kind: \"tools\",\n word: \"/tools\",\n aliases: [],\n summary: \"what the model may call, and what the catalogue costs every turn\",\n },\n {\n // Next to `/reset` deliberately: they are the pair a person picks between, and picking wrong\n // is destructive in one direction only. The summaries carry the distinction rather than the\n // names, because \"new\" and \"reset\" do not tell you which one keeps the conversation.\n kind: \"new\",\n word: \"/new\",\n aliases: [],\n summary:\n \"start a fresh conversation — this one stays in the store under its own key, and /sessions goes back to it\",\n },\n {\n kind: \"reset\",\n word: \"/reset\",\n aliases: [],\n summary:\n \"clear this conversation's history in place, keeping its key — memory files on disk are untouched\",\n },\n {\n kind: \"exit\",\n word: \"/exit\",\n aliases: [\"/quit\", \":q\"],\n // Says that it asks, because it does. The session takes the whole terminal and its buffer is\n // discarded on the way out, so leaving is not a keystroke to make by accident — the same reasoning\n // that made ^C take two presses.\n summary: \"leave — asks first, because the screen goes with it\",\n },\n]\n\nexport interface KeyBindingSpec {\n /** As shown to a reader. Ctrl chords are written `^X`, and the drift test reads them back out. */\n readonly chord: string\n readonly summary: string\n}\n\n/**\n * How to put a line break in a message, as one line of hint text.\n *\n * ⌥⏎ leads because it is the chord that works everywhere: it arrives as ESC then carriage return, which\n * is a sequence every terminal can send and Ink already parses. The backslash is the fallback for anyone\n * whose Option key is bound to something else.\n *\n * Shift+⏎ is deliberately absent. It requires the terminal to send a distinguishable sequence — kitty's\n * `CSI 13;2u`, which `terminal-setup` installs for the terminals that can be taught — and whether it\n * reaches this process cannot be detected from inside it. A hint naming a chord that silently *sends*\n * the message instead is worse than one naming only what always works.\n */\nexport const NEWLINE_HINT = \"⌥⏎ or a trailing \\\\ for a new line · ⏎ sends\"\n\n/**\n * The one line of guidance a brand-new conversation carries.\n *\n * Everything on it is true of this runtime, which is the whole reason it is written here rather than\n * copied from a screenshot of another tool: `/` really does open the palette, and `^C` really does take\n * two presses. A hint naming a chord that does something else — or nothing — is worse than no hint, and\n * this is the one screen where a person has no conversation to learn the keys from.\n */\nexport const NEW_SESSION_HINT = \"/ commands · ⏎ sends · ⇧⏎ new line · ^C twice leaves\"\n\nexport const KEY_BINDINGS: readonly KeyBindingSpec[] = [\n {\n chord: \"^C\",\n summary:\n \"cancel the turn in flight — at an idle prompt, press it twice to leave (the screen goes with it)\",\n },\n { chord: \"^D\", summary: \"leave when the line is empty; delete forward when it is not\" },\n { chord: \"^A / ^E\", summary: \"start of line / end of line\" },\n { chord: \"^B / ^F\", summary: \"back one character / forward one\" },\n { chord: \"^U / ^K\", summary: \"delete to the start of the line / to the end\" },\n { chord: \"^W\", summary: \"delete the word before the cursor\" },\n { chord: \"^P / ^N\", summary: \"previous / next of what you have already sent\" },\n {\n chord: \"↑ / ↓\",\n summary:\n \"a line up or down inside the message — the same history at its first and last line\",\n },\n {\n // Both, and the qualification belongs here rather than in the composer hint. ⌥⏎ arrives as `ESC`\n // then carriage return and works in every terminal; ⇧⏎ needs one that can distinguish it, which\n // the kitty keyboard protocol delivers where it negotiates — and where it does not, ⇧⏎ *is* ⏎ and\n // silently sends the message. A permanently-visible hint cannot carry that condition; this line\n // can, which is the split `Prompt.tsx` documents.\n chord: \"⌥⏎ / ⇧⏎\",\n summary:\n \"a new line in the message — ⌥⏎ everywhere, ⇧⏎ where the terminal can tell it apart (`keys` says); a trailing \\\\ does the same; ⏎ sends it\",\n },\n { chord: \"⌥← / ⌥→\", summary: \"back one word / forward one — ^← / ^→ do the same\" },\n { chord: \"⌥⌫ / ⌥d\", summary: \"delete the word before the cursor / after it\" },\n { chord: \"Home / End\", summary: \"start of line / end of line, the same as ^A / ^E\" },\n {\n // Cmd chords need the kitty keyboard protocol, which is negotiated at mount and simply does not\n // arrive on a terminal that declines it — so this row names the readline equivalent alongside,\n // rather than describing a chord that silently does nothing on half the terminals in use.\n chord: \"cmd← / cmd→\",\n summary: \"start of line / end of line, where the terminal reports cmd (else ^A / ^E)\",\n },\n {\n chord: \"cmd↑ / cmd↓\",\n summary: \"the start / end of the whole message, however many lines it has\",\n },\n { chord: \"cmd⌫ / cmd⌦\", summary: \"delete to the start of the line / to the end\" },\n { chord: \"cmdz / cmd⇧z\", summary: \"undo / redo, the same as ^Z / ^Y\" },\n {\n // One row for the whole family, because the rule is one sentence: shift turns any motion above\n // into a selection. Listing ten shifted chords separately would be ten rows saying that once each.\n chord: \"⇧ + any motion\",\n summary:\n \"select as the cursor moves — ⇧← a character, ⇧⌥← a word, ⇧cmd← to the line start, ⇧cmd↑ to the top; typing or ⌫ replaces what is selected\",\n },\n { chord: \"cmda\", summary: \"select the whole message\" },\n {\n chord: \"^R\",\n summary: \"search what you have already sent — ↑↓ to pick, ⏎ to use it, esc to cancel\",\n },\n {\n // Not SIGTSTP: Ink puts stdin in raw mode, so the terminal never generates the signal. Suspend\n // is genuinely gone here, which is why it is written down rather than left to be discovered.\n chord: \"^Z / ^Y\",\n summary: \"undo / redo the last edit — suspend is not available inside a session\",\n },\n {\n // Deliberately not ^U/^D, which would be the shell habit: both are already taken above, both are\n // documented, and a scroll key that silently deleted half a message is the worse bug by far.\n chord: \"PgUp / PgDn\",\n summary: \"back and forward through the conversation a screen at a time\",\n },\n { chord: \"⌥↑ / ⌥↓\", summary: \"the same, one row at a time\" },\n { chord: \"⌥PgUp / ⌥PgDn\", summary: \"the start of the conversation / back to the newest reply\" },\n {\n chord: \"^O / ⌥r\",\n summary:\n \"show the model's reasoning whole — folded to a few rows so the reply stays findable; ^O works on every terminal, ⌥r needs one that reports it\",\n },\n {\n // The one entry that is not a keystroke, and it earns its place: mouse tracking is what makes the\n // wheel scroll, and the same tracking is what stops the *terminal* selecting text — so without a\n // line here, a person reasonably concludes selection is broken rather than reimplemented.\n chord: \"drag\",\n summary:\n \"select text — in the conversation it goes to the clipboard when you let go, so ⌘V works; in the input box it does not, because you are usually about to type over it (⌘C copies, ⌘X cuts). Double-click a word, triple-click a line, esc clears\",\n },\n { chord: \"esc\", summary: \"return to the newest reply when you have scrolled away\" },\n]\n\n/**\n * Every Ctrl letter the table documents, read back out of the chord strings rather than listed\n * again — a second list is one more thing that can disagree with the first. The drift test walks\n * these through `keyToIntent` and requires every letter it honours to appear here.\n */\nexport const DOCUMENTED_CTRL_LETTERS: readonly string[] = KEY_BINDINGS.flatMap((spec) =>\n [...spec.chord.matchAll(/\\^([A-Za-z])/g)].map((match) => (match[1] ?? \"\").toLowerCase()),\n)\n\n/**\n * Every option-letter chord the table documents, read back the same way.\n *\n * The ctrl list above has had a two-way drift test since Phase 2 and the option chords never did — so\n * `⌥r` was documented, bound, handled, and reaching nothing, with no test anywhere able to say so. The\n * asymmetry was not a decision: `^` is one character to match and `⌥` is one the regex simply never\n * learned about.\n */\nexport const DOCUMENTED_META_LETTERS: readonly string[] = KEY_BINDINGS.flatMap((spec) =>\n // A *lowercase* letter that no other letter follows, which is narrower than the ctrl regex for two\n // reasons the first version of this got wrong. `⌥PgUp` starts with a capital and is a key name, so\n // a `[A-Za-z]` class extracted a phantom `⌥p` and the test failed against a chord that does not\n // exist. And a letter chord is always one letter here, so requiring nothing after it keeps a future\n // `⌥Home` out of the list too.\n [...spec.chord.matchAll(/⌥([a-z])(?![A-Za-z])/g)].map((match) => match[1] ?? \"\"),\n)\n\n/**\n * Letters a terminal sends *as* an option chord without anybody pressing them.\n *\n * `⌥←` reaches us as `ESC b` from Apple Terminal and as `CSI 1;3D` from iTerm2, so `keyToIntent` honours\n * `meta` plus the letter `b` — and that is an encoding, not a binding. Documenting `⌥b` would advertise a\n * chord nobody uses to mean a thing they already have an arrow key for. Listed here rather than dropped\n * from the check, so the exemption is a decision with a reason on it instead of a hole in the test.\n */\nexport const META_LETTERS_THAT_ARE_ARROWS: readonly string[] = [\"b\", \"f\"]\n\nexport type SessionCommand =\n | { readonly kind: SessionCommandKind; readonly rest?: string }\n /**\n * A slash command this table does not own — a CLI command, offered in a session.\n *\n * Resolved here rather than in the renderer so both paths agree about what a typed line means, and\n * carried with its arguments intact for whichever host runs it.\n */\n | { readonly kind: \"command\"; readonly name: string; readonly rest: string }\n /** Looked like a command and was not one. Refused rather than billed as a prompt. */\n | { readonly kind: \"unknown\"; readonly word: string; readonly nearest?: string }\n\n/**\n * One word starting with a slash, and nothing else on the line.\n *\n * Deliberately narrow, because the alternative costs real messages. `/etc/passwd is world-readable`\n * and `and/or` are things a person says to an agent; a second slash or a space means this is prose\n * and goes to the model untouched. What remains — a lone `/word` — can only have been meant as a\n * command, so getting it wrong is worth reporting.\n */\nconst COMMAND_SHAPE = /^\\/[A-Za-z][\\w-]*$/\n\n/**\n * The same word, followed by arguments.\n *\n * The narrow rule above still decides everything it can, and this only adds a case it cannot reach:\n * `/logs 200` and `/skills validate` need a space, which the narrow rule reads as prose. The escape is\n * **the first token being exactly a known command** — decidable from the tables alone, with no\n * heuristic. So `/etc/passwd is world-readable` still goes to the model, because `/etc` is not a\n * command; and a mistyped `/skils validate` is prose rather than a refusal, which is the one thing this\n * loosening costs and the cheaper of the two errors.\n */\nconst COMMAND_WITH_ARGS = /^(\\/[A-Za-z][\\w-]*)\\s+(.*)$/\n\nconst KNOWN = new Map<string, SessionCommandKind>(\n SESSION_COMMANDS.flatMap((spec) =>\n [spec.word, ...spec.aliases].map((word) => [word.toLowerCase(), spec.kind] as const),\n ),\n)\n\n/**\n * `undefined` means \"this is a prompt\" — the overwhelming majority of lines.\n *\n * `offered` is the set of CLI command names a session exposes, passed in rather than imported: this\n * module is dispatch and `commands.ts` is the table, and importing one into the other would put the\n * whole command surface behind every consumer of `resolveSessionCommand`, including the plain path.\n */\nexport function resolveSessionCommand(\n text: string,\n offered: readonly string[] = [],\n): SessionCommand | undefined {\n const trimmed = text.trim()\n const kind = KNOWN.get(trimmed.toLowerCase())\n if (kind !== undefined) return { kind }\n\n const names = new Set(offered)\n if (names.has(trimmed.slice(1).toLowerCase()) && COMMAND_SHAPE.test(trimmed)) {\n return { kind: \"command\", name: trimmed.slice(1).toLowerCase(), rest: \"\" }\n }\n\n const withArgs = COMMAND_WITH_ARGS.exec(trimmed)\n if (withArgs !== null) {\n const head = (withArgs[1] ?? \"\").toLowerCase()\n const rest = withArgs[2] ?? \"\"\n const known = KNOWN.get(head)\n if (known !== undefined) return { kind: known, rest }\n if (names.has(head.slice(1))) {\n return { kind: \"command\", name: head.slice(1), rest }\n }\n // Not a known first token, so the narrow rule stands and this is prose.\n return undefined\n }\n\n if (!COMMAND_SHAPE.test(trimmed)) return undefined\n\n const suggestion = nearest(trimmed.toLowerCase(), [\n ...KNOWN.keys(),\n ...offered.map((name) => `/${name}`),\n ])\n return {\n kind: \"unknown\",\n word: trimmed,\n ...(suggestion === undefined ? {} : { nearest: suggestion }),\n }\n}\n\nconst COMMAND_COLUMN = 20\n\nfunction commandLine(spec: SessionCommandSpec): string {\n const forms = [spec.word, ...spec.aliases].join(\" / \")\n return ` ${forms.padEnd(COMMAND_COLUMN)}${spec.summary}`\n}\n\nfunction keyLine(spec: KeyBindingSpec): string {\n return ` ${spec.chord.padEnd(COMMAND_COLUMN)}${spec.summary}`\n}\n\n/** Generated, so a command the prompt honours cannot be missing from it. */\nexport function sessionHelpText(): string {\n return [\n \"commands:\",\n ...SESSION_COMMANDS.map(commandLine),\n \"\",\n \"keys:\",\n ...KEY_BINDINGS.map(keyLine),\n ].join(\"\\n\")\n}\n\nexport function unknownCommandText(command: {\n readonly word: string\n readonly nearest?: string\n}): string {\n const suggestion = command.nearest === undefined ? \"\" : ` Did you mean ${command.nearest}?`\n return `${command.word} is not a command.${suggestion} Type /help for the list — or add a space if you meant to say it to the model.`\n}\n\n/** The narrow slice of an agent `/tools` reports on. Structural, so core owns no CLI shapes. */\nexport interface ToolsView {\n readonly dialect: string\n readonly catalogueTokens: number\n readonly tools: readonly {\n readonly slug: string\n readonly mutating: boolean\n /**\n * Whether this tool's output may carry text a stranger wrote.\n *\n * Shown because it is not cosmetic: an untrusted tool taints the turn, and after it has run\n * a mutating call needs an explicit rule or a live approval. \"Why did my second `exec` get\n * blocked?\" is answered by this column and by nothing else on this surface.\n */\n readonly trust: string\n /**\n * Why a tool declares itself trusted when a provider tool defaults to untrusted.\n *\n * Shown here rather than warned about at boot. The warning fired on every start of every agent\n * using the system provider — four tools whose output the runtime composed — and a warning that\n * is always present for a correct configuration is one people stop reading. The reason belongs\n * where someone is already looking at the catalogue.\n */\n readonly trustReason?: string\n readonly summary: string\n }[]\n}\n\n/**\n * The part of an agent this needs, stated structurally.\n *\n * `Agent` satisfies it without being named, which keeps the projection below testable with a plain\n * object rather than a live runtime — and a projection nobody can test is one that quietly stops\n * matching what it projects.\n */\nexport interface AgentToolsSource {\n describe(): { readonly dialect: string; readonly catalogueTokens: number }\n readonly tools: {\n specs(): readonly {\n readonly slug: string\n readonly mutating: boolean\n /** Optional here because it is optional on `ToolSpec`; the registry settles it. */\n readonly trust?: string\n readonly trustReason?: string\n readonly summary: string\n }[]\n }\n}\n\n/** Here rather than in each renderer, so the two cannot show different things. */\nexport function toolsView(agent: AgentToolsSource): ToolsView {\n const described = agent.describe()\n return {\n dialect: described.dialect,\n catalogueTokens: described.catalogueTokens,\n tools: agent.tools.specs().map((spec) => ({\n slug: spec.slug,\n mutating: spec.mutating,\n // Already normalised by the registry, so the fallback is unreachable for anything that\n // came through one — but `ToolSpec.trust` is optional in the type, and a view that\n // silently printed nothing would be the wrong way to find that out.\n trust: spec.trust ?? \"trusted\",\n ...(spec.trustReason === undefined ? {} : { trustReason: spec.trustReason }),\n summary: spec.summary,\n })),\n }\n}\n\n/**\n * What the model can actually call.\n *\n * Worth a command because the catalogue is resolved once at load and is otherwise invisible: when a\n * model will not call a tool you believe is pinned, whether it is *in* the catalogue is the first\n * question, and `catalogueTokens` is the recurring cost of every turn in the session.\n */\nexport function toolsReport(view: ToolsView): string {\n if (view.tools.length === 0) {\n return `no tools — this agent pinned none, so the model can only reply. Add them under tools.local or tools.pinned. (call format ${view.dialect})`\n }\n\n const pad = view.tools.reduce((longest, tool) => Math.max(longest, tool.slug.length), 0)\n const rows = view.tools.flatMap((tool) => [\n ` ${tool.slug.padEnd(pad)} ${tool.mutating ? \"write\" : \"read \"} ${\n tool.trust === \"untrusted\" ? \"untrusted\" : \"trusted \"\n } ${tool.summary}`,\n // Only a tool that opted out of the untrusted default has one, so this is rare and worth the\n // line when it appears: it is the difference between a fence someone removed on purpose and one\n // a package forgot.\n // Aligned under the summary column: 2 leading spaces, the slug, and the two fixed columns\n // with their separators. Computed rather than hardcoded, or it drifts the first time a column\n // changes width.\n ...(tool.trustReason === undefined\n ? []\n : [`${\" \".repeat(2 + pad + 2 + 5 + 2 + 9 + 2)}trusted: ${tool.trustReason}`]),\n ])\n return [\n // \"dialect nlt\" led the line once and read as a third tool — and asked about it, the model\n // guessed NLTK, because the dialect is harness plumbing it is never told the name of. The\n // count leads; the protocol is labelled as what it is.\n `${view.tools.length} tool${view.tools.length === 1 ? \"\" : \"s\"} · call format ${view.dialect} · catalogue ${view.catalogueTokens} tokens, on every turn`,\n ...rows,\n ].join(\"\\n\")\n}\n\n/**\n * Everything `/context` needs, gathered by the host.\n *\n * A view rather than the agent itself, for the reason every view in this file is one: the report is a\n * pure function of these numbers, and a test that has to boot a runtime to check an arithmetic line\n * is a test nobody writes.\n */\nexport interface ContextView {\n readonly slots: readonly {\n readonly slot: number\n readonly label: string\n readonly tokens: number\n readonly pinned: boolean\n }[]\n /** What the history slot is made of, largest first. Empty on a conversation with no history. */\n readonly history: readonly {\n readonly label: string\n readonly tokens: number\n readonly messages: number\n }[]\n readonly total: number\n readonly window: number\n /** Already rendered by `describeWindowSource` — the CLI owns no second wording for it. */\n readonly windowSource: string\n readonly wireTokens: number\n readonly reserveOutput: number\n readonly calibration: { readonly ratio: number; readonly samples: number }\n /** The last compaction stage this session ran, if any. */\n readonly lastCompaction: string | undefined\n /** Undefined when no turn's endpoint reported a cache figure — not the same as nothing cached. */\n readonly cache:\n | {\n readonly cached: number\n readonly prompt: number\n readonly turns: number\n readonly source: string\n }\n | undefined\n}\n\n/**\n * `/context` — what is in the prompt right now, and what the percentage is a percentage *of*.\n *\n * The status line has carried `ctx 61%` since Phase 7A without ever saying what the denominator is,\n * and it is not the window: `assembleContext` is handed `window − wireTokens` and then subtracts\n * `reserveOutput` from that. Three terms, two of them invisible. So the budget line is written out as\n * the subtraction rather than as a result — a reader who disagrees with the number can see which term\n * they disagree with.\n *\n * `estimated` versus `corrected` is the other thing worth a line. The estimator runs **16–20% low**\n * on the prompts that matter (`evals/budget`, measured over a session filling with tool results),\n * which is the overflow direction exactly when the window is tight; a percentage from a session with\n * no samples yet is that raw estimate, and the reader deserves to know which one they are reading.\n */\nexport function contextReport(view: ContextView): string {\n const budget = Math.max(1, view.window - view.wireTokens - view.reserveOutput)\n const percent = ((view.total / budget) * 100).toFixed(1)\n const trust =\n view.calibration.samples === 0\n ? // Deliberately short: at 100 columns the longer version wrapped, and a wrapped value in a\n // `keyValue` block loses its alignment. \"estimated\" already carries \"no figure yet\"; what\n // it does not carry is the direction of the error, and that is the half worth the words.\n \"estimated — the estimator runs low on tool-heavy prompts\"\n : `corrected ×${view.calibration.ratio.toFixed(2)} from ${view.calibration.samples} reported ${view.calibration.samples === 1 ? \"figure\" : \"figures\"}`\n // Widest label decides the column, so a slot named later cannot push the numbers out of line.\n const pad = view.slots.reduce((longest, entry) => Math.max(longest, entry.label.length), 0)\n const slots = view.slots.map(\n (entry) =>\n ` ${String(entry.slot).padStart(2)} ${entry.label.padEnd(pad)} ${String(entry.tokens).padStart(6)}${entry.pinned ? \" pinned\" : \"\"}`,\n )\n // Indented under the history slot it decomposes, and only when there is something to decompose:\n // a fresh session's empty breakdown would be a heading with nothing under it.\n const historyPad = view.history.reduce((longest, e) => Math.max(longest, e.label.length), 0)\n const historyRows =\n view.history.length === 0\n ? []\n : view.history.map(\n (entry) =>\n ` ${entry.label.padEnd(historyPad)} ${String(entry.tokens).padStart(6)} ${percentOf(entry.tokens, view.total).padStart(6)} ${String(entry.messages).padStart(3)} msg`,\n )\n\n return [\n keyValue([\n { label: \"window\", value: `${view.window} (${view.windowSource})` },\n {\n label: \"budget\",\n // Written as the subtraction on purpose. `wireTokens` is zero under `nlt` and the term\n // is still printed: a zero that is shown is a term a reader can rule out, and a term\n // that is absent is one they have to know about to miss.\n value: `${budget} = window ${view.window} − wire ${view.wireTokens} − reserveOutput ${view.reserveOutput}`,\n },\n { label: \"prompt\", value: `${view.total} tokens · ${percent}% of budget` },\n { label: \"counted\", value: trust },\n {\n label: \"compaction\",\n value: view.lastCompaction ?? \"none this session\",\n },\n // Absent rather than \"0%\" when nothing reported: an endpoint that caches nothing and one\n // that declines to say are the same bill and opposite conclusions, and only one of them\n // is a reason to go looking at the prefix.\n {\n label: \"cache\",\n value:\n view.cache === undefined\n ? \"not reported by this endpoint\"\n : `${view.cache.cached} of ${view.cache.prompt} prompt tokens (${percentOf(view.cache.cached, view.cache.prompt)}) over ${view.cache.turns} turn${view.cache.turns === 1 ? \"\" : \"s\"} · ${view.cache.source}`,\n },\n ]),\n \"\",\n \" slots\",\n ...slots,\n // The heading names the denominator, because these are shares of the *whole prompt* and not of\n // the history — so they do not sum to 100 and, unlabelled, read as an arithmetic bug. Total is\n // the right denominator anyway: the question is what fraction of the bill each kind is, which\n // makes these directly comparable with the slot figures above.\n ...(historyRows.length === 0\n ? []\n : [\"\", \" history, by kind — share of the whole prompt\", ...historyRows]),\n ].join(\"\\n\")\n}\n\n/** A share, to one decimal, with the degenerate denominator handled rather than printed as NaN. */\nfunction percentOf(part: number, whole: number): string {\n return whole <= 0 ? \"—\" : `${((part / whole) * 100).toFixed(1)}%`\n}\n",
6
6
  "/**\n * The slash-command palette: what a partially typed `/word` could mean.\n *\n * ## Generated, not listed\n *\n * The entries come from two tables that already exist. `SESSION_COMMANDS` holds the verbs that only make\n * sense inside a session — `/help`, `/reset`, `/exit` — and `COMMANDS` holds the whole CLI, with every\n * flag, every `choices` value and every summary already written down for `--help`.\n *\n * Reading `COMMANDS` rather than a second list is the load-bearing decision. A flag added to the CLI\n * appears in the TUI with nothing to remember, which is the discipline `session-commands.ts`'s own header\n * argues for after watching `/help` drift in both directions when it was a string in a component. A\n * command that should not be offered in a session declares `inSession: \"hidden\"` — hiding by omission\n * from a hand-written list is the same drift wearing a different hat, and a required field means a new\n * command cannot be silently absent instead.\n *\n * ## Pure\n *\n * Derived from the editor's value, so the only state the renderer adds is a cursor index. No filesystem,\n * no process, no renderer — PURE-listed, and the matching rules are asserted as data.\n */\n\nimport { COMMANDS } from \"#lib/commands\"\nimport type { CommandSpec } from \"#lib/schema\"\nimport { SESSION_COMMANDS } from \"#lib/session-commands\"\n\nexport interface PaletteEntry {\n /** With the slash, as it would be typed. */\n readonly word: string\n readonly summary: string\n /**\n * `session` — dispatched by `resolveSessionCommand`.\n * `view` — a bespoke screen.\n * `output` — run the command and show what it printed.\n */\n readonly kind: \"session\" | \"view\" | \"output\"\n /** Present for a CLI command, so a host can read its flags and actions. */\n readonly spec?: CommandSpec\n}\n\n/**\n * Every entry a session offers, session verbs first.\n *\n * Session verbs lead because they are the ones with no shell equivalent and the ones typed most: `/help`\n * and `/exit` at the top of an unfiltered list is what makes the palette answer \"what can I do here\"\n * rather than \"what commands exist\".\n */\nexport function paletteEntries(): readonly PaletteEntry[] {\n const session: PaletteEntry[] = SESSION_COMMANDS.map((spec) => ({\n word: spec.word,\n summary: spec.summary,\n kind: \"session\" as const,\n }))\n const own = new Set(session.map((entry) => entry.word))\n const commands: PaletteEntry[] = COMMANDS.filter((spec) => spec.inSession !== \"hidden\")\n // A CLI command whose name collides with a session verb loses: `/tools` inside a session means\n // the running agent's catalogue, not a fresh load of the manifest from disk.\n .filter((spec) => !own.has(`/${spec.name}`))\n .map((spec) => ({\n word: `/${spec.name}`,\n summary: spec.summary,\n kind: spec.inSession === \"view\" ? (\"view\" as const) : (\"output\" as const),\n spec,\n }))\n return [...session, ...commands]\n}\n\nexport interface Palette {\n /** What has been typed after the slash, lowercased. */\n readonly query: string\n readonly matches: readonly PaletteEntry[]\n}\n\n/**\n * The palette for a buffer, or `undefined` when the buffer is not a slash command being typed.\n *\n * Open only while the *whole* buffer is one `/word` under construction. Two consequences, both\n * deliberate: a message that merely mentions a path never opens it, and once arguments are being typed\n * the list closes, because there is nothing left to complete and a list covering the line would hide\n * what is being written.\n */\nexport function paletteFor(\n value: string,\n entries: readonly PaletteEntry[] = paletteEntries(),\n): Palette | undefined {\n if (!/^\\/[A-Za-z-]*$/.test(value)) return undefined\n const query = value.slice(1).toLowerCase()\n const matches = entries.filter((entry) => entry.word.slice(1).toLowerCase().startsWith(query))\n // Prefix, not fuzzy. A palette that offers `/sessions` for `/st` reads as noise, and the words are\n // short enough that a prefix always reaches them in two or three characters.\n return { query, matches }\n}\n\n/** The entry a cursor is on, clamped, or `undefined` when nothing matches. */\nexport function paletteSelection(palette: Palette, index: number): PaletteEntry | undefined {\n if (palette.matches.length === 0) return undefined\n return palette.matches[Math.max(0, Math.min(index, palette.matches.length - 1))]\n}\n\n/**\n * The command names a typed slash line may use, without the leading slash.\n *\n * `resolveSessionCommand` takes this list, and it defaulted to empty at the one call site that mattered\n * — so a typed `/config get x` was prose and the same command chosen from the palette ran. Derived from\n * the palette rather than from `COMMANDS` directly, because the palette is what the person was just\n * shown: anything offered there has to be typeable, and anything typeable has to be offered.\n */\nexport function offeredCommands(): readonly string[] {\n return paletteEntries()\n .filter((entry) => entry.kind !== \"session\")\n .map((entry) => entry.word.slice(1))\n}\n",
7
- "/**\n * Events in, view state out. Pure, and the only place that decides what a turn looks like.\n *\n * The CLI has always been a `runtime.bus` subscriber; this makes it a *reducer* over that bus\n * instead of a set of callbacks writing to stdout. Three things follow from that:\n *\n * - \"What does the reader see when a turn errors mid-stream?\" is a unit test rather than something\n * reproduced by hand against a live endpoint.\n * - Finished items are append-only and immutable, which is exactly the contract Ink's `<Static>`\n * needs: a node written once and never re-rendered. The still-moving reply lives in `live`, so\n * the dynamic region stays one item regardless of how long the conversation gets.\n * - Phase 4's SSE client and Phase 12's TUI client can consume the same reduction instead of\n * re-deriving it.\n *\n * No clock and no randomness: ids come from a counter in the state, so the same events always\n * produce the same output and the tests need no fakes.\n */\n\nimport { type AnyEvent, endNote, SUBMIT_ARTIFACT } from \"@dispach/core\"\nimport { MAX_TRANSCRIPT_ITEMS, REASONING_FOLD_ROWS } from \"#lib/const\"\nimport { compactTokens } from \"#lib/rows\"\nimport { ROLE_PREFIX } from \"#lib/theme\"\nimport type {\n SubagentView,\n TranscriptItem,\n TranscriptRole,\n TranscriptRow,\n TranscriptState,\n TurnStats,\n} from \"#lib/types\"\nimport { wrapText } from \"#lib/wrap\"\n\n/**\n * The transcript is driven by more than the bus — a typed line and a cancellation request are not\n * events — so the reducer takes an action union rather than an event directly.\n */\nexport type TranscriptAction =\n | { readonly kind: \"user\"; readonly text: string }\n | { readonly kind: \"event\"; readonly event: AnyEvent }\n | { readonly kind: \"note\"; readonly text: string }\n | { readonly kind: \"cancelling\" }\n /**\n * A model delta that has already been through the dialect's stream filter.\n *\n * Filtering cannot happen in here: a filter is stateful and this reducer is pure. So the caller\n * owns one per step and dispatches what is left. A caller that dispatches the raw `model.chunk`\n * event instead still works — it just shows the invocation blocks, which is right for a dialect\n * with no in-band protocol and wrong for NLT.\n */\n | { readonly kind: \"delta\"; readonly of: \"text\" | \"reasoning\"; readonly text: string }\n /**\n * Drop the oldest items if the buffer is over `MAX_TRANSCRIPT_ITEMS`.\n *\n * An action rather than something `append` does on its own, because whether it is *safe* depends on\n * a fact this reducer cannot see: rows are addressed by position, so dropping any from the front\n * moves every offset below them. A reader parked twelve turns back would keep their offset and\n * silently start reading different text — the appearance of a live session that is not one, which is\n * the failure `ScrollState.pinned` exists to make impossible. Only the layer holding that flag knows\n * when eviction is allowed, so only it can ask.\n */\n | { readonly kind: \"trim\" }\n\nexport const EMPTY_TRANSCRIPT: TranscriptState = {\n items: [],\n live: undefined,\n status: \"idle\",\n nextId: 0,\n turnFrom: undefined,\n}\n\nfunction append(\n state: TranscriptState,\n role: TranscriptRole,\n text: string,\n extra: {\n readonly stats?: TurnStats\n readonly callId?: string\n readonly pending?: boolean\n } = {},\n): TranscriptState {\n const item: TranscriptItem = {\n id: `t${state.nextId}`,\n role,\n text,\n ...(extra.stats === undefined ? {} : { stats: extra.stats }),\n ...(extra.callId === undefined ? {} : { callId: extra.callId }),\n ...(extra.pending === undefined ? {} : { pending: extra.pending }),\n }\n return { ...state, items: [...state.items, item], nextId: state.nextId + 1 }\n}\n\n/**\n * Commit whatever the model has streamed so far, and clear it.\n *\n * Called at each step boundary rather than once at the end of the turn, which is what puts the\n * transcript back in the order things happened. Committing at `turn.end` alone produced a turn shaped\n * \"every tool row, then all the reasoning, then all the text\" — so the reasoning that *decided* to call\n * a tool was printed below the tool's result, and step one's reasoning was concatenated onto step two's\n * with no break between them. Live output on a real turn read `…look for it in my workspace.The user is\n * asking me to…`, two sentences from two steps with nothing marking the join.\n *\n * Reasoning goes in ahead of the text it produced. Whether it is *shown* is the view's business — the\n * item is written either way, so `--show-reasoning` can be honoured after the fact.\n */\nfunction flushLive(state: TranscriptState): TranscriptState {\n const live = state.live\n if (live === undefined) return state\n let next = state\n if (live.reasoning !== \"\") next = append(next, \"reasoning\", live.reasoning)\n if (live.text !== \"\") next = append(next, \"assistant\", live.text)\n return { ...next, live: undefined }\n}\n\n/** `data` is typed per event in core's map; narrowing by `type` first is what makes this safe. */\nexport function reduce(state: TranscriptState, action: TranscriptAction): TranscriptState {\n switch (action.kind) {\n case \"user\":\n return append(state, \"user\", action.text)\n\n case \"note\":\n return append(state, \"note\", action.text)\n\n case \"cancelling\":\n // A state, not an item. Cancellation that produced partial text still ends in a\n // `turn.end`, and that is what commits the text.\n return state.status === \"idle\" ? state : { ...state, status: \"cancelling\" }\n\n case \"delta\":\n return applyDelta(state, action.of, action.text)\n\n case \"event\":\n return reduceEvent(state, action.event)\n\n case \"trim\":\n return trim(state)\n }\n}\n\n/**\n * The oldest items above the cap, dropped. Identity when there is nothing to do.\n *\n * Returning the same object rather than a copy is what makes this cheap to ask about: `useReducer`\n * compares by reference and skips the render, so the caller can dispatch on every change without\n * checking first — and a caller that has to check first is a caller that eventually forgets.\n *\n * The banner is an ordinary item and goes with the rest. It is four hundred turns of scrollback above\n * the reader by then, and exempting it would leave the session's opening line pinned above a\n * conversation it no longer describes.\n */\nfunction trim(state: TranscriptState): TranscriptState {\n const over = state.items.length - MAX_TRANSCRIPT_ITEMS\n return over <= 0 ? state : { ...state, items: state.items.slice(over) }\n}\n\nfunction applyDelta(\n state: TranscriptState,\n kind: \"text\" | \"reasoning\",\n delta: string,\n): TranscriptState {\n if (delta === \"\") return state\n const live = state.live ?? { text: \"\", reasoning: \"\", last: undefined }\n return {\n ...state,\n live: {\n text: kind === \"text\" ? live.text + delta : live.text,\n reasoning: kind === \"reasoning\" ? live.reasoning + delta : live.reasoning,\n last: kind,\n },\n // A cancellation already asked for is not undone by another token arriving in flight; the\n // request stands until the turn actually ends.\n status: state.status === \"cancelling\" ? \"cancelling\" : \"streaming\",\n }\n}\n\n/** The tool row `match` picks, with its subagent replaced. Unchanged state when no row matches. */\nfunction withSubagent(\n state: TranscriptState,\n match: (item: TranscriptItem) => boolean,\n change: (view: SubagentView | undefined, item: TranscriptItem) => SubagentView | undefined,\n): TranscriptState {\n const at = state.items.findIndex(match)\n if (at === -1) return state\n const items = [...state.items]\n const item = items[at] as TranscriptItem\n const view = change(item.subagent, item)\n if (view === undefined) return state\n items[at] = { ...item, subagent: view }\n return { ...state, items }\n}\n\n/**\n * A subagent's own event: its tool calls become lines under the routed call's row. Its text and\n * turn events stay out of the conversation, which is the parent's; `handoff.result` reports the end.\n */\nfunction reduceChild(state: TranscriptState, event: AnyEvent): TranscriptState {\n const mine = (item: TranscriptItem) => item.subagent?.sessionKey === event.sessionKey\n // The child's return channel is how it hands back its answer, not work it did for the person.\n if (\"slug\" in event.data && event.data.slug === SUBMIT_ARTIFACT) return state\n switch (event.type) {\n case \"tool.call\":\n return withSubagent(state, mine, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: [\n ...view.lines,\n { callId: event.data.callId, text: `${event.data.slug} …` },\n ],\n },\n )\n case \"tool.result\": {\n const { slug, callId, ok, latencyMs } = event.data\n const text = `${slug} — ${ok ? \"ok\" : \"failed\"} · ${latencyMs} ms`\n return withSubagent(state, mine, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: view.lines.some((line) => line.callId === callId)\n ? view.lines.map((line) =>\n line.callId === callId ? { callId, text } : line,\n )\n : [...view.lines, { callId, text }],\n },\n )\n }\n case \"tool.gated\":\n return withSubagent(state, mine, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: [\n ...view.lines,\n { text: `${event.data.slug} — blocked: ${event.data.reason}` },\n ],\n },\n )\n default:\n return state\n }\n}\n\nfunction reduceEvent(state: TranscriptState, event: AnyEvent): TranscriptState {\n if (event.parentTurnId !== undefined) return reduceChild(state, event)\n switch (event.type) {\n case \"handoff.start\": {\n const { kind, name, callId, sessionKey } = event.data\n if (kind !== \"self\" || callId === undefined) return state\n return withSubagent(\n state,\n (item) => item.callId === callId,\n () => ({ name: name ?? \"subagent\", sessionKey, lines: [] }),\n )\n }\n\n case \"handoff.result\": {\n const { sessionKey, steps, tokens, outcome } = event.data\n const summary = `${steps} step${steps === 1 ? \"\" : \"s\"} · ${compactTokens(tokens.prompt + tokens.output)} tokens · ${outcome === \"ok\" ? \"ok\" : outcome.replace(\"_\", \" \")}`\n return withSubagent(\n state,\n (item) => item.subagent?.sessionKey === sessionKey,\n (view) => (view === undefined ? undefined : { ...view, summary }),\n )\n }\n\n case \"turn.start\":\n return {\n ...state,\n live: { text: \"\", reasoning: \"\", last: undefined },\n status: \"thinking\",\n turnFrom: state.items.length,\n }\n\n case \"model.result\":\n // The step boundary. `model.result` is emitted once per model call, so this is where a step's\n // reasoning and text stop growing — no new event was needed to find it.\n return flushLive(state)\n\n case \"model.chunk\":\n return applyDelta(state, event.data.kind, event.data.delta)\n\n case \"tool.call\":\n // Committed the moment the call starts, not when it returns: a tool that takes eight\n // seconds must not leave the screen looking like a stalled model. Anything the model\n // streamed before deciding to call it is flushed first, so the reasoning sits above the\n // call it explains rather than below the call's result.\n return {\n ...append(\n flushLive(state),\n \"tool\",\n `${event.data.slug}${event.data.mutating ? \" (changes state)\" : \"\"}`,\n { callId: event.data.callId, pending: true },\n ),\n status: state.status === \"cancelling\" ? \"cancelling\" : \"working\",\n }\n\n case \"tool.result\": {\n const { slug, callId, ok, latencyMs, truncated } = event.data\n const text = `${slug} — ${ok ? \"ok\" : \"failed\"} · ${latencyMs} ms${truncated ? \" · observation trimmed\" : \"\"}`\n // The call's own row, completed. Matched on `callId` rather than on position, because calls\n // can overlap and \"the last tool row\" is then not the row this result belongs to.\n const at = state.items.findIndex(\n (item) => item.callId === callId && item.pending === true,\n )\n if (at === -1) {\n // No row to complete — a result for a call this transcript never saw. Appended rather\n // than dropped: an observation nobody can account for is exactly the thing worth seeing.\n return append(state, ok ? \"tool\" : \"error\", text)\n }\n const items = [...state.items]\n const item = items[at] as TranscriptItem\n items[at] = {\n id: item.id,\n role: ok ? \"tool\" : \"error\",\n text,\n callId,\n // The routed call's block outlives its own completion: the child's lines are the point.\n ...(item.subagent === undefined ? {} : { subagent: item.subagent }),\n }\n return { ...state, items }\n }\n\n case \"tool.gated\":\n // Deliberately visible. A blocked write is the one tool outcome a person must not have\n // to go looking for — and it is a `note` rather than an `error` because the wire spec is\n // explicit that this is not one: the turn continues and the model reports back.\n return append(state, \"note\", `${event.data.slug} — blocked: ${event.data.reason}`)\n\n case \"tool.repair\":\n // A silent repair is indistinguishable from a slow turn, and it costs a whole step.\n return append(\n state,\n \"note\",\n `${event.data.slugs.join(\", \")} — could not be used, asking the model again`,\n )\n\n case \"model.retry\": {\n const { status, attempt, delayMs } = event.data\n return append(\n state,\n \"note\",\n `retrying after HTTP ${status} — attempt ${attempt}, waiting ${delayMs} ms`,\n )\n }\n\n case \"turn.end\": {\n const { reason, steps, tokens, durationMs } = event.data\n const stats: TurnStats = {\n promptTokens: tokens.prompt,\n outputTokens: tokens.output,\n durationMs,\n steps,\n reason,\n }\n\n // Whatever the last step streamed but never got a `model.result` for — a cancelled turn, or\n // one that ended on an error mid-stream. On a clean turn this is a no-op, because each step\n // committed itself as it finished.\n const next = flushLive(state)\n const from = state.turnFrom ?? 0\n // The reply this turn produced, which is where its cost belongs. Searched from the turn's own\n // first item: without that floor, a turn that produced no text would hang its statistics on\n // the *previous* turn's reply, which reads as that reply having cost twice.\n let reply = -1\n for (let at = next.items.length - 1; at >= from; at -= 1) {\n if (next.items[at]?.role === \"assistant\") {\n reply = at\n break\n }\n }\n // Why the turn stopped, from the formatter the plain path uses. Until this existed\n // `stats.reason` reached the reducer and was rendered nowhere, so a turn the step budget\n // cut off looked exactly like a completed one — which is how an agent came to stop\n // mid-task on \"Let me install it\" with nothing on screen explaining it.\n const why = endNote(reason, { steps, durationMs })\n\n if (reply === -1) {\n // A turn that produced nothing is not a normal outcome and must not look like one.\n const said = append(\n next,\n \"note\",\n why ?? (reason === \"final\" ? \"the model returned no text\" : \"\"),\n { stats },\n )\n return { ...said, live: undefined, status: \"idle\", turnFrom: undefined }\n }\n const items = [...next.items]\n const item = items[reply] as TranscriptItem\n items[reply] = { ...item, stats }\n const settled: TranscriptState = {\n ...next,\n items,\n live: undefined,\n status: \"idle\",\n turnFrom: undefined,\n }\n // Below the reply, not attached to it: the reply is what the model said, and this is what\n // the runtime did. Attaching it to the item would put a harness sentence in the model's\n // voice — the distinction `note` exists for.\n return why === undefined ? settled : append(settled, \"note\", why)\n }\n\n // `agent.error` used to fall through to here. It was declared in Phase 1, carried a\n // hint, and was emitted by **nothing, ever** — so this label was reachable only from a\n // test that constructed one by hand. Deleted rather than wired up: `error` already\n // carries every uncaught failure, and a second error event with no emitter is vocabulary\n // that makes the catalogue look richer than it is.\n case \"error\": {\n const { code, message, hint } = event.data\n return append(state, \"error\", `${code}: ${message}\\nhint: ${hint}`)\n }\n\n case \"context.dropped\": {\n const { messages, budget } = event.data\n // A note, not a stage line: the ladder decided what to compact and this is the budget\n // running out regardless. Worth saying because the agent is now answering without part of\n // the conversation, and nothing else on any surface would mention it.\n return append(\n state,\n \"note\",\n `context: ${messages} older message(s) did not fit the ${budget}-token budget and were left out`,\n )\n }\n\n case \"agent.warning\": {\n const { code, message } = event.data\n return append(state, \"note\", `${code}: ${message}`)\n }\n\n case \"context.pressure\":\n // A gauge, so it replaces rather than accumulates. `source` is deliberately not shown: it\n // is diagnostic and the status line has no room for a word that changes nothing a person\n // would do — it is on the event for whoever is reading events.\n return { ...state, pressure: event.data.fraction }\n\n case \"compaction.stage\": {\n const { stage, changed, before, after } = event.data\n // Only the stages that destroy detail get a line. trim, snip and micro are recoverable —\n // the conversation is still in the store and a snipped observation keeps a pointer — while\n // collapse and reset replace a span of the conversation with a summary, and a person who\n // was not watching the gauge still needs to know that happened.\n if (!changed || (stage !== \"collapse\" && stage !== \"reset\")) return state\n const what =\n stage === \"reset\"\n ? \"the conversation so far was replaced by a summary\"\n : \"earlier turns were replaced by a summary\"\n return append(state, \"note\", `context: ${what} (${before} → ${after} tokens)`)\n }\n\n case \"phase.changed\": {\n const { to, tools } = event.data\n // A line *and* the gauge. The line because a phase change is the reason the agent's\n // abilities changed mid-conversation, and a person scrolling back needs it where it\n // happened; the gauge because \"which phase am I in\" is a current-state question.\n const next = append(\n state,\n \"note\",\n `phase: now in ${to} · ${tools} tool${tools === 1 ? \"\" : \"s\"} available`,\n )\n return { ...next, phase: to }\n }\n\n case \"context.reset\": {\n const { warning } = event.data\n // The count itself is not shown — the note above already said what happened. A *second*\n // reset is a configuration problem rather than a busy session, and that is worth a line.\n return warning === undefined ? state : append(state, \"note\", `context: ${warning}`)\n }\n\n default:\n // Boot and bookkeeping events — `runtime.ready`, `store.ready`, `model.call`,\n // `context.assembled`. They belong to the banner and the status bar, not the transcript. Ignored explicitly so that a new event type added in a later\n // phase is inert here rather than a crash.\n return state\n }\n}\n\n/** What a renderer writes for a turn's cost. Kept here so the plain and rich paths agree. */\nexport function formatStats(stats: TurnStats): string {\n return `${stats.promptTokens} prompt · ${stats.outputTokens} output · ${stats.durationMs} ms`\n}\n\n/**\n * Opening banner — version, session, store, any turn a previous process left unfinished.\n *\n * One `banner` item rather than N notes, so the rich renderer can box it as a unit. The plain\n * path never calls this — it writes the lines directly — so plain output is unchanged by the\n * boxing.\n */\nexport function seed(notes: readonly string[]): TranscriptState {\n if (notes.length === 0) return EMPTY_TRANSCRIPT\n return append(EMPTY_TRANSCRIPT, \"banner\", notes.join(\"\\n\"))\n}\n\n/** One earlier message, as much of it as a transcript row needs. */\nexport interface PriorMessage {\n readonly role: \"user\" | \"assistant\"\n readonly text: string\n}\n\n/**\n * Put the conversation that already happened on the screen.\n *\n * Resuming used to paint an empty transcript over a full history: the messages reached the *model* and\n * never the person, so the banner said `17 message(s)` above a blank screen and the only honest reading\n * was that something had been lost. Rendering them is what makes that count verifiable.\n *\n * A separate function rather than a second argument to `seed`, because an optional parameter here would\n * have to distinguish \"no history\" from \"not asked for\" — and under `exactOptionalPropertyTypes` a\n * default parameter fires on an explicitly passed `undefined`, which has already cost this repo a\n * debugging round. `seedHistory(seed(banner), prior)` composes with nothing to remember.\n *\n * **Prose only.** Tool calls and observations are left out for the same reason they are left out of the\n * memory index: an observation is a wall of text a stranger wrote, and replaying forty of them above the\n * composer buries the conversation the person came back for. The turn statistics are left off too — they\n * were true of a process that has exited, and a cost line under a resumed reply reads as this session's.\n */\nexport function seedHistory(\n state: TranscriptState,\n messages: readonly PriorMessage[],\n): TranscriptState {\n let next = state\n for (const message of messages) {\n if (message.text.trim() === \"\") continue\n next = append(next, message.role, message.text)\n }\n return next\n}\n\n/** The most recent completed turn's cost, for the status bar. */\nexport function lastStats(items: readonly TranscriptItem[]): TurnStats | undefined {\n for (let i = items.length - 1; i >= 0; i -= 1) {\n const stats = items[i]?.stats\n if (stats !== undefined) return stats\n }\n return undefined\n}\n\n// ─── the finished conversation, as rows ──────────────────────────────────────────────────\n\n/**\n * Flatten items into the rows a windowed transcript scrolls through.\n *\n * ## Why rows rather than items\n *\n * Scrolling by item is the cheaper thing to build and the wrong unit. One assistant reply is a single\n * item and forty rows on screen, so an item-indexed window either shows the whole answer or none of it —\n * page-up from the bottom of a long reply would jump over the entire thing and land on the question\n * before it. Rows are what a reader moves through, so rows are what the offset counts.\n *\n * Wrapping happens here, not in Ink. A window has to know its content's height before it draws any of\n * it, and a count Ink might disagree with is a window off by however many lines wrapped — which shows up\n * as the last line of a reply hidden under the composer, intermittently, depending on the text.\n *\n * Pure, and one derivation for both halves of the frame: the component renders these rows and the layout\n * asks how many there are.\n */\nexport function transcriptRows(\n items: readonly TranscriptItem[],\n options: {\n readonly showReasoning: boolean\n readonly quiet: boolean\n readonly columns: number\n /** Reasoning blocks are shown whole rather than folded to `REASONING_FOLD_ROWS`. */\n readonly expandReasoning?: boolean\n },\n): readonly TranscriptRow[] {\n const rows: TranscriptRow[] = []\n const visible = items.filter((item) => item.role !== \"reasoning\" || options.showReasoning)\n\n /**\n * A row this renderer invented: a gap, a label, a fold notice, a stats line.\n *\n * `lead: 0` because there is no prefix to exclude, and `continuation: false` because it starts a line of\n * its own. Selectable, deliberately — a stats line or a banner note is text somebody may well want to\n * copy, and the cells worth excluding are the role prefixes, which are per-row and handled below.\n */\n const chrome = (row: Omit<TranscriptRow, \"lead\" | \"continuation\">): TranscriptRow => ({\n ...row,\n lead: 0,\n continuation: false,\n })\n\n for (const [at, item] of visible.entries()) {\n // A blank row between items, and never a trailing one. The rich transcript is read rather than\n // grepped, and two turns that touch each other read as one wall of text; a blank row at the end\n // would instead be a permanent gap above the composer.\n if (at > 0) rows.push(chrome({ key: `${item.id}:gap`, role: item.role, text: \"\" }))\n\n if (item.role === \"banner\") {\n // The banner keeps its content and loses its border. A bordered box inside a windowed list\n // costs two rows this module cannot count — Ink measures the frame, not us — and the frame\n // was decoration on a surface that is now itself a frame.\n const [title = \"\", ...lines] = item.text.split(\"\\n\")\n rows.push(chrome({ key: `${item.id}:title`, role: \"banner\", text: title, bold: true }))\n for (const [n, line] of lines.entries()) {\n for (const [w, wrapped] of wrapText(line, options.columns).entries()) {\n rows.push({\n key: `${item.id}:note-${n}-${w}`,\n role: \"banner\",\n text: wrapped,\n dim: true,\n lead: 0,\n // Only rows the *wrap* invented continue; a fresh source line does not.\n continuation: w > 0,\n })\n }\n }\n continue\n }\n\n const prefix = ROLE_PREFIX[item.role]\n const pad = \" \".repeat([...prefix].length)\n // The prefix is part of the first row's width and an indent on every row after it, so a reply\n // that wraps stays in one column instead of reading as a second message.\n const body = wrapText(item.text, Math.max(1, options.columns - [...prefix].length))\n\n if (item.role === \"reasoning\") {\n // A header row and an indented body, rather than a label wide enough to be the indent. Folded\n // unless asked for: the block is secondary, and at full length it routinely fills the screen\n // and pushes the reply it produced out of sight.\n const shown =\n options.expandReasoning === true\n ? body.length\n : Math.min(body.length, REASONING_FOLD_ROWS)\n const folded = body.length - shown\n rows.push(\n chrome({\n key: `${item.id}:label`,\n role: \"reasoning\",\n dim: true,\n text:\n folded > 0\n ? `· reasoning · ${body.length} rows · ⌥r expands`\n : `· reasoning · ${body.length} row${body.length === 1 ? \"\" : \"s\"}`,\n }),\n )\n for (const [n, line] of body.slice(0, shown).entries()) {\n rows.push({\n key: `${item.id}:${n}`,\n role: \"reasoning\",\n text: `${pad}${line}`,\n lead: pad.length,\n continuation: n > 0,\n })\n }\n if (folded > 0) {\n rows.push(\n chrome({\n key: `${item.id}:folded`,\n role: \"reasoning\",\n dim: true,\n text: `${pad}… ${folded} more row${folded === 1 ? \"\" : \"s\"}`,\n }),\n )\n }\n continue\n }\n\n for (const [n, line] of body.entries()) {\n rows.push({\n key: `${item.id}:${n}`,\n role: item.role,\n text: `${n === 0 ? prefix : pad}${line}`,\n // The prefix on the first row and its hanging indent on every row after it are the same\n // width, so one number covers both — and it is exactly the span a copy must drop.\n lead: [...prefix].length,\n continuation: n > 0,\n })\n }\n\n if (item.subagent !== undefined) {\n // Folded with the reasoning blocks, by the same key: both are the detail behind a row, and\n // the reply is what a person reads first.\n const view = item.subagent\n const open = options.expandReasoning === true\n const status = view.summary ?? \"running\"\n const more =\n !open && view.lines.length > 0\n ? ` · ⌥r shows ${view.lines.length} call${view.lines.length === 1 ? \"\" : \"s\"}`\n : \"\"\n for (const [n, line] of wrapText(\n `↳ subagent ${view.name} · ${status}${more}`,\n Math.max(1, options.columns - pad.length),\n ).entries()) {\n rows.push(\n chrome({\n key: `${item.id}:sub-${n}`,\n role: item.role,\n text: `${pad}${line}`,\n dim: true,\n }),\n )\n }\n if (open) {\n const inner = `${pad} `\n for (const [n, line] of view.lines.entries()) {\n for (const [w, wrapped] of wrapText(\n line.text,\n Math.max(1, options.columns - inner.length),\n ).entries()) {\n rows.push({\n key: `${item.id}:sub-${n}-${w}`,\n role: item.role,\n text: `${inner}${wrapped}`,\n dim: true,\n lead: inner.length,\n continuation: w > 0,\n })\n }\n }\n }\n }\n\n if (item.stats !== undefined && !options.quiet) {\n rows.push(\n chrome({\n key: `${item.id}:stats`,\n role: item.role,\n text: ` ${formatStats(item.stats)}`,\n dim: true,\n }),\n )\n }\n }\n\n return rows\n}\n"
7
+ "/**\n * Events in, view state out. Pure, and the only place that decides what a turn looks like.\n *\n * The CLI has always been a `runtime.bus` subscriber; this makes it a *reducer* over that bus\n * instead of a set of callbacks writing to stdout. Three things follow from that:\n *\n * - \"What does the reader see when a turn errors mid-stream?\" is a unit test rather than something\n * reproduced by hand against a live endpoint.\n * - Finished items are append-only and immutable, which is exactly the contract Ink's `<Static>`\n * needs: a node written once and never re-rendered. The still-moving reply lives in `live`, so\n * the dynamic region stays one item regardless of how long the conversation gets.\n * - Phase 4's SSE client and Phase 12's TUI client can consume the same reduction instead of\n * re-deriving it.\n *\n * No clock and no randomness: ids come from a counter in the state, so the same events always\n * produce the same output and the tests need no fakes.\n */\n\nimport { type AnyEvent, endNote, SUBMIT_ARTIFACT } from \"@dispach/core\"\nimport { MAX_TRANSCRIPT_ITEMS, REASONING_FOLD_ROWS } from \"#lib/const\"\nimport { compactTokens } from \"#lib/rows\"\nimport { ROLE_PREFIX } from \"#lib/theme\"\nimport type {\n SubagentView,\n TranscriptItem,\n TranscriptRole,\n TranscriptRow,\n TranscriptState,\n TurnStats,\n} from \"#lib/types\"\nimport { wrapText } from \"#lib/wrap\"\n\n/**\n * The transcript is driven by more than the bus — a typed line and a cancellation request are not\n * events — so the reducer takes an action union rather than an event directly.\n */\nexport type TranscriptAction =\n | { readonly kind: \"user\"; readonly text: string }\n | { readonly kind: \"event\"; readonly event: AnyEvent }\n | { readonly kind: \"note\"; readonly text: string }\n | { readonly kind: \"cancelling\" }\n /**\n * A model delta that has already been through the dialect's stream filter.\n *\n * Filtering cannot happen in here: a filter is stateful and this reducer is pure. So the caller\n * owns one per step and dispatches what is left. A caller that dispatches the raw `model.chunk`\n * event instead still works — it just shows the invocation blocks, which is right for a dialect\n * with no in-band protocol and wrong for NLT.\n */\n | { readonly kind: \"delta\"; readonly of: \"text\" | \"reasoning\"; readonly text: string }\n /**\n * Drop the oldest items if the buffer is over `MAX_TRANSCRIPT_ITEMS`.\n *\n * An action rather than something `append` does on its own, because whether it is *safe* depends on\n * a fact this reducer cannot see: rows are addressed by position, so dropping any from the front\n * moves every offset below them. A reader parked twelve turns back would keep their offset and\n * silently start reading different text — the appearance of a live session that is not one, which is\n * the failure `ScrollState.pinned` exists to make impossible. Only the layer holding that flag knows\n * when eviction is allowed, so only it can ask.\n */\n | { readonly kind: \"trim\" }\n\nexport const EMPTY_TRANSCRIPT: TranscriptState = {\n items: [],\n live: undefined,\n status: \"idle\",\n nextId: 0,\n turnFrom: undefined,\n}\n\nfunction append(\n state: TranscriptState,\n role: TranscriptRole,\n text: string,\n extra: {\n readonly stats?: TurnStats\n readonly callId?: string\n readonly pending?: boolean\n } = {},\n): TranscriptState {\n const item: TranscriptItem = {\n id: `t${state.nextId}`,\n role,\n text,\n ...(extra.stats === undefined ? {} : { stats: extra.stats }),\n ...(extra.callId === undefined ? {} : { callId: extra.callId }),\n ...(extra.pending === undefined ? {} : { pending: extra.pending }),\n }\n return { ...state, items: [...state.items, item], nextId: state.nextId + 1 }\n}\n\n/**\n * Commit whatever the model has streamed so far, and clear it.\n *\n * Called at each step boundary rather than once at the end of the turn, which is what puts the\n * transcript back in the order things happened. Committing at `turn.end` alone produced a turn shaped\n * \"every tool row, then all the reasoning, then all the text\" — so the reasoning that *decided* to call\n * a tool was printed below the tool's result, and step one's reasoning was concatenated onto step two's\n * with no break between them. Live output on a real turn read `…look for it in my workspace.The user is\n * asking me to…`, two sentences from two steps with nothing marking the join.\n *\n * Reasoning goes in ahead of the text it produced. Whether it is *shown* is the view's business — the\n * item is written either way, so `--show-reasoning` can be honoured after the fact.\n */\nfunction flushLive(state: TranscriptState): TranscriptState {\n const live = state.live\n if (live === undefined) return state\n let next = state\n if (live.reasoning !== \"\") next = append(next, \"reasoning\", live.reasoning)\n if (live.text !== \"\") next = append(next, \"assistant\", live.text)\n return { ...next, live: undefined }\n}\n\n/** `data` is typed per event in core's map; narrowing by `type` first is what makes this safe. */\nexport function reduce(state: TranscriptState, action: TranscriptAction): TranscriptState {\n switch (action.kind) {\n case \"user\":\n return append(state, \"user\", action.text)\n\n case \"note\":\n return append(state, \"note\", action.text)\n\n case \"cancelling\":\n // A state, not an item. Cancellation that produced partial text still ends in a\n // `turn.end`, and that is what commits the text.\n return state.status === \"idle\" ? state : { ...state, status: \"cancelling\" }\n\n case \"delta\":\n return applyDelta(state, action.of, action.text)\n\n case \"event\":\n return reduceEvent(state, action.event)\n\n case \"trim\":\n return trim(state)\n }\n}\n\n/**\n * The oldest items above the cap, dropped. Identity when there is nothing to do.\n *\n * Returning the same object rather than a copy is what makes this cheap to ask about: `useReducer`\n * compares by reference and skips the render, so the caller can dispatch on every change without\n * checking first — and a caller that has to check first is a caller that eventually forgets.\n *\n * The banner is an ordinary item and goes with the rest. It is four hundred turns of scrollback above\n * the reader by then, and exempting it would leave the session's opening line pinned above a\n * conversation it no longer describes.\n */\nfunction trim(state: TranscriptState): TranscriptState {\n const over = state.items.length - MAX_TRANSCRIPT_ITEMS\n return over <= 0 ? state : { ...state, items: state.items.slice(over) }\n}\n\nfunction applyDelta(\n state: TranscriptState,\n kind: \"text\" | \"reasoning\",\n delta: string,\n): TranscriptState {\n if (delta === \"\") return state\n const live = state.live ?? { text: \"\", reasoning: \"\", last: undefined }\n return {\n ...state,\n live: {\n text: kind === \"text\" ? live.text + delta : live.text,\n reasoning: kind === \"reasoning\" ? live.reasoning + delta : live.reasoning,\n last: kind,\n },\n // A cancellation already asked for is not undone by another token arriving in flight; the\n // request stands until the turn actually ends.\n status: state.status === \"cancelling\" ? \"cancelling\" : \"streaming\",\n }\n}\n\n/** The tool row `match` picks, with its subagent replaced. Unchanged state when no row matches. */\nfunction withSubagent(\n state: TranscriptState,\n match: (item: TranscriptItem) => boolean,\n change: (view: SubagentView | undefined, item: TranscriptItem) => SubagentView | undefined,\n): TranscriptState {\n const at = state.items.findIndex(match)\n if (at === -1) return state\n const items = [...state.items]\n const item = items[at] as TranscriptItem\n const view = change(item.subagent, item)\n if (view === undefined) return state\n items[at] = { ...item, subagent: view }\n return { ...state, items }\n}\n\n/**\n * A subagent's own event: its tool calls become lines under the routed call's row. Its text and\n * turn events stay out of the conversation, which is the parent's; `handoff.result` reports the end.\n */\nfunction reduceChild(state: TranscriptState, event: AnyEvent): TranscriptState {\n const mine = (item: TranscriptItem) => item.subagent?.sessionKey === event.sessionKey\n // The child's return channel is how it hands back its answer, not work it did for the person.\n if (\"slug\" in event.data && event.data.slug === SUBMIT_ARTIFACT) return state\n switch (event.type) {\n case \"tool.call\":\n return withSubagent(state, mine, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: [\n ...view.lines,\n { callId: event.data.callId, text: `${event.data.slug} …` },\n ],\n },\n )\n case \"tool.result\": {\n const { slug, callId, ok, latencyMs } = event.data\n const text = `${slug} — ${ok ? \"ok\" : \"failed\"} · ${latencyMs} ms`\n return withSubagent(state, mine, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: view.lines.some((line) => line.callId === callId)\n ? view.lines.map((line) =>\n line.callId === callId ? { callId, text } : line,\n )\n : [...view.lines, { callId, text }],\n },\n )\n }\n case \"tool.gated\":\n return withSubagent(state, mine, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: [\n ...view.lines,\n { text: `${event.data.slug} — blocked: ${event.data.reason}` },\n ],\n },\n )\n default:\n return state\n }\n}\n\nfunction reduceEvent(state: TranscriptState, event: AnyEvent): TranscriptState {\n if (event.parentTurnId !== undefined) return reduceChild(state, event)\n switch (event.type) {\n case \"handoff.start\": {\n const { kind, name, callId, sessionKey } = event.data\n if (kind !== \"self\" || callId === undefined) return state\n return withSubagent(\n state,\n (item) => item.callId === callId,\n () => ({ name: name ?? \"subagent\", sessionKey, lines: [] }),\n )\n }\n\n case \"handoff.result\": {\n const { sessionKey, steps, tokens, outcome } = event.data\n const summary = `${steps} step${steps === 1 ? \"\" : \"s\"} · ${compactTokens(tokens.prompt + tokens.output)} tokens · ${outcome === \"ok\" ? \"ok\" : outcome.replace(\"_\", \" \")}`\n return withSubagent(\n state,\n (item) => item.subagent?.sessionKey === sessionKey,\n (view) => (view === undefined ? undefined : { ...view, summary }),\n )\n }\n\n case \"turn.start\":\n return {\n ...state,\n live: { text: \"\", reasoning: \"\", last: undefined },\n status: \"thinking\",\n turnFrom: state.items.length,\n }\n\n case \"model.result\":\n // The step boundary. `model.result` is emitted once per model call, so this is where a step's\n // reasoning and text stop growing — no new event was needed to find it.\n return flushLive(state)\n\n case \"model.chunk\":\n return applyDelta(state, event.data.kind, event.data.delta)\n\n case \"tool.call\":\n // Committed the moment the call starts, not when it returns: a tool that takes eight\n // seconds must not leave the screen looking like a stalled model. Anything the model\n // streamed before deciding to call it is flushed first, so the reasoning sits above the\n // call it explains rather than below the call's result.\n return {\n ...append(\n flushLive(state),\n \"tool\",\n `${event.data.slug}${event.data.mutating ? \" (changes state)\" : \"\"}`,\n { callId: event.data.callId, pending: true },\n ),\n status: state.status === \"cancelling\" ? \"cancelling\" : \"working\",\n }\n\n case \"tool.result\": {\n const { slug, callId, ok, latencyMs, truncated } = event.data\n const text = `${slug} — ${ok ? \"ok\" : \"failed\"} · ${latencyMs} ms${truncated ? \" · observation trimmed\" : \"\"}`\n // The call's own row, completed. Matched on `callId` rather than on position, because calls\n // can overlap and \"the last tool row\" is then not the row this result belongs to.\n const at = state.items.findIndex(\n (item) => item.callId === callId && item.pending === true,\n )\n if (at === -1) {\n // No row to complete — a result for a call this transcript never saw. Appended rather\n // than dropped: an observation nobody can account for is exactly the thing worth seeing.\n return append(state, ok ? \"tool\" : \"error\", text)\n }\n const items = [...state.items]\n const item = items[at] as TranscriptItem\n items[at] = {\n id: item.id,\n role: ok ? \"tool\" : \"error\",\n text,\n callId,\n // The routed call's block outlives its own completion: the child's lines are the point.\n ...(item.subagent === undefined ? {} : { subagent: item.subagent }),\n }\n return { ...state, items }\n }\n\n case \"tool.gated\":\n // Deliberately visible. A blocked write is the one tool outcome a person must not have\n // to go looking for — and it is a `note` rather than an `error` because the wire spec is\n // explicit that this is not one: the turn continues and the model reports back.\n return append(state, \"note\", `${event.data.slug} — blocked: ${event.data.reason}`)\n\n case \"tool.repair\":\n // A silent repair is indistinguishable from a slow turn, and it costs a whole step. With no\n // slugs it is the runtime's nudge (14.123), not a tool that failed, and says so.\n return append(\n state,\n \"note\",\n event.data.slugs.length === 0\n ? `reply stopped short (${event.data.errors.join(\"; \")}), asking the model to finish`\n : `${event.data.slugs.join(\", \")} — could not be used, asking the model again`,\n )\n\n case \"model.retry\": {\n const { status, attempt, delayMs } = event.data\n return append(\n state,\n \"note\",\n `retrying after HTTP ${status} — attempt ${attempt}, waiting ${delayMs} ms`,\n )\n }\n\n case \"turn.end\": {\n const { reason, steps, tokens, durationMs } = event.data\n const stats: TurnStats = {\n promptTokens: tokens.prompt,\n outputTokens: tokens.output,\n durationMs,\n steps,\n reason,\n }\n\n // Whatever the last step streamed but never got a `model.result` for — a cancelled turn, or\n // one that ended on an error mid-stream. On a clean turn this is a no-op, because each step\n // committed itself as it finished.\n const next = flushLive(state)\n const from = state.turnFrom ?? 0\n // The reply this turn produced, which is where its cost belongs. Searched from the turn's own\n // first item: without that floor, a turn that produced no text would hang its statistics on\n // the *previous* turn's reply, which reads as that reply having cost twice.\n let reply = -1\n for (let at = next.items.length - 1; at >= from; at -= 1) {\n if (next.items[at]?.role === \"assistant\") {\n reply = at\n break\n }\n }\n // Why the turn stopped, from the formatter the plain path uses. Until this existed\n // `stats.reason` reached the reducer and was rendered nowhere, so a turn the step budget\n // cut off looked exactly like a completed one — which is how an agent came to stop\n // mid-task on \"Let me install it\" with nothing on screen explaining it.\n const why = endNote(reason, { steps, durationMs })\n\n if (reply === -1) {\n // A turn that produced nothing is not a normal outcome and must not look like one.\n const said = append(\n next,\n \"note\",\n why ?? (reason === \"final\" ? \"the model returned no text\" : \"\"),\n { stats },\n )\n return { ...said, live: undefined, status: \"idle\", turnFrom: undefined }\n }\n const items = [...next.items]\n const item = items[reply] as TranscriptItem\n items[reply] = { ...item, stats }\n const settled: TranscriptState = {\n ...next,\n items,\n live: undefined,\n status: \"idle\",\n turnFrom: undefined,\n }\n // Below the reply, not attached to it: the reply is what the model said, and this is what\n // the runtime did. Attaching it to the item would put a harness sentence in the model's\n // voice — the distinction `note` exists for.\n return why === undefined ? settled : append(settled, \"note\", why)\n }\n\n // `agent.error` used to fall through to here. It was declared in Phase 1, carried a\n // hint, and was emitted by **nothing, ever** — so this label was reachable only from a\n // test that constructed one by hand. Deleted rather than wired up: `error` already\n // carries every uncaught failure, and a second error event with no emitter is vocabulary\n // that makes the catalogue look richer than it is.\n case \"error\": {\n const { code, message, hint } = event.data\n return append(state, \"error\", `${code}: ${message}\\nhint: ${hint}`)\n }\n\n case \"context.dropped\": {\n const { messages, budget } = event.data\n // A note, not a stage line: the ladder decided what to compact and this is the budget\n // running out regardless. Worth saying because the agent is now answering without part of\n // the conversation, and nothing else on any surface would mention it.\n return append(\n state,\n \"note\",\n `context: ${messages} older message(s) did not fit the ${budget}-token budget and were left out`,\n )\n }\n\n case \"agent.warning\": {\n const { code, message } = event.data\n return append(state, \"note\", `${code}: ${message}`)\n }\n\n case \"context.pressure\":\n // A gauge, so it replaces rather than accumulates. `source` is deliberately not shown: it\n // is diagnostic and the status line has no room for a word that changes nothing a person\n // would do — it is on the event for whoever is reading events.\n return { ...state, pressure: event.data.fraction }\n\n case \"compaction.stage\": {\n const { stage, changed, before, after } = event.data\n // Only the stages that destroy detail get a line. trim, snip and micro are recoverable —\n // the conversation is still in the store and a snipped observation keeps a pointer — while\n // collapse and reset replace a span of the conversation with a summary, and a person who\n // was not watching the gauge still needs to know that happened.\n if (!changed || (stage !== \"collapse\" && stage !== \"reset\")) return state\n const what =\n stage === \"reset\"\n ? \"the conversation so far was replaced by a summary\"\n : \"earlier turns were replaced by a summary\"\n return append(state, \"note\", `context: ${what} (${before} → ${after} tokens)`)\n }\n\n case \"phase.changed\": {\n const { to, tools } = event.data\n // A line *and* the gauge. The line because a phase change is the reason the agent's\n // abilities changed mid-conversation, and a person scrolling back needs it where it\n // happened; the gauge because \"which phase am I in\" is a current-state question.\n const next = append(\n state,\n \"note\",\n `phase: now in ${to} · ${tools} tool${tools === 1 ? \"\" : \"s\"} available`,\n )\n return { ...next, phase: to }\n }\n\n case \"context.reset\": {\n const { warning } = event.data\n // The count itself is not shown — the note above already said what happened. A *second*\n // reset is a configuration problem rather than a busy session, and that is worth a line.\n return warning === undefined ? state : append(state, \"note\", `context: ${warning}`)\n }\n\n default:\n // Boot and bookkeeping events — `runtime.ready`, `store.ready`, `model.call`,\n // `context.assembled`. They belong to the banner and the status bar, not the transcript. Ignored explicitly so that a new event type added in a later\n // phase is inert here rather than a crash.\n return state\n }\n}\n\n/** What a renderer writes for a turn's cost. Kept here so the plain and rich paths agree. */\nexport function formatStats(stats: TurnStats): string {\n return `${stats.promptTokens} prompt · ${stats.outputTokens} output · ${stats.durationMs} ms`\n}\n\n/**\n * Opening banner — version, session, store, any turn a previous process left unfinished.\n *\n * One `banner` item rather than N notes, so the rich renderer can box it as a unit. The plain\n * path never calls this — it writes the lines directly — so plain output is unchanged by the\n * boxing.\n */\nexport function seed(notes: readonly string[]): TranscriptState {\n if (notes.length === 0) return EMPTY_TRANSCRIPT\n return append(EMPTY_TRANSCRIPT, \"banner\", notes.join(\"\\n\"))\n}\n\n/** One earlier message, as much of it as a transcript row needs. */\nexport interface PriorMessage {\n readonly role: \"user\" | \"assistant\"\n readonly text: string\n}\n\n/**\n * Put the conversation that already happened on the screen.\n *\n * Resuming used to paint an empty transcript over a full history: the messages reached the *model* and\n * never the person, so the banner said `17 message(s)` above a blank screen and the only honest reading\n * was that something had been lost. Rendering them is what makes that count verifiable.\n *\n * A separate function rather than a second argument to `seed`, because an optional parameter here would\n * have to distinguish \"no history\" from \"not asked for\" — and under `exactOptionalPropertyTypes` a\n * default parameter fires on an explicitly passed `undefined`, which has already cost this repo a\n * debugging round. `seedHistory(seed(banner), prior)` composes with nothing to remember.\n *\n * **Prose only.** Tool calls and observations are left out for the same reason they are left out of the\n * memory index: an observation is a wall of text a stranger wrote, and replaying forty of them above the\n * composer buries the conversation the person came back for. The turn statistics are left off too — they\n * were true of a process that has exited, and a cost line under a resumed reply reads as this session's.\n */\nexport function seedHistory(\n state: TranscriptState,\n messages: readonly PriorMessage[],\n): TranscriptState {\n let next = state\n for (const message of messages) {\n if (message.text.trim() === \"\") continue\n next = append(next, message.role, message.text)\n }\n return next\n}\n\n/** The most recent completed turn's cost, for the status bar. */\nexport function lastStats(items: readonly TranscriptItem[]): TurnStats | undefined {\n for (let i = items.length - 1; i >= 0; i -= 1) {\n const stats = items[i]?.stats\n if (stats !== undefined) return stats\n }\n return undefined\n}\n\n// ─── the finished conversation, as rows ──────────────────────────────────────────────────\n\n/**\n * Flatten items into the rows a windowed transcript scrolls through.\n *\n * ## Why rows rather than items\n *\n * Scrolling by item is the cheaper thing to build and the wrong unit. One assistant reply is a single\n * item and forty rows on screen, so an item-indexed window either shows the whole answer or none of it —\n * page-up from the bottom of a long reply would jump over the entire thing and land on the question\n * before it. Rows are what a reader moves through, so rows are what the offset counts.\n *\n * Wrapping happens here, not in Ink. A window has to know its content's height before it draws any of\n * it, and a count Ink might disagree with is a window off by however many lines wrapped — which shows up\n * as the last line of a reply hidden under the composer, intermittently, depending on the text.\n *\n * Pure, and one derivation for both halves of the frame: the component renders these rows and the layout\n * asks how many there are.\n */\nexport function transcriptRows(\n items: readonly TranscriptItem[],\n options: {\n readonly showReasoning: boolean\n readonly quiet: boolean\n readonly columns: number\n /** Reasoning blocks are shown whole rather than folded to `REASONING_FOLD_ROWS`. */\n readonly expandReasoning?: boolean\n },\n): readonly TranscriptRow[] {\n const rows: TranscriptRow[] = []\n const visible = items.filter((item) => item.role !== \"reasoning\" || options.showReasoning)\n\n /**\n * A row this renderer invented: a gap, a label, a fold notice, a stats line.\n *\n * `lead: 0` because there is no prefix to exclude, and `continuation: false` because it starts a line of\n * its own. Selectable, deliberately — a stats line or a banner note is text somebody may well want to\n * copy, and the cells worth excluding are the role prefixes, which are per-row and handled below.\n */\n const chrome = (row: Omit<TranscriptRow, \"lead\" | \"continuation\">): TranscriptRow => ({\n ...row,\n lead: 0,\n continuation: false,\n })\n\n for (const [at, item] of visible.entries()) {\n // A blank row between items, and never a trailing one. The rich transcript is read rather than\n // grepped, and two turns that touch each other read as one wall of text; a blank row at the end\n // would instead be a permanent gap above the composer.\n if (at > 0) rows.push(chrome({ key: `${item.id}:gap`, role: item.role, text: \"\" }))\n\n if (item.role === \"banner\") {\n // The banner keeps its content and loses its border. A bordered box inside a windowed list\n // costs two rows this module cannot count — Ink measures the frame, not us — and the frame\n // was decoration on a surface that is now itself a frame.\n const [title = \"\", ...lines] = item.text.split(\"\\n\")\n rows.push(chrome({ key: `${item.id}:title`, role: \"banner\", text: title, bold: true }))\n for (const [n, line] of lines.entries()) {\n for (const [w, wrapped] of wrapText(line, options.columns).entries()) {\n rows.push({\n key: `${item.id}:note-${n}-${w}`,\n role: \"banner\",\n text: wrapped,\n dim: true,\n lead: 0,\n // Only rows the *wrap* invented continue; a fresh source line does not.\n continuation: w > 0,\n })\n }\n }\n continue\n }\n\n const prefix = ROLE_PREFIX[item.role]\n const pad = \" \".repeat([...prefix].length)\n // The prefix is part of the first row's width and an indent on every row after it, so a reply\n // that wraps stays in one column instead of reading as a second message.\n const body = wrapText(item.text, Math.max(1, options.columns - [...prefix].length))\n\n if (item.role === \"reasoning\") {\n // A header row and an indented body, rather than a label wide enough to be the indent. Folded\n // unless asked for: the block is secondary, and at full length it routinely fills the screen\n // and pushes the reply it produced out of sight.\n const shown =\n options.expandReasoning === true\n ? body.length\n : Math.min(body.length, REASONING_FOLD_ROWS)\n const folded = body.length - shown\n rows.push(\n chrome({\n key: `${item.id}:label`,\n role: \"reasoning\",\n dim: true,\n text:\n folded > 0\n ? `· reasoning · ${body.length} rows · ⌥r expands`\n : `· reasoning · ${body.length} row${body.length === 1 ? \"\" : \"s\"}`,\n }),\n )\n for (const [n, line] of body.slice(0, shown).entries()) {\n rows.push({\n key: `${item.id}:${n}`,\n role: \"reasoning\",\n text: `${pad}${line}`,\n lead: pad.length,\n continuation: n > 0,\n })\n }\n if (folded > 0) {\n rows.push(\n chrome({\n key: `${item.id}:folded`,\n role: \"reasoning\",\n dim: true,\n text: `${pad}… ${folded} more row${folded === 1 ? \"\" : \"s\"}`,\n }),\n )\n }\n continue\n }\n\n for (const [n, line] of body.entries()) {\n rows.push({\n key: `${item.id}:${n}`,\n role: item.role,\n text: `${n === 0 ? prefix : pad}${line}`,\n // The prefix on the first row and its hanging indent on every row after it are the same\n // width, so one number covers both — and it is exactly the span a copy must drop.\n lead: [...prefix].length,\n continuation: n > 0,\n })\n }\n\n if (item.subagent !== undefined) {\n // Folded with the reasoning blocks, by the same key: both are the detail behind a row, and\n // the reply is what a person reads first.\n const view = item.subagent\n const open = options.expandReasoning === true\n const status = view.summary ?? \"running\"\n const more =\n !open && view.lines.length > 0\n ? ` · ⌥r shows ${view.lines.length} call${view.lines.length === 1 ? \"\" : \"s\"}`\n : \"\"\n for (const [n, line] of wrapText(\n `↳ subagent ${view.name} · ${status}${more}`,\n Math.max(1, options.columns - pad.length),\n ).entries()) {\n rows.push(\n chrome({\n key: `${item.id}:sub-${n}`,\n role: item.role,\n text: `${pad}${line}`,\n dim: true,\n }),\n )\n }\n if (open) {\n const inner = `${pad} `\n for (const [n, line] of view.lines.entries()) {\n for (const [w, wrapped] of wrapText(\n line.text,\n Math.max(1, options.columns - inner.length),\n ).entries()) {\n rows.push({\n key: `${item.id}:sub-${n}-${w}`,\n role: item.role,\n text: `${inner}${wrapped}`,\n dim: true,\n lead: inner.length,\n continuation: w > 0,\n })\n }\n }\n }\n }\n\n if (item.stats !== undefined && !options.quiet) {\n rows.push(\n chrome({\n key: `${item.id}:stats`,\n role: item.role,\n text: ` ${formatStats(item.stats)}`,\n dim: true,\n }),\n )\n }\n }\n\n return rows\n}\n"
8
8
  ],
9
- "mappings": ";mQAuCO,IAAM,EAAkD,CAC3D,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EAAK,MAAM,cAAc,EAAK,MAAM,SAAW,EAAI,GAAK,MACvE,GACV,QAAY,EAAG,KAAS,GACpB,cAAc,EAAK,UAAU,IAAS,IACtC,KAAK,IAAI,EAAG,EAAQ,QAAU,EAAI,MAAM,CAC5C,EAAE,QAAQ,EACN,EAAK,KACD,EAAO,CACH,IAAK,GAAG,EAAK,UAAU,IACvB,KAAM,EAAK,KACX,KAAM,GAAG,IAAM,IACf,IAAK,EACT,CAAC,CACL,EAEJ,GAAI,EAAM,CACN,IAAM,EAAQ,GAAG,MACjB,QAAY,EAAG,KAAS,EAAK,MAAM,QAAQ,EACvC,QAAY,EAAG,KAAY,GACvB,EAAK,KACL,KAAK,IAAI,EAAG,EAAQ,QAAU,EAAM,MAAM,CAC9C,EAAE,QAAQ,EACN,EAAK,KAAK,CACN,IAAK,GAAG,EAAK,UAAU,KAAK,IAC5B,KAAM,EAAK,KACX,KAAM,GAAG,IAAQ,IACjB,IAAK,GACL,KAAM,EAAM,OACZ,aAAc,EAAI,CACtB,CAAC,GAMjB,GAAI,EAAK,QAAU,QAAa,CAAC,EAAQ,MACrC,EAAK,KACD,EAAO,CACH,IAAK,GAAG,EAAK,WACb,KAAM,EAAK,KACX,KAAM,KAAK,GAAY,EAAK,KAAK,IACjC,IAAK,EACT,CAAC,CACL,EAIR,OAAO",
10
+ "debugId": "B9B41FE7D091615A64756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{X,yA,K}from"./index-fcqy46mh.js";import{e}from"./index-t6xnecdx.js";var T=e(function(B){var{buildQueryString:_}=K(),U=(t)=>typeof t==="string"&&t.indexOf("arn:")===0&&t.split(":").length>=6,L=(t)=>{let r=t.split(":");if(r.length<6||r[0]!=="arn")throw Error("Malformed ARN");let[,n,o,s,a,...c]=r;return{partition:n,service:o,region:s,accountId:a,resource:c.join(":")}},D=(t)=>{let{partition:r="aws",service:n,region:o,accountId:s,resource:a}=t;if([n,o,s,a].some((c)=>typeof c!=="string"))throw Error("Input ARN object is invalid");return`arn:${r}:${n}:${o}:${s}:${a}`};function z(t){let{port:r,query:n}=t,{protocol:o,path:s,hostname:a}=t;if(o&&o.slice(-1)!==":")o+=":";if(r)a+=`:${r}`;if(s&&s.charAt(0)!=="/")s=`/${s}`;let c=n?_(n):"";if(c&&c[0]!=="?")c=`?${c}`;let u="";if(t.username!=null||t.password!=null){let d=t.username??"",f=t.password??"";u=`${d}:${f}@`}let i="";if(t.fragment)i=`#${t.fragment}`;return`${o}//${u}${a}${s}${c}${i}`}function F(t,r){return Object.prototype.hasOwnProperty.call(t,r)}B.build=D;B.formatUrl=z;B.hasOwn=F;B.parse=L;B.validate=U});var H=e(function(re){var{buildQueryString:Z,HttpResponse:R}=K(),{streamCollector:ee}=X();re.streamCollector=ee;function x(t,r){return new Request(t,r)}function te(t=0){return new Promise((r,n)=>{if(t)setTimeout(()=>{let o=Error(`Request did not complete within ${t} ms`);o.name="TimeoutError",n(o)},t)})}var v={supported:void 0};class E{config;configProvider;static create(t){if(typeof t?.handle==="function")return t;return new E(t)}constructor(t){if(typeof t==="function")this.configProvider=t().then((r)=>r||{});else this.config=t??{},this.configProvider=Promise.resolve(this.config);if(v.supported===void 0)v.supported=Boolean(typeof Request<"u"&&"keepalive"in x("https://[::1]"))}destroy(){}async handle(t,{abortSignal:r,requestTimeout:n}={}){if(!this.config)this.config=await this.configProvider;let o=n??this.config.requestTimeout,s=this.config.keepAlive===!0,a=this.config.credentials,c=this.config.customFetch??fetch;if(r?.aborted){let l=I(r);return Promise.reject(l)}let u=t.path,i=Z(t.query||{});if(i)u+=`?${i}`;if(t.fragment)u+=`#${t.fragment}`;let d="";if(t.username!=null||t.password!=null){let l=t.username??"",w=t.password??"";d=`${l}:${w}@`}let{port:f,method:h}=t,m=`${t.protocol}//${d}${t.hostname}${f?`:${f}`:""}${u}`,y=h==="GET"||h==="HEAD"?void 0:t.body,g={body:y,headers:new Headers(t.headers),method:h,credentials:a};if(this.config?.cache)g.cache=this.config.cache;if(y)g.duplex="half";if(typeof AbortController<"u")g.signal=r;if(v.supported)g.keepalive=s;if(typeof this.config.requestInit==="function")Object.assign(g,this.config.requestInit(t));let P=()=>{},q=x(m,g),C=[c(q).then((l)=>{let w=l.headers,p={};for(let S of w.entries())p[S[0]]=S[1];if(l.body==null)return l.blob().then((S)=>({response:new R({headers:p,reason:l.statusText,statusCode:l.status,body:S})}));return{response:new R({headers:p,reason:l.statusText,statusCode:l.status,body:l.body})}}),te(o)];if(r)C.push(new Promise((l,w)=>{let p=()=>{let b=I(r);w(b)};if(typeof r.addEventListener==="function"){let b=r;b.addEventListener("abort",p,{once:!0}),P=()=>b.removeEventListener("abort",p)}else r.onabort=p}));return Promise.race(C).finally(P)}updateHttpClientConfig(t,r){this.config=void 0,this.configProvider=this.configProvider.then((n)=>(n[t]=r,n))}httpHandlerConfigs(){return this.config??{}}}function I(t){let r=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(r){if(r instanceof Error){let s=Error("Request aborted");return s.name="AbortError",s.cause=r,s}let o=Error(String(r));return o.name="AbortError",o}let n=Error("Request aborted");return n.name="AbortError",n}re.FetchHttpHandler=E;re.keepAliveSupport=v});var qo=e(function(Pe){var{formatUrl:ie}=T(),{iterableToReadableStream:ae,readableStreamToIterable:ce,EventStreamCodec:de}=yA(),{HttpResponse:ue,HttpRequest:A}=K(),{fromBase64:le,fromHex:fe}=X(),{FetchHttpHandler:O}=H(),M=(t)=>t.protocol==="ws:"||t.protocol==="wss:";class k{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(t,r=new O){if(typeof t?.handle==="function")return t;return new k(t,r)}constructor(t,r=new O){this.httpHandler=r;let n=(o)=>(this.config={...o??{}},this.config);if(typeof t==="function")this.config={},this.configPromise=t().then((o)=>n(o));else this.configPromise=Promise.resolve(n(t))}destroy(){for(let[t,r]of Object.entries(this.sockets)){for(let n of r)n.close(1000,"Socket closed through destroy() call");delete this.sockets[t]}}async handle(t){this.config=await this.configPromise;let{logger:r}=this.config;if(!M(t))return r?.debug?.(`@aws-sdk - ws fetching ${t.protocol}${t.hostname}${t.path}`),this.httpHandler.handle(t);let n=ie(t);r?.debug?.(`@aws-sdk - ws connecting ${n.split("?")[0]}`);let o=new WebSocket(n);if(!this.sockets[n])this.sockets[n]=[];this.sockets[n].push(o),o.binaryType="arraybuffer";let{connectionTimeout:s=3000}=this.config;await this.waitForReady(o,s);let{body:a}=t,c=he(a),u=this.connect(o,c),i=pe(u);return{response:new ue({statusCode:200,body:i})}}updateHttpClientConfig(t,r){this.configPromise=this.configPromise.then((n)=>(n[t]=r,n))}httpHandlerConfigs(){return this.config??{}}removeNotUsableSockets(t){this.sockets[t]=(this.sockets[t]??[]).filter((r)=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(r.readyState))}waitForReady(t,r){return new Promise((n,o)=>{let s=setTimeout(()=>{this.removeNotUsableSockets(t.url),o({$metadata:{httpStatusCode:500,websocketSynthetic500Error:!0}})},r);t.onopen=()=>{clearTimeout(s),n()}})}connect(t,r){let n=[],o=null,s=null,a=(i)=>{if(o){if(i.error)s(i.error);else o({done:i.done,value:i.value});o=null,s=null}else n.push(i)};t.onmessage=(i)=>{let{data:d}=i;if(typeof d==="string")a({done:!1,value:le(d)});else a({done:!1,value:new Uint8Array(d)})},t.onerror=(i)=>{t.close(),a({done:!0,error:i})},t.onclose=()=>{this.removeNotUsableSockets(t.url),a({done:!0})};let c={[Symbol.asyncIterator]:()=>({async next(){if(n.length>0){let i=n.shift();if(i.error)throw i.error;return{done:i.done,value:i.value}}return new Promise((i,d)=>{o=i,s=d})}})};return(async()=>{try{for await(let i of r)if(t.readyState>=WebSocket.CLOSING)break;else t.send(i)}catch(i){a({done:!0,error:i})}finally{t.close(1000)}})(),c}}var he=(t)=>{if(t[Symbol.asyncIterator])return t;if(ge(t))return ce(t);return{[Symbol.asyncIterator]:async function*(){yield t}}},pe=(t)=>typeof ReadableStream==="function"?ae(t):t,ge=(t)=>typeof ReadableStream==="function"&&t instanceof ReadableStream,me=(t,r)=>(n)=>(o)=>{let{request:s}=o;if(A.isInstance(s)&&t.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")){s.protocol="wss:",s.method="GET",s.path=`${s.path}-websocket`;let{headers:a}=s;delete a["content-type"],delete a["x-amz-content-sha256"];for(let c of Object.keys(a))if(c.indexOf(r.headerPrefix)===0){let u=c.replace(r.headerPrefix,"");s.query[u]=a[c]}if(a["x-amz-user-agent"])s.query["user-agent"]=a["x-amz-user-agent"];s.headers={host:a.host??s.hostname}}return n(o)},ye={name:"websocketEndpointMiddleware",tags:["WEBSOCKET","EVENT_STREAM"],relation:"after",toMiddleware:"eventStreamHeaderMiddleware",override:!0},we=()=>(t)=>async(r)=>{let n={...r.input},o=await t(r),s=o.output;if(n.SessionId&&s.SessionId==null)s.SessionId=n.SessionId;return o},be={step:"initialize",name:"injectSessionIdMiddleware",tags:["WEBSOCKET","EVENT_STREAM"],override:!0},Se=(t,r)=>({applyToStack:(n)=>{n.addRelativeTo(me(t,r),ye),n.add(we(),be)}});class N{signer;constructor(t){this.signer=t.signer}presign(t,r={}){return this.signer.presign(t,r)}async sign(t,r){if(A.isInstance(t)&&M(t))return{...await this.signer.presign({...t,body:""},{...r,expiresIn:60,unsignableHeaders:new Set(Object.keys(t.headers).filter((o)=>o!=="host"))}),body:t.body};else return this.signer.sign(t,r)}signMessage(t,r){return this.signer.signMessage(t,r)}}var ve=(t)=>{let{signer:r}=t;return Object.assign(t,{signer:async(n)=>{let o=await r(n);if(Ee(o))return new N({signer:o});throw Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},Ee=(t)=>!!t;class j extends TransformStream{constructor(t,r,n,o,s){let a=t,c=s?.();super({start(){},async transform(u,i){try{let d=new Date(Date.now()+await o()),f={":date":{type:"timestamp",value:d}},h=await r.sign({message:{body:u,headers:f},priorSignature:a},{signingDate:d,eventStreamCredentials:await c});a=h.signature;let m=n.encode({headers:{...f,":chunk-signature":{type:"binary",value:fe(h.signature)}},body:u});i.enqueue(m)}catch(d){i.error(d)}}})}}class W{messageSigner;eventStreamCodec;systemClockOffsetProvider;credentials;constructor(t){this.messageSigner=t.messageSigner,this.eventStreamCodec=new de(t.utf8Encoder,t.utf8Decoder),this.systemClockOffsetProvider=async()=>t.systemClockOffset??0,this.credentials=t.credentials}async handle(t,r,n={}){let o=r.request,{body:s,headers:a,query:c}=o;if(!(s instanceof ReadableStream))throw Error("Eventstream payload must be a ReadableStream.");let u=new TransformStream;o.body=u.readable;let d=((a?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(c&&c["X-Amz-Signature"])??"";if(n.__staticSignature)d="";let f=new j(d,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider,this.credentials);s.pipeThrough(f).pipeThrough(u);let h;try{h=await t(r)}catch(m){let y=s.cancel?.();if(y instanceof Promise)y.catch(()=>{});throw m}return h}}var ke=(t)=>new W(t);Pe.WebSocketFetchHandler=k;Pe.eventStreamPayloadHandlerProvider=ke;Pe.getWebSocketPlugin=Se;Pe.resolveWebSocketConfig=ve});
2
+ import{X,yt,K}from"./index-0pddq849.js";import{e}from"./index-t6xnecdx.js";var T=e(function(B){var{buildQueryString:_}=K(),U=(t)=>typeof t==="string"&&t.indexOf("arn:")===0&&t.split(":").length>=6,L=(t)=>{let r=t.split(":");if(r.length<6||r[0]!=="arn")throw Error("Malformed ARN");let[,n,o,s,a,...c]=r;return{partition:n,service:o,region:s,accountId:a,resource:c.join(":")}},D=(t)=>{let{partition:r="aws",service:n,region:o,accountId:s,resource:a}=t;if([n,o,s,a].some((c)=>typeof c!=="string"))throw Error("Input ARN object is invalid");return`arn:${r}:${n}:${o}:${s}:${a}`};function z(t){let{port:r,query:n}=t,{protocol:o,path:s,hostname:a}=t;if(o&&o.slice(-1)!==":")o+=":";if(r)a+=`:${r}`;if(s&&s.charAt(0)!=="/")s=`/${s}`;let c=n?_(n):"";if(c&&c[0]!=="?")c=`?${c}`;let u="";if(t.username!=null||t.password!=null){let d=t.username??"",f=t.password??"";u=`${d}:${f}@`}let i="";if(t.fragment)i=`#${t.fragment}`;return`${o}//${u}${a}${s}${c}${i}`}function F(t,r){return Object.prototype.hasOwnProperty.call(t,r)}B.build=D;B.formatUrl=z;B.hasOwn=F;B.parse=L;B.validate=U});var H=e(function(re){var{buildQueryString:Z,HttpResponse:R}=K(),{streamCollector:ee}=X();re.streamCollector=ee;function x(t,r){return new Request(t,r)}function te(t=0){return new Promise((r,n)=>{if(t)setTimeout(()=>{let o=Error(`Request did not complete within ${t} ms`);o.name="TimeoutError",n(o)},t)})}var v={supported:void 0};class E{config;configProvider;static create(t){if(typeof t?.handle==="function")return t;return new E(t)}constructor(t){if(typeof t==="function")this.configProvider=t().then((r)=>r||{});else this.config=t??{},this.configProvider=Promise.resolve(this.config);if(v.supported===void 0)v.supported=Boolean(typeof Request<"u"&&"keepalive"in x("https://[::1]"))}destroy(){}async handle(t,{abortSignal:r,requestTimeout:n}={}){if(!this.config)this.config=await this.configProvider;let o=n??this.config.requestTimeout,s=this.config.keepAlive===!0,a=this.config.credentials,c=this.config.customFetch??fetch;if(r?.aborted){let l=I(r);return Promise.reject(l)}let u=t.path,i=Z(t.query||{});if(i)u+=`?${i}`;if(t.fragment)u+=`#${t.fragment}`;let d="";if(t.username!=null||t.password!=null){let l=t.username??"",w=t.password??"";d=`${l}:${w}@`}let{port:f,method:h}=t,m=`${t.protocol}//${d}${t.hostname}${f?`:${f}`:""}${u}`,y=h==="GET"||h==="HEAD"?void 0:t.body,g={body:y,headers:new Headers(t.headers),method:h,credentials:a};if(this.config?.cache)g.cache=this.config.cache;if(y)g.duplex="half";if(typeof AbortController<"u")g.signal=r;if(v.supported)g.keepalive=s;if(typeof this.config.requestInit==="function")Object.assign(g,this.config.requestInit(t));let P=()=>{},q=x(m,g),C=[c(q).then((l)=>{let w=l.headers,p={};for(let S of w.entries())p[S[0]]=S[1];if(l.body==null)return l.blob().then((S)=>({response:new R({headers:p,reason:l.statusText,statusCode:l.status,body:S})}));return{response:new R({headers:p,reason:l.statusText,statusCode:l.status,body:l.body})}}),te(o)];if(r)C.push(new Promise((l,w)=>{let p=()=>{let b=I(r);w(b)};if(typeof r.addEventListener==="function"){let b=r;b.addEventListener("abort",p,{once:!0}),P=()=>b.removeEventListener("abort",p)}else r.onabort=p}));return Promise.race(C).finally(P)}updateHttpClientConfig(t,r){this.config=void 0,this.configProvider=this.configProvider.then((n)=>(n[t]=r,n))}httpHandlerConfigs(){return this.config??{}}}function I(t){let r=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(r){if(r instanceof Error){let s=Error("Request aborted");return s.name="AbortError",s.cause=r,s}let o=Error(String(r));return o.name="AbortError",o}let n=Error("Request aborted");return n.name="AbortError",n}re.FetchHttpHandler=E;re.keepAliveSupport=v});var qo=e(function(Pe){var{formatUrl:ie}=T(),{iterableToReadableStream:ae,readableStreamToIterable:ce,EventStreamCodec:de}=yt(),{HttpResponse:ue,HttpRequest:A}=K(),{fromBase64:le,fromHex:fe}=X(),{FetchHttpHandler:O}=H(),M=(t)=>t.protocol==="ws:"||t.protocol==="wss:";class k{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(t,r=new O){if(typeof t?.handle==="function")return t;return new k(t,r)}constructor(t,r=new O){this.httpHandler=r;let n=(o)=>(this.config={...o??{}},this.config);if(typeof t==="function")this.config={},this.configPromise=t().then((o)=>n(o));else this.configPromise=Promise.resolve(n(t))}destroy(){for(let[t,r]of Object.entries(this.sockets)){for(let n of r)n.close(1000,"Socket closed through destroy() call");delete this.sockets[t]}}async handle(t){this.config=await this.configPromise;let{logger:r}=this.config;if(!M(t))return r?.debug?.(`@aws-sdk - ws fetching ${t.protocol}${t.hostname}${t.path}`),this.httpHandler.handle(t);let n=ie(t);r?.debug?.(`@aws-sdk - ws connecting ${n.split("?")[0]}`);let o=new WebSocket(n);if(!this.sockets[n])this.sockets[n]=[];this.sockets[n].push(o),o.binaryType="arraybuffer";let{connectionTimeout:s=3000}=this.config;await this.waitForReady(o,s);let{body:a}=t,c=he(a),u=this.connect(o,c),i=pe(u);return{response:new ue({statusCode:200,body:i})}}updateHttpClientConfig(t,r){this.configPromise=this.configPromise.then((n)=>(n[t]=r,n))}httpHandlerConfigs(){return this.config??{}}removeNotUsableSockets(t){this.sockets[t]=(this.sockets[t]??[]).filter((r)=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(r.readyState))}waitForReady(t,r){return new Promise((n,o)=>{let s=setTimeout(()=>{this.removeNotUsableSockets(t.url),o({$metadata:{httpStatusCode:500,websocketSynthetic500Error:!0}})},r);t.onopen=()=>{clearTimeout(s),n()}})}connect(t,r){let n=[],o=null,s=null,a=(i)=>{if(o){if(i.error)s(i.error);else o({done:i.done,value:i.value});o=null,s=null}else n.push(i)};t.onmessage=(i)=>{let{data:d}=i;if(typeof d==="string")a({done:!1,value:le(d)});else a({done:!1,value:new Uint8Array(d)})},t.onerror=(i)=>{t.close(),a({done:!0,error:i})},t.onclose=()=>{this.removeNotUsableSockets(t.url),a({done:!0})};let c={[Symbol.asyncIterator]:()=>({async next(){if(n.length>0){let i=n.shift();if(i.error)throw i.error;return{done:i.done,value:i.value}}return new Promise((i,d)=>{o=i,s=d})}})};return(async()=>{try{for await(let i of r)if(t.readyState>=WebSocket.CLOSING)break;else t.send(i)}catch(i){a({done:!0,error:i})}finally{t.close(1000)}})(),c}}var he=(t)=>{if(t[Symbol.asyncIterator])return t;if(ge(t))return ce(t);return{[Symbol.asyncIterator]:async function*(){yield t}}},pe=(t)=>typeof ReadableStream==="function"?ae(t):t,ge=(t)=>typeof ReadableStream==="function"&&t instanceof ReadableStream,me=(t,r)=>(n)=>(o)=>{let{request:s}=o;if(A.isInstance(s)&&t.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")){s.protocol="wss:",s.method="GET",s.path=`${s.path}-websocket`;let{headers:a}=s;delete a["content-type"],delete a["x-amz-content-sha256"];for(let c of Object.keys(a))if(c.indexOf(r.headerPrefix)===0){let u=c.replace(r.headerPrefix,"");s.query[u]=a[c]}if(a["x-amz-user-agent"])s.query["user-agent"]=a["x-amz-user-agent"];s.headers={host:a.host??s.hostname}}return n(o)},ye={name:"websocketEndpointMiddleware",tags:["WEBSOCKET","EVENT_STREAM"],relation:"after",toMiddleware:"eventStreamHeaderMiddleware",override:!0},we=()=>(t)=>async(r)=>{let n={...r.input},o=await t(r),s=o.output;if(n.SessionId&&s.SessionId==null)s.SessionId=n.SessionId;return o},be={step:"initialize",name:"injectSessionIdMiddleware",tags:["WEBSOCKET","EVENT_STREAM"],override:!0},Se=(t,r)=>({applyToStack:(n)=>{n.addRelativeTo(me(t,r),ye),n.add(we(),be)}});class N{signer;constructor(t){this.signer=t.signer}presign(t,r={}){return this.signer.presign(t,r)}async sign(t,r){if(A.isInstance(t)&&M(t))return{...await this.signer.presign({...t,body:""},{...r,expiresIn:60,unsignableHeaders:new Set(Object.keys(t.headers).filter((o)=>o!=="host"))}),body:t.body};else return this.signer.sign(t,r)}signMessage(t,r){return this.signer.signMessage(t,r)}}var ve=(t)=>{let{signer:r}=t;return Object.assign(t,{signer:async(n)=>{let o=await r(n);if(Ee(o))return new N({signer:o});throw Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},Ee=(t)=>!!t;class j extends TransformStream{constructor(t,r,n,o,s){let a=t,c=s?.();super({start(){},async transform(u,i){try{let d=new Date(Date.now()+await o()),f={":date":{type:"timestamp",value:d}},h=await r.sign({message:{body:u,headers:f},priorSignature:a},{signingDate:d,eventStreamCredentials:await c});a=h.signature;let m=n.encode({headers:{...f,":chunk-signature":{type:"binary",value:fe(h.signature)}},body:u});i.enqueue(m)}catch(d){i.error(d)}}})}}class W{messageSigner;eventStreamCodec;systemClockOffsetProvider;credentials;constructor(t){this.messageSigner=t.messageSigner,this.eventStreamCodec=new de(t.utf8Encoder,t.utf8Decoder),this.systemClockOffsetProvider=async()=>t.systemClockOffset??0,this.credentials=t.credentials}async handle(t,r,n={}){let o=r.request,{body:s,headers:a,query:c}=o;if(!(s instanceof ReadableStream))throw Error("Eventstream payload must be a ReadableStream.");let u=new TransformStream;o.body=u.readable;let d=((a?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(c&&c["X-Amz-Signature"])??"";if(n.__staticSignature)d="";let f=new j(d,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider,this.credentials);s.pipeThrough(f).pipeThrough(u);let h;try{h=await t(r)}catch(m){let y=s.cancel?.();if(y instanceof Promise)y.catch(()=>{});throw m}return h}}var ke=(t)=>new W(t);Pe.WebSocketFetchHandler=k;Pe.eventStreamPayloadHandlerProvider=ke;Pe.getWebSocketPlugin=Se;Pe.resolveWebSocketConfig=ve});
3
3
  export{qo};
4
4
 
5
- //# debugId=8C260E56E728FCE964756E2164756E21
6
- //# sourceMappingURL=index-dh2g58s1.js.map
5
+ //# debugId=13EF6BBE4CA5229E64756E2164756E21
6
+ //# sourceMappingURL=index-4emtktc0.js.map
@@ -7,6 +7,6 @@
7
7
  "const { formatUrl } = require(\"@aws-sdk/core/util\");\nconst { iterableToReadableStream, readableStreamToIterable, EventStreamCodec } = require(\"@smithy/core/event-streams\");\nconst { HttpResponse, HttpRequest } = require(\"@smithy/core/protocols\");\nconst { fromBase64, fromHex } = require(\"@smithy/core/serde\");\nconst { FetchHttpHandler } = require(\"@smithy/fetch-http-handler\");\n\nconst isWebSocketRequest = (request) => request.protocol === \"ws:\" || request.protocol === \"wss:\";\n\nconst DEFAULT_WS_CONNECTION_TIMEOUT_MS = 3000;\nclass WebSocketFetchHandler {\n metadata = {\n handlerProtocol: \"websocket/h1.1\",\n };\n config = {};\n configPromise;\n httpHandler;\n sockets = {};\n static create(instanceOrOptions, httpHandler = new FetchHttpHandler()) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new WebSocketFetchHandler(instanceOrOptions, httpHandler);\n }\n constructor(options, httpHandler = new FetchHttpHandler()) {\n this.httpHandler = httpHandler;\n const setConfig = (opts) => {\n this.config = {\n ...(opts ?? {}),\n };\n return this.config;\n };\n if (typeof options === \"function\") {\n this.config = {};\n this.configPromise = options().then((opts) => {\n return setConfig(opts);\n });\n }\n else {\n this.configPromise = Promise.resolve(setConfig(options));\n }\n }\n destroy() {\n for (const [key, sockets] of Object.entries(this.sockets)) {\n for (const socket of sockets) {\n socket.close(1000, `Socket closed through destroy() call`);\n }\n delete this.sockets[key];\n }\n }\n async handle(request) {\n this.config = await this.configPromise;\n const { logger } = this.config;\n if (!isWebSocketRequest(request)) {\n logger?.debug?.(`@aws-sdk - ws fetching ${request.protocol}${request.hostname}${request.path}`);\n return this.httpHandler.handle(request);\n }\n const url = formatUrl(request);\n logger?.debug?.(`@aws-sdk - ws connecting ${url.split(\"?\")[0]}`);\n const socket = new WebSocket(url);\n if (!this.sockets[url]) {\n this.sockets[url] = [];\n }\n this.sockets[url].push(socket);\n socket.binaryType = \"arraybuffer\";\n const { connectionTimeout = DEFAULT_WS_CONNECTION_TIMEOUT_MS } = this.config;\n await this.waitForReady(socket, connectionTimeout);\n const { body } = request;\n const bodyStream = getIterator(body);\n const asyncIterable = this.connect(socket, bodyStream);\n const outputPayload = toReadableStream(asyncIterable);\n return {\n response: new HttpResponse({\n statusCode: 200,\n body: outputPayload,\n }),\n };\n }\n updateHttpClientConfig(key, value) {\n this.configPromise = this.configPromise.then((config) => {\n config[key] = value;\n return config;\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n removeNotUsableSockets(url) {\n this.sockets[url] = (this.sockets[url] ?? []).filter((socket) => ![WebSocket.CLOSING, WebSocket.CLOSED].includes(socket.readyState));\n }\n waitForReady(socket, connectionTimeout) {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.removeNotUsableSockets(socket.url);\n reject({\n $metadata: {\n httpStatusCode: 500,\n websocketSynthetic500Error: true,\n },\n });\n }, connectionTimeout);\n socket.onopen = () => {\n clearTimeout(timeout);\n resolve();\n };\n });\n }\n connect(socket, data) {\n const messageQueue = [];\n let pendingResolve = null;\n let pendingReject = null;\n const push = (item) => {\n if (pendingResolve) {\n if (item.error) {\n pendingReject(item.error);\n }\n else {\n pendingResolve({ done: item.done, value: item.value });\n }\n pendingResolve = null;\n pendingReject = null;\n }\n else {\n messageQueue.push(item);\n }\n };\n socket.onmessage = (event) => {\n const { data } = event;\n if (typeof data === \"string\") {\n push({\n done: false,\n value: fromBase64(data),\n });\n }\n else {\n push({\n done: false,\n value: new Uint8Array(data),\n });\n }\n };\n socket.onerror = (event) => {\n socket.close();\n push({ done: true, error: event });\n };\n socket.onclose = () => {\n this.removeNotUsableSockets(socket.url);\n push({ done: true });\n };\n const outputStream = {\n [Symbol.asyncIterator]: () => ({\n async next() {\n if (messageQueue.length > 0) {\n const item = messageQueue.shift();\n if (item.error) {\n throw item.error;\n }\n return { done: item.done, value: item.value };\n }\n return new Promise((resolve, reject) => {\n pendingResolve = resolve;\n pendingReject = reject;\n });\n },\n }),\n };\n const send = async () => {\n try {\n for await (const chunk of data) {\n if (socket.readyState >= WebSocket.CLOSING) {\n break;\n }\n else {\n socket.send(chunk);\n }\n }\n }\n catch (err) {\n push({\n done: true,\n error: err,\n });\n }\n finally {\n socket.close(1000);\n }\n };\n send();\n return outputStream;\n }\n}\nconst getIterator = (stream) => {\n if (stream[Symbol.asyncIterator]) {\n return stream;\n }\n if (isReadableStream(stream)) {\n return readableStreamToIterable(stream);\n }\n return {\n [Symbol.asyncIterator]: async function* () {\n yield stream;\n },\n };\n};\nconst toReadableStream = (asyncIterable) => typeof ReadableStream === \"function\" ? iterableToReadableStream(asyncIterable) : asyncIterable;\nconst isReadableStream = (payload) => typeof ReadableStream === \"function\" && payload instanceof ReadableStream;\n\nconst websocketEndpointMiddleware = (config, options) => (next) => (args) => {\n const { request } = args;\n if (HttpRequest.isInstance(request) &&\n config.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes(\"websocket\")) {\n request.protocol = \"wss:\";\n request.method = \"GET\";\n request.path = `${request.path}-websocket`;\n const { headers } = request;\n delete headers[\"content-type\"];\n delete headers[\"x-amz-content-sha256\"];\n for (const name of Object.keys(headers)) {\n if (name.indexOf(options.headerPrefix) === 0) {\n const chunkedName = name.replace(options.headerPrefix, \"\");\n request.query[chunkedName] = headers[name];\n }\n }\n if (headers[\"x-amz-user-agent\"]) {\n request.query[\"user-agent\"] = headers[\"x-amz-user-agent\"];\n }\n request.headers = { host: headers.host ?? request.hostname };\n }\n return next(args);\n};\nconst websocketEndpointMiddlewareOptions = {\n name: \"websocketEndpointMiddleware\",\n tags: [\"WEBSOCKET\", \"EVENT_STREAM\"],\n relation: \"after\",\n toMiddleware: \"eventStreamHeaderMiddleware\",\n override: true,\n};\n\nconst injectSessionIdMiddleware = () => (next) => async (args) => {\n const requestParams = {\n ...args.input,\n };\n const response = await next(args);\n const output = response.output;\n if (requestParams.SessionId && output.SessionId == null) {\n output.SessionId = requestParams.SessionId;\n }\n return response;\n};\nconst injectSessionIdMiddlewareOptions = {\n step: \"initialize\",\n name: \"injectSessionIdMiddleware\",\n tags: [\"WEBSOCKET\", \"EVENT_STREAM\"],\n override: true,\n};\n\nconst getWebSocketPlugin = (config, options) => ({\n applyToStack: (clientStack) => {\n clientStack.addRelativeTo(websocketEndpointMiddleware(config, options), websocketEndpointMiddlewareOptions);\n clientStack.add(injectSessionIdMiddleware(), injectSessionIdMiddlewareOptions);\n },\n});\n\nclass WebsocketSignatureV4 {\n signer;\n constructor(options) {\n this.signer = options.signer;\n }\n presign(originalRequest, options = {}) {\n return this.signer.presign(originalRequest, options);\n }\n async sign(toSign, options) {\n if (HttpRequest.isInstance(toSign) && isWebSocketRequest(toSign)) {\n const signedRequest = await this.signer.presign({ ...toSign, body: \"\" }, {\n ...options,\n expiresIn: 60,\n unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== \"host\")),\n });\n return {\n ...signedRequest,\n body: toSign.body,\n };\n }\n else {\n return this.signer.sign(toSign, options);\n }\n }\n signMessage(message, args) {\n return this.signer.signMessage(message, args);\n }\n}\n\nconst resolveWebSocketConfig = (input) => {\n const { signer } = input;\n return Object.assign(input, {\n signer: async (authScheme) => {\n const signerObj = await signer(authScheme);\n if (validateSigner(signerObj)) {\n return new WebsocketSignatureV4({ signer: signerObj });\n }\n throw new Error(\"Expected WebsocketSignatureV4 signer, please check the client constructor.\");\n },\n });\n};\nconst validateSigner = (signer) => !!signer;\n\nclass EventSigningTransformStream extends TransformStream {\n constructor(initialSignature, messageSigner, eventStreamCodec, systemClockOffsetProvider, credentials) {\n let priorSignature = initialSignature;\n const staticCredentials = credentials?.();\n super({\n start() { },\n async transform(chunk, controller) {\n try {\n const now = new Date(Date.now() + (await systemClockOffsetProvider()));\n const dateHeader = {\n \":date\": { type: \"timestamp\", value: now },\n };\n const signedMessage = await messageSigner.sign({\n message: {\n body: chunk,\n headers: dateHeader,\n },\n priorSignature: priorSignature,\n }, {\n signingDate: now,\n eventStreamCredentials: await staticCredentials,\n });\n priorSignature = signedMessage.signature;\n const serializedSigned = eventStreamCodec.encode({\n headers: {\n ...dateHeader,\n \":chunk-signature\": {\n type: \"binary\",\n value: fromHex(signedMessage.signature),\n },\n },\n body: chunk,\n });\n controller.enqueue(serializedSigned);\n }\n catch (error) {\n controller.error(error);\n }\n },\n });\n }\n}\n\nclass EventStreamPayloadHandler {\n messageSigner;\n eventStreamCodec;\n systemClockOffsetProvider;\n credentials;\n constructor(options) {\n this.messageSigner = options.messageSigner;\n this.eventStreamCodec = new EventStreamCodec(options.utf8Encoder, options.utf8Decoder);\n this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0;\n this.credentials = options.credentials;\n }\n async handle(next, args, context = {}) {\n const request = args.request;\n const { body: payload, headers, query } = request;\n if (!(payload instanceof ReadableStream)) {\n throw new Error(\"Eventstream payload must be a ReadableStream.\");\n }\n const placeHolderStream = new TransformStream();\n request.body = placeHolderStream.readable;\n const match = (headers?.authorization ?? \"\").match(/Signature=(\\w+)$/);\n let priorSignature = (match ?? [])[1] ?? (query && query[\"X-Amz-Signature\"]) ?? \"\";\n if (context.__staticSignature) {\n priorSignature = \"\";\n }\n const signingStream = new EventSigningTransformStream(priorSignature, await this.messageSigner(), this.eventStreamCodec, this.systemClockOffsetProvider, this.credentials);\n payload.pipeThrough(signingStream).pipeThrough(placeHolderStream);\n let result;\n try {\n result = await next(args);\n }\n catch (e) {\n const p = payload.cancel?.();\n if (p instanceof Promise) {\n p.catch(() => { });\n }\n throw e;\n }\n return result;\n }\n}\n\nconst eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options);\n\nexports.WebSocketFetchHandler = WebSocketFetchHandler;\nexports.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider;\nexports.getWebSocketPlugin = getWebSocketPlugin;\nexports.resolveWebSocketConfig = resolveWebSocketConfig;\n"
8
8
  ],
9
9
  "mappings": ";+FAAA,IAAQ,oBAAqB,IAEvB,EAAW,CAAC,IAAQ,OAAO,IAAQ,UAAY,EAAI,QAAQ,MAAM,IAAM,GAAK,EAAI,MAAM,GAAG,EAAE,QAAU,EACrG,EAAQ,CAAC,IAAQ,CACnB,IAAM,EAAW,EAAI,MAAM,GAAG,EAC9B,GAAI,EAAS,OAAS,GAAK,EAAS,KAAO,MACvC,MAAU,MAAM,eAAe,EACnC,KAAS,EAAW,EAAS,EAAQ,KAAc,GAAY,EAC/D,MAAO,CACH,YACA,UACA,SACA,YACA,SAAU,EAAS,KAAK,GAAG,CAC/B,GAEE,EAAQ,CAAC,IAAc,CACzB,IAAQ,YAAY,MAAO,UAAS,SAAQ,YAAW,YAAa,EACpE,GAAI,CAAC,EAAS,EAAQ,EAAW,CAAQ,EAAE,KAAK,CAAC,IAAY,OAAO,IAAY,QAAQ,EACpF,MAAU,MAAM,6BAA6B,EAEjD,MAAO,OAAO,KAAa,KAAW,KAAU,KAAa,KAGjE,SAAS,CAAS,CAAC,EAAS,CACxB,IAAQ,OAAM,SAAU,GAClB,WAAU,OA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EAAiB,GAErB,IAAM,EAAgB,IAAI,EAA4B,EAAgB,MAAM,KAAK,cAAc,EAAG,KAAK,iBAAkB,KAAK,0BAA2B,KAAK,WAAW,EACzK,EAAQ,YAAY,CAAa,EAAE,YAAY,CAAiB,EAChE,IAAI,EACJ,GAAI,CACA,EAAS,MAAM,EAAK,CAAI,EAE5B,MAAO,EAAG,CACN,IAAM,EAAI,EAAQ,SAAS,EAC3B,GAAI,aAAa,QACb,EAAE,MAAM,IAAM,EAAG,EAErB,MAAM,EAEV,OAAO,EAEf,CAEA,IAAM,GAAoC,CAAC,IAAY,IAAI,EAA0B,CAAO,EAEpF,yBAAwB,EACxB,qCAAoC,GACpC,sBAAqB,GACrB,0BAAyB",
10
- "debugId": "8C260E56E728FCE964756E2164756E21",
10
+ "debugId": "13EF6BBE4CA5229E64756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{A}from"./index-1h9pqnec.js";import{CA}from"./index-y605a1rj.js";import{Uo,Ia}from"./index-v6taf4vn.js";var sn=[{name:"plain",kind:"boolean",help:"force plain text — no interactive rendering, no colour"},{name:"help",short:"h",kind:"boolean",help:"show this help and exit"},{name:"version",short:"v",kind:"boolean",help:"print the version and exit"},{name:"no-bootstrap",kind:"boolean",help:"never start a background server on this run"}],n={name:"manifest",required:!0,help:"path to an agent.yaml, or the name of a sandbox agent"},a={name:"store",kind:"string",placeholder:"path",help:"session database",defaultHelp:`~/${A.stateDir}/store.db`},l={name:"session",kind:"string",placeholder:"key",help:"session key",bare:""},e={name:"json",kind:"boolean",help:"machine-readable output"},nA=[{name:"init",inSession:"hidden",needsServer:!1,summary:"create a new agent: manifest, workspace, and env files",args:[],unexpectedArgHint:"init takes no positional argument. To name the agent, --name <name>; to place it somewhere other than the sandbox, --dir <path>.",flags:[{name:"user",kind:"string",placeholder:"name",help:"your name"},{name:"name",kind:"string",placeholder:"name",help:"the agent's name"},{name:"purpose",kind:"string",placeholder:"text",help:"one line: what the agent is for"},{name:"preset",kind:"string",placeholder:"id",help:`model endpoint: ${CA.map((t)=>t.id).join(" | ")}`,defaultHelp:"openai"},{name:"model",kind:"string",placeholder:"id",help:"model id"},{name:"base-url",kind:"string",placeholder:"url",help:"endpoint base URL"},{name:"api-key-env",kind:"string",placeholder:"VAR",help:"env var that will hold the key; omitted for ollama",defaultHelp:"MODEL_API_KEY"},{name:"system",kind:"string",placeholder:"level",help:"what it may touch on this machine: none | read | write | full",defaultHelp:"none"},{name:"web",kind:"string",placeholder:"level",help:"internet access: none | fetch | search",defaultHelp:"none"},{name:"web-backend",kind:"string",placeholder:"id",help:"search backend when --web search: tavily | brave | exa",defaultHelp:"tavily"},{name:"composio",kind:"string",placeholder:"level",help:"your other apps via Composio: none | connected",defaultHelp:"none"},{name:"telegram",kind:"string",placeholder:"level",help:"reachable on Telegram: none | connected",defaultHelp:"none"},{name:"telegram-allow",kind:"string",placeholder:"@handle",help:"who may message it — empty permits nobody, which is the safe default"},{name:"whatsapp",kind:"string",placeholder:"level",help:"reachable on WhatsApp: none | connected — unofficial, and an opt-in plugin",defaultHelp:"none"},{name:"whatsapp-number",kind:"string",placeholder:"digits",help:"whose number may message it — digits with no +, empty permits nobody"},{name:"server",kind:"string",placeholder:"level",help:"serve the HTTP API: none | local",defaultHelp:"local"},{name:"schedules",kind:"string",placeholder:"what",help:"run something on a schedule: none | daily | hourly",defaultHelp:"none"},{name:"skills",kind:"string",placeholder:"level",help:'none | starter, or words to search the catalogues for — --skills "pdf tables"',defaultHelp:"starter"},{name:"daemon",kind:"string",placeholder:"level",help:"keep it running in the background: none | service",defaultHelp:"none"},{name:"dir",kind:"string",placeholder:"path",help:"write the agent here instead of the sandbox",defaultHelp:`~/${A.stateDir}/agents/<agent-name-slug>`},{name:"yes",kind:"boolean",help:"take every default; never ask, even at a terminal"},{name:"measure-window",kind:"boolean",help:"ask the endpoint for the model's window and write it (the wizard always asks)"}]},{name:"run",inSession:"hidden",needsServer:!0,summary:"start an interactive session — bare `run` picks from the sandbox",args:[{...n,required:!1,help:"path or sandbox agent name (omit to pick from the sandbox)"}],flags:[{...l,defaultHelp:"a new one each run; bare --session picks from the list"},{name:"continue",short:"c",kind:"boolean",help:"pick up the most recent conversation with this agent"},{name:"input",kind:"string",placeholder:"text",help:"run one turn, print the reply, exit"},a,{name:"ephemeral",kind:"boolean",help:"keep this session in memory only; nothing is written"},{name:"quiet",kind:"boolean",help:"suppress the banner and per-turn stats"},{name:"no-enhanced-keys",kind:"boolean",help:"do not negotiate the kitty keyboard protocol (cmd chords stop arriving)"},{name:"no-reasoning",kind:"boolean",help:"hide the thinking a reasoning model streams (shown by default)"},{name:"show-reasoning",kind:"boolean",help:"no-op: reasoning is shown by default when the model has any"}]},{name:"schedules",inSession:"view",needsServer:!0,summary:"list schedules, when they next fire, and how the last run went",args:[n],flags:[{name:"id",kind:"string",placeholder:"schedule",help:"show one schedule in full instead of the list"},{name:"enable",kind:"string",placeholder:"schedule",help:"switch an API-created schedule on; a manifest one is enabled in agent.yaml"},{name:"disable",kind:"string",placeholder:"schedule",help:"switch an API-created schedule off; a manifest one is disabled in agent.yaml"},{name:"recipients",kind:"boolean",help:"list the addresses this agent can deliver to — what deliver.to takes"},a,e]},{name:"sessions",inSession:"view",needsServer:!1,summary:"list stored sessions, or inspect one",args:[n],flags:[{...l,help:"show one session instead of the list"},{name:"turns",kind:"boolean",help:"show turn records instead of messages"},{name:"clear",kind:"boolean",help:"delete the named session's history; memory files are untouched"},{name:"limit",kind:"number",placeholder:"n",help:"rows to show",defaultHelp:String(Uo),min:Ia,integer:!0},a,e]},{name:"memory",inSession:"view",needsServer:!1,summary:"search what the agent remembers, or rebuild the index from the files",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"search",help:"rank the corpus against a query, exactly as a turn would"},{value:"rebuild",help:"forget the index and re-read every file — for an edit that kept the mtime"}]},{...n,required:!0},{name:"query",required:!1,help:"the words to search for (search only); quote a phrase"}],flags:[a,{name:"limit",kind:"number",placeholder:"n",help:"passages to show",defaultHelp:"10",min:1,integer:!0},{name:"all",kind:"boolean",help:"show passages below the manifest's threshold too, marked"},e]},{name:"config",inSession:"view",needsServer:!1,summary:"read and change an agent's settings, and fill in its secrets",args:[{name:"action",required:!1,help:"what to do (default: edit)",choices:[{value:"edit",help:"the full-screen editor — also what bare `config <agent>` opens"},{value:"list",help:"every setting, its current value, and who may set it"},{value:"get",help:"one setting"},{value:"set",help:"change one setting"},{value:"env",help:"put a secret in the .env beside the manifest, prompted and not echoed"},{value:"allow",help:"add or remove a handle a channel accepts messages from"}]},{...n,required:!1},{name:"name",required:!1,help:"the setting's dotted path, an env variable name, or a handle"},{name:"value",required:!1,help:"the new value (set only)"}],flags:[a,{name:"channel",kind:"string",placeholder:"id",help:"which channel to allow on, when there is more than one"},{name:"remove",kind:"boolean",help:"take the handle off instead of adding it (allow only)"},{name:"yes",kind:"boolean",help:"skip the confirmation on an edit that weakens a check"}]},{name:"validate",inSession:"output",needsServer:!1,summary:"load and validate a manifest, then exit",args:[n],flags:[e]},{name:"workspace",inSession:"output",needsServer:!1,summary:"check the workspace files against the authoring rules",args:[n],flags:[{name:"strict",kind:"boolean",help:"exit non-zero when any authoring warning is reported"},e]},{name:"soul",inSession:"output",needsServer:!1,summary:"scaffold a hand-edited compact identity from a long-form document",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"distill",help:"scaffold a compact identity beside the source"}]},{name:"file",required:!0,help:"path to the long-form identity document"}],flags:[{name:"out",kind:"string",placeholder:"path",help:"where to write the scaffold",defaultHelp:"<file>.compact.md beside the source"}]},{name:"skills",inSession:"view",needsServer:!1,summary:"browse the catalogue and install — or list, scaffold, check one agent's skills",args:[{name:"action",required:!1,help:"what to do — omit to browse the catalogue and tick what you want",choices:[{value:"list",help:"every skill, its size, and whether it ships scripts"},{value:"show",help:"one skill in full, including what the model never sees"},{value:"new",help:"scaffold a skill, turning skills on for this agent if they are not"},{value:"install",help:"install one by name — anthropic/pdf — or copy from a local path (see `sources`)"},{value:"remove",help:"delete a skill's directory and everything in it"},{value:"validate",help:"authoring warnings — never a refusal"}]},{...n,required:!1,help:"path or sandbox agent name (not used when browsing)"},{name:"name",required:!1,help:"the skill for show, new and remove — for install, <source>/<skill> or a local path"}],flags:[{name:"strict",kind:"boolean",help:"exit non-zero when any authoring warning is reported"},e]},{name:"sources",inSession:"view",needsServer:!1,summary:"the repositories skills come from: list, add, search",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"list",help:"every source, and whether it has been fetched"},{value:"add",help:"add a repository — a URL, or a name and a URL"},{value:"remove",help:"stop searching a source; built-ins included"},{value:"update",help:"re-fetch every source, or the ones named"},{value:"search",help:"find a skill across every source; fetches on first use"}]},{name:"rest",required:!1,variadic:!0,help:"a name and URL for add, a name for remove or update, words for search"}],flags:[{name:"path",kind:"string",placeholder:"dir",help:"subdirectory holding the skills (add)",defaultHelp:"the whole repository"},{name:"ref",kind:"string",placeholder:"branch",help:"branch or tag to track (add)",defaultHelp:"the remote's default branch"},e]},{name:"channels",inSession:"output",needsServer:!1,summary:"what an agent is reachable on: connect, disconnect, set a credential, unpair",args:[{name:"action",required:!1,help:"what to do — omit for the listing",choices:[{value:"list",help:"every channel, whether it is on, and whether its credential is filled in"},{value:"connect",help:"switch a channel on; it starts at the agent's next start"},{value:"disconnect",help:"switch it off — a disabled channel is never constructed"},{value:"credential",help:"set the channel's token in the .env, prompted and not echoed"},{value:"pair",help:"connect it the way that channel needs — a code for WhatsApp, a token for Telegram"},{value:"unpair",help:"forget a scanned pairing, so the next start offers a new code"}]},{...n,required:!1,help:"path or sandbox agent name"},{name:"channel",required:!1,help:"which channel — its id, not its type. Optional when the agent has exactly one"}],flags:[e]},{name:"plugins",inSession:"output",needsServer:!1,summary:"install a plugin, list what an agent loaded, or remove one",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"list",help:"what this agent loaded, from where, and what it asked for"},{value:"add",help:"fetch a plugin from git and name it in this agent"},{value:"remove",help:"drop the entry, and the directory when no agent needs it"}]},n,{name:"rest",required:!1,variadic:!0,help:"a repository for add — owner/repo, a clone URL, or a page URL — or a name for remove"}],flags:[{name:"ref",kind:"string",placeholder:"tag",help:"branch, tag or commit to fetch (add) — the only thing that pins the code",defaultHelp:"the remote's default branch"},{name:"name",kind:"string",placeholder:"name",help:"install under this name (add), which is what the `plugins:` entry will say",defaultHelp:"the repository or subdirectory name"},e]},{name:"agents",inSession:"output",needsServer:!1,summary:"the agents in the sandbox, and whether anything is serving them",args:[{...n,required:!1,variadic:!0,help:"paths or sandbox names to describe in full — bare, lists the sandbox"}],flags:[a,e]},{name:"restart",inSession:"hidden",needsServer:!1,summary:"reload one agent on the running host, or restart the whole service",args:[{...n,required:!1,help:"path or sandbox agent name — bare, restarts the background service"}],flags:[a,e]},{name:"status",inSession:"output",needsServer:!1,summary:"the service, the hosts, every agent and its channels — one screen",args:[],flags:[a,e]},{name:"logs",inSession:"hidden",needsServer:!1,summary:"the server's stderr tail — the same as `daemon logs`",args:[{...n,required:!1,help:"path or sandbox agent name — bare, the server's own log"}],flags:[{name:"lines",kind:"number",placeholder:"n",integer:!0,min:1,help:"how much of the log to show",defaultHelp:"40"},{name:"follow",short:"f",kind:"boolean",help:"keep printing new lines until interrupted"},{name:"truncate",kind:"boolean",help:"empty the log first, in place"},a,e]},{name:"tools",inSession:"output",needsServer:!1,summary:"show the resolved tool catalogue, or fetch a remote provider's schemas into the cache",args:[n],flags:[{name:"warm",kind:"boolean",help:"fetch every pinned slug from the provider and write the resolution cache"},e]},{name:"serve",inSession:"hidden",needsServer:!1,summary:"run the HTTP API and connect the agents' channels",args:[{...n,required:!1,variadic:!0,help:"paths to an agent.yaml, or sandbox agent names (omit for every enabled agent)"}],flags:[{name:"port",kind:"number",placeholder:"n",help:"port to bind",defaultHelp:"server.port, or 7420"},{name:"host",kind:"string",placeholder:"addr",help:"address to bind — a non-loopback host requires an API token",defaultHelp:"server.host, or 127.0.0.1"},{name:"claim",kind:"boolean",help:"print a one-time claim even when a key already exists"},a,e]},{name:"credential",inSession:"hidden",needsServer:!0,summary:"mint, list and revoke operator credentials, optionally scoped",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"create",help:"mint one and print the secret, once"},{value:"list",help:"every credential, live and revoked, with its scope"},{value:"revoke",help:"kill one permanently"}]},{name:"keyId",required:!1,help:"which credential, for revoke (`credential list` prints the ids)"}],flags:[{name:"label",kind:"string",placeholder:"text",help:"how it is shown in a listing — required for create"},{name:"agents",kind:"string",placeholder:"a,b",help:"narrow it to these agents",defaultHelp:"every agent"},{name:"sessions",kind:"string",placeholder:"prefix",help:"narrow it to session keys starting with this",defaultHelp:"every session"},{name:"can",kind:"string",placeholder:"list",help:"narrow it to these capabilities: read | chat | write | admin",defaultHelp:"all of them"},{name:"expires",kind:"string",placeholder:"dur",help:"how long it lives: 30s, 15m, 2h, 7d, or seconds",defaultHelp:"never"},a,e]},{name:"keys",inSession:"hidden",needsServer:!1,summary:"press a chord and see the bytes, Ink's reading of them, and the intent",args:[],flags:[{name:"no-enhanced-keys",kind:"boolean",help:"do not negotiate the kitty keyboard protocol"}]},{name:"terminal-setup",inSession:"hidden",needsServer:!1,summary:"teach this terminal to send shift+enter as a new line",args:[],flags:[{name:"dry-run",kind:"boolean",help:"print the change and write nothing"},{name:"yes",kind:"boolean",help:"write it without asking"},e]},{name:"remove",inSession:"hidden",needsServer:!1,summary:"delete a sandbox agent: its directory, sessions, memory, logs and service",args:[{name:"agent",required:!1,help:"sandbox agent name (a path is refused — remove only manages agents `init` made)"}],flags:[{name:"dry-run",kind:"boolean",help:"show exactly what would go; delete nothing"},{name:"files-only",kind:"boolean",help:"delete the directory and keep the sessions, memory and logs"},{name:"prune",kind:"boolean",help:"delete sessions, memory and logs that no sandbox agent claims any more"},{name:"all",kind:"boolean",help:"remove every agent in the sandbox"},{name:"yes",kind:"boolean",help:"skip the typed confirmation (required to delete anything non-interactively)"},a,e]},{name:"stop",inSession:"hidden",needsServer:!1,summary:"stop one agent for good, or everything — named, it stays stopped across restarts",args:[{name:"agent",required:!1,help:"path or sandbox agent name (omit to stop the whole host)"}],flags:[{name:"dry-run",kind:"boolean",help:"list what would be stopped; stop nothing"},{name:"reason",kind:"string",help:"why — recorded, and shown wherever the agent is reported as off"},a,e]},{name:"start",inSession:"hidden",needsServer:!0,summary:"switch an agent back on, and have a running host adopt it now",args:[n],flags:[a,e]},{name:"model",inSession:"output",needsServer:!1,summary:"ask the endpoint what it can actually do — window, output cap, prompt caching",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"probe",help:"measure every configured role against its own endpoint"}]},{name:"agent",required:!0,help:"path or sandbox agent name"}],flags:[{name:"window",kind:"boolean",help:"search for the window by growing a prompt until it is refused — costs real tokens, and prints the estimate first"},{name:"price",kind:"number",placeholder:"usd",help:"dollars per million input tokens, if you want --window's estimate in money"},{name:"write",kind:"boolean",help:"record a measured ceiling in the manifest; a floor is refused, because a floor is not a window"},{name:"yes",kind:"boolean",help:"answer the --window spend prompt; nothing else is affected"},{name:"json",kind:"boolean",help:"machine-readable findings"}]},{name:"web",inSession:"output",needsServer:!0,summary:"open the browser view of a running agent",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"run",help:"start a server if needed, then open the page"},{value:"open",help:"open the page of a server already running"},{value:"url",help:"print the address and open nothing — the form a pipe reads"}]},{name:"agent",required:!1,help:"path or sandbox agent name (omit to open the page itself)"}],flags:[{name:"no-open",kind:"boolean",help:"print the URL instead of opening it"},a,e]},{name:"daemon",inSession:"output",needsServer:!1,summary:"keep an agent serving in the background — starts at login, restarts on crash",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"install",help:"check it will boot, write the service, load it, and watch it start"},{value:"uninstall",help:"unload it and remove the service definition"},{value:"start",help:"load it again after a stop"},{value:"stop",help:"unload it, and keep it stopped across a login"},{value:"restart",help:"what you run after editing agent.yaml or .env"},{value:"status",help:"running? how many restarts? why did it stop? — bare, reports every agent"},{value:"logs",help:"the tail of stderr; --lines, --follow, --truncate"}]},{name:"agent",required:!1,help:"path or sandbox agent name (omit only for status)"}],flags:[{name:"lines",kind:"number",placeholder:"n",integer:!0,min:1,help:"how much of the log to show",defaultHelp:"40"},{name:"follow",short:"f",kind:"boolean",help:"keep printing as the service writes — both streams; ctrl-C stops (logs)"},{name:"truncate",kind:"boolean",help:"empty the log files (logs)"},{name:"dry-run",kind:"boolean",help:"print the service definition and the checks; write nothing"},a,e]}];function Ot(t){return nA.find((r)=>r.name===t)}function an(t){return[...t.flags,...sn]}function es(t,r){return nA.filter((s)=>s.name!==r&&s.flags.some((i)=>i.name===t)).map((s)=>s.name)}function As(t,r){let s=(r??"").trim();if(s==="")return{action:void 0,ref:void 0};return(Ot(t)?.args??[]).find((o)=>o.name==="action")?.choices?.map((o)=>o.value)?.includes(s)===!0?{action:s,ref:void 0}:{action:void 0,ref:s}}
3
- export{sn,nA,Ot,an,es,As};
2
+ import{t}from"./index-26ejkp8q.js";import{Ct}from"./index-z0dgxd7d.js";import{Uo,Ia}from"./index-vw2hf4d8.js";var sn=[{name:"plain",kind:"boolean",help:"force plain text — no interactive rendering, no colour"},{name:"help",short:"h",kind:"boolean",help:"show this help and exit"},{name:"version",short:"v",kind:"boolean",help:"print the version and exit"},{name:"no-bootstrap",kind:"boolean",help:"never start a background server on this run"}],n={name:"manifest",required:!0,help:"path to an agent.yaml, or the name of a sandbox agent"},a={name:"store",kind:"string",placeholder:"path",help:"session database",defaultHelp:`~/${t.stateDir}/store.db`},d={name:"session",kind:"string",placeholder:"key",help:"session key",bare:""},e={name:"json",kind:"boolean",help:"machine-readable output"},nt=[{name:"init",inSession:"hidden",needsServer:!1,summary:"create a new agent: manifest, workspace, and env files",args:[],unexpectedArgHint:"init takes no positional argument. To name the agent, --name <name>; to place it somewhere other than the sandbox, --dir <path>.",flags:[{name:"user",kind:"string",placeholder:"name",help:"your name"},{name:"name",kind:"string",placeholder:"name",help:"the agent's name"},{name:"purpose",kind:"string",placeholder:"text",help:"one line: what the agent is for"},{name:"preset",kind:"string",placeholder:"id",help:`model endpoint: ${Ct.map((s)=>s.id).join(" | ")}`,defaultHelp:"openai"},{name:"model",kind:"string",placeholder:"id",help:"model id"},{name:"base-url",kind:"string",placeholder:"url",help:"endpoint base URL"},{name:"api-key-env",kind:"string",placeholder:"VAR",help:"env var that will hold the key; omitted for ollama",defaultHelp:"MODEL_API_KEY"},{name:"system",kind:"string",placeholder:"level",help:"what it may touch on this machine: none | read | write | full",defaultHelp:"none"},{name:"web",kind:"string",placeholder:"level",help:"internet access: none | fetch | search",defaultHelp:"none"},{name:"web-backend",kind:"string",placeholder:"id",help:"search backend when --web search: tavily | brave | exa",defaultHelp:"tavily"},{name:"composio",kind:"string",placeholder:"level",help:"your other apps via Composio: none | connected",defaultHelp:"none"},{name:"telegram",kind:"string",placeholder:"level",help:"reachable on Telegram: none | connected",defaultHelp:"none"},{name:"telegram-allow",kind:"string",placeholder:"@handle",help:"who may message it — empty permits nobody, which is the safe default"},{name:"whatsapp",kind:"string",placeholder:"level",help:"reachable on WhatsApp: none | connected — unofficial, and an opt-in plugin",defaultHelp:"none"},{name:"whatsapp-number",kind:"string",placeholder:"digits",help:"whose number may message it — digits with no +, empty permits nobody"},{name:"server",kind:"string",placeholder:"level",help:"serve the HTTP API: none | local",defaultHelp:"local"},{name:"schedules",kind:"string",placeholder:"what",help:"run something on a schedule: none | daily | hourly",defaultHelp:"none"},{name:"skills",kind:"string",placeholder:"level",help:'none | starter, or words to search the catalogues for — --skills "pdf tables"',defaultHelp:"starter"},{name:"daemon",kind:"string",placeholder:"level",help:"keep it running in the background: none | service",defaultHelp:"none"},{name:"dir",kind:"string",placeholder:"path",help:"write the agent here instead of the sandbox",defaultHelp:`~/${t.stateDir}/agents/<agent-name-slug>`},{name:"yes",kind:"boolean",help:"take every default; never ask, even at a terminal"},{name:"measure-window",kind:"boolean",help:"ask the endpoint for the model's window and write it (the wizard always asks)"}]},{name:"run",inSession:"hidden",needsServer:!0,summary:"start an interactive session — bare `run` picks from the sandbox",args:[{...n,required:!1,help:"path or sandbox agent name (omit to pick from the sandbox)"}],flags:[{...d,defaultHelp:"a new one each run; bare --session picks from the list"},{name:"continue",short:"c",kind:"boolean",help:"pick up the most recent conversation with this agent"},{name:"input",kind:"string",placeholder:"text",help:"run one turn, print the reply, exit"},a,{name:"ephemeral",kind:"boolean",help:"keep this session in memory only; nothing is written"},{name:"quiet",kind:"boolean",help:"suppress the banner and per-turn stats"},{name:"no-enhanced-keys",kind:"boolean",help:"do not negotiate the kitty keyboard protocol (cmd chords stop arriving)"},{name:"no-reasoning",kind:"boolean",help:"hide the thinking a reasoning model streams (shown by default)"},{name:"show-reasoning",kind:"boolean",help:"no-op: reasoning is shown by default when the model has any"}]},{name:"schedules",inSession:"view",needsServer:!0,summary:"list schedules, when they next fire, and how the last run went",args:[n],flags:[{name:"id",kind:"string",placeholder:"schedule",help:"show one schedule in full instead of the list"},{name:"enable",kind:"string",placeholder:"schedule",help:"switch an API-created schedule on; a manifest one is enabled in agent.yaml"},{name:"disable",kind:"string",placeholder:"schedule",help:"switch an API-created schedule off; a manifest one is disabled in agent.yaml"},{name:"recipients",kind:"boolean",help:"list the addresses this agent can deliver to — what deliver.to takes"},a,e]},{name:"sessions",inSession:"view",needsServer:!1,summary:"list stored sessions, or inspect one",args:[n],flags:[{...d,help:"show one session instead of the list"},{name:"turns",kind:"boolean",help:"show turn records instead of messages"},{name:"clear",kind:"boolean",help:"delete the named session's history; memory files are untouched"},{name:"limit",kind:"number",placeholder:"n",help:"rows to show",defaultHelp:String(Uo),min:Ia,integer:!0},a,e]},{name:"memory",inSession:"view",needsServer:!1,summary:"search what the agent remembers, or rebuild the index from the files",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"search",help:"rank the corpus against a query, exactly as a turn would"},{value:"rebuild",help:"forget the index and re-read every file — for an edit that kept the mtime"}]},{...n,required:!0},{name:"query",required:!1,help:"the words to search for (search only); quote a phrase"}],flags:[a,{name:"limit",kind:"number",placeholder:"n",help:"passages to show",defaultHelp:"10",min:1,integer:!0},{name:"all",kind:"boolean",help:"show passages below the manifest's threshold too, marked"},e]},{name:"config",inSession:"view",needsServer:!1,summary:"read and change an agent's settings, and fill in its secrets",args:[{name:"action",required:!1,help:"what to do (default: edit)",choices:[{value:"edit",help:"the full-screen editor — also what bare `config <agent>` opens"},{value:"list",help:"every setting, its current value, and who may set it"},{value:"get",help:"one setting"},{value:"set",help:"change one setting"},{value:"env",help:"put a secret in the .env beside the manifest, prompted and not echoed"},{value:"allow",help:"add or remove a handle a channel accepts messages from"}]},{...n,required:!1},{name:"name",required:!1,help:"the setting's dotted path, an env variable name, or a handle"},{name:"value",required:!1,help:"the new value (set only)"}],flags:[a,{name:"channel",kind:"string",placeholder:"id",help:"which channel to allow on, when there is more than one"},{name:"remove",kind:"boolean",help:"take the handle off instead of adding it (allow only)"},{name:"yes",kind:"boolean",help:"skip the confirmation on an edit that weakens a check"}]},{name:"validate",inSession:"output",needsServer:!1,summary:"load and validate a manifest, then exit",args:[n],flags:[e]},{name:"workspace",inSession:"output",needsServer:!1,summary:"check the workspace files against the authoring rules",args:[n],flags:[{name:"strict",kind:"boolean",help:"exit non-zero when any authoring warning is reported"},e]},{name:"soul",inSession:"output",needsServer:!1,summary:"scaffold a hand-edited compact identity from a long-form document",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"distill",help:"scaffold a compact identity beside the source"}]},{name:"file",required:!0,help:"path to the long-form identity document"}],flags:[{name:"out",kind:"string",placeholder:"path",help:"where to write the scaffold",defaultHelp:"<file>.compact.md beside the source"}]},{name:"skills",inSession:"view",needsServer:!1,summary:"browse the catalogue and install — or list, scaffold, check one agent's skills",args:[{name:"action",required:!1,help:"what to do — omit to browse the catalogue and tick what you want",choices:[{value:"list",help:"every skill, its size, and whether it ships scripts"},{value:"show",help:"one skill in full, including what the model never sees"},{value:"new",help:"scaffold a skill, turning skills on for this agent if they are not"},{value:"install",help:"install one by name — anthropic/pdf — or copy from a local path (see `sources`)"},{value:"remove",help:"delete a skill's directory and everything in it"},{value:"validate",help:"authoring warnings — never a refusal"}]},{...n,required:!1,help:"path or sandbox agent name (not used when browsing)"},{name:"name",required:!1,help:"the skill for show, new and remove — for install, <source>/<skill> or a local path"}],flags:[{name:"strict",kind:"boolean",help:"exit non-zero when any authoring warning is reported"},e]},{name:"sources",inSession:"view",needsServer:!1,summary:"the repositories skills come from: list, add, search",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"list",help:"every source, and whether it has been fetched"},{value:"add",help:"add a repository — a URL, or a name and a URL"},{value:"remove",help:"stop searching a source; built-ins included"},{value:"update",help:"re-fetch every source, or the ones named"},{value:"search",help:"find a skill across every source; fetches on first use"}]},{name:"rest",required:!1,variadic:!0,help:"a name and URL for add, a name for remove or update, words for search"}],flags:[{name:"path",kind:"string",placeholder:"dir",help:"subdirectory holding the skills (add)",defaultHelp:"the whole repository"},{name:"ref",kind:"string",placeholder:"branch",help:"branch or tag to track (add)",defaultHelp:"the remote's default branch"},e]},{name:"channels",inSession:"output",needsServer:!1,summary:"what an agent is reachable on: connect, disconnect, set a credential, unpair",args:[{name:"action",required:!1,help:"what to do — omit for the listing",choices:[{value:"list",help:"every channel, whether it is on, and whether its credential is filled in"},{value:"connect",help:"switch a channel on; it starts at the agent's next start"},{value:"disconnect",help:"switch it off — a disabled channel is never constructed"},{value:"credential",help:"set the channel's token in the .env, prompted and not echoed"},{value:"pair",help:"connect it the way that channel needs — a code for WhatsApp, a token for Telegram"},{value:"unpair",help:"forget a scanned pairing, so the next start offers a new code"}]},{...n,required:!1,help:"path or sandbox agent name"},{name:"channel",required:!1,help:"which channel — its id, not its type. Optional when the agent has exactly one"}],flags:[e]},{name:"plugins",inSession:"output",needsServer:!1,summary:"install a plugin, list what an agent loaded, or remove one",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"list",help:"what this agent loaded, from where, and what it asked for"},{value:"add",help:"fetch a plugin from git and name it in this agent"},{value:"remove",help:"drop the entry, and the directory when no agent needs it"}]},n,{name:"rest",required:!1,variadic:!0,help:"a repository for add — owner/repo, a clone URL, or a page URL — or a name for remove"}],flags:[{name:"ref",kind:"string",placeholder:"tag",help:"branch, tag or commit to fetch (add) — the only thing that pins the code",defaultHelp:"the remote's default branch"},{name:"name",kind:"string",placeholder:"name",help:"install under this name (add), which is what the `plugins:` entry will say",defaultHelp:"the repository or subdirectory name"},e]},{name:"agents",inSession:"output",needsServer:!1,summary:"the agents in the sandbox, and whether anything is serving them",args:[{...n,required:!1,variadic:!0,help:"paths or sandbox names to describe in full — bare, lists the sandbox"}],flags:[a,e]},{name:"restart",inSession:"hidden",needsServer:!1,summary:"reload one agent on the running host, or restart the whole service",args:[{...n,required:!1,help:"path or sandbox agent name — bare, restarts the background service"}],flags:[a,e]},{name:"status",inSession:"output",needsServer:!1,summary:"the service, the hosts, every agent and its channels — one screen",args:[],flags:[a,e]},{name:"logs",inSession:"hidden",needsServer:!1,summary:"the server's stderr tail — the same as `daemon logs`",args:[{...n,required:!1,help:"path or sandbox agent name — bare, the server's own log"}],flags:[{name:"lines",kind:"number",placeholder:"n",integer:!0,min:1,help:"how much of the log to show",defaultHelp:"40"},{name:"follow",short:"f",kind:"boolean",help:"keep printing new lines until interrupted"},{name:"truncate",kind:"boolean",help:"empty the log first, in place"},a,e]},{name:"tools",inSession:"output",needsServer:!1,summary:"show the resolved tool catalogue, or fetch a remote provider's schemas into the cache",args:[n],flags:[{name:"warm",kind:"boolean",help:"fetch every pinned slug from the provider and write the resolution cache"},e]},{name:"serve",inSession:"hidden",needsServer:!1,summary:"run the HTTP API and connect the agents' channels",args:[{...n,required:!1,variadic:!0,help:"paths to an agent.yaml, or sandbox agent names (omit for every enabled agent)"}],flags:[{name:"port",kind:"number",placeholder:"n",help:"port to bind",defaultHelp:"server.port, or 7420"},{name:"host",kind:"string",placeholder:"addr",help:"address to bind — a non-loopback host requires an API token",defaultHelp:"server.host, or 127.0.0.1"},{name:"claim",kind:"boolean",help:"print a one-time claim even when a key already exists"},a,e]},{name:"credential",inSession:"hidden",needsServer:!0,summary:"mint, list and revoke operator credentials, optionally scoped",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"create",help:"mint one and print the secret, once"},{value:"list",help:"every credential, live and revoked, with its scope"},{value:"revoke",help:"kill one permanently"}]},{name:"keyId",required:!1,help:"which credential, for revoke (`credential list` prints the ids)"}],flags:[{name:"label",kind:"string",placeholder:"text",help:"how it is shown in a listing — required for create"},{name:"agents",kind:"string",placeholder:"a,b",help:"narrow it to these agents",defaultHelp:"every agent"},{name:"sessions",kind:"string",placeholder:"prefix",help:"narrow it to session keys starting with this",defaultHelp:"every session"},{name:"can",kind:"string",placeholder:"list",help:"narrow it to these capabilities: read | chat | write | admin",defaultHelp:"all of them"},{name:"expires",kind:"string",placeholder:"dur",help:"how long it lives: 30s, 15m, 2h, 7d, or seconds",defaultHelp:"never"},a,e]},{name:"keys",inSession:"hidden",needsServer:!1,summary:"press a chord and see the bytes, Ink's reading of them, and the intent",args:[],flags:[{name:"no-enhanced-keys",kind:"boolean",help:"do not negotiate the kitty keyboard protocol"}]},{name:"terminal-setup",inSession:"hidden",needsServer:!1,summary:"teach this terminal to send shift+enter as a new line",args:[],flags:[{name:"dry-run",kind:"boolean",help:"print the change and write nothing"},{name:"yes",kind:"boolean",help:"write it without asking"},e]},{name:"remove",inSession:"hidden",needsServer:!1,summary:"delete a sandbox agent: its directory, sessions, memory, logs and service",args:[{name:"agent",required:!1,help:"sandbox agent name (a path is refused — remove only manages agents `init` made)"}],flags:[{name:"dry-run",kind:"boolean",help:"show exactly what would go; delete nothing"},{name:"files-only",kind:"boolean",help:"delete the directory and keep the sessions, memory and logs"},{name:"prune",kind:"boolean",help:"delete sessions, memory and logs that no sandbox agent claims any more"},{name:"all",kind:"boolean",help:"remove every agent in the sandbox"},{name:"yes",kind:"boolean",help:"skip the typed confirmation (required to delete anything non-interactively)"},a,e]},{name:"stop",inSession:"hidden",needsServer:!1,summary:"stop one agent for good, or everything — named, it stays stopped across restarts",args:[{name:"agent",required:!1,help:"path or sandbox agent name (omit to stop the whole host)"}],flags:[{name:"dry-run",kind:"boolean",help:"list what would be stopped; stop nothing"},{name:"reason",kind:"string",help:"why — recorded, and shown wherever the agent is reported as off"},a,e]},{name:"start",inSession:"hidden",needsServer:!0,summary:"switch an agent back on, and have a running host adopt it now",args:[n],flags:[a,e]},{name:"model",inSession:"output",needsServer:!1,summary:"ask the endpoint what it can actually do — window, output cap, prompt caching",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"probe",help:"measure every configured role against its own endpoint"}]},{name:"agent",required:!0,help:"path or sandbox agent name"}],flags:[{name:"window",kind:"boolean",help:"search for the window by growing a prompt until it is refused — costs real tokens, and prints the estimate first"},{name:"price",kind:"number",placeholder:"usd",help:"dollars per million input tokens, if you want --window's estimate in money"},{name:"write",kind:"boolean",help:"record a measured ceiling in the manifest; a floor is refused, because a floor is not a window"},{name:"yes",kind:"boolean",help:"answer the --window spend prompt; nothing else is affected"},{name:"json",kind:"boolean",help:"machine-readable findings"}]},{name:"web",inSession:"output",needsServer:!0,summary:"open the browser view of a running agent",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"run",help:"start a server if needed, then open the page"},{value:"open",help:"open the page of a server already running"},{value:"url",help:"print the address and open nothing — the form a pipe reads"}]},{name:"agent",required:!1,help:"path or sandbox agent name (omit to open the page itself)"}],flags:[{name:"no-open",kind:"boolean",help:"print the URL instead of opening it"},a,e]},{name:"daemon",inSession:"output",needsServer:!1,summary:"keep an agent serving in the background — starts at login, restarts on crash",args:[{name:"action",required:!0,help:"what to do",choices:[{value:"install",help:"check it will boot, write the service, load it, and watch it start"},{value:"uninstall",help:"unload it and remove the service definition"},{value:"start",help:"load it again after a stop"},{value:"stop",help:"unload it, and keep it stopped across a login"},{value:"restart",help:"what you run after editing agent.yaml or .env"},{value:"status",help:"running? how many restarts? why did it stop? — bare, reports every agent"},{value:"logs",help:"the tail of stderr; --lines, --follow, --truncate"}]},{name:"agent",required:!1,help:"path or sandbox agent name (omit only for status)"}],flags:[{name:"lines",kind:"number",placeholder:"n",integer:!0,min:1,help:"how much of the log to show",defaultHelp:"40"},{name:"follow",short:"f",kind:"boolean",help:"keep printing as the service writes — both streams; ctrl-C stops (logs)"},{name:"truncate",kind:"boolean",help:"empty the log files (logs)"},{name:"dry-run",kind:"boolean",help:"print the service definition and the checks; write nothing"},a,e]}];function OA(s){return nt.find((o)=>o.name===s)}function an(s){return[...s.flags,...sn]}function es(s,o){return nt.filter((r)=>r.name!==o&&r.flags.some((l)=>l.name===s)).map((r)=>r.name)}function ts(s,o){let r=(o??"").trim();if(r==="")return{action:void 0,ref:void 0};return(OA(s)?.args??[]).find((i)=>i.name==="action")?.choices?.map((i)=>i.value)?.includes(r)===!0?{action:r,ref:void 0}:{action:void 0,ref:r}}
3
+ export{sn,nt,OA,an,es,ts};
4
4
 
5
- //# debugId=2041D1579D06EA7464756E2164756E21
6
- //# sourceMappingURL=index-026q0y3a.js.map
5
+ //# debugId=470A4AB15C851C7E64756E2164756E21
6
+ //# sourceMappingURL=index-4t3p7vm9.js.map