@north-light/cli 0.3.707 → 0.3.709

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 (278) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/crons.d.ts +3 -0
  6. package/dist/api/dto/human.d.ts +9 -6
  7. package/dist/api/dto/inbox.d.ts +2 -0
  8. package/dist/api/dto/review-comments.d.ts +12 -35
  9. package/dist/api/dto/reviews.d.ts +3 -10
  10. package/dist/api/routes.d.ts +0 -1
  11. package/dist/api/routes.js +1 -1
  12. package/dist/builtin-memory/05-kinds/review/companion/00-base.md +2 -2
  13. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  14. package/dist/clients/attach/chrome/canvas-panels.d.ts +1 -1
  15. package/dist/clients/attach/chrome/canvas-panels.js +1 -1
  16. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  17. package/dist/clients/attach/chrome/roster.js +6 -6
  18. package/dist/clients/attach/chrome/status-line.d.ts +1 -1
  19. package/dist/clients/attach/chrome/status-line.js +1 -1
  20. package/dist/clients/attach/chrome/ticket-panel.js +1 -1
  21. package/dist/clients/attach/input/capabilities.js +1 -1
  22. package/dist/clients/attach/input/controller.d.ts +4 -1
  23. package/dist/clients/attach/input/controller.js +3 -3
  24. package/dist/clients/attach/input/overlay-owner.d.ts +0 -1
  25. package/dist/clients/attach/input/overlay-owner.js +1 -1
  26. package/dist/clients/attach/overlays/graph.d.ts +3 -2
  27. package/dist/clients/attach/overlays/graph.js +1 -1
  28. package/dist/clients/attach/render/chat-view.d.ts +2 -0
  29. package/dist/clients/attach/render/chat-view.js +1 -1
  30. package/dist/clients/attach/render/doc-links.d.ts +1 -1
  31. package/dist/clients/attach/session/chrome-refresh.js +1 -1
  32. package/dist/clients/attach/session/connection.d.ts +10 -9
  33. package/dist/clients/attach/session/connection.js +1 -1
  34. package/dist/clients/attach/session/context.d.ts +1 -1
  35. package/dist/clients/attach/session/document-links.d.ts +1 -1
  36. package/dist/clients/attach/session/document-links.js +1 -1
  37. package/dist/clients/attach/session/identity.d.ts +2 -0
  38. package/dist/clients/attach/session/identity.js +1 -1
  39. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  40. package/dist/clients/attach/session/input-wiring.js +1 -1
  41. package/dist/clients/attach/session/keys.d.ts +2 -2
  42. package/dist/clients/attach/session/keys.js +1 -1
  43. package/dist/clients/attach/session/pane-tag.d.ts +3 -1
  44. package/dist/clients/attach/session/pane-tag.js +1 -1
  45. package/dist/clients/attach/session/reconnect.js +1 -1
  46. package/dist/clients/attach/session/surface-host.d.ts +0 -5
  47. package/dist/clients/attach/session/surface-host.js +1 -1
  48. package/dist/clients/attach/session/teardown.d.ts +2 -2
  49. package/dist/clients/attach/session/teardown.js +9 -7
  50. package/dist/clients/attach/viewer.d.ts +7 -5
  51. package/dist/clients/attach/viewer.js +571 -584
  52. package/dist/clients/editor-roundtrip.js +3 -0
  53. package/dist/clients/inbox/controller.d.ts +1 -6
  54. package/dist/clients/inbox/controller.js +1 -1
  55. package/dist/clients/inbox/dto-adapt.js +1 -1
  56. package/dist/clients/inbox/tui/page-body.js +1 -1
  57. package/dist/clients/inbox/tui/render.js +2 -2
  58. package/dist/clients/open-browser.d.ts +2 -0
  59. package/dist/clients/open-browser.js +1 -0
  60. package/dist/clients/surfaces/host.d.ts +0 -6
  61. package/dist/commands/human/review.js +1 -1
  62. package/dist/commands/node/wait.js +2 -6
  63. package/dist/commands/sys/context/admin/shell.js +1 -1
  64. package/dist/core/broker-client/client.d.ts +6 -3
  65. package/dist/core/broker-client/client.js +1 -1
  66. package/dist/core/canvas/crons.d.ts +11 -1
  67. package/dist/core/canvas/crons.js +14 -14
  68. package/dist/core/canvas/executions.js +1 -1
  69. package/dist/core/canvas/schema-pg/025-review-anchors.sql +19 -0
  70. package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
  71. package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
  72. package/dist/core/canvas/schema-version.d.ts +1 -1
  73. package/dist/core/canvas/schema-version.js +1 -1
  74. package/dist/core/command.js +5 -5
  75. package/dist/core/feed/messages.d.ts +5 -0
  76. package/dist/core/feed/messages.js +5 -5
  77. package/dist/core/human/page-markdown.js +10 -12
  78. package/dist/core/human/tickets.js +1 -1
  79. package/dist/core/human/types.d.ts +4 -6
  80. package/dist/core/keybindings/attach-control.d.ts +0 -3
  81. package/dist/core/keybindings/attach-control.js +1 -1
  82. package/dist/core/keybindings/catalog.d.ts +1 -1
  83. package/dist/core/keybindings/catalog.js +1 -1
  84. package/dist/core/review/anchors.d.ts +28 -0
  85. package/dist/core/review/anchors.js +6 -0
  86. package/dist/core/review/comments.d.ts +2 -2
  87. package/dist/core/review/comments.js +7 -8
  88. package/dist/core/review/companion.d.ts +2 -1
  89. package/dist/core/review/companion.js +1 -1
  90. package/dist/core/review/document.d.ts +4 -17
  91. package/dist/core/review/document.js +1 -2
  92. package/dist/core/review/fork.js +2 -4
  93. package/dist/core/review/project.d.ts +1 -1
  94. package/dist/core/review/project.js +2 -2
  95. package/dist/core/review/realize.js +1 -1
  96. package/dist/core/review/stage.d.ts +2 -9
  97. package/dist/core/review/stage.js +1 -1
  98. package/dist/core/review/types.d.ts +16 -12
  99. package/dist/core/review/types.js +1 -1
  100. package/dist/core/runtime/bearings.js +4 -4
  101. package/dist/core/runtime/boot-root.js +4 -4
  102. package/dist/core/runtime/broker-cli.js +3 -3
  103. package/dist/core/runtime/broker-extension-render.js +1 -1
  104. package/dist/core/runtime/lifecycle.js +2 -2
  105. package/dist/core/runtime/revive.js +2 -2
  106. package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
  107. package/dist/core/runtime/runner/blaxel/client.js +1 -1
  108. package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
  109. package/dist/core/runtime/runner/blaxel/runner.js +3 -3
  110. package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
  111. package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
  112. package/dist/core/runtime/runner/types.d.ts +19 -3
  113. package/dist/core/runtime/tmux-bindings.js +3 -3
  114. package/dist/daemon/api/bridge.d.ts +5 -0
  115. package/dist/daemon/api/bridge.js +3 -3
  116. package/dist/daemon/api/canvas-host.js +1 -1
  117. package/dist/daemon/api/document-page.d.ts +12 -1
  118. package/dist/daemon/api/document-page.js +6 -6
  119. package/dist/daemon/api/handlers/crons.d.ts +2 -0
  120. package/dist/daemon/api/handlers/crons.js +1 -1
  121. package/dist/daemon/api/handlers/inbox.js +1 -1
  122. package/dist/daemon/api/handlers/nodes.js +1 -1
  123. package/dist/daemon/api/handlers/review-comments.js +1 -1
  124. package/dist/daemon/api/handlers/reviews.js +1 -1
  125. package/dist/daemon/api/map.js +2 -2
  126. package/dist/daemon/api/operations.js +1 -1
  127. package/dist/daemon/api/review-page.d.ts +3 -0
  128. package/dist/daemon/api/review-page.js +13 -0
  129. package/dist/daemon/broker-memory-cap.d.ts +9 -0
  130. package/dist/daemon/broker-memory-cap.js +2 -0
  131. package/dist/daemon/broker-signals/bus.d.ts +1 -1
  132. package/dist/daemon/broker-signals/bus.js +1 -1
  133. package/dist/daemon/cron/ended.d.ts +3 -0
  134. package/dist/daemon/cron/ended.js +2 -2
  135. package/dist/daemon/cron/lease-recovery.js +1 -1
  136. package/dist/daemon/cron/machine-fire.d.ts +9 -2
  137. package/dist/daemon/cron/machine-fire.js +1 -1
  138. package/dist/daemon/cron/passes.js +1 -1
  139. package/dist/daemon/cron-run.js +2 -2
  140. package/dist/daemon/crtrd.js +14 -14
  141. package/dist/daemon/machine-daemon.js +1 -1
  142. package/dist/daemon/machine-link/client.js +1 -1
  143. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  144. package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
  145. package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
  146. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  147. package/dist/daemon/review/comment-notify.js +2 -2
  148. package/dist/daemon/review/deliver.d.ts +2 -2
  149. package/dist/daemon/review/deliver.js +6 -2
  150. package/dist/daemon/review/finish.js +1 -1
  151. package/dist/doc-editor/Geist-Variable.woff2 +0 -0
  152. package/dist/doc-editor/GeistMono-Variable.woff2 +0 -0
  153. package/dist/doc-editor/editor.css +1 -1
  154. package/dist/doc-editor/review.css +2 -0
  155. package/dist/doc-editor/review.js +149 -0
  156. package/dist/pi-extensions/canvas-review-boundary.js +3 -3
  157. package/docs/sdk/release-notes.md +6 -0
  158. package/package.json +13 -4
  159. package/packages/crouter-api/dist/api/client.js +0 -3
  160. package/packages/crouter-api/dist/api/contract.js +1 -1
  161. package/packages/crouter-api/dist/api/routes.js +0 -1
  162. package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +3 -3
  163. package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
  164. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +17 -28
  165. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +2 -7
  166. package/packages/crouter-api/dist/clients/attach/chrome/ticket-panel.js +1 -1
  167. package/packages/crouter-api/dist/clients/attach/input/capabilities.js +2 -1
  168. package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -3
  169. package/packages/crouter-api/dist/clients/attach/input/overlay-owner.js +0 -7
  170. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
  171. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
  172. package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
  173. package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
  174. package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
  175. package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
  176. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
  177. package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -5
  178. package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
  179. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
  180. package/packages/crouter-api/dist/clients/attach/session/surface-host.js +0 -17
  181. package/packages/crouter-api/dist/clients/attach/session/teardown.js +7 -4
  182. package/packages/crouter-api/dist/clients/attach/viewer.js +77 -67
  183. package/packages/crouter-api/dist/clients/{inbox/review/roundtrip.js → editor-roundtrip.js} +1 -1
  184. package/packages/crouter-api/dist/clients/inbox/controller.js +12 -31
  185. package/packages/crouter-api/dist/clients/inbox/dto-adapt.js +1 -0
  186. package/packages/crouter-api/dist/clients/inbox/tui/page-body.js +0 -7
  187. package/packages/crouter-api/dist/clients/inbox/tui/render.js +0 -7
  188. package/packages/crouter-api/dist/clients/open-browser.js +6 -0
  189. package/packages/crouter-api/dist/commands/human/review.js +17 -18
  190. package/packages/crouter-api/dist/commands/node/wait.js +2 -10
  191. package/packages/crouter-api/dist/commands/sys/context/admin/shell.js +1 -1
  192. package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
  193. package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
  194. package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
  195. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  196. package/packages/crouter-api/dist/core/command.js +3 -0
  197. package/packages/crouter-api/dist/core/feed/messages.js +15 -0
  198. package/packages/crouter-api/dist/core/human/page-markdown.js +2 -6
  199. package/packages/crouter-api/dist/core/human/tickets.js +2 -11
  200. package/packages/crouter-api/dist/core/keybindings/attach-control.js +0 -1
  201. package/packages/crouter-api/dist/core/keybindings/catalog.js +1 -3
  202. package/packages/crouter-api/dist/core/review/anchors.js +91 -0
  203. package/packages/crouter-api/dist/core/review/comments.js +27 -46
  204. package/packages/crouter-api/dist/core/review/companion.js +5 -9
  205. package/packages/crouter-api/dist/core/review/document.js +17 -89
  206. package/packages/crouter-api/dist/core/review/project.js +2 -1
  207. package/packages/crouter-api/dist/core/review/types.js +2 -2
  208. package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
  209. package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
  210. package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
  211. package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
  212. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
  213. package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
  214. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +0 -5
  215. package/packages/crouter-api/dist/daemon/api/map.js +2 -6
  216. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  217. package/packages/crouter-api/dist/daemon/broker-signals/bus.js +1 -1
  218. package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
  219. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
  220. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  221. package/packages/crouter-api/dist/daemon/review/deliver.js +4 -3
  222. package/packages/crouter-api/dist/daemon/review/finish.js +26 -47
  223. package/packages/crouter-api/package.json +1 -1
  224. package/packages/crouter-identity/package.json +1 -1
  225. package/packages/crouter-plugin/package.json +3 -3
  226. package/runtime.lock.json +1740 -505
  227. package/dist/clients/attach/overlays/file-review.d.ts +0 -10
  228. package/dist/clients/attach/overlays/file-review.js +0 -2
  229. package/dist/clients/inbox/review/anchors.d.ts +0 -41
  230. package/dist/clients/inbox/review/anchors.js +0 -1
  231. package/dist/clients/inbox/review/comments-client.d.ts +0 -74
  232. package/dist/clients/inbox/review/comments-client.js +0 -1
  233. package/dist/clients/inbox/review/companion-pane.d.ts +0 -47
  234. package/dist/clients/inbox/review/companion-pane.js +0 -1
  235. package/dist/clients/inbox/review/document-surface.d.ts +0 -212
  236. package/dist/clients/inbox/review/document-surface.js +0 -2
  237. package/dist/clients/inbox/review/frame.d.ts +0 -57
  238. package/dist/clients/inbox/review/frame.js +0 -1
  239. package/dist/clients/inbox/review/keys.d.ts +0 -69
  240. package/dist/clients/inbox/review/keys.js +0 -1
  241. package/dist/clients/inbox/review/launch.d.ts +0 -16
  242. package/dist/clients/inbox/review/launch.js +0 -1
  243. package/dist/clients/inbox/review/live-source.d.ts +0 -24
  244. package/dist/clients/inbox/review/live-source.js +0 -1
  245. package/dist/clients/inbox/review/nvim.d.ts +0 -15
  246. package/dist/clients/inbox/review/nvim.js +0 -1
  247. package/dist/clients/inbox/review/remap.d.ts +0 -51
  248. package/dist/clients/inbox/review/remap.js +0 -1
  249. package/dist/clients/inbox/review/review-client.d.ts +0 -43
  250. package/dist/clients/inbox/review/review-client.js +0 -1
  251. package/dist/clients/inbox/review/roundtrip.js +0 -3
  252. package/dist/clients/inbox/review/state.d.ts +0 -153
  253. package/dist/clients/inbox/review/state.js +0 -4
  254. package/dist/clients/inbox/review-adapter.d.ts +0 -17
  255. package/dist/clients/inbox/review-adapter.js +0 -1
  256. package/dist/core/review/remap.d.ts +0 -24
  257. package/dist/core/review/remap.js +0 -19
  258. package/dist/core/review/signal.d.ts +0 -5
  259. package/dist/core/review/signal.js +0 -1
  260. package/dist/core/runtime/starting-screen.d.ts +0 -12
  261. package/dist/core/runtime/starting-screen.js +0 -9
  262. package/packages/crouter-api/dist/clients/attach/overlays/file-review.js +0 -146
  263. package/packages/crouter-api/dist/clients/inbox/review/anchors.js +0 -89
  264. package/packages/crouter-api/dist/clients/inbox/review/comments-client.js +0 -103
  265. package/packages/crouter-api/dist/clients/inbox/review/companion-pane.js +0 -109
  266. package/packages/crouter-api/dist/clients/inbox/review/document-surface.js +0 -1268
  267. package/packages/crouter-api/dist/clients/inbox/review/frame.js +0 -309
  268. package/packages/crouter-api/dist/clients/inbox/review/keys.js +0 -133
  269. package/packages/crouter-api/dist/clients/inbox/review/launch.js +0 -170
  270. package/packages/crouter-api/dist/clients/inbox/review/live-source.js +0 -160
  271. package/packages/crouter-api/dist/clients/inbox/review/nvim.js +0 -43
  272. package/packages/crouter-api/dist/clients/inbox/review/remap.js +0 -157
  273. package/packages/crouter-api/dist/clients/inbox/review/review-client.js +0 -125
  274. package/packages/crouter-api/dist/clients/inbox/review/state.js +0 -315
  275. package/packages/crouter-api/dist/clients/inbox/review-adapter.js +0 -43
  276. package/packages/crouter-api/dist/core/review/signal.js +0 -12
  277. package/packages/crouter-api/dist/core/termrender/code-doc.js +0 -92
  278. /package/dist/clients/{inbox/review/roundtrip.d.ts → editor-roundtrip.d.ts} +0 -0
@@ -1,6 +1,6 @@
1
- var U=Object.defineProperty;var r=(g,n)=>U(g,"name",{value:n,configurable:!0});import{execFile as E}from"node:child_process";import{Text as k,decodeKittyPrintable as V,matchesKey as N}from"@earendil-works/pi-tui";import{cliClient as w}from"../../../commands/api-client.js";import{focusNode as X}from"../../../core/runtime/focus-viewer.js";import{daemonErrorMessage as j}from"../../inbox/resolve.js";import{toBashJobStatus as K}from"./bash-jobs.js";import{fillBar as D,fillWidth as F,stripSgr as L,REVERSE as W}from"../../../core/canvas/nav-render.js";import{buildCanvasPanelLines as z}from"./canvas-panels.js";const G=15e3;function de(g,n){const{editor:A,tui:B,pal:M,nodeId:f,remote:p,role:R,canvasSource:I}=g,T=g.containers.reports;let s=[],o,v=process.env.CRTR_ATTACH_ROSTER;v!==void 0&&delete process.env.CRTR_ATTACH_ROSTER;let a,h;const b=r(()=>{n.syncCursor(),T.clear();for(const e of s){const i=e.key===o;T.addChild(new k(i?D(L(e.line),F(),W):e.line,1,0))}B.requestRender()},"paint"),C=r(async()=>(await w().listBashJobs(f)).map(K),"listJobs"),P=r(async e=>{const i=p?[]:await w().listCrons(),c=i.filter(d=>d.created_by===f),t=p?[]:await C(),u=p?[]:(await w().listReviews({state:"open"})).reviews,m=u.filter(d=>d.origin_node_id===f),_=p?void 0:{crons:i,reviews:u,jobsOf:r(async d=>(await w().listBashJobs(d)).map(K),"jobsOf")};if(s=(await z(f,n.asks(),M,I,c,t,m,_,e??await I.panelView?.(f))).items,v!==void 0){const d=v;v=void 0;const $=s.find(x=>x.kind==="node"&&x.nodeId===d);$!==void 0&&(o=$.key)}o!==void 0&&!s.some(d=>d.key===o)&&(o=void 0),a!==void 0&&!t.some(d=>d.jobId===a?.jobId)&&y(!0),b()},"refresh"),y=r(e=>{h!==void 0&&(clearTimeout(h),h=void 0),a!==void 0&&(a=void 0,e&&n.setNotice(""))},"disarmKill"),l=r(()=>{y(!0),o!==void 0&&(o=void 0,b())},"exit"),S=r(e=>V(e)??(e.length===1?e:void 0),"typed"),J=r((e,i=40)=>{const c=(e.split(`
2
- `)[0]??"").replace(/\s+/g," ").trim();return c.length>i?`${c.slice(0,i-1)}\u2026`:c},"commandHead"),O=r(async()=>{if(R!=="controller"){n.setNotice("Read-only observer attach \u2014 cannot stop background jobs");return}const e=await C();if(e.length===0){n.setNotice("Background job already finished"),n.requestChromeRefresh();return}if(e.length>1){n.setNotice(`${e.length} background jobs \u2014 press \u21B5 to pick one in the Inspector`);return}const i=e[0];a={jobId:i.jobId,label:J(i.command)},n.setNotice(`Stop \u201C${a.label}\u201D? Press y to confirm.`,{sticky:!0}),h=setTimeout(()=>y(!0),G)},"armKill"),q=r(()=>{const e=a;e!==void 0&&(y(!1),n.setNotice(`Stopping \u201C${e.label}\u201D\u2026`),E("crtr",["node","bash","kill",e.jobId,"--node",f],i=>{n.setNotice(i===null?`Stopped \u201C${e.label}\u201D.`:`Could not stop the job: ${i.message.split(`
3
- `)[0]}`),n.requestChromeRefresh()}))},"confirmKill");A.onCursorDownAtBottom=p?void 0:()=>{o!==void 0||s.length===0||(o=s[0].key,b())};const H=r(()=>{const e=s.find(t=>t.key===o);if(e===void 0||p)return;if(e.kind==="crons"){l(),n.openInspector("schedule");return}if(e.kind==="review"){if(R!=="controller"){n.setNotice("Read-only observer attach \u2014 cannot open the review companion");return}l();const t=process.env.TMUX_PANE;if(t===void 0||t===""){n.setNotice("Could not open the companion: no tmux pane");return}(async()=>{const u=w(),m=await u.getNode(e.companionNodeId);(await X(u,m,{pane:t})).focused||n.setNotice("Could not open the companion")})().catch(u=>n.setNotice(`Could not open the companion: ${j(u).split(`
4
- `)[0]}`));return}if(e.kind==="bash"){C().then(t=>{if(t.length===0){n.setNotice("Background job already finished"),n.requestChromeRefresh();return}l(),n.openInspector("jobs")},t=>n.setNotice(`Could not list background jobs: ${j(t).split(`
5
- `)[0]}`));return}if(e.kind==="object-wait"){l(),n.openObject(e.objectId);return}const i=e.nodeId;if(i===f){l();return}if(R!=="controller"){n.setNotice("Read-only observer attach \u2014 cannot focus nodes");return}const c=process.env.TMUX_PANE;if(c===void 0||c===""){n.setNotice("cannot swap \u2014 no tmux pane");return}E("tmux",["run-shell","-b",`crtr surface node focus ${i} --pane ${c} --in-place >/dev/null 2>&1`],()=>{})},"openSelected");return{refresh:P,handleKey:r(e=>{if(p)return!1;const i=N(e,"down"),c=N(e,"up");if(o===void 0)return!1;const t=s.findIndex(m=>m.key===o),u=s[t];if(a!==void 0){if(S(e)==="y")return q(),!0;y(!0)}return u?.kind==="bash"&&S(e)==="x"?(O().catch(m=>n.setNotice(`Could not list background jobs: ${j(m).split(`
6
- `)[0]}`)),!0):c?(t<=0?l():(o=s[t-1].key,b()),!0):i?(t>=0&&t<s.length-1&&(o=s[t+1].key,b()),!0):N(e,"enter")?(H(),!0):N(e,"escape")?(l(),!0):(l(),!1)},"handleKey"),active:r(()=>o!==void 0,"active"),exit:l}}r(de,"createRoster");export{de as createRoster};
1
+ var H=Object.defineProperty;var o=(d,n)=>H(d,"name",{value:n,configurable:!0});import{execFile as $}from"node:child_process";import{Text as P,decodeKittyPrintable as U,matchesKey as g}from"@earendil-works/pi-tui";import{cliClient as y}from"../../../commands/api-client.js";import{daemonErrorMessage as R}from"../../inbox/resolve.js";import{openBrowser as V}from"../../open-browser.js";import{toBashJobStatus as x}from"./bash-jobs.js";import{fillBar as D,fillWidth as F,stripSgr as L,REVERSE as W}from"../../../core/canvas/nav-render.js";import{buildCanvasPanelLines as X}from"./canvas-panels.js";const z=15e3;function de(d,n){const{editor:K,tui:k,pal:B,remote:f,role:j,canvasSource:C}=d,N=d.containers.reports;let s=[],r,v=process.env.CRTR_ATTACH_ROSTER;v!==void 0&&delete process.env.CRTR_ATTACH_ROSTER;let a,h;const m=o(()=>{n.syncCursor(),N.clear();for(const e of s){const i=e.key===r;N.addChild(new P(i?D(L(e.line),F(),W):e.line,1,0))}k.requestRender()},"paint"),I=o(async()=>(await y().listBashJobs(d.nodeId)).map(x),"listJobs"),E=o(async e=>{const i=f?[]:await y().listCrons(),c=i.filter(l=>l.created_by===d.nodeId),t=f?[]:await I(),p=f?[]:(await y().listReviews({state:"open"})).reviews,w=p.filter(l=>l.origin_node_id===d.nodeId),O=f?void 0:{crons:i,reviews:p,jobsOf:o(async l=>(await y().listBashJobs(l)).map(x),"jobsOf")};if(s=(await X(d.nodeId,n.asks(),B,C,c,t,w,O,e??await C.panelView?.(d.nodeId))).items,v!==void 0){const l=v;v=void 0;const S=s.find(_=>_.kind==="node"&&_.nodeId===l);S!==void 0&&(r=S.key)}r!==void 0&&!s.some(l=>l.key===r)&&(r=void 0),a!==void 0&&!t.some(l=>l.jobId===a?.jobId)&&b(!0),m()},"refresh"),b=o(e=>{h!==void 0&&(clearTimeout(h),h=void 0),a!==void 0&&(a=void 0,e&&n.setNotice(""))},"disarmKill"),u=o(()=>{b(!0),r!==void 0&&(r=void 0,m())},"exit"),T=o(e=>U(e)??(e.length===1?e:void 0),"typed"),A=o((e,i=40)=>{const c=(e.split(`
2
+ `)[0]??"").replace(/\s+/g," ").trim();return c.length>i?`${c.slice(0,i-1)}\u2026`:c},"commandHead"),q=o(async()=>{if(j!=="controller"){n.setNotice("Read-only observer attach \u2014 cannot stop background jobs");return}const e=await I();if(e.length===0){n.setNotice("Background job already finished"),n.requestChromeRefresh();return}if(e.length>1){n.setNotice(`${e.length} background jobs \u2014 press \u21B5 to pick one in the Inspector`);return}const i=e[0];a={jobId:i.jobId,label:A(i.command)},n.setNotice(`Stop \u201C${a.label}\u201D? Press y to confirm.`,{sticky:!0}),h=setTimeout(()=>b(!0),z)},"armKill"),J=o(()=>{const e=a;e!==void 0&&(b(!1),n.setNotice(`Stopping \u201C${e.label}\u201D\u2026`),$("crtr",["node","bash","kill",e.jobId,"--node",d.nodeId],i=>{n.setNotice(i===null?`Stopped \u201C${e.label}\u201D.`:`Could not stop the job: ${i.message.split(`
3
+ `)[0]}`),n.requestChromeRefresh()}))},"confirmKill");K.onCursorDownAtBottom=f?void 0:()=>{r!==void 0||s.length===0||(r=s[0].key,m())};const M=o(()=>{const e=s.find(t=>t.key===r);if(e===void 0||f)return;if(e.kind==="crons"){u(),n.openInspector("schedule");return}if(e.kind==="review"){u(),(async()=>{const t=(await y().listHumanInbox()).tickets.find(p=>p.kind==="review"&&p.request_id===e.reviewId);if(t?.kind!=="review"||t.url===void 0){n.setNotice("Reviews open on canvas.northlight.ai; this runtime has no canvas host");return}V(t.url)})().catch(t=>n.setNotice(`Could not open the review: ${R(t).split(`
4
+ `)[0]}`));return}if(e.kind==="bash"){I().then(t=>{if(t.length===0){n.setNotice("Background job already finished"),n.requestChromeRefresh();return}u(),n.openInspector("jobs")},t=>n.setNotice(`Could not list background jobs: ${R(t).split(`
5
+ `)[0]}`));return}if(e.kind==="object-wait"){u(),n.openObject(e.objectId);return}const i=e.nodeId;if(i===d.nodeId){u();return}if(j!=="controller"){n.setNotice("Read-only observer attach \u2014 cannot focus nodes");return}const c=process.env.TMUX_PANE;if(c===void 0||c===""){n.setNotice("cannot swap \u2014 no tmux pane");return}$("tmux",["run-shell","-b",`crtr surface node focus ${i} --pane ${c} --in-place >/dev/null 2>&1`],()=>{})},"openSelected");return{refresh:E,handleKey:o(e=>{if(f)return!1;const i=g(e,"down"),c=g(e,"up");if(r===void 0)return!1;const t=s.findIndex(w=>w.key===r),p=s[t];if(a!==void 0){if(T(e)==="y")return J(),!0;b(!0)}return p?.kind==="bash"&&T(e)==="x"?(q().catch(w=>n.setNotice(`Could not list background jobs: ${R(w).split(`
6
+ `)[0]}`)),!0):c?(t<=0?u():(r=s[t-1].key,m()),!0):i?(t>=0&&t<s.length-1&&(r=s[t+1].key,m()),!0):g(e,"enter")?(M(),!0):g(e,"escape")?(u(),!0):(u(),!1)},"handleKey"),active:o(()=>r!==void 0,"active"),exit:u}}o(de,"createRoster");export{de as createRoster};
@@ -5,7 +5,7 @@ import type { AttachSession } from '../session/context.js';
5
5
  * 2 = `!!` (output hidden from the agent). Drives both the editor border hue
6
6
  * and the leading status segment explaining what will happen. */
7
7
  export type BashMode = 0 | 1 | 2;
8
- export type StatusLineSession = Pick<AttachSession, 'nodeId' | 'remote' | 'tui' | 'pal' | 'containers'>;
8
+ export type StatusLineSession = Pick<AttachSession, 'remote' | 'tui' | 'pal' | 'containers'>;
9
9
  export interface StatusLineHooks {
10
10
  /** The reducer-folded broker state — role, engine, context tokens, queue. */
11
11
  state: () => SessionState;
@@ -1 +1 @@
1
- var L=Object.defineProperty;var r=(n,i)=>L(n,"name",{value:i,configurable:!0});import{Text as N,truncateToWidth as O}from"@earendil-works/pi-tui";import{visibleWidth as g}from"../../../core/canvas/nav-render.js";import{inTmux as S}from"../../../core/runtime/placement-tmux.js";import{formatBinding as W,inboxOpenHint as _}from"../../../core/keybindings/index.js";import{viewerKeyHint as j}from"./key-hint.js";const q=3e3,F=r(n=>n>=1e3?`${(n/1e3).toFixed(n>=1e4?0:1)}k`:`${n}`,"formatTokens");function G(n,i){const{pal:e,tui:w,nodeId:H,remote:I}=n,x=n.containers.footer;let u="",d;const m=r(()=>{const o=i.state(),a=i.bashMode(),f=i.bindings(),t=[];o.role!=="controller"&&t.push(e.muted("\u25CB read-only")),a===2?t.unshift(e.bashModeAlt("\u25CF bash \u2014 output hidden from agent")):a===1&&t.unshift(e.bashMode("\u25CF bash \u2014 output added to context"));const s=o.engine;s?.model&&t.push(e.info(s.model.id)),s?.isStreaming&&t.push(e.active("\u27F3")),o.contextTokens!==void 0&&t.push(e.muted(`${F(o.contextTokens)} ctx`)),s&&s.pendingMessageCount>0&&t.push(e.muted(`queued ${s.pendingMessageCount}`));let T=!1;if(i.inboxAffordance){const v=Object.values(i.asks()).reduce((y,E)=>y+E,0);v>0&&(T=!0,t.push(e.muted(`\u2691 ${v} \xB7 ${_(f)}`)))}i.mouseEnabled()||t.push(e.muted("mouse off")),S()&&f.gestures("crtr.attach.file-review").length>0&&t.push(e.muted(`${W(f,"crtr.attach.file-review")} review file`)),i.inboxAffordance&&t.push(e.muted(j(f,{inbox:!T})));const l=t.join(e.muted(" \xB7 ")),c=u?e.warning(`\u26A0 ${u}`):"",p=Math.max(1,(process.stdout.columns??80)-2),M=g(c),$=c?Math.max(0,p-M-1):p,h=g(l)>$?O(l,$,"\u2026"):l,C=Math.max(c?1:0,p-g(h)-M),A=c?h+" ".repeat(C)+c:h;x.clear(),x.addChild(new N(A,1,0)),w.requestRender()},"render"),b=r(()=>{d!==void 0&&(clearTimeout(d),d=void 0)},"clearTimer");return{render:m,setNotice:r((o,a)=>{u=o,b(),o&&!a?.sticky&&(d=setTimeout(()=>{d=void 0,u="",m()},q)),m()},"setNotice"),dispose:b}}r(G,"createStatusLine");export{G as createStatusLine};
1
+ var L=Object.defineProperty;var d=(n,o)=>L(n,"name",{value:o,configurable:!0});import{Text as N,truncateToWidth as O}from"@earendil-works/pi-tui";import{visibleWidth as h}from"../../../core/canvas/nav-render.js";import{inboxOpenHint as S}from"../../../core/keybindings/index.js";import{viewerKeyHint as W}from"./key-hint.js";const _=3e3,j=d(n=>n>=1e3?`${(n/1e3).toFixed(n>=1e4?0:1)}k`:`${n}`,"formatTokens");function k(n,o){const{pal:e,tui:v,remote:q}=n,b=n.containers.footer;let r="",c;const f=d(()=>{const i=o.state(),a=o.bashMode(),g=o.bindings(),t=[];i.role!=="controller"&&t.push(e.muted("\u25CB read-only")),a===2?t.unshift(e.bashModeAlt("\u25CF bash \u2014 output hidden from agent")):a===1&&t.unshift(e.bashMode("\u25CF bash \u2014 output added to context"));const s=i.engine;s?.model&&t.push(e.info(s.model.id)),s?.isStreaming&&t.push(e.active("\u27F3")),i.contextTokens!==void 0&&t.push(e.muted(`${j(i.contextTokens)} ctx`)),s&&s.pendingMessageCount>0&&t.push(e.muted(`queued ${s.pendingMessageCount}`));let M=!1;if(o.inboxAffordance){const C=Object.values(o.asks()).reduce((y,E)=>y+E,0);C>0&&(M=!0,t.push(e.muted(`\u2691 ${C} \xB7 ${S(g)}`)))}o.mouseEnabled()||t.push(e.muted("mouse off")),o.inboxAffordance&&t.push(e.muted(W(g,{inbox:!M})));const m=t.join(e.muted(" \xB7 ")),u=r?e.warning(`\u26A0 ${r}`):"",l=Math.max(1,(process.stdout.columns??80)-2),T=h(u),$=u?Math.max(0,l-T-1):l,p=h(m)>$?O(m,$,"\u2026"):m,A=Math.max(u?1:0,l-h(p)-T),w=u?p+" ".repeat(A)+u:p;b.clear(),b.addChild(new N(w,1,0)),v.requestRender()},"render"),x=d(()=>{c!==void 0&&(clearTimeout(c),c=void 0)},"clearTimer");return{render:f,setNotice:d((i,a)=>{r=i,x(),i&&!a?.sticky&&(c=setTimeout(()=>{c=void 0,r="",f()},_)),f()},"setNotice"),dispose:x}}d(k,"createStatusLine");export{k as createStatusLine};
@@ -1 +1 @@
1
- var N=Object.defineProperty;var n=(s,t)=>N(s,"name",{value:t,configurable:!0});import{watchInboxActivity as P}from"../../../core/human/root.js";import{resolvePageComponents as q}from"../../../core/config.js";import{fillBar as E,stripSgr as x,truncate as $,REVERSE as A}from"../../../core/canvas/nav-render.js";import{cliClient as g}from"../../../commands/api-client.js";import{visibleWidth as M}from"../../inbox/tui/ansi.js";import{pageViewFromDTO as v,settledStatusOf as w}from"../../inbox/dto-adapt.js";import{PageAdapter as S}from"../../inbox/page-adapter.js";import{decodeInboxKey as K}from"../../inbox/tui/keys.js";import{daemonErrorMessage as p,resolveFailureKind as D,resolveTicketPage as F}from"../../inbox/resolve.js";import{editBufferInEditor as H}from"../../inbox/review/roundtrip.js";function ne(s,t){const{tui:o,pal:y}=s;let c,l=!1,f=0,m=0;const b=n(()=>Math.max(3,o.terminal.rows-10),"capRows"),u=n(()=>{const e=c;e!==void 0&&(c=void 0,e.unwatch(),e.adapter.close(),t.syncCursor(),t.refreshStrip(),o.requestRender())},"closeSession"),I=n(async(e,r)=>{l=!0;try{await F(e.id,r),u(),t.setNotice("Response sent")}catch(a){const i=D(a);if(i==="unreachable"||i==="other"){t.setNotice(p(a));return}u(),t.setNotice(i==="already_settled"?await O(e.ticketId):p(a))}finally{l=!1}},"complete"),h=n(async e=>{if(c!==e||l)return;let r;try{r=await g().getHumanInboxPage(e.ticketId)}catch(a){if(c!==e)return;u(),t.setNotice(`Ticket could not be read: ${p(a)}`);return}if(!(c!==e||l)){if(r.state==="resolved"||r.state==="canceled"){u(),t.setNotice(r.state==="canceled"?"Ticket was canceled by its requester":"Ticket was resolved elsewhere");return}if(r.revision!==e.revision){e.revision=r.revision;try{e.adapter.reload(v(r))}catch{t.setNotice("Page could not be read")}o.requestRender()}}},"onActivity"),R=n(e=>{const r=e.adapter.inputBuffer();if(r===void 0)return;const a=t.suspendForChild();let i={text:r};try{i=H(r)}finally{a(),e.adapter.setInputBuffer(i.text),i.error!==void 0&&t.setNotice(i.error),o.requestRender()}},"editPageInput");return{component:{render(e){const r=c;if(r===void 0)return[];const a=Math.max(20,e-2),i=b();(a!==f||i!==m)&&(f=a,m=i,r.adapter.resize(a,i));const d=E(x($(` \u2691 ${r.title} \xB7 Esc closes`,e)),e,A),T=V(),B=U(r.adapter.render()).map(C=>z(` ${C}`,e,T));return[d,...B,y.border("\u2500".repeat(Math.max(0,e)))]},invalidate(){}},open:n(async e=>{if(c!==void 0&&u(),e.kind!=="page"){t.openInbox(e.dir);return}let r,a;try{const d=await g().getHumanInboxPage(e.inboxTicketId);if(d.state==="resolved"||d.state==="canceled"){t.setNotice(w(d));return}r=v(d),a=d.revision}catch{t.openInbox(e.dir);return}if(c!==void 0)return;f=Math.max(20,o.terminal.columns-2),m=b();const i={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,title:e.title,revision:a,adapter:new S({ticketId:e.inboxTicketId,page:r,productKinds:q(),cols:f,rows:m,onDirty:n(()=>o.requestRender(),"onDirty"),onBack:n(()=>u(),"onBack"),onComplete:n(d=>{I(i,d)},"onComplete"),onEditorRequest:n(()=>R(i),"onEditorRequest")}),unwatch:n(()=>{},"unwatch")};i.unwatch=P(()=>{h(i)}),c=i,t.syncCursor(),t.refreshStrip(),o.requestRender()},"open"),handleKey:n(e=>{const r=c;if(r===void 0)return!1;const{input:a,key:i}=K(e);return r.adapter.handleKey(a,i),o.requestRender(),!0},"handleKey"),close:n(()=>u(),"close"),active:n(()=>c!==void 0,"active"),currentDir:n(()=>c?.dir,"currentDir")}}n(ne,"createTicketPanel");async function O(s){let t;try{t=w(await g().getHumanInboxPage(s))}catch(o){return`Ticket result is unreadable: ${p(o)}`}return t.charAt(0).toUpperCase()+t.slice(1)}n(O,"resolvedElsewhereNotice");function V(){const s=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];try{return s?.getBgAnsi?.("customMessageBg")}catch{return}}n(V,"contextCardBg");function z(s,t,o){if(o===void 0)return s;const y=s.replaceAll("\x1B[0m",`\x1B[0m${o}`).replaceAll("\x1B[49m",o),c=" ".repeat(Math.max(0,t-M(s)));return`${o}${y}${c}\x1B[49m`}n(z,"paintBg");function U(s){let t=s.length;for(;t>0&&x(s[t-1]).trim()==="";)t--;return s.slice(0,t)}n(U,"trimTrailingBlank");export{ne as createTicketPanel};
1
+ var N=Object.defineProperty;var n=(s,t)=>N(s,"name",{value:t,configurable:!0});import{watchInboxActivity as P}from"../../../core/human/root.js";import{resolvePageComponents as q}from"../../../core/config.js";import{fillBar as E,stripSgr as x,truncate as $,REVERSE as A}from"../../../core/canvas/nav-render.js";import{cliClient as g}from"../../../commands/api-client.js";import{visibleWidth as M}from"../../inbox/tui/ansi.js";import{pageViewFromDTO as v,settledStatusOf as w}from"../../inbox/dto-adapt.js";import{PageAdapter as S}from"../../inbox/page-adapter.js";import{decodeInboxKey as K}from"../../inbox/tui/keys.js";import{daemonErrorMessage as p,resolveFailureKind as D,resolveTicketPage as F}from"../../inbox/resolve.js";import{editBufferInEditor as H}from"../../editor-roundtrip.js";function ne(s,t){const{tui:o,pal:y}=s;let c,l=!1,f=0,m=0;const b=n(()=>Math.max(3,o.terminal.rows-10),"capRows"),u=n(()=>{const e=c;e!==void 0&&(c=void 0,e.unwatch(),e.adapter.close(),t.syncCursor(),t.refreshStrip(),o.requestRender())},"closeSession"),I=n(async(e,r)=>{l=!0;try{await F(e.id,r),u(),t.setNotice("Response sent")}catch(a){const i=D(a);if(i==="unreachable"||i==="other"){t.setNotice(p(a));return}u(),t.setNotice(i==="already_settled"?await O(e.ticketId):p(a))}finally{l=!1}},"complete"),h=n(async e=>{if(c!==e||l)return;let r;try{r=await g().getHumanInboxPage(e.ticketId)}catch(a){if(c!==e)return;u(),t.setNotice(`Ticket could not be read: ${p(a)}`);return}if(!(c!==e||l)){if(r.state==="resolved"||r.state==="canceled"){u(),t.setNotice(r.state==="canceled"?"Ticket was canceled by its requester":"Ticket was resolved elsewhere");return}if(r.revision!==e.revision){e.revision=r.revision;try{e.adapter.reload(v(r))}catch{t.setNotice("Page could not be read")}o.requestRender()}}},"onActivity"),R=n(e=>{const r=e.adapter.inputBuffer();if(r===void 0)return;const a=t.suspendForChild();let i={text:r};try{i=H(r)}finally{a(),e.adapter.setInputBuffer(i.text),i.error!==void 0&&t.setNotice(i.error),o.requestRender()}},"editPageInput");return{component:{render(e){const r=c;if(r===void 0)return[];const a=Math.max(20,e-2),i=b();(a!==f||i!==m)&&(f=a,m=i,r.adapter.resize(a,i));const d=E(x($(` \u2691 ${r.title} \xB7 Esc closes`,e)),e,A),T=V(),B=U(r.adapter.render()).map(C=>z(` ${C}`,e,T));return[d,...B,y.border("\u2500".repeat(Math.max(0,e)))]},invalidate(){}},open:n(async e=>{if(c!==void 0&&u(),e.kind!=="page"){t.openInbox(e.dir);return}let r,a;try{const d=await g().getHumanInboxPage(e.inboxTicketId);if(d.state==="resolved"||d.state==="canceled"){t.setNotice(w(d));return}r=v(d),a=d.revision}catch{t.openInbox(e.dir);return}if(c!==void 0)return;f=Math.max(20,o.terminal.columns-2),m=b();const i={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,title:e.title,revision:a,adapter:new S({ticketId:e.inboxTicketId,page:r,productKinds:q(),cols:f,rows:m,onDirty:n(()=>o.requestRender(),"onDirty"),onBack:n(()=>u(),"onBack"),onComplete:n(d=>{I(i,d)},"onComplete"),onEditorRequest:n(()=>R(i),"onEditorRequest")}),unwatch:n(()=>{},"unwatch")};i.unwatch=P(()=>{h(i)}),c=i,t.syncCursor(),t.refreshStrip(),o.requestRender()},"open"),handleKey:n(e=>{const r=c;if(r===void 0)return!1;const{input:a,key:i}=K(e);return r.adapter.handleKey(a,i),o.requestRender(),!0},"handleKey"),close:n(()=>u(),"close"),active:n(()=>c!==void 0,"active"),currentDir:n(()=>c?.dir,"currentDir")}}n(ne,"createTicketPanel");async function O(s){let t;try{t=w(await g().getHumanInboxPage(s))}catch(o){return`Ticket result is unreadable: ${p(o)}`}return t.charAt(0).toUpperCase()+t.slice(1)}n(O,"resolvedElsewhereNotice");function V(){const s=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];try{return s?.getBgAnsi?.("customMessageBg")}catch{return}}n(V,"contextCardBg");function z(s,t,o){if(o===void 0)return s;const y=s.replaceAll("\x1B[0m",`\x1B[0m${o}`).replaceAll("\x1B[49m",o),c=" ".repeat(Math.max(0,t-M(s)));return`${o}${y}${c}\x1B[49m`}n(z,"paintBg");function U(s){let t=s.length;for(;t>0&&x(s[t-1]).trim()==="";)t--;return s.slice(0,t)}n(U,"trimTrailingBlank");export{ne as createTicketPanel};
@@ -1 +1 @@
1
- var o=Object.defineProperty;var r=(e,s)=>o(e,"name",{value:s,configurable:!0});function l(e){const s=e.remote,n=e.role,a=new Set;return s||(a.add("local-canvas-inspect"),a.add("canvas-inbox")),n==="controller"&&(a.add("engine-drive"),a.add("dequeue")),n==="controller"&&!s&&(a.add("wake-dormant"),a.add("auth"),a.add("canvas-resume"),a.add("local-host")),{role:n,remote:s,nodeId:e.nodeId,profileId:e.profileId,permittedOperations:a,permits:r(t=>a.has(t),"permits"),refusal:r((t,i)=>{const c=i===void 0?"":`/${i} `;if(e.isBrokerOffline?.()===!0&&(t==="engine-drive"||t==="dequeue"||t==="auth"))return`${c}needs a live broker; this node is parked \u2014 submit a message to wake it`;if(!a.has(t))return s&&(t==="canvas-resume"||t==="local-canvas-inspect"||t==="canvas-inbox")?`${c}Not available with --canvas because it acts on this machine's local canvas`:s&&n==="controller"?`${c}Not available with --canvas because it acts on this machine, not the remote node`:`${c}is not available to a read-only observer attach (--observer) \u2014 it would drive this node`},"refusal")}}r(l,"createViewerCapabilities");function u(e){switch(e.type){case"prompt":case"steer":case"follow_up":case"abort":case"bash":case"set_model":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"new_session":case"switch_session":case"fork":case"set_session_name":case"navigate_tree":case"reload":case"export":case"clone":case"share":case"reload_auth":return"engine-drive";default:return}}r(u,"viewerOperationForFrame");function f(e,s,n){if(n)switch(e){case"resume":return"canvas-resume";case"context":case"node-metadata":return"local-canvas-inspect";case"plugins":return;case"inbox":return"canvas-inbox";case"clear":case"resume-session":case"tutorial":return"engine-drive";case"promote":case"rename":case"mcp":return"local-host";default:return}if(s)switch(e){case"copy":case"session":case"changelog":case"hotkeys":case"quit":return;case"login":case"logout":return"auth";default:return"engine-drive"}}r(f,"viewerOperationForSlash");export{l as createViewerCapabilities,u as viewerOperationForFrame,f as viewerOperationForSlash};
1
+ var o=Object.defineProperty;var r=(e,s)=>o(e,"name",{value:s,configurable:!0});function l(e){const s=e.remote,n=e.role,a=new Set;return s||(a.add("local-canvas-inspect"),a.add("canvas-inbox")),n==="controller"&&(a.add("engine-drive"),a.add("dequeue")),n==="controller"&&!s&&(a.add("wake-dormant"),a.add("auth"),a.add("canvas-resume"),a.add("local-host")),{role:n,remote:s,get nodeId(){return e.nodeId},profileId:e.profileId,permittedOperations:a,permits:r(t=>a.has(t),"permits"),refusal:r((t,i)=>{const c=i===void 0?"":`/${i} `;if(e.isBrokerOffline?.()===!0&&(t==="engine-drive"||t==="dequeue"||t==="auth"))return`${c}needs a live broker; this node is parked \u2014 submit a message to wake it`;if(!a.has(t))return s&&(t==="canvas-resume"||t==="local-canvas-inspect"||t==="canvas-inbox")?`${c}Not available with --canvas because it acts on this machine's local canvas`:s&&n==="controller"?`${c}Not available with --canvas because it acts on this machine, not the remote node`:`${c}is not available to a read-only observer attach (--observer) \u2014 it would drive this node`},"refusal")}}r(l,"createViewerCapabilities");function u(e){switch(e.type){case"prompt":case"steer":case"follow_up":case"abort":case"bash":case"set_model":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"new_session":case"switch_session":case"fork":case"set_session_name":case"navigate_tree":case"reload":case"export":case"clone":case"share":case"reload_auth":return"engine-drive";default:return}}r(u,"viewerOperationForFrame");function f(e,s,n){if(n)switch(e){case"resume":return"canvas-resume";case"context":case"node-metadata":return"local-canvas-inspect";case"plugins":return;case"inbox":return"canvas-inbox";case"clear":case"resume-session":case"tutorial":return"engine-drive";case"promote":case"rename":case"mcp":return"local-host";default:return}if(s)switch(e){case"copy":case"session":case"changelog":case"hotkeys":case"quit":return;case"login":case"logout":return"auth";default:return"engine-drive"}}r(f,"viewerOperationForSlash");export{l as createViewerCapabilities,u as viewerOperationForFrame,f as viewerOperationForSlash};
@@ -30,6 +30,8 @@ export interface InputControllerHooks {
30
30
  openLoginPicker?: () => void;
31
31
  openLogoutPicker?: () => void;
32
32
  isDormant?: () => boolean;
33
+ /** True while the node is still being created. */
34
+ isStarting?: () => boolean;
33
35
  onDormantSubmit?: (text: string) => void;
34
36
  onPromptSent?: () => void;
35
37
  /** A new message (not a steer) left the editor; the viewer shows it pending
@@ -63,10 +65,11 @@ export declare class InputController {
63
65
  attachDialog(request: RpcExtensionUIRequest): void;
64
66
  dismissDialog(id: string): void;
65
67
  setState(state: BrokerSnapshot['state']): void;
66
- openFileReviewPicker(candidates: string[], cwd: string, onChoose: (file: string) => void): void;
67
68
  /** Retained as a narrow delegate for auth affordances wired by the session. */
68
69
  openAuthPicker(prepare: Parameters<InputOverlayOwner['openAuthPicker']>[0]): Promise<void>;
69
70
  private readonly send;
71
+ /** While the node is being created only these frames are accepted (prompts are held until the welcome; a `!` command is refused like a slash command); everything else needs the node. */
72
+ private refuseStarting;
70
73
  private emitCommand;
71
74
  private openBrokerPicker;
72
75
  private wire;
@@ -1,7 +1,7 @@
1
- var p=Object.defineProperty;var n=(h,e)=>p(h,"name",{value:e,configurable:!0});import{spawn as u}from"node:child_process";import{readFileSync as f,unlinkSync as k,writeFileSync as g}from"node:fs";import{tmpdir as y}from"node:os";import{join as P}from"node:path";import{BROKER_READ_CAPS as v,encodeFrame as x}from"../../../core/runtime/broker-protocol.js";import{classifySubmit as w}from"../../conversation/submit.js";import{findRefTokens as C}from"../../../shared/inline-ref-grammar.js";import{dispatchSlashCommand as S,isSlashCommand as m}from"../slash/dispatch.js";import{viewerOperationForFrame as b}from"./capabilities.js";import{readClipboardImage as T,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as D}from"./overlay-owner.js";import{announceFallbackEditor as E,NO_EDITOR_MESSAGE as M,resolveEditor as A}from"../../../core/editor-resolver.js";const q=500,R=v.maxLineBytes-4*1024*1024;class z{static{n(this,"InputController")}tui;editor;keybindings;hooks;capabilities;overlays;state;lastEscapeAt=0;pastedImages=new Map;pasteSeq=0;constructor(e,t,o,i,s){this.tui=e,this.editor=t,this.keybindings=o,this.hooks=i,this.capabilities=s,this.overlays=new D(e,t,o,{send:n(r=>this.emitCommand(r),"send"),notify:n(r=>this.notify(r),"notify"),onDialogResponse:i.onDialogResponse,onRequest:i.onRequest,onMountPicker:i.onMountPicker,onUnmountPicker:i.onUnmountPicker,state:n(()=>this.state,"state")}),this.wire()}cycleLadder(e){this.emitCommand({type:"cycle_ladder",direction:e})}sendInterrupting(e){return this.emitDrive({type:"prompt",text:e,interrupt:!0})}abortTurn(){return this.state?.isStreaming!==!0?!1:this.emitCommand({type:"abort"})}attachDialog(e){this.overlays.attachDialog(e)}dismissDialog(e){this.overlays.dismissDialog(e)}setState(e){this.state=e}openFileReviewPicker(e,t,o){this.overlays.openFileReviewPicker(e,t,o)}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=n(e=>{this.emitCommand(e)},"send");emitCommand(e){const t=b(e),o=t===void 0?void 0:this.capabilities.refusal(t);return o===void 0?(this.hooks.onCommand(e),!0):(this.notify(o),!1)}openBrokerPicker(e){const t=this.capabilities.refusal("engine-drive");if(t!==void 0){this.notify(t);return}e()}wire(){this.editor.onSubmit=t=>this.handleSubmit(t),this.editor.onEscape=()=>{if(this.state?.isStreaming){this.emitCommand({type:"abort"});return}if(this.editor.getText().trim())return;const t=Date.now();t-this.lastEscapeAt<q?(this.lastEscapeAt=0,this.openBrokerPicker(()=>{this.overlays.openTreePicker()})):this.lastEscapeAt=t},this.editor.onPasteImage=()=>{this.handlePaste()};const e=this.editor;e.onPasteImagePath=t=>(this.attachImage(t),!0),this.editor.onAction("app.session.new",()=>this.emitCommand({type:"new_session"})),this.editor.onAction("app.model.cycleForward",()=>this.emitCommand({type:"cycle_model",direction:"forward"})),this.editor.onAction("app.model.cycleBackward",()=>this.emitCommand({type:"cycle_model",direction:"backward"})),this.editor.onAction("app.thinking.cycle",()=>this.emitCommand({type:"cycle_thinking"})),this.editor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.editor.onAction("app.message.dequeue",()=>{this.handleDequeue()}),this.editor.onAction("app.tools.expand",()=>this.hooks.onMoreDetail?.()),this.editor.onAction("app.thinking.toggle",()=>this.hooks.onToggleThinking?.()),this.editor.onAction("app.editor.external",()=>{this.openExternalEditor()}),this.editor.onAction("app.model.select",()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()})),this.editor.onAction("app.session.tree",()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()})),this.editor.onAction("app.session.fork",()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()})),this.editor.onAction("app.session.resume",()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}))}slashContext(){return{send:this.send,notify:n(e=>this.notify(e),"notify"),capabilities:this.capabilities,state:this.state,cwd:process.cwd(),onGraph:this.hooks.onGraph,onInbox:this.hooks.onInbox,onHelp:this.hooks.onHelp,onQuit:this.hooks.onQuit,onCopy:this.hooks.onCopy,onCopyTarget:this.hooks.onCopyTarget,onToggleMouse:this.hooks.onToggleMouse,onColor:this.hooks.onColor,onNodeMetadata:this.hooks.onNodeMetadata,onMoreDetail:this.hooks.onMoreDetail,onLessDetail:this.hooks.onLessDetail,openModelPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()}),"openModelPicker"),openSessionPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}),"openSessionPicker"),openForkPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()}),"openForkPicker"),openTreePicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()}),"openTreePicker"),openSettingsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSettingsPicker()}),"openSettingsPicker"),openScopedModelsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openScopedModelsPicker()}),"openScopedModelsPicker"),openMcpPicker:n(e=>this.overlays.openMcpPicker(e),"openMcpPicker"),openLoginPicker:this.hooks.openLoginPicker,openLogoutPicker:this.hooks.openLogoutPicker}}recordCommandUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.slice(1).split(/\s/,1)[0];o&&t.record(`command:${o}`)}recordCompletionUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.trim();if(m(o)){this.recordCommandUse(o);return}const i=this.hooks.knownRefNames?.();if(!i||i.size===0)return;const s=new Set;for(const r of C(e))i.has(r.candidate)&&!s.has(r.candidate)&&(s.add(r.candidate),t.record(`ref:${r.candidate}`))}handleSubmit(e){const t=e.trim();if(!t)return;if(m(t)&&S(t,this.slashContext())){this.recordCommandUse(t),this.editor.setText("");return}const o=this.hooks.isDormant?.()===!0;if(o&&(t.startsWith("/")||t.startsWith("!"))){this.notify("This node is parked \u2014 submit a message to wake it; broker commands need a live engine");return}const i=w(e,{isDormant:o,canWakeDormant:o&&this.capabilities.permits("wake-dormant")&&this.hooks.onDormantSubmit!==void 0,isStreaming:this.state?.isStreaming===!0});if(i.kind==="empty")return;if(i.kind==="dormant"){const a=this.hooks.onDormantSubmit;if(a===void 0)return;const d=this.expandImagePlaceholders(i.text);a(d),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onMessageSent?.(d),this.hooks.onPromptSent?.();return}if(i.kind==="bash"){if(!this.emitDrive({type:"bash",command:i.command,excludeFromContext:i.excludeFromContext}))return;this.editor.addToHistory(i.trimmed),this.editor.setText("");return}const s=i.kind==="slash"?this.state?.isStreaming===!0?"steer":"prompt":i.kind;if(s!=="steer"&&s!=="prompt")return;const r=this.expandImagePlaceholders(i.kind==="slash"?e:i.text);this.emitDrive(s==="steer"?{type:"steer",text:r}:{type:"prompt",text:r})&&(this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),s==="prompt"&&this.hooks.onMessageSent?.(r),this.hooks.onPromptSent?.())}handleFollowUp(){const e=this.editor.getText(),t=e.trim();t&&this.emitDrive({type:"follow_up",text:this.expandImagePlaceholders(e)})&&(this.editor.addToHistory(t),this.editor.setText(""),this.clearPastedImages())}async handleDequeue(){const e=this.capabilities.refusal("dequeue");if(e!==void 0){this.notify(e);return}const t=this.hooks.onRequest;if(t===void 0){this.notify("Restoring queued messages isn't available in this viewer");return}let o;try{o=await t({type:"dequeue"})}catch(s){this.notify(`Could not restore queued messages: ${s instanceof Error?s.message:String(s)}`);return}if(o.kind!=="dequeue"){this.notify("Unexpected reply restoring queued messages");return}const i=[...o.steering,...o.followUp];if(i.length===0){this.notify("No queued messages to restore");return}this.editor.setText([i.join(`
1
+ var l=Object.defineProperty;var n=(c,e)=>l(c,"name",{value:e,configurable:!0});import{spawn as u}from"node:child_process";import{readFileSync as f,unlinkSync as k,writeFileSync as g}from"node:fs";import{tmpdir as y}from"node:os";import{join as P}from"node:path";import{BROKER_READ_CAPS as v,encodeFrame as S}from"../../../core/runtime/broker-protocol.js";import{classifySubmit as x}from"../../conversation/submit.js";import{findRefTokens as w}from"../../../shared/inline-ref-grammar.js";import{dispatchSlashCommand as C,isSlashCommand as d}from"../slash/dispatch.js";import{viewerOperationForFrame as b}from"./capabilities.js";import{readClipboardImage as T,writeClipboardImageToFile as I}from"./clipboard-image.js";import{InputOverlayOwner as D}from"./overlay-owner.js";import{announceFallbackEditor as E,NO_EDITOR_MESSAGE as M,resolveEditor as A}from"../../../core/editor-resolver.js";const q=500,B=v.maxLineBytes-4*1024*1024;class z{static{n(this,"InputController")}tui;editor;keybindings;hooks;capabilities;overlays;state;lastEscapeAt=0;pastedImages=new Map;pasteSeq=0;constructor(e,t,o,i,s){this.tui=e,this.editor=t,this.keybindings=o,this.hooks=i,this.capabilities=s,this.overlays=new D(e,t,o,{send:n(r=>this.emitCommand(r),"send"),notify:n(r=>this.notify(r),"notify"),onDialogResponse:i.onDialogResponse,onRequest:i.onRequest,onMountPicker:i.onMountPicker,onUnmountPicker:i.onUnmountPicker,state:n(()=>this.state,"state")}),this.wire()}cycleLadder(e){this.emitCommand({type:"cycle_ladder",direction:e})}sendInterrupting(e){return this.emitDrive({type:"prompt",text:e,interrupt:!0})}abortTurn(){return this.state?.isStreaming!==!0?!1:this.emitCommand({type:"abort"})}attachDialog(e){this.overlays.attachDialog(e)}dismissDialog(e){this.overlays.dismissDialog(e)}setState(e){this.state=e}openAuthPicker(e){return this.overlays.openAuthPicker(e)}send=n(e=>{this.emitCommand(e)},"send");refuseStarting(e){return this.hooks.isStarting?.()!==!0||e!==void 0&&(e.type==="prompt"||e.type==="follow_up")?!1:(this.notify("The node is starting \u2014 try again in a moment"),!0)}emitCommand(e){if(this.refuseStarting(e))return!1;const t=b(e),o=t===void 0?void 0:this.capabilities.refusal(t);return o===void 0?(this.hooks.onCommand(e),!0):(this.notify(o),!1)}openBrokerPicker(e){if(this.refuseStarting())return;const t=this.capabilities.refusal("engine-drive");if(t!==void 0){this.notify(t);return}e()}wire(){this.editor.onSubmit=t=>this.handleSubmit(t),this.editor.onEscape=()=>{if(this.state?.isStreaming){this.emitCommand({type:"abort"});return}if(this.editor.getText().trim())return;const t=Date.now();t-this.lastEscapeAt<q?(this.lastEscapeAt=0,this.openBrokerPicker(()=>{this.overlays.openTreePicker()})):this.lastEscapeAt=t},this.editor.onPasteImage=()=>{this.handlePaste()};const e=this.editor;e.onPasteImagePath=t=>(this.attachImage(t),!0),this.editor.onAction("app.session.new",()=>this.emitCommand({type:"new_session"})),this.editor.onAction("app.model.cycleForward",()=>this.emitCommand({type:"cycle_model",direction:"forward"})),this.editor.onAction("app.model.cycleBackward",()=>this.emitCommand({type:"cycle_model",direction:"backward"})),this.editor.onAction("app.thinking.cycle",()=>this.emitCommand({type:"cycle_thinking"})),this.editor.onAction("app.message.followUp",()=>this.handleFollowUp()),this.editor.onAction("app.message.dequeue",()=>{this.handleDequeue()}),this.editor.onAction("app.tools.expand",()=>this.hooks.onMoreDetail?.()),this.editor.onAction("app.thinking.toggle",()=>this.hooks.onToggleThinking?.()),this.editor.onAction("app.editor.external",()=>{this.openExternalEditor()}),this.editor.onAction("app.model.select",()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()})),this.editor.onAction("app.session.tree",()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()})),this.editor.onAction("app.session.fork",()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()})),this.editor.onAction("app.session.resume",()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}))}slashContext(){return{send:this.send,notify:n(e=>this.notify(e),"notify"),capabilities:this.capabilities,state:this.state,cwd:process.cwd(),onGraph:this.hooks.onGraph,onInbox:this.hooks.onInbox,onHelp:this.hooks.onHelp,onQuit:this.hooks.onQuit,onCopy:this.hooks.onCopy,onCopyTarget:this.hooks.onCopyTarget,onToggleMouse:this.hooks.onToggleMouse,onColor:this.hooks.onColor,onNodeMetadata:this.hooks.onNodeMetadata,onMoreDetail:this.hooks.onMoreDetail,onLessDetail:this.hooks.onLessDetail,openModelPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openModelPicker()}),"openModelPicker"),openSessionPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSessionPicker()}),"openSessionPicker"),openForkPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openForkPicker()}),"openForkPicker"),openTreePicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openTreePicker()}),"openTreePicker"),openSettingsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openSettingsPicker()}),"openSettingsPicker"),openScopedModelsPicker:n(()=>this.openBrokerPicker(()=>{this.overlays.openScopedModelsPicker()}),"openScopedModelsPicker"),openMcpPicker:n(e=>this.overlays.openMcpPicker(e),"openMcpPicker"),openLoginPicker:this.hooks.openLoginPicker,openLogoutPicker:this.hooks.openLogoutPicker}}recordCommandUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.slice(1).split(/\s/,1)[0];o&&t.record(`command:${o}`)}recordCompletionUse(e){const t=this.hooks.frecency;if(!t)return;const o=e.trim();if(d(o)){this.recordCommandUse(o);return}const i=this.hooks.knownRefNames?.();if(!i||i.size===0)return;const s=new Set;for(const r of w(e))i.has(r.candidate)&&!s.has(r.candidate)&&(s.add(r.candidate),t.record(`ref:${r.candidate}`))}handleSubmit(e){const t=e.trim();if(!t||d(t)&&this.refuseStarting())return;if(d(t)&&C(t,this.slashContext())){this.recordCommandUse(t),this.editor.setText("");return}const o=this.hooks.isDormant?.()===!0;if(o&&(t.startsWith("/")||t.startsWith("!"))){this.notify("This node is parked \u2014 submit a message to wake it; broker commands need a live engine");return}const i=x(e,{isDormant:o,canWakeDormant:o&&this.capabilities.permits("wake-dormant")&&this.hooks.onDormantSubmit!==void 0,isStreaming:this.state?.isStreaming===!0});if(i.kind==="empty")return;if(i.kind==="dormant"){const a=this.hooks.onDormantSubmit;if(a===void 0)return;const h=this.expandImagePlaceholders(i.text);a(h),this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),this.hooks.onMessageSent?.(h),this.hooks.onPromptSent?.();return}if(i.kind==="bash"){if(!this.emitDrive({type:"bash",command:i.command,excludeFromContext:i.excludeFromContext}))return;this.editor.addToHistory(i.trimmed),this.editor.setText("");return}const s=i.kind==="slash"?this.state?.isStreaming===!0?"steer":"prompt":i.kind;if(s!=="steer"&&s!=="prompt")return;const r=this.expandImagePlaceholders(i.kind==="slash"?e:i.text);this.emitDrive(s==="steer"?{type:"steer",text:r}:{type:"prompt",text:r})&&(this.recordCompletionUse(e),this.editor.addToHistory(i.trimmed),this.editor.setText(""),this.clearPastedImages(),s==="prompt"&&this.hooks.onMessageSent?.(r),this.hooks.onPromptSent?.())}handleFollowUp(){const e=this.editor.getText(),t=e.trim();t&&this.emitDrive({type:"follow_up",text:this.expandImagePlaceholders(e)})&&(this.editor.addToHistory(t),this.editor.setText(""),this.clearPastedImages())}async handleDequeue(){if(this.refuseStarting())return;const e=this.capabilities.refusal("dequeue");if(e!==void 0){this.notify(e);return}const t=this.hooks.onRequest;if(t===void 0){this.notify("Restoring queued messages isn't available in this viewer");return}let o;try{o=await t({type:"dequeue"})}catch(s){this.notify(`Could not restore queued messages: ${s instanceof Error?s.message:String(s)}`);return}if(o.kind!=="dequeue"){this.notify("Unexpected reply restoring queued messages");return}const i=[...o.steering,...o.followUp];if(i.length===0){this.notify("No queued messages to restore");return}this.editor.setText([i.join(`
2
2
 
3
3
  `),this.editor.getText()].filter(s=>s.trim()).join(`
4
4
 
5
- `)),this.tui.requestRender(),this.notify(`Restored ${i.length} queued message${i.length>1?"s":""} to editor`)}emitDrive(e){try{const t=Buffer.byteLength(x(e));if(t>R)return this.notify(`Message too large to send (${Math.round(t/(1024*1024))} MiB) \u2014 shorten the text or remove an attached image`),!1}catch{return this.notify("Message could not be encoded"),!1}return this.emitCommand(e)}async handlePaste(){try{const e=await T();if(!e){this.notify("No image in the clipboard");return}if(!e.image){this.notify(e.note??"Image not pasted");return}this.attachImage(I(e.image),e.note)}catch{this.notify("Could not read the clipboard image")}}attachImage(e,t){const o=++this.pasteSeq;this.pastedImages.set(o,e);const i=this.editor.getText();this.editor.insertTextAtCursor(`${i&&!/\s$/.test(i)?" ":""}[Image #${o}] `),this.notify(t?`Image #${o} attached (${t})`:`Image #${o} attached`),this.tui.requestRender()}expandImagePlaceholders(e){return e.replace(/\[Image #(\d+)\]/g,(t,o)=>this.pastedImages.get(Number(o))??t)}clearPastedImages(){this.pastedImages.clear(),this.pasteSeq=0}async openExternalEditor(){const e=A();if(e===null){this.notify(M);return}const t=e.command,o=this.editor,i=P(y(),`crtr-attach-editor-${Date.now()}.pi.md`);try{g(i,o.getExpandedText?.()??this.editor.getText(),"utf-8"),this.tui.stop();const[s,...r]=t.split(" ");process.stdout.write(`Launching external editor: ${t}
5
+ `)),this.tui.requestRender(),this.notify(`Restored ${i.length} queued message${i.length>1?"s":""} to editor`)}emitDrive(e){try{const t=Buffer.byteLength(S(e));if(t>B)return this.notify(`Message too large to send (${Math.round(t/(1024*1024))} MiB) \u2014 shorten the text or remove an attached image`),!1}catch{return this.notify("Message could not be encoded"),!1}return this.emitCommand(e)}async handlePaste(){try{const e=await T();if(!e){this.notify("No image in the clipboard");return}if(!e.image){this.notify(e.note??"Image not pasted");return}this.attachImage(I(e.image),e.note)}catch{this.notify("Could not read the clipboard image")}}attachImage(e,t){const o=++this.pasteSeq;this.pastedImages.set(o,e);const i=this.editor.getText();this.editor.insertTextAtCursor(`${i&&!/\s$/.test(i)?" ":""}[Image #${o}] `),this.notify(t?`Image #${o} attached (${t})`:`Image #${o} attached`),this.tui.requestRender()}expandImagePlaceholders(e){return e.replace(/\[Image #(\d+)\]/g,(t,o)=>this.pastedImages.get(Number(o))??t)}clearPastedImages(){this.pastedImages.clear(),this.pasteSeq=0}async openExternalEditor(){const e=A();if(e===null){this.notify(M);return}const t=e.command,o=this.editor,i=P(y(),`crtr-attach-editor-${Date.now()}.pi.md`);try{g(i,o.getExpandedText?.()??this.editor.getText(),"utf-8"),this.tui.stop();const[s,...r]=t.split(" ");process.stdout.write(`Launching external editor: ${t}
6
6
  The viewer resumes when it exits.
7
- `),E(e);const a=await new Promise(d=>{const c=u(s,[...r,i],{stdio:"inherit",shell:process.platform==="win32"});c.on("error",()=>d(null)),c.on("close",l=>d(l))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${t} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(f(i,"utf-8").replace(/\n$/,""))}catch(s){this.notify(`External editor failed: ${s instanceof Error?s.message:String(s)}`)}finally{try{k(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}}export{z as InputController};
7
+ `),E(e);const a=await new Promise(h=>{const m=u(s,[...r,i],{stdio:"inherit",shell:process.platform==="win32"});m.on("error",()=>h(null)),m.on("close",p=>h(p))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${t} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(f(i,"utf-8").replace(/\n$/,""))}catch(s){this.notify(`External editor failed: ${s instanceof Error?s.message:String(s)}`)}finally{try{k(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}}export{z as InputController};
@@ -34,7 +34,6 @@ export declare class InputOverlayOwner {
34
34
  openSettingsPicker(): Promise<void>;
35
35
  openScopedModelsPicker(): Promise<void>;
36
36
  openMcpPicker(serverName?: string): void;
37
- openFileReviewPicker(candidates: string[], cwd: string, onChoose: (file: string) => void): void;
38
37
  openAuthPicker(prepare: () => Promise<(controls: PickerControls) => Picker>): Promise<void>;
39
38
  private openPicker;
40
39
  private showPicker;
@@ -1 +1 @@
1
- var f=Object.defineProperty;var h=(u,e)=>f(u,"name",{value:e,configurable:!0});import{isBlockingDialog as a,renderDialog as g}from"../overlays/dialogs.js";import{buildForkPicker as P,buildModelPicker as y,buildScopedModelsPicker as m,buildSessionPicker as S,buildSettingsPicker as w,buildTreePicker as _}from"../overlays/pickers.js";import{buildMcpPicker as b,readMcpServers as M,startMcpServerAction as R,MCP_EMPTY_STATE_HINT as q}from"../overlays/mcp.js";import{buildFileReviewPicker as v}from"../overlays/file-review.js";const T={anchor:"center",width:"80%",maxHeight:"85%"};class O{static{h(this,"InputOverlayOwner")}tui;editor;keybindings;hooks;dialog;dialogId;picker;openSeq=0;constructor(e,i,t,s){this.tui=e,this.editor=i,this.keybindings=t,this.hooks=s}attachDialog(e){if(e.method==="notify"){const i=e.notifyType==="error"?"Error: ":e.notifyType==="warning"?"Warning: ":"";this.hooks.notify(`${i}${e.message}`),this.tui.requestRender();return}a(e)&&(this.dialog?.dismiss(),this.dialogId=e.id,this.dialog=g(this.tui,e,i=>{this.dialog=void 0,this.dialogId=void 0,this.hooks.onDialogResponse(i)},this.keybindings),this.tui.requestRender())}dismissDialog(e){this.dialogId===e&&(this.dialog?.dismiss(),this.dialog=void 0,this.dialogId=void 0,this.tui.requestRender())}openModelPicker(){return this.openPicker({type:"list_models"},"list_models","model",(e,i)=>y(this.tui,e,this.hooks.send,i))}openSessionPicker(){const e=this.hooks.onRequest;return e===void 0?(this.hooks.notify("The session picker isn't available in this viewer"),Promise.resolve()):(this.openSeq++,this.showPicker(i=>S(this.tui,this.hooks.state()?.sessionFile,e,this.keybindings,this.hooks.send,i.close)),Promise.resolve())}openTreePicker(){return this.openPicker({type:"get_tree"},"get_tree","tree",(e,i)=>_(this.tui,e,this.hooks.send,i))}openForkPicker(){return this.openPicker({type:"get_tree"},"get_tree","fork",(e,i)=>P(e,this.hooks.send,i))}openSettingsPicker(){return this.openPicker({type:"get_settings"},"get_settings","settings",(e,i)=>w(e,this.hooks.send,i))}openScopedModelsPicker(){return this.openPicker({type:"list_scoped_models"},"list_scoped_models","scoped-models",(e,i)=>m(e,i,this.hooks.notify))}openMcpPicker(e){const i=M();if(i.length===0){this.hooks.notify(q);return}if(e!==void 0){const t=i.find(s=>s.name===e);if(t===void 0){this.hooks.notify(`No MCP server named ${JSON.stringify(e)} \u2014 usage: /mcp [server]`);return}R(t,this.hooks.send,this.hooks.notify);return}this.showPicker(t=>b(i,this.hooks.send,t.close,this.hooks.notify))}openFileReviewPicker(e,i,t){this.showPicker(s=>v(e,i,n=>{s.close(),t(n)},s.close,this.hooks.notify))}async openAuthPicker(e){const i=++this.openSeq;let t;try{t=await e()}catch(s){this.hooks.notify(`Could not open the auth picker: ${s instanceof Error?s.message:String(s)}`);return}i===this.openSeq&&this.showPicker(t)}async openPicker(e,i,t,s){const n=this.hooks.onRequest;if(n===void 0){this.hooks.notify(`The ${t} picker isn't available in this viewer`);return}const c=++this.openSeq;let d;try{d=await n(e)}catch(r){this.hooks.notify(`Could not open the ${t} picker: ${r instanceof Error?r.message:String(r)}`);return}if(c===this.openSeq){if(d.kind!==i){this.hooks.notify(`Unexpected reply building the ${t} picker`);return}this.showPicker(r=>s(d,r.close))}}showPicker(e){this.picker?.dismiss();const i=this.hooks.onMountPicker!==void 0&&this.hooks.onUnmountPicker!==void 0;let t,s,n=!1;const c=h(()=>{const o=s?.component;try{o?.dispose?.()}catch{}},"disposeCurrent"),d=h(o=>{i?this.hooks.onMountPicker(o.component):t=this.tui.showOverlay(o.component,T),this.tui.setFocus(o.focus)},"mount"),r=h(()=>{i?this.hooks.onUnmountPicker?.():t?.hide()},"unmount"),k=h((o,p)=>{n||(c(),r(),s={component:o,focus:p},d(s),this.tui.requestRender())},"replace"),l=h(()=>{n||(n=!0,c(),r(),this.picker=void 0,this.tui.setFocus(this.editor),this.tui.requestRender())},"close");try{s=e({close:l,replace:k})}catch(o){this.hooks.notify(`Could not open picker: ${o instanceof Error?o.message:String(o)}`);return}d(s),this.picker={dismiss:h(()=>{n||(n=!0,c(),r())},"dismiss")},this.tui.requestRender()}}export{O as InputOverlayOwner};
1
+ var a=Object.defineProperty;var h=(u,e)=>a(u,"name",{value:e,configurable:!0});import{isBlockingDialog as f,renderDialog as g}from"../overlays/dialogs.js";import{buildForkPicker as y,buildModelPicker as P,buildScopedModelsPicker as m,buildSessionPicker as S,buildSettingsPicker as _,buildTreePicker as w}from"../overlays/pickers.js";import{buildMcpPicker as b,readMcpServers as M,startMcpServerAction as q,MCP_EMPTY_STATE_HINT as R}from"../overlays/mcp.js";const T={anchor:"center",width:"80%",maxHeight:"85%"};class C{static{h(this,"InputOverlayOwner")}tui;editor;keybindings;hooks;dialog;dialogId;picker;openSeq=0;constructor(e,i,t,s){this.tui=e,this.editor=i,this.keybindings=t,this.hooks=s}attachDialog(e){if(e.method==="notify"){const i=e.notifyType==="error"?"Error: ":e.notifyType==="warning"?"Warning: ":"";this.hooks.notify(`${i}${e.message}`),this.tui.requestRender();return}f(e)&&(this.dialog?.dismiss(),this.dialogId=e.id,this.dialog=g(this.tui,e,i=>{this.dialog=void 0,this.dialogId=void 0,this.hooks.onDialogResponse(i)},this.keybindings),this.tui.requestRender())}dismissDialog(e){this.dialogId===e&&(this.dialog?.dismiss(),this.dialog=void 0,this.dialogId=void 0,this.tui.requestRender())}openModelPicker(){return this.openPicker({type:"list_models"},"list_models","model",(e,i)=>P(this.tui,e,this.hooks.send,i))}openSessionPicker(){const e=this.hooks.onRequest;return e===void 0?(this.hooks.notify("The session picker isn't available in this viewer"),Promise.resolve()):(this.openSeq++,this.showPicker(i=>S(this.tui,this.hooks.state()?.sessionFile,e,this.keybindings,this.hooks.send,i.close)),Promise.resolve())}openTreePicker(){return this.openPicker({type:"get_tree"},"get_tree","tree",(e,i)=>w(this.tui,e,this.hooks.send,i))}openForkPicker(){return this.openPicker({type:"get_tree"},"get_tree","fork",(e,i)=>y(e,this.hooks.send,i))}openSettingsPicker(){return this.openPicker({type:"get_settings"},"get_settings","settings",(e,i)=>_(e,this.hooks.send,i))}openScopedModelsPicker(){return this.openPicker({type:"list_scoped_models"},"list_scoped_models","scoped-models",(e,i)=>m(e,i,this.hooks.notify))}openMcpPicker(e){const i=M();if(i.length===0){this.hooks.notify(R);return}if(e!==void 0){const t=i.find(s=>s.name===e);if(t===void 0){this.hooks.notify(`No MCP server named ${JSON.stringify(e)} \u2014 usage: /mcp [server]`);return}q(t,this.hooks.send,this.hooks.notify);return}this.showPicker(t=>b(i,this.hooks.send,t.close,this.hooks.notify))}async openAuthPicker(e){const i=++this.openSeq;let t;try{t=await e()}catch(s){this.hooks.notify(`Could not open the auth picker: ${s instanceof Error?s.message:String(s)}`);return}i===this.openSeq&&this.showPicker(t)}async openPicker(e,i,t,s){const r=this.hooks.onRequest;if(r===void 0){this.hooks.notify(`The ${t} picker isn't available in this viewer`);return}const c=++this.openSeq;let d;try{d=await r(e)}catch(n){this.hooks.notify(`Could not open the ${t} picker: ${n instanceof Error?n.message:String(n)}`);return}if(c===this.openSeq){if(d.kind!==i){this.hooks.notify(`Unexpected reply building the ${t} picker`);return}this.showPicker(n=>s(d,n.close))}}showPicker(e){this.picker?.dismiss();const i=this.hooks.onMountPicker!==void 0&&this.hooks.onUnmountPicker!==void 0;let t,s,r=!1;const c=h(()=>{const o=s?.component;try{o?.dispose?.()}catch{}},"disposeCurrent"),d=h(o=>{i?this.hooks.onMountPicker(o.component):t=this.tui.showOverlay(o.component,T),this.tui.setFocus(o.focus)},"mount"),n=h(()=>{i?this.hooks.onUnmountPicker?.():t?.hide()},"unmount"),k=h((o,p)=>{r||(c(),n(),s={component:o,focus:p},d(s),this.tui.requestRender())},"replace"),l=h(()=>{r||(r=!0,c(),n(),this.picker=void 0,this.tui.setFocus(this.editor),this.tui.requestRender())},"close");try{s=e({close:l,replace:k})}catch(o){this.hooks.notify(`Could not open picker: ${o instanceof Error?o.message:String(o)}`);return}d(s),this.picker={dismiss:h(()=>{r||(r=!0,c(),n())},"dismiss")},this.tui.requestRender()}}export{C as InputOverlayOwner};
@@ -5,7 +5,7 @@ import type { ClientRole } from '../../../core/runtime/broker-protocol.js';
5
5
  import type { AttachPalette } from '../config.js';
6
6
  export declare class GraphOverlay implements Component {
7
7
  private readonly tui;
8
- private readonly self;
8
+ private readonly selfId;
9
9
  private readonly getAsks;
10
10
  private readonly palette;
11
11
  private bindings;
@@ -32,7 +32,8 @@ export declare class GraphOverlay implements Component {
32
32
  * default and makes Enter/r/m/x no-op instead of shelling local lifecycle
33
33
  * commands against a remote graph row. See the file header. */
34
34
  private readonly remote;
35
- constructor(tui: TUI, self: string, getAsks: () => Record<string, number>, palette: AttachPalette, bindings: BindingResolution<BindingId>, source: CanvasSource, role?: ClientRole, onRefreshFailure?: (cause?: unknown) => void, onNotice?: (message: string) => void);
35
+ constructor(tui: TUI, selfId: () => string, getAsks: () => Record<string, number>, palette: AttachPalette, bindings: BindingResolution<BindingId>, source: CanvasSource, role?: ClientRole, onRefreshFailure?: (cause?: unknown) => void, onNotice?: (message: string) => void);
36
+ private get self();
36
37
  setBindings(bindings: BindingResolution<BindingId>): void;
37
38
  private matches;
38
39
  private hint;
@@ -1 +1 @@
1
- var q=Object.defineProperty;var m=(u,t)=>q(u,"name",{value:t,configurable:!0});import{execFile as P}from"node:child_process";import{matchesKey as H,truncateToWidth as T}from"@earendil-works/pi-tui";import{formatBinding as L,matchesPiTuiInput as B}from"../../../core/keybindings/index.js";import{fullName as G}from"../../../core/canvas/labels.js";import{faultSummary as F,resolveNodeVisual as C}from"../../../core/canvas/status-glyph.js";import{RemoteCanvasSource as W}from"../../../core/canvas/remote-canvas-source.js";import{cliClient as M}from"../../../commands/api-client.js";import{focusNode as K}from"../../../core/runtime/focus-viewer.js";import{daemonErrorMessage as j}from"../../inbox/resolve.js";import{statusRank as E}from"../../../core/canvas/node-order.js";import{navLabel as D,nodeGlyph as V,tokensCell as Y,cycleBadge as z,askBadge as U,activityCell as X,shortId as N,visibleWidth as k,fillBar as A,fillWidth as O,truncate as J,isAttached as Q,VIEWPORT_FALLBACK_ROWS as Z,ESC as ee,DIM as R,RESET as g,BOLD as S,YELLOW as te,REVERSE as se,BG_ATTACHED as ie,GREEN as ne}from"../../../core/canvas/nav-render.js";const re=.72,oe={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},ce=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],ae=[["crtr.graph.dismiss","dismiss"]],he=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],de=[...["active","idle","done","dead","canceled"].map(u=>[C(u,{}),u]),[C("active",{streaming:!0}),"live"],[C("active",{frozen:!0}),"frozen"],[C("active",{hanging:{kind:"wedged"}}),"fault"]].map(([u,t])=>`${ee}${u.color}m${u.glyph}${g} ${R}${t}${g}`).join(" ");function le(u){return{node_id:u.node_id,name:u.name,kind:u.kind,description:u.description??void 0,cycles:u.cycles??void 0,status:u.status,frozen_at:u.frozen_at,pi_pid:u.pi_pid,telemetry_context_tokens:u.telemetry_context_tokens,telemetry_last_activity:u.telemetry_last_activity,fault:u.fault??null,streaming:u.streaming}}m(le,"graphRow");class Ie{static{m(this,"GraphOverlay")}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;constructor(t,s,i,e,n,o,f="controller",p=()=>{},r=()=>{}){this.tui=t,this.self=s,this.getAsks=i,this.palette=e,this.bindings=n,this.source=o,this.role=f,this.onRefreshFailure=p,this.onNotice=r,this.remote=o instanceof W}setBindings(t){this.bindings=t,this.handle!==void 0&&this.tui.requestRender()}matches(t,s){return B(this.bindings,t,s,(i,e)=>H(i,e))}hint(t){return t.flatMap(([s,i])=>this.bindings.gestures(s).length===0?[]:[`${L(this.bindings,s)} ${i}`])}fitHints(t,s){const e=[];let n=0;for(const o of this.hint(t)){const f=(e.length===0?0:3)+k(o);if(n+f>s)break;e.push(o),n+=f}return e.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,oe),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;const t=++this.snapshotSeq;this.buildSnapshot().then(s=>{t===this.snapshotSeq&&(this.snapshot=s,this.tui.requestRender())}).catch(s=>{this.onRefreshFailure(s),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){const e=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(e.map(n=>[n.node_id,n])),subscriptions:m(async n=>(await this.source.subscriptionsOf(n)).map(o=>o.node_id),"subscriptions"),subscribers:m(async n=>(await this.source.subscribersOf(n)).map(o=>o.node_id),"subscribers"),focused:new Set}}const t=await M().canvasGraph(),s=new Map,i=new Map;for(const e of t.edges){const n=s.get(e.from_id);n===void 0?s.set(e.from_id,[e.to_id]):n.push(e.to_id);const o=i.get(e.to_id);o===void 0?i.set(e.to_id,[e.from_id]):o.push(e.from_id)}return{nodes:new Map(t.nodes.map(e=>[e.node_id,le(e)])),subscriptions:m(e=>Promise.resolve(s.get(e)??[]),"subscriptions"),subscribers:m(e=>Promise.resolve(i.get(e)??[]),"subscribers"),focused:new Set(t.focused_node_ids)}}async buildSnapshot(){const t=await this.fetchInput(),{nodes:s,focused:i}=t,e=new Map,n=new Map,o=new Map,f=new Map,p=m(async c=>{const l=e.get(c);if(l!==void 0)return l;let a;try{a=await t.subscriptions(c)}catch{a=[]}const $=a.filter(b=>s.get(b)?.kind!=="human");return e.set(c,$),$},"children"),r=m(async c=>{if(o.has(c))return o.get(c);let l;try{l=(await t.subscribers(c))[0]}catch{l=void 0}return o.set(c,l),l},"manager"),h=m(async()=>{let c=this.self;const l=new Set([c]);for(;;){const a=await r(c);if(a===void 0||l.has(a))break;l.add(a),c=a}return c},"climbRoot"),d=m(async c=>{const l=n.get(c);if(l!==void 0)return l;const a=[...await p(c)];return a.sort(($,b)=>E(s.get($)?.status)-E(s.get(b)?.status)),n.set(c,a),a},"sortedChildren"),w=new Set,v=new Set,I=m(async c=>{const l=s.get(c)?.status==="active";if(v.has(c))return{active:l?1:0,reveal:l||c===this.self};v.add(c);let a=0,$=!1;for(const b of await p(c)){const x=await I(b);a+=x.active,x.reveal&&($=!0)}return f.set(c,a),$&&w.add(c),{active:a+(l?1:0),reveal:$||l||c===this.self}},"visitActivity"),y=await h();await I(y),await Promise.all([...e.keys()].map(c=>d(c)));const _={root:y,rows:[],autoExpanded:w,activeBelow:f,nodes:s,childIds:e,sortedChildIds:n,managerOf:o,focused:i};return _.rows=this.projectRows(_),_}projectRows(t){const s=[],i=new Set,e=[{id:t.root,prefix:"",isRoot:!0,isLast:!0}];for(;e.length>0;){const{id:n,prefix:o,isRoot:f,isLast:p}=e.pop(),r=f?"":p?"\u2514\u2500 ":"\u251C\u2500 ";if(i.has(n)){s.push({id:n,hasKids:!1,isSelf:n===this.self,branch:o+r,cycle:!0,collapsed:!1});continue}i.add(n);const h=t.sortedChildIds.get(n)??[],d=this.folds.userExpanded.has(n)?!1:this.folds.userCollapsed.has(n)?!0:!t.autoExpanded.has(n);if(s.push({id:n,hasKids:h.length>0,isSelf:n===this.self,branch:o+r,cycle:!1,collapsed:d}),d)continue;const w=f?"":o+(p?" ":"\u2502 ");for(let v=h.length-1;v>=0;v--)e.push({id:h[v],prefix:w,isRoot:!1,isLast:v===h.length-1})}return s}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(t,s,i,e){const n=m((b,x)=>i?A(b,O(),se):x?A(b,O(),ie):J(b),"wrap");if(s.cycle){const b=`${s.branch} ${R}\u21BA ${N(s.id)}${g}`;return n(b,!1)}const o=t.nodes.get(s.id)??null,f=V(o),p=D(o,s.id),r=s.isSelf?`${S}${p}${g}`:p,h=`${R}${o?.kind??""}${g}`,d=`${R}${Y(o,this.remote)}${g}`,w=s.hasKids&&s.collapsed,v=!i&&w?`${R}\u25B8${g} `:" ",I=z(o),y=t.childIds.get(s.id)?.length??0,_=o!==null&&y>0?` ${R}\u2933${y}${g}`:"",c=o!==null&&o.status!=="active"&&(t.activeBelow.get(o.node_id)??0)>0?` ${ne}\u21E3${t.activeBelow.get(o.node_id)??0}${g}`:"",l=o?.fault??null,a=l!==null?` \xB7 ${F(l)}`:"",$=`${s.branch}${v}${f} ${r} ${h} ${d}${I}${_}${c}${U(s.id,e)}${X(o,this.remote)}${a}`;return n($,Q(s.id,o,t.focused,this.remote))}render(t){const s=this.getAsks(),i=this.snapshot?.rows??[];let e=i.findIndex(a=>a.id===this.cursorId);e<0&&(e=i.findIndex(a=>a.id===this.self),e<0&&(e=0)),this.cursorId=i[e]?.id??this.self;const n=process.stdout.rows??Z,o=Math.max(3,Math.min(Math.floor(n*re),n-2)),f=Math.min(o-2,1+Math.max(1,i.length)),p=f-1,r=p>=3;let h=p;for(let a=0;p>0&&a<4;a++){e<this.scrollTop&&(this.scrollTop=e),e>=this.scrollTop+h&&(this.scrollTop=e-h+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-h)));const $=p-(r&&this.scrollTop>0?1:0)-(r&&this.scrollTop+h<i.length?1:0);if($===h)break;h=Math.max(1,$)}const d=Math.min(i.length,this.scrollTop+h),w=[];r&&this.scrollTop>0&&w.push(`${R} \u2191 ${this.scrollTop} more${g}`);for(let a=this.scrollTop;a<d;a++){const $=this.snapshot;w.push($!==void 0?this.renderSnapshotRow($,i[a],a===e,s):"")}for(r&&d<i.length&&w.push(`${R} \u2193 ${i.length-d} more${g}`),w.unshift(de);w.length<f;)w.push("");const v=i.length>0?`${S}\u2317 canvas graph${g} ${R}(${e+1}/${i.length})${g}`:`${S}\u2317 canvas graph${g} ${R}(loading)${g}`,I=this.pendingConfirm!==void 0?`${te}${this.pendingConfirm.label} ${S}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${g}`:`${R}${this.fitHints([...this.remote||this.role!=="controller"?ae:ce,...he],Math.max(1,t-5))}${g}`,y=this.palette.border,_=Math.max(1,t-4),c=w.map(a=>`${y("\u2502")} ${T(a,_,"",!0)} ${y("\u2502")}`),l=this.palette.surface;return[this.borderRow("\u256D","\u256E",v,t),...c,this.borderRow("\u2570","\u256F",I,t)].map(l)}borderRow(t,s,i,e){const n=this.palette.border,o=Math.max(1,e-5),f=T(i,o,"\u2026"),p=Math.max(0,e-5-k(f));return`${n(`${t}\u2500`)} ${f} ${n("\u2500".repeat(p)+s)}`}handleInput(t){try{this.dispatch(t)}catch{}}dispatch(t){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",t)){const r=this.pendingConfirm.action;this.pendingConfirm=void 0,r()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",t)){this.close();return}const s=this.snapshot,i=s?.rows??[];let e=i.findIndex(r=>r.id===this.cursorId);e<0&&(e=Math.max(0,i.findIndex(r=>r.id===this.self)));const n=i[e],o=m(r=>r!==void 0&&!r.cycle,"isSelectable"),f=m((r,h)=>{for(let d=r+h;d>=0&&d<i.length;d+=h)if(o(i[d]))return d;return r},"step"),p=m(r=>{const h=r===1?0:i.length-1;for(let d=h;d>=0&&d<i.length;d+=r)if(o(i[d]))return d;return e},"edge");if(this.matches("crtr.graph.down",t)){e=f(e,1),this.cursorId=i[e]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",t)){e=f(e,-1),this.cursorId=i[e]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",t)){this.cursorId=i[p(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",t)){this.cursorId=i[p(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",t)){if(n!==void 0&&n.hasKids&&!n.collapsed)this.userCollapsed.add(n.id),this.userExpanded.delete(n.id),this.repaintFolds();else{const r=s?.managerOf.get(this.cursorId??this.self);r!==void 0&&i.some(h=>h.id===r)&&(this.cursorId=r),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",t)){if(n!==void 0&&n.collapsed&&n.hasKids)this.userExpanded.add(n.id),this.userCollapsed.delete(n.id),this.repaintFolds();else if(n!==void 0&&n.hasKids){const r=s?.sortedChildIds.get(n.id)?.[0];r!==void 0&&(this.cursorId=r),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}const r=this.cursorId,h=r===void 0?null:s?.nodes.get(r)??null;r!==void 0&&h!==null&&h.status!=="active"&&h.status!=="idle"&&(this.reviveTarget(r),this.close());return}if(this.matches("crtr.graph.focus-manager",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}const r=s?.managerOf.get(this.self);r!==void 0&&(this.focusTarget(r),this.close());return}if(this.matches("crtr.graph.close-subtree",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}const r=this.cursorId??this.self,h=s?.nodes.get(r)??null,d=h!==null?G(h):N(r);this.pendingConfirm={label:`kill ${d}?`,action:m(()=>this.shellCrtr(["node","lifecycle","close","--node",r]),"action")},this.tui.requestRender();return}}focusTarget(t){const s=process.env.TMUX_PANE;if(s===void 0||s===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{const i=M(),e=await i.getNode(t);(await K(i,e,{pane:s})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(i=>this.onNotice(j(i)))}reviveTarget(t){this.shellCrtr(["node","lifecycle","revive",t],()=>this.focusTarget(t))}shellCrtr(t,s){try{P("crtr",t,e=>{e==null&&s?.()}).stdin?.end()}catch{}}}export{Ie as GraphOverlay};
1
+ var q=Object.defineProperty;var m=(u,t)=>q(u,"name",{value:t,configurable:!0});import{execFile as P}from"node:child_process";import{matchesKey as H,truncateToWidth as T}from"@earendil-works/pi-tui";import{formatBinding as L,matchesPiTuiInput as B}from"../../../core/keybindings/index.js";import{fullName as G}from"../../../core/canvas/labels.js";import{faultSummary as F,resolveNodeVisual as C}from"../../../core/canvas/status-glyph.js";import{RemoteCanvasSource as W}from"../../../core/canvas/remote-canvas-source.js";import{cliClient as M}from"../../../commands/api-client.js";import{focusNode as K}from"../../../core/runtime/focus-viewer.js";import{daemonErrorMessage as j}from"../../inbox/resolve.js";import{statusRank as E}from"../../../core/canvas/node-order.js";import{navLabel as D,nodeGlyph as V,tokensCell as Y,cycleBadge as z,askBadge as U,activityCell as X,shortId as N,visibleWidth as k,fillBar as A,fillWidth as O,truncate as J,isAttached as Q,VIEWPORT_FALLBACK_ROWS as Z,ESC as ee,DIM as R,RESET as g,BOLD as S,YELLOW as te,REVERSE as se,BG_ATTACHED as ie,GREEN as ne}from"../../../core/canvas/nav-render.js";const re=.72,oe={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},ce=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],ae=[["crtr.graph.dismiss","dismiss"]],he=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],de=[...["active","idle","done","dead","canceled"].map(u=>[C(u,{}),u]),[C("active",{streaming:!0}),"live"],[C("active",{frozen:!0}),"frozen"],[C("active",{hanging:{kind:"wedged"}}),"fault"]].map(([u,t])=>`${ee}${u.color}m${u.glyph}${g} ${R}${t}${g}`).join(" ");function le(u){return{node_id:u.node_id,name:u.name,kind:u.kind,description:u.description??void 0,cycles:u.cycles??void 0,status:u.status,frozen_at:u.frozen_at,pi_pid:u.pi_pid,telemetry_context_tokens:u.telemetry_context_tokens,telemetry_last_activity:u.telemetry_last_activity,fault:u.fault??null,streaming:u.streaming}}m(le,"graphRow");class _e{static{m(this,"GraphOverlay")}tui;selfId;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;constructor(t,s,i,e,n,o,f="controller",p=()=>{},r=()=>{}){this.tui=t,this.selfId=s,this.getAsks=i,this.palette=e,this.bindings=n,this.source=o,this.role=f,this.onRefreshFailure=p,this.onNotice=r,this.remote=o instanceof W}get self(){return this.selfId()}setBindings(t){this.bindings=t,this.handle!==void 0&&this.tui.requestRender()}matches(t,s){return B(this.bindings,t,s,(i,e)=>H(i,e))}hint(t){return t.flatMap(([s,i])=>this.bindings.gestures(s).length===0?[]:[`${L(this.bindings,s)} ${i}`])}fitHints(t,s){const e=[];let n=0;for(const o of this.hint(t)){const f=(e.length===0?0:3)+k(o);if(n+f>s)break;e.push(o),n+=f}return e.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,oe),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;const t=++this.snapshotSeq;this.buildSnapshot().then(s=>{t===this.snapshotSeq&&(this.snapshot=s,this.tui.requestRender())}).catch(s=>{this.onRefreshFailure(s),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){const e=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(e.map(n=>[n.node_id,n])),subscriptions:m(async n=>(await this.source.subscriptionsOf(n)).map(o=>o.node_id),"subscriptions"),subscribers:m(async n=>(await this.source.subscribersOf(n)).map(o=>o.node_id),"subscribers"),focused:new Set}}const t=await M().canvasGraph(),s=new Map,i=new Map;for(const e of t.edges){const n=s.get(e.from_id);n===void 0?s.set(e.from_id,[e.to_id]):n.push(e.to_id);const o=i.get(e.to_id);o===void 0?i.set(e.to_id,[e.from_id]):o.push(e.from_id)}return{nodes:new Map(t.nodes.map(e=>[e.node_id,le(e)])),subscriptions:m(e=>Promise.resolve(s.get(e)??[]),"subscriptions"),subscribers:m(e=>Promise.resolve(i.get(e)??[]),"subscribers"),focused:new Set(t.focused_node_ids)}}async buildSnapshot(){const t=await this.fetchInput(),{nodes:s,focused:i}=t,e=new Map,n=new Map,o=new Map,f=new Map,p=m(async c=>{const l=e.get(c);if(l!==void 0)return l;let a;try{a=await t.subscriptions(c)}catch{a=[]}const $=a.filter(b=>s.get(b)?.kind!=="human");return e.set(c,$),$},"children"),r=m(async c=>{if(o.has(c))return o.get(c);let l;try{l=(await t.subscribers(c))[0]}catch{l=void 0}return o.set(c,l),l},"manager"),h=m(async()=>{let c=this.self;const l=new Set([c]);for(;;){const a=await r(c);if(a===void 0||l.has(a))break;l.add(a),c=a}return c},"climbRoot"),d=m(async c=>{const l=n.get(c);if(l!==void 0)return l;const a=[...await p(c)];return a.sort(($,b)=>E(s.get($)?.status)-E(s.get(b)?.status)),n.set(c,a),a},"sortedChildren"),w=new Set,v=new Set,_=m(async c=>{const l=s.get(c)?.status==="active";if(v.has(c))return{active:l?1:0,reveal:l||c===this.self};v.add(c);let a=0,$=!1;for(const b of await p(c)){const x=await _(b);a+=x.active,x.reveal&&($=!0)}return f.set(c,a),$&&w.add(c),{active:a+(l?1:0),reveal:$||l||c===this.self}},"visitActivity"),I=await h();await _(I),await Promise.all([...e.keys()].map(c=>d(c)));const y={root:I,rows:[],autoExpanded:w,activeBelow:f,nodes:s,childIds:e,sortedChildIds:n,managerOf:o,focused:i};return y.rows=this.projectRows(y),y}projectRows(t){const s=[],i=new Set,e=[{id:t.root,prefix:"",isRoot:!0,isLast:!0}];for(;e.length>0;){const{id:n,prefix:o,isRoot:f,isLast:p}=e.pop(),r=f?"":p?"\u2514\u2500 ":"\u251C\u2500 ";if(i.has(n)){s.push({id:n,hasKids:!1,isSelf:n===this.self,branch:o+r,cycle:!0,collapsed:!1});continue}i.add(n);const h=t.sortedChildIds.get(n)??[],d=this.folds.userExpanded.has(n)?!1:this.folds.userCollapsed.has(n)?!0:!t.autoExpanded.has(n);if(s.push({id:n,hasKids:h.length>0,isSelf:n===this.self,branch:o+r,cycle:!1,collapsed:d}),d)continue;const w=f?"":o+(p?" ":"\u2502 ");for(let v=h.length-1;v>=0;v--)e.push({id:h[v],prefix:w,isRoot:!1,isLast:v===h.length-1})}return s}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(t,s,i,e){const n=m((b,x)=>i?A(b,O(),se):x?A(b,O(),ie):J(b),"wrap");if(s.cycle){const b=`${s.branch} ${R}\u21BA ${N(s.id)}${g}`;return n(b,!1)}const o=t.nodes.get(s.id)??null,f=V(o),p=D(o,s.id),r=s.isSelf?`${S}${p}${g}`:p,h=`${R}${o?.kind??""}${g}`,d=`${R}${Y(o,this.remote)}${g}`,w=s.hasKids&&s.collapsed,v=!i&&w?`${R}\u25B8${g} `:" ",_=z(o),I=t.childIds.get(s.id)?.length??0,y=o!==null&&I>0?` ${R}\u2933${I}${g}`:"",c=o!==null&&o.status!=="active"&&(t.activeBelow.get(o.node_id)??0)>0?` ${ne}\u21E3${t.activeBelow.get(o.node_id)??0}${g}`:"",l=o?.fault??null,a=l!==null?` \xB7 ${F(l)}`:"",$=`${s.branch}${v}${f} ${r} ${h} ${d}${_}${y}${c}${U(s.id,e)}${X(o,this.remote)}${a}`;return n($,Q(s.id,o,t.focused,this.remote))}render(t){const s=this.getAsks(),i=this.snapshot?.rows??[];let e=i.findIndex(a=>a.id===this.cursorId);e<0&&(e=i.findIndex(a=>a.id===this.self),e<0&&(e=0)),this.cursorId=i[e]?.id??this.self;const n=process.stdout.rows??Z,o=Math.max(3,Math.min(Math.floor(n*re),n-2)),f=Math.min(o-2,1+Math.max(1,i.length)),p=f-1,r=p>=3;let h=p;for(let a=0;p>0&&a<4;a++){e<this.scrollTop&&(this.scrollTop=e),e>=this.scrollTop+h&&(this.scrollTop=e-h+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-h)));const $=p-(r&&this.scrollTop>0?1:0)-(r&&this.scrollTop+h<i.length?1:0);if($===h)break;h=Math.max(1,$)}const d=Math.min(i.length,this.scrollTop+h),w=[];r&&this.scrollTop>0&&w.push(`${R} \u2191 ${this.scrollTop} more${g}`);for(let a=this.scrollTop;a<d;a++){const $=this.snapshot;w.push($!==void 0?this.renderSnapshotRow($,i[a],a===e,s):"")}for(r&&d<i.length&&w.push(`${R} \u2193 ${i.length-d} more${g}`),w.unshift(de);w.length<f;)w.push("");const v=i.length>0?`${S}\u2317 canvas graph${g} ${R}(${e+1}/${i.length})${g}`:`${S}\u2317 canvas graph${g} ${R}(loading)${g}`,_=this.pendingConfirm!==void 0?`${te}${this.pendingConfirm.label} ${S}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${g}`:`${R}${this.fitHints([...this.remote||this.role!=="controller"?ae:ce,...he],Math.max(1,t-5))}${g}`,I=this.palette.border,y=Math.max(1,t-4),c=w.map(a=>`${I("\u2502")} ${T(a,y,"",!0)} ${I("\u2502")}`),l=this.palette.surface;return[this.borderRow("\u256D","\u256E",v,t),...c,this.borderRow("\u2570","\u256F",_,t)].map(l)}borderRow(t,s,i,e){const n=this.palette.border,o=Math.max(1,e-5),f=T(i,o,"\u2026"),p=Math.max(0,e-5-k(f));return`${n(`${t}\u2500`)} ${f} ${n("\u2500".repeat(p)+s)}`}handleInput(t){try{this.dispatch(t)}catch{}}dispatch(t){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",t)){const r=this.pendingConfirm.action;this.pendingConfirm=void 0,r()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",t)){this.close();return}const s=this.snapshot,i=s?.rows??[];let e=i.findIndex(r=>r.id===this.cursorId);e<0&&(e=Math.max(0,i.findIndex(r=>r.id===this.self)));const n=i[e],o=m(r=>r!==void 0&&!r.cycle,"isSelectable"),f=m((r,h)=>{for(let d=r+h;d>=0&&d<i.length;d+=h)if(o(i[d]))return d;return r},"step"),p=m(r=>{const h=r===1?0:i.length-1;for(let d=h;d>=0&&d<i.length;d+=r)if(o(i[d]))return d;return e},"edge");if(this.matches("crtr.graph.down",t)){e=f(e,1),this.cursorId=i[e]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",t)){e=f(e,-1),this.cursorId=i[e]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",t)){this.cursorId=i[p(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",t)){this.cursorId=i[p(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",t)){if(n!==void 0&&n.hasKids&&!n.collapsed)this.userCollapsed.add(n.id),this.userExpanded.delete(n.id),this.repaintFolds();else{const r=s?.managerOf.get(this.cursorId??this.self);r!==void 0&&i.some(h=>h.id===r)&&(this.cursorId=r),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",t)){if(n!==void 0&&n.collapsed&&n.hasKids)this.userExpanded.add(n.id),this.userCollapsed.delete(n.id),this.repaintFolds();else if(n!==void 0&&n.hasKids){const r=s?.sortedChildIds.get(n.id)?.[0];r!==void 0&&(this.cursorId=r),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}const r=this.cursorId,h=r===void 0?null:s?.nodes.get(r)??null;r!==void 0&&h!==null&&h.status!=="active"&&h.status!=="idle"&&(this.reviveTarget(r),this.close());return}if(this.matches("crtr.graph.focus-manager",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}const r=s?.managerOf.get(this.self);r!==void 0&&(this.focusTarget(r),this.close());return}if(this.matches("crtr.graph.close-subtree",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}const r=this.cursorId??this.self,h=s?.nodes.get(r)??null,d=h!==null?G(h):N(r);this.pendingConfirm={label:`kill ${d}?`,action:m(()=>this.shellCrtr(["node","lifecycle","close","--node",r]),"action")},this.tui.requestRender();return}}focusTarget(t){const s=process.env.TMUX_PANE;if(s===void 0||s===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{const i=M(),e=await i.getNode(t);(await K(i,e,{pane:s})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(i=>this.onNotice(j(i)))}reviveTarget(t){this.shellCrtr(["node","lifecycle","revive",t],()=>this.focusTarget(t))}shellCrtr(t,s){try{P("crtr",t,e=>{e==null&&s?.()}).stdin?.end()}catch{}}}export{_e as GraphOverlay};
@@ -77,6 +77,8 @@ export declare class ChatView {
77
77
  private readonly pendingSends;
78
78
  /** Optional banner, above history and status in the viewport's flat source. */
79
79
  private readonly bannerContainer;
80
+ /** Add one line to the banner after construction: a new root learns its id only when its create returns. */
81
+ setBannerHint(line: string): void;
80
82
  private readonly transcript;
81
83
  /** Inline page blocks placed in this transcript, by page id — one block per
82
84
  * page, so a `--replace` revision refreshes the block already on screen. */
@@ -1,3 +1,3 @@
1
- var W=Object.defineProperty;var h=(a,t)=>W(a,"name",{value:t,configurable:!0});import{Container as $,Loader as q,Markdown as V,Spacer as c,Text as b}from"@earendil-works/pi-tui";import{AssistantMessageComponent as U,BashExecutionComponent as E,BranchSummaryMessageComponent as N,CompactionSummaryMessageComponent as z,CustomMessageComponent as O,parseSkillBlock as Y,SkillInvocationMessageComponent as K,ToolExecutionComponent as J,UserMessageComponent as R}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as p}from"../config.js";import{ContextMessageComponent as I}from"./context-message.js";import{presentationFor as X}from"./card-presentation.js";import{detectInlinePageResult as Q,PageBlockComponent as Z}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as tt,CrtrOutputMessageComponent as v,createCrtrBashToolDefinition as et}from"./crtr-output.js";import{endedByAbort as A}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as D,parseCard as st}from"../../../shared/generated-context.js";import{assistantVisibleText as d,isGroupBoundaryKind as it,isTrueUserMessage as g}from"../../../shared/tool-groups.js";import{messageKey as P,normalizeTurnReplyRecord as nt,START_TURN_KEY as ot,turnReplyText as rt}from"../../../shared/turn-replies.js";import{transformDiagramFences as at}from"./diagram.js";import{styleAttachAgentMarkdown as ht,styleAttachMarkdownSource as j,styleAttachMessageMarkdown as lt,styleAttachSummaryMarkdown as F}from"./markdown-source.js";import{createCrtrEditToolDefinition as pt}from"./edit-diff.js";import{GroupActivityRecorder as dt}from"./group-activity.js";import{GroupRecapComponent as ct}from"./group-recap.js";import{FoldedToolCallController as ut,bashCallBackgroundHintLines as mt,createCrtrPlainBashToolDefinition as ft,createCrtrReadToolDefinition as gt,createCrtrWriteToolDefinition as yt}from"./tool-calls.js";import{ringCompletionBell as Ct}from"../chrome/completion-bell.js";import{extractFilePaths as Tt}from"../../../core/human/visible-paths.js";import{extractDocRefs as kt}from"./doc-links.js";import{ViewerAssistantMessageComponent as x}from"./assistant-message.js";import{CompositeViewportSource as bt,MeasuredContainer as w}from"./measured-container.js";import{readConfig as _}from"../../../core/config.js";import{DEFAULT_VERBOSITY as xt,VERBOSITY_LEVELS as u}from"../../../types.js";import{applySnapshot as wt,applyToolGroupSummary as St,applyWorkingActivity as Rt,bashEnd as At,bashOutput as Bt,bashStart as Mt,initialConvState as Gt,reduce as Et}from"../../conversation/projection.js";const H=h(a=>`\x1B[2m${a}\x1B[22m`,"defaultDimStyle"),Ot=50;function It(){try{return _("user").verbosity}catch{return xt}}h(It,"readVerbosity");function vt(){try{return _("user").detailed_tool_recaps}catch{return!0}}h(vt,"readDetailedToolRecaps");function Dt(a){return typeof a=="object"&&a!==null&&"setExpanded"in a&&typeof a.setExpanded=="function"}h(Dt,"isExpandable");const Pt=/\x1b\[[0-9;]*m/g,jt=/\x1b\[([0-9;]*)m/g;function Ft(a){return a.replace(jt,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const r=Number(s[n]===""?0:s[n]);if(r===38||r===48||r===58){const o=Number(s[n+1]),l=n+(o===5?2:o===2?4:1);r!==48&&i.push(...s.slice(n,l+1)),n=l;continue}r>=40&&r<=47||r>=100&&r<=107||i.push(String(r))}return i.length>0?`\x1B[${i.join(";")}m`:""})}h(Ft,"stripBackground");const _t=/<from\b[^>]*>[\s\S]*?<\/from>/g;class B extends c{static{h(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class Ht extends ${static{h(this,"WorkingRow")}label=new b("",1,0);constructor(){super(),this.addChild(new c(1)),this.addChild(this.label)}setLabel(t){this.label.setText(t)}}function M(a,t,e){return`${a} ${a===1?t:e}`}h(M,"plural");class S extends J{static{h(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1);const e=t[0],s=e.content;Array.isArray(s)&&/^elapsed \d+(?:h \d+)?m \d+s(?:\n|$)/.test(s.at(-1)?.text??"")?super.updateResult({...e,content:s.slice(0,-1)},t[1]):super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...mt(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(Pt,"").trim().length>0).map(s=>Ft(s).trimEnd()):super.render(t)}}const Lt=h(a=>`\x1B[31m${a}\x1B[39m`,"defaultErrorStyle"),Wt={accent:h(a=>`\x1B[33m${a}\x1B[39m`,"accent"),active:h(a=>`\x1B[36m${a}\x1B[39m`,"active"),info:h(a=>`\x1B[34m${a}\x1B[39m`,"info"),muted:H,faint:H,border:h(a=>a,"border"),surface:h(a=>a,"surface"),bold:h(a=>`\x1B[1m${a}\x1B[22m`,"bold"),error:Lt,warning:h(a=>`\x1B[33m${a}\x1B[39m`,"warning"),diffAdded:h(a=>`\x1B[32m${a}\x1B[39m`,"diffAdded"),diffRemoved:h(a=>`\x1B[91m${a}\x1B[39m`,"diffRemoved"),bashMode:h(a=>`\x1B[32m${a}\x1B[39m`,"bashMode"),bashModeAlt:h(a=>`\x1B[92m${a}\x1B[39m`,"bashModeAlt")};class me{static{h(this,"ChatView")}tui;container;historyContainer=new w;statusContainer=new w;pendingContainer=new w;pendingSends=[];bannerContainer;transcript;pageBlocks=new Map;pageRefresh=!1;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;level;detailedToolRecaps=vt();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;outsideTurns=0;turnHidden=new Set;lastReplyText;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=h(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?at(t,s):t,(t,{messageType:e})=>e==="user"?j(t):ht(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Gt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];transcriptDocRefs=[];copyBlockRecords=[];copyIndex=new Map;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.level=s.verbosity??It(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Wt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new w;i.addChild(new c(1));for(const n of s.banner)i.addChild(new b(n,1,0));i.addChild(new c(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.container.addChild(this.pendingContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new bt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,this.pendingContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=wt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails),this.turnReplies.clear();for(const[r,o]of Object.entries(nt(t.turnReplies)))this.turnReplies.set(r,o);const s=new Map,i=this.projection.messages,n=i.length-1;for(let r=0;r<i.length;r++){if(!this.projection.isStreaming&&r>0&&r%Ot===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const o=i[r];if(o.role==="assistant"){const l=d(o);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const G=r===n&&this.projection.isStreaming&&o.stopReason!=="aborted"&&o.stopReason!=="error",y=d(o).trim()!=="",L=this.assistantToolCalls(o),C=o.stopReason==="aborted"||o.stopReason==="error",T=A(o)?"Interrupted":o.errorMessage??"Error";if(C){for(const m of s.values()){const f={content:[{type:"text",text:T}],isError:!0};m.updateResult(f),this.registerCopyBlock(m,"tool",T),this.settleGroupTool(m,f,!0)}s.clear()}(y||C)&&this.closeOpenGroup();let k;G?(this.streamingComponent=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!y),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!y,this.streamingComponent.updateContent(o),this.registerCopyBlock(this.streamingComponent,"assistant",d(o)),k=this.streamingToolSeparator=this.appendAssistantSeparator(!y)):k=this.appendAssistantMessage(o,!y&&!C),k&&this.setAssistantSeparatorContent(k,o);for(const m of L){this.pushTranscriptValue(m.arguments);const f=this.appendToolComponent(m.name,m.id,m.arguments);o.stopReason==="aborted"||o.stopReason==="error"?(f.updateResult({content:[{type:"text",text:T}],isError:!0}),this.registerCopyBlock(f,"tool",T),this.settleGroupTool(f,{content:[{type:"text",text:T}],isError:!0},!0)):s.set(m.id,f)}C&&this.closeOpenGroup(),!G&&!C&&this.recordTurnProse(o,!1)}else if(o.role==="toolResult"){this.pushTranscriptText(this.userMessageText(o));const l=s.get(o.toolCallId);l&&(l.updateResult(o),this.registerCopyBlock(l,"tool",this.toolResultText(o)),this.historyContainer.markDirty(l),this.settleGroupTool(l,o,o.isError===!0),s.delete(o.toolCallId),this.maybeAppendPageBlock(o))}else this.addMessageToChat(o)}for(const[r,o]of s)this.pendingTools.set(r,o);for(const r of this.turns)this.refreshTurn(r);this.confirmPendingSendsIn(i),this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=Rt(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);if(this.streamingComponent){this.historyContainer.removeChild(this.streamingComponent);for(const t of this.turns)t.members.delete(this.streamingComponent);this.turnHidden.delete(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0}this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}moreDetail(){const t=u.indexOf(this.level);return this.setLevel(u[(t+1)%u.length]),{level:this.level,atEnd:this.level===u.at(-1)}}lessDetail(){const t=u.indexOf(this.level);return this.setLevel(u[Math.max(0,t-1)]),{level:this.level,atEnd:this.level===u[0]}}setLevel(t){this.level=t;for(const e of this.turns)this.refreshTurn(e);this.applyToolDisplay()}repliesOnly(){return this.level==="replies"}foldsSettledTools(){return u.indexOf(this.level)<=u.indexOf("tools")}showsGroupSummaries(){return u.indexOf(this.level)<=u.indexOf("summaries")}toolOutputExpanded(){return this.level==="full"}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const i of this.groups)for(const n of i.inFlight)t.add(n);for(const i of this.historyContainer.children)i instanceof S&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),Dt(i)&&i.setExpanded(this.toolOutputExpanded());const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e,this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showsGroupSummaries()}applyInboxExchangeDisplay(){const t=this.hidesInboxExchange();for(const e of this.inboxAnswers)this.historyContainer.setHidden(e,t);for(const e of this.pageBlocks.values())this.historyContainer.setHidden(e,e.settled)}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))){this.turnReplies.set(t,e);for(const s of this.turns)s.key===t&&this.refreshTurn(s);this.tui.requestRender()}}turnFoldedComponents(t){const e=new Set;if(!this.repliesOnly())return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),i=new Ht;this.outsideTurns++;try{this.append(i),this.append(s)}finally{this.outsideTurns--}this.registerCopyBlock(s,"assistant","");const n={key:t,reply:s,working:i,members:new Set,prose:e};return this.turns.push(n),this.openReplyTurn=n,this.refreshTurn(n),n}currentTurn(){return this.openReplyTurn??this.beginTurn(ot)}recordTurnProse(t,e){if(t.role!=="assistant"||t.stopReason==="aborted"||t.stopReason==="error")return;const s=d(t).trim(),i=P(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(r=>r.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=rt(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""||!this.repliesOnly()),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastReplyText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const l of t.members)l instanceof S?e++:(l instanceof I||l instanceof O||l instanceof v)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,r=[i>0?M(i,"message","messages"):void 0,e>0?M(e,"tool call","tool calls"):void 0,s>0?M(s,"card","cards"):void 0].filter(l=>l!==void 0),o=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`\u25B8 ${o?"working \u2014 ":""}${r.join(" \xB7 ")}`)),this.historyContainer.setHidden(t.working,!n||!this.repliesOnly()),this.historyContainer.markDirty(t.working)}replyMessage(t){return{role:"assistant",content:t===""?[]:[{type:"text",text:t}],stopReason:"stop"}}toggleThinking(){this.hideThinking=!this.hideThinking;for(const t of this.historyContainer.children)t instanceof U&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Et(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),Ct();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="user"&&g(t.message)&&this.confirmPendingSend(this.userMessageText(t.message).trim()),t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();else if(t.message.role==="assistant"){const e=d(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),this.streamingWasGroupMember=!e,this.appendAssistantPart(this.streamingComponent,!e),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",d(t.message)),this.streamingToolSeparator=this.appendAssistantSeparator(!e),this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message)}break}case"message_update":{if(this.streamingComponent&&t.message.role==="assistant"){this.promoteStreamingAssistantToBoundary(t.message),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",d(t.message)),this.historyContainer.markDirty(this.streamingComponent);const e=this.assistantToolCalls(t.message);this.streamingToolSeparator&&this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message);for(const s of e){this.pushTranscriptValue(s.arguments);const i=this.pendingTools.get(s.id);if(i)i.updateArgs(s.arguments),this.noteGroupTool(i,s.name,s.arguments),this.historyContainer.markDirty(i);else{const n=this.appendToolComponent(s.name,s.id,s.arguments);this.pendingTools.set(s.id,n)}}}break}case"message_end":{if(t.message.role!=="assistant")break;const e=t.message.stopReason==="aborted"||t.message.stopReason==="error";if(this.promoteStreamingAssistantToBoundary(t.message,e),this.streamingComponent&&this.registerCopyBlock(this.streamingComponent,"assistant",d(t.message)),t.message.stopReason!=="aborted"&&t.message.stopReason!=="error"){const s=d(t.message);s.trim()&&(this.lastAssistantText=s,this.pushTranscriptText(s))}if(this.streamingComponent){const s=t.message.stopReason;let i=t.message.errorMessage;if(A(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const n=i??"Error";for(const r of this.pendingTools.values())r.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(r,"tool",n),this.settleGroupTool(r,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(r);this.pendingTools.clear()}else for(const n of this.pendingTools.values())n.setArgsComplete(),this.historyContainer.markDirty(n);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay()),this.recordTurnProse(t.message,!0),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=Mt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new E(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Bt(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=At(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=st(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(D).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(_t,"").trim()===""&&e.senders.every(n=>n.entries.every(D)))){const n=X(e.kind),r=new I(e,n,this.toolOutputExpanded(),this.dimStyle,o=>this.spinnerStyle(this.labelStyle(o)));it(e.kind)?(this.closeOpenGroup(),this.append(r)):this.appendGroupMember(r)?.activity.noteCard(e,n)}for(const n of s)this.appendHumanAnswer(n);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new E(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===tt){this.appendGroupMember(new v(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}const s=new O(lt(t),void 0,p());s.setExpanded(this.toolOutputExpanded()),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new c(1));const s=new z(F(t),p());s.setExpanded(this.toolOutputExpanded()),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new c(1));const s=new N(F(t),p());s.setExpanded(this.toolOutputExpanded()),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{if(g(t)&&this.closeOpenGroup(),g(t)){this.outsideTurns++;try{this.appendUserMessage(t)}finally{this.outsideTurns--}this.beginTurn(P(t)??`local-${this.turns.length}`);break}this.appendUserMessage(t);break}case"assistant":{const s=d(t).trim()!=="";s&&this.closeOpenGroup(),this.appendAssistantMessage(t,!s);break}default:break}}appendUserMessage(t){const e=this.userMessageText(t);if(!e)return;this.pushTranscriptText(e),this.chatChildCount()>0&&this.appendUserPart(new c(1),!g(t));const s=Y(e);if(s){const i=new K({...s,content:j(s.content)},p());if(i.setExpanded(this.toolOutputExpanded()),this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new R(s.userMessage,p(),void 0,this.markdownTransformers);this.appendUserPart(n,!g(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new R(e,p(),void 0,this.markdownTransformers);this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new x(void 0,this.hideThinking,p(),this.hiddenThinkingLabel,this.markdownTransformers),i=A(t)?{...t,stopReason:"aborted",errorMessage:"Interrupted"}:t;s.updateContent(i),this.appendAssistantPart(s,e),this.registerCopyBlock(s,"assistant",d(t));const n=this.appendAssistantSeparator(e);return this.setAssistantSeparatorContent(n,t),n}appendAssistantSeparator(t=!1){const e=new B;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.outsideTurns++;try{this.appendHumanAnswerParts(t)}finally{this.outsideTurns--}}appendHumanAnswerParts(t){if(this.closeOpenGroup(),this.chatChildCount()>0){const s=new c(1);this.append(s),this.trackInboxAnswer(s)}const e=new R(t,p(),void 0,this.markdownTransformers);this.append(e),this.trackInboxAnswer(e),this.registerCopyBlock(e,"user",t)}trackInboxAnswer(t){this.inboxAnswers.add(t),this.hidesInboxExchange()&&this.historyContainer.setHidden(t,!0)}ensureGroup(){if(this.openGroup)return this.openGroup;const t=new ct,e={members:[],recap:t,activity:new dt(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=!this.openGroup&&this.historyContainer.children.at(-1)instanceof B?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const n=this.ensureGroup();i&&(this.append(i),n?.members.push(i));const r=this.makeToolComponent(t,e,s);return r.activityCallId=e,this.appendGroupMember(r),this.registerCopyBlock(r,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(r),n.activity.noteCall(e,t,s)),r}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&d(t).trim()===""||(this.streamingComponent&&this.removeGroupMember(this.streamingComponent),this.streamingToolSeparator&&this.removeGroupMember(this.streamingToolSeparator),this.streamingWasGroupMember=!1,this.closeOpenGroup())}seedToolGroupSummaries(t){this.groupSummaries.clear();for(const[e,s]of Object.entries(t))this.groupSummaries.set(e,s)}applyToolGroupSummary(t,e){if(this.deferIfBuilding(()=>this.applyToolGroupSummary(t,e)))return;this.projection=St(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t,e){const s=t.key===void 0?void 0:this.groupSummaries.get(t.key),i=this.showsGroupSummaries()&&t.toolCount>0&&t.inFlight.size===0&&s!==void 0;t.recap.setRecap(i?s:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!i||e.has(t.recap));for(const n of t.members)this.historyContainer.setHidden(n,i||e.has(n))}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof B))continue;const n=e[s+1];i.setFolded(this.foldsSettledTools()&&!this.historyContainer.hiddenChildren.has(i)&&n instanceof S&&!this.historyContainer.hiddenChildren.has(n)&&!t.has(n)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],n=i.some(o=>typeof o=="object"&&o!==null&&o.type==="text"&&typeof o.text=="string"&&o.text.trim()!==""),r=i.some(o=>typeof o=="object"&&o!==null&&o.type==="thinking"&&typeof o.thinking=="string"&&o.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:r}),t.setSeparatesToolGroup(n||!this.hideThinking&&r)}makeToolComponent(t,e,s){const i=new ut;let n,r;if(t==="bash"){const l=et(s,i);l===void 0?r=ft(this.cwd,i,this.backgroundBashHint):r=l.definition}else if(t==="edit"){const l=pt(this.cwd,i);r=l.definition,n=l.observeResult}else t==="read"?r=gt(this.cwd,i):t==="write"&&(r=yt(this.cwd,i));let o;return o=new S(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},r,this.componentTui(()=>o),this.cwd),o.setToolView(r===void 0?void 0:i,n),o.setExpanded(this.toolOutputExpanded()),o}append(t){if(this.outsideTurns===0){const e=this.currentTurn();this.historyContainer.addChild(t),e.members.add(t);return}this.historyContainer.addChild(t)}chatChildCount(){return this.historyContainer.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.turns.length=0,this.openReplyTurn=void 0,this.turnHidden=new Set,this.lastReplyText=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.transcriptDocRefs.length=0,this.pageBlocks.clear(),this.inboxAnswers.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks)return;const e=Q(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new Z(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.outsideTurns++;try{this.append(s)}finally{this.outsideTurns--}this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.setHidden(t,t.settled),this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){if(this.pageRefresh)return;const t=[...this.pageBlocks.values()].filter(s=>!s.settled);this.pageRefresh=!0,(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,s.settled),this.historyContainer.markDirty(s)),i})).finally(()=>{this.pageRefresh=!1})).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:h(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new q(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:h(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}addPendingSend(t){const e=t.trim();if(!e)return;const s=[new c(1),new V(e,1,1,p(),{color:this.dimStyle})];for(const i of s)this.pendingContainer.addChild(i);this.pendingSends.push({text:e,parts:s}),this.tui.requestRender()}confirmPendingSend(t){const e=this.pendingSends.findIndex(n=>n.text===t),s=e>=0?e:0;if(this.pendingSends.length===0)return;const[i]=this.pendingSends.splice(s,1);for(const n of i.parts)this.pendingContainer.removeChild(n)}confirmPendingSendsIn(t){if(this.pendingSends.length===0)return;const e=new Set;for(const s of t.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());for(const s of[...this.pendingSends])if(e.has(s.text)){this.pendingSends.splice(this.pendingSends.indexOf(s),1);for(const i of s.parts)this.pendingContainer.removeChild(i)}}setActivity(t){if(this.activityLoader?.stop(),this.activityLoader=t,this.onActivityChange){this.onActivityChange(t);return}this.statusContainer.clear(),t&&this.statusContainer.addChild(t)}showStatus(t){this.closeOpenGroup(),this.append(new c(1)),this.append(new b(this.dimStyle(t),1,0))}showError(t){if(!this.deferIfBuilding(()=>this.showError(t))){this.closeOpenGroup(),this.outsideTurns++;try{this.append(new c(1)),this.append(new b(this.errorStyle(t),1,0))}finally{this.outsideTurns--}this.tui.requestRender()}}crtrOutputTheme(){return{fg:h((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:h((t,e)=>e,"bg"),bold:h(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getTranscriptDocRefsNewestFirst(){return[...this.transcriptDocRefs]}refreshMarkdown(){this.historyContainer.invalidate(),this.tui.requestRender()}getLastAssistantText(){const t=(this.repliesOnly()?this.lastReplyText??this.lastAssistantText:this.lastAssistantText)?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){const t=this.inactiveFormBlocks();return this.copyBlockRecords.filter(e=>!t.has(e.block)).map(e=>e.text).filter(e=>e.trim()!=="").join(`
1
+ var W=Object.defineProperty;var h=(a,t)=>W(a,"name",{value:t,configurable:!0});import{Container as $,Loader as q,Markdown as V,Spacer as p,Text as k}from"@earendil-works/pi-tui";import{AssistantMessageComponent as U,BashExecutionComponent as E,BranchSummaryMessageComponent as N,CompactionSummaryMessageComponent as z,CustomMessageComponent as O,parseSkillBlock as Y,SkillInvocationMessageComponent as K,ToolExecutionComponent as J,UserMessageComponent as R}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as d}from"../config.js";import{ContextMessageComponent as I}from"./context-message.js";import{presentationFor as X}from"./card-presentation.js";import{detectInlinePageResult as Q,PageBlockComponent as Z}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as tt,CrtrOutputMessageComponent as v,createCrtrBashToolDefinition as et}from"./crtr-output.js";import{endedByAbort as A}from"../../../core/runtime/session-cycles.js";import{isHumanWordsEntry as D,parseCard as st}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as it,isTrueUserMessage as g}from"../../../shared/tool-groups.js";import{messageKey as P,normalizeTurnReplyRecord as nt,START_TURN_KEY as ot,turnReplyText as rt}from"../../../shared/turn-replies.js";import{transformDiagramFences as at}from"./diagram.js";import{styleAttachAgentMarkdown as ht,styleAttachMarkdownSource as j,styleAttachMessageMarkdown as lt,styleAttachSummaryMarkdown as F}from"./markdown-source.js";import{createCrtrEditToolDefinition as pt}from"./edit-diff.js";import{GroupActivityRecorder as dt}from"./group-activity.js";import{GroupRecapComponent as ct}from"./group-recap.js";import{FoldedToolCallController as ut,bashCallBackgroundHintLines as mt,createCrtrPlainBashToolDefinition as ft,createCrtrReadToolDefinition as gt,createCrtrWriteToolDefinition as yt}from"./tool-calls.js";import{ringCompletionBell as Ct}from"../chrome/completion-bell.js";import{extractFilePaths as Tt}from"../../../core/human/visible-paths.js";import{extractDocRefs as kt}from"./doc-links.js";import{ViewerAssistantMessageComponent as x}from"./assistant-message.js";import{CompositeViewportSource as bt,MeasuredContainer as w}from"./measured-container.js";import{readConfig as _}from"../../../core/config.js";import{DEFAULT_VERBOSITY as xt,VERBOSITY_LEVELS as u}from"../../../types.js";import{applySnapshot as wt,applyToolGroupSummary as St,applyWorkingActivity as Rt,bashEnd as At,bashOutput as Bt,bashStart as Mt,initialConvState as Gt,reduce as Et}from"../../conversation/projection.js";const H=h(a=>`\x1B[2m${a}\x1B[22m`,"defaultDimStyle"),Ot=50;function It(){try{return _("user").verbosity}catch{return xt}}h(It,"readVerbosity");function vt(){try{return _("user").detailed_tool_recaps}catch{return!0}}h(vt,"readDetailedToolRecaps");function Dt(a){return typeof a=="object"&&a!==null&&"setExpanded"in a&&typeof a.setExpanded=="function"}h(Dt,"isExpandable");const Pt=/\x1b\[[0-9;]*m/g,jt=/\x1b\[([0-9;]*)m/g;function Ft(a){return a.replace(jt,(t,e)=>{const s=e.split(";"),i=[];for(let n=0;n<s.length;n++){const r=Number(s[n]===""?0:s[n]);if(r===38||r===48||r===58){const o=Number(s[n+1]),l=n+(o===5?2:o===2?4:1);r!==48&&i.push(...s.slice(n,l+1)),n=l;continue}r>=40&&r<=47||r>=100&&r<=107||i.push(String(r))}return i.length>0?`\x1B[${i.join(";")}m`:""})}h(Ft,"stripBackground");const _t=/<from\b[^>]*>[\s\S]*?<\/from>/g;class B extends p{static{h(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class Ht extends ${static{h(this,"WorkingRow")}label=new k("",1,0);constructor(){super(),this.addChild(new p(1)),this.addChild(this.label)}setLabel(t){this.label.setText(t)}}function M(a,t,e){return`${a} ${a===1?t:e}`}h(M,"plural");class S extends J{static{h(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1);const e=t[0],s=e.content;Array.isArray(s)&&/^elapsed \d+(?:h \d+)?m \d+s(?:\n|$)/.test(s.at(-1)?.text??"")?super.updateResult({...e,content:s.slice(0,-1)},t[1]):super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...mt(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(Pt,"").trim().length>0).map(s=>Ft(s).trimEnd()):super.render(t)}}const Lt=h(a=>`\x1B[31m${a}\x1B[39m`,"defaultErrorStyle"),Wt={accent:h(a=>`\x1B[33m${a}\x1B[39m`,"accent"),active:h(a=>`\x1B[36m${a}\x1B[39m`,"active"),info:h(a=>`\x1B[34m${a}\x1B[39m`,"info"),muted:H,faint:H,border:h(a=>a,"border"),surface:h(a=>a,"surface"),bold:h(a=>`\x1B[1m${a}\x1B[22m`,"bold"),error:Lt,warning:h(a=>`\x1B[33m${a}\x1B[39m`,"warning"),diffAdded:h(a=>`\x1B[32m${a}\x1B[39m`,"diffAdded"),diffRemoved:h(a=>`\x1B[91m${a}\x1B[39m`,"diffRemoved"),bashMode:h(a=>`\x1B[32m${a}\x1B[39m`,"bashMode"),bashModeAlt:h(a=>`\x1B[92m${a}\x1B[39m`,"bashModeAlt")};class me{static{h(this,"ChatView")}tui;container;historyContainer=new w;statusContainer=new w;pendingContainer=new w;pendingSends=[];bannerContainer;setBannerHint(t){const e=this.bannerContainer;e!==void 0&&(e.removeChild(e.children[e.children.length-1]),e.addChild(new k(t,1,0)),e.addChild(new p(1)))}transcript;pageBlocks=new Map;pageRefresh=!1;inboxAnswers=new Set;inlinePageBlocks;pageOpenHint;backgroundBashHint;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;level;detailedToolRecaps=vt();groups=[];openGroup;turnReplies=new Map;turns=[];openReplyTurn;outsideTurns=0;turnHidden=new Set;lastReplyText;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=h(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?at(t,s):t,(t,{messageType:e})=>e==="user"?j(t):ht(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Gt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];transcriptDocRefs=[];copyBlockRecords=[];copyIndex=new Map;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.level=s.verbosity??It(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Wt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new w;i.addChild(new p(1));for(const n of s.banner)i.addChild(new k(n,1,0));i.addChild(new p(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.container.addChild(this.pendingContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new bt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,this.pendingContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=wt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails),this.turnReplies.clear();for(const[r,o]of Object.entries(nt(t.turnReplies)))this.turnReplies.set(r,o);const s=new Map,i=this.projection.messages,n=i.length-1;for(let r=0;r<i.length;r++){if(!this.projection.isStreaming&&r>0&&r%Ot===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const o=i[r];if(o.role==="assistant"){const l=c(o);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const G=r===n&&this.projection.isStreaming&&o.stopReason!=="aborted"&&o.stopReason!=="error",y=c(o).trim()!=="",L=this.assistantToolCalls(o),C=o.stopReason==="aborted"||o.stopReason==="error",T=A(o)?"Interrupted":o.errorMessage??"Error";if(C){for(const m of s.values()){const f={content:[{type:"text",text:T}],isError:!0};m.updateResult(f),this.registerCopyBlock(m,"tool",T),this.settleGroupTool(m,f,!0)}s.clear()}(y||C)&&this.closeOpenGroup();let b;G?(this.streamingComponent=new x(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!y),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!y,this.streamingComponent.updateContent(o),this.registerCopyBlock(this.streamingComponent,"assistant",c(o)),b=this.streamingToolSeparator=this.appendAssistantSeparator(!y)):b=this.appendAssistantMessage(o,!y&&!C),b&&this.setAssistantSeparatorContent(b,o);for(const m of L){this.pushTranscriptValue(m.arguments);const f=this.appendToolComponent(m.name,m.id,m.arguments);o.stopReason==="aborted"||o.stopReason==="error"?(f.updateResult({content:[{type:"text",text:T}],isError:!0}),this.registerCopyBlock(f,"tool",T),this.settleGroupTool(f,{content:[{type:"text",text:T}],isError:!0},!0)):s.set(m.id,f)}C&&this.closeOpenGroup(),!G&&!C&&this.recordTurnProse(o,!1)}else if(o.role==="toolResult"){this.pushTranscriptText(this.userMessageText(o));const l=s.get(o.toolCallId);l&&(l.updateResult(o),this.registerCopyBlock(l,"tool",this.toolResultText(o)),this.historyContainer.markDirty(l),this.settleGroupTool(l,o,o.isError===!0),s.delete(o.toolCallId),this.maybeAppendPageBlock(o))}else this.addMessageToChat(o)}for(const[r,o]of s)this.pendingTools.set(r,o);for(const r of this.turns)this.refreshTurn(r);this.confirmPendingSendsIn(i),this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=Rt(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);if(this.streamingComponent){this.historyContainer.removeChild(this.streamingComponent);for(const t of this.turns)t.members.delete(this.streamingComponent);this.turnHidden.delete(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0}this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}moreDetail(){const t=u.indexOf(this.level);return this.setLevel(u[(t+1)%u.length]),{level:this.level,atEnd:this.level===u.at(-1)}}lessDetail(){const t=u.indexOf(this.level);return this.setLevel(u[Math.max(0,t-1)]),{level:this.level,atEnd:this.level===u[0]}}setLevel(t){this.level=t;for(const e of this.turns)this.refreshTurn(e);this.applyToolDisplay()}repliesOnly(){return this.level==="replies"}foldsSettledTools(){return u.indexOf(this.level)<=u.indexOf("tools")}showsGroupSummaries(){return u.indexOf(this.level)<=u.indexOf("summaries")}toolOutputExpanded(){return this.level==="full"}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const i of this.groups)for(const n of i.inFlight)t.add(n);for(const i of this.historyContainer.children)i instanceof S&&i.setMinimized(this.foldsSettledTools()&&!t.has(i)),Dt(i)&&i.setExpanded(this.toolOutputExpanded());const e=this.turnFoldedComponents(t),s=new Set;for(const i of this.groups){this.applyGroupDisplay(i,e),s.add(i.recap);for(const n of i.members)s.add(n)}for(const i of this.turnHidden)!e.has(i)&&!s.has(i)&&this.historyContainer.setHidden(i,!1);for(const i of e)!s.has(i)&&!this.historyContainer.hiddenChildren.has(i)&&this.historyContainer.setHidden(i,!0);this.turnHidden=e,this.applyInboxExchangeDisplay(),this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}hidesInboxExchange(){return this.showsGroupSummaries()}applyInboxExchangeDisplay(){const t=this.hidesInboxExchange();for(const e of this.inboxAnswers)this.historyContainer.setHidden(e,t);for(const e of this.pageBlocks.values())this.historyContainer.setHidden(e,e.settled)}applyTurnReply(t,e){if(!this.deferIfBuilding(()=>this.applyTurnReply(t,e))){this.turnReplies.set(t,e);for(const s of this.turns)s.key===t&&this.refreshTurn(s);this.tui.requestRender()}}turnFoldedComponents(t){const e=new Set;if(!this.repliesOnly())return e;for(const s of this.turns){const i=s===this.openReplyTurn;for(const n of s.members)i&&(n===this.streamingComponent||n===this.streamingToolSeparator||n===this.bashComponent||t.has(n))||e.add(n)}return e}beginTurn(t,e=[]){const s=new x(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),i=new Ht;this.outsideTurns++;try{this.append(i),this.append(s)}finally{this.outsideTurns--}this.registerCopyBlock(s,"assistant","");const n={key:t,reply:s,working:i,members:new Set,prose:e};return this.turns.push(n),this.openReplyTurn=n,this.refreshTurn(n),n}currentTurn(){return this.openReplyTurn??this.beginTurn(ot)}recordTurnProse(t,e){if(t.role!=="assistant"||t.stopReason==="aborted"||t.stopReason==="error")return;const s=c(t).trim(),i=P(t);if(s===""||i===void 0)return;const n=this.currentTurn();n.prose.some(r=>r.key===i)||(n.prose.push({key:i,text:s}),e&&this.refreshTurn(n))}refreshTurn(t){const e=rt(t.prose,this.turnReplies.get(t.key));t.reply.updateContent(this.replyMessage(e)),this.historyContainer.setHidden(t.reply,e===""||!this.repliesOnly()),this.historyContainer.markDirty(t.reply),this.registerCopyBlock(t.reply,"assistant",e),e!==""&&t===this.turns.at(-1)&&(this.lastReplyText=e),this.refreshWorkingRow(t)}refreshWorkingRow(t){let e=0,s=0;for(const l of t.members)l instanceof S?e++:(l instanceof I||l instanceof O||l instanceof v)&&s++;const i=t.prose.length,n=e>0||s>0||i>1,r=[i>0?M(i,"message","messages"):void 0,e>0?M(e,"tool call","tool calls"):void 0,s>0?M(s,"card","cards"):void 0].filter(l=>l!==void 0),o=this.runActive&&t===this.openReplyTurn;t.working.setLabel(this.dimStyle(`\u25B8 ${o?"working \u2014 ":""}${r.join(" \xB7 ")}`)),this.historyContainer.setHidden(t.working,!n||!this.repliesOnly()),this.historyContainer.markDirty(t.working)}replyMessage(t){return{role:"assistant",content:t===""?[]:[{type:"text",text:t}],stopReason:"stop"}}toggleThinking(){this.hideThinking=!this.hideThinking;for(const t of this.historyContainer.children)t instanceof U&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Et(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),Ct();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="user"&&g(t.message)&&this.confirmPendingSend(this.userMessageText(t.message).trim()),t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();else if(t.message.role==="assistant"){const e=c(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new x(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),this.streamingWasGroupMember=!e,this.appendAssistantPart(this.streamingComponent,!e),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),this.streamingToolSeparator=this.appendAssistantSeparator(!e),this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message)}break}case"message_update":{if(this.streamingComponent&&t.message.role==="assistant"){this.promoteStreamingAssistantToBoundary(t.message),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),this.historyContainer.markDirty(this.streamingComponent);const e=this.assistantToolCalls(t.message);this.streamingToolSeparator&&this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message);for(const s of e){this.pushTranscriptValue(s.arguments);const i=this.pendingTools.get(s.id);if(i)i.updateArgs(s.arguments),this.noteGroupTool(i,s.name,s.arguments),this.historyContainer.markDirty(i);else{const n=this.appendToolComponent(s.name,s.id,s.arguments);this.pendingTools.set(s.id,n)}}}break}case"message_end":{if(t.message.role!=="assistant")break;const e=t.message.stopReason==="aborted"||t.message.stopReason==="error";if(this.promoteStreamingAssistantToBoundary(t.message,e),this.streamingComponent&&this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),t.message.stopReason!=="aborted"&&t.message.stopReason!=="error"){const s=c(t.message);s.trim()&&(this.lastAssistantText=s,this.pushTranscriptText(s))}if(this.streamingComponent){const s=t.message.stopReason;let i=t.message.errorMessage;if(A(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const n=i??"Error";for(const r of this.pendingTools.values())r.updateResult({content:[{type:"text",text:n}],isError:!0}),this.registerCopyBlock(r,"tool",n),this.settleGroupTool(r,{content:[{type:"text",text:n}],isError:!0},!0),this.historyContainer.markDirty(r);this.pendingTools.clear()}else for(const n of this.pendingTools.values())n.setArgsComplete(),this.historyContainer.markDirty(n);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay()),this.recordTurnProse(t.message,!0),this.openReplyTurn&&this.refreshWorkingRow(this.openReplyTurn),this.applyToolDisplay();break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=Mt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new E(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Bt(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=At(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=st(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(n=>n.entries).filter(D).map(n=>n.body.trim()).filter(n=>n!=="");if(!(s.length>0&&e.body.replace(_t,"").trim()===""&&e.senders.every(n=>n.entries.every(D)))){const n=X(e.kind),r=new I(e,n,this.toolOutputExpanded(),this.dimStyle,o=>this.spinnerStyle(this.labelStyle(o)));it(e.kind)?(this.closeOpenGroup(),this.append(r)):this.appendGroupMember(r)?.activity.noteCard(e,n)}for(const n of s)this.appendHumanAnswer(n);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new E(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===tt){this.appendGroupMember(new v(this.userMessageText(t),this.toolOutputExpanded(),this.crtrOutputTheme()));break}const s=new O(lt(t),void 0,d());s.setExpanded(this.toolOutputExpanded()),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new p(1));const s=new z(F(t),d());s.setExpanded(this.toolOutputExpanded()),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new p(1));const s=new N(F(t),d());s.setExpanded(this.toolOutputExpanded()),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{if(g(t)&&this.closeOpenGroup(),g(t)){this.outsideTurns++;try{this.appendUserMessage(t)}finally{this.outsideTurns--}this.beginTurn(P(t)??`local-${this.turns.length}`);break}this.appendUserMessage(t);break}case"assistant":{const s=c(t).trim()!=="";s&&this.closeOpenGroup(),this.appendAssistantMessage(t,!s);break}default:break}}appendUserMessage(t){const e=this.userMessageText(t);if(!e)return;this.pushTranscriptText(e),this.chatChildCount()>0&&this.appendUserPart(new p(1),!g(t));const s=Y(e);if(s){const i=new K({...s,content:j(s.content)},d());if(i.setExpanded(this.toolOutputExpanded()),this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e),s.userMessage){const n=new R(s.userMessage,d(),void 0,this.markdownTransformers);this.appendUserPart(n,!g(t)),this.registerCopyBlock(n,"user",s.userMessage)}}else{const i=new R(e,d(),void 0,this.markdownTransformers);this.appendUserPart(i,!g(t)),this.registerCopyBlock(i,"user",e)}}appendAssistantMessage(t,e=!1){const s=new x(void 0,this.hideThinking,d(),this.hiddenThinkingLabel,this.markdownTransformers),i=A(t)?{...t,stopReason:"aborted",errorMessage:"Interrupted"}:t;s.updateContent(i),this.appendAssistantPart(s,e),this.registerCopyBlock(s,"assistant",c(t));const n=this.appendAssistantSeparator(e);return this.setAssistantSeparatorContent(n,t),n}appendAssistantSeparator(t=!1){const e=new B;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.outsideTurns++;try{this.appendHumanAnswerParts(t)}finally{this.outsideTurns--}}appendHumanAnswerParts(t){if(this.closeOpenGroup(),this.chatChildCount()>0){const s=new p(1);this.append(s),this.trackInboxAnswer(s)}const e=new R(t,d(),void 0,this.markdownTransformers);this.append(e),this.trackInboxAnswer(e),this.registerCopyBlock(e,"user",t)}trackInboxAnswer(t){this.inboxAnswers.add(t),this.hidesInboxExchange()&&this.historyContainer.setHidden(t,!0)}ensureGroup(){if(this.openGroup)return this.openGroup;const t=new ct,e={members:[],recap:t,activity:new dt(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=!this.openGroup&&this.historyContainer.children.at(-1)instanceof B?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const n=this.ensureGroup();i&&(this.append(i),n?.members.push(i));const r=this.makeToolComponent(t,e,s);return r.activityCallId=e,this.appendGroupMember(r),this.registerCopyBlock(r,"tool",""),n&&(n.key??=e,n.toolCount++,n.inFlight.add(r),n.activity.noteCall(e,t,s)),r}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&c(t).trim()===""||(this.streamingComponent&&this.removeGroupMember(this.streamingComponent),this.streamingToolSeparator&&this.removeGroupMember(this.streamingToolSeparator),this.streamingWasGroupMember=!1,this.closeOpenGroup())}seedToolGroupSummaries(t){this.groupSummaries.clear();for(const[e,s]of Object.entries(t))this.groupSummaries.set(e,s)}applyToolGroupSummary(t,e){if(this.deferIfBuilding(()=>this.applyToolGroupSummary(t,e)))return;this.projection=St(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t,e){const s=t.key===void 0?void 0:this.groupSummaries.get(t.key),i=this.showsGroupSummaries()&&t.toolCount>0&&t.inFlight.size===0&&s!==void 0;t.recap.setRecap(i?s:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!i||e.has(t.recap));for(const n of t.members)this.historyContainer.setHidden(n,i||e.has(n))}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof B))continue;const n=e[s+1];i.setFolded(this.foldsSettledTools()&&!this.historyContainer.hiddenChildren.has(i)&&n instanceof S&&!this.historyContainer.hiddenChildren.has(n)&&!t.has(n)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],n=i.some(o=>typeof o=="object"&&o!==null&&o.type==="text"&&typeof o.text=="string"&&o.text.trim()!==""),r=i.some(o=>typeof o=="object"&&o!==null&&o.type==="thinking"&&typeof o.thinking=="string"&&o.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:n,hasThinking:r}),t.setSeparatesToolGroup(n||!this.hideThinking&&r)}makeToolComponent(t,e,s){const i=new ut;let n,r;if(t==="bash"){const l=et(s,i);l===void 0?r=ft(this.cwd,i,this.backgroundBashHint):r=l.definition}else if(t==="edit"){const l=pt(this.cwd,i);r=l.definition,n=l.observeResult}else t==="read"?r=gt(this.cwd,i):t==="write"&&(r=yt(this.cwd,i));let o;return o=new S(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},r,this.componentTui(()=>o),this.cwd),o.setToolView(r===void 0?void 0:i,n),o.setExpanded(this.toolOutputExpanded()),o}append(t){if(this.outsideTurns===0){const e=this.currentTurn();this.historyContainer.addChild(t),e.members.add(t);return}this.historyContainer.addChild(t)}chatChildCount(){return this.historyContainer.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.turns.length=0,this.openReplyTurn=void 0,this.turnHidden=new Set,this.lastReplyText=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.transcriptDocRefs.length=0,this.pageBlocks.clear(),this.inboxAnswers.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks)return;const e=Q(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new Z(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.outsideTurns++;try{this.append(s)}finally{this.outsideTurns--}this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.setHidden(t,t.settled),this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){if(this.pageRefresh)return;const t=[...this.pageBlocks.values()].filter(s=>!s.settled);this.pageRefresh=!0,(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&(this.historyContainer.setHidden(s,s.settled),this.historyContainer.markDirty(s)),i})).finally(()=>{this.pageRefresh=!1})).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:h(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new q(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:h(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}addPendingSend(t){const e=t.trim();if(!e)return;const s=[new p(1),new V(e,1,1,d(),{color:this.dimStyle})];for(const i of s)this.pendingContainer.addChild(i);this.pendingSends.push({text:e,parts:s}),this.tui.requestRender()}confirmPendingSend(t){const e=this.pendingSends.findIndex(n=>n.text===t),s=e>=0?e:0;if(this.pendingSends.length===0)return;const[i]=this.pendingSends.splice(s,1);for(const n of i.parts)this.pendingContainer.removeChild(n)}confirmPendingSendsIn(t){if(this.pendingSends.length===0)return;const e=new Set;for(const s of t.slice(-50))s.role==="user"&&e.add(this.userMessageText(s).trim());for(const s of[...this.pendingSends])if(e.has(s.text)){this.pendingSends.splice(this.pendingSends.indexOf(s),1);for(const i of s.parts)this.pendingContainer.removeChild(i)}}setActivity(t){if(this.activityLoader?.stop(),this.activityLoader=t,this.onActivityChange){this.onActivityChange(t);return}this.statusContainer.clear(),t&&this.statusContainer.addChild(t)}showStatus(t){this.closeOpenGroup(),this.append(new p(1)),this.append(new k(this.dimStyle(t),1,0))}showError(t){if(!this.deferIfBuilding(()=>this.showError(t))){this.closeOpenGroup(),this.outsideTurns++;try{this.append(new p(1)),this.append(new k(this.errorStyle(t),1,0))}finally{this.outsideTurns--}this.tui.requestRender()}}crtrOutputTheme(){return{fg:h((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:h((t,e)=>e,"bg"),bold:h(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getTranscriptDocRefsNewestFirst(){return[...this.transcriptDocRefs]}refreshMarkdown(){this.historyContainer.invalidate(),this.tui.requestRender()}getLastAssistantText(){const t=(this.repliesOnly()?this.lastReplyText??this.lastAssistantText:this.lastAssistantText)?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){const t=this.inactiveFormBlocks();return this.copyBlockRecords.filter(e=>!t.has(e.block)).map(e=>e.text).filter(e=>e.trim()!=="").join(`
2
2
 
3
3
  `)}inactiveFormBlocks(){const t=new Set;if(!this.repliesOnly())for(const e of this.turns)t.add(e.reply);return t}registerCopyBlock(t,e,s){const i=this.copyIndex.get(t);i===void 0?(this.copyIndex.set(t,this.copyBlockRecords.length),this.copyBlockRecords.push({block:t,kind:e,text:s})):this.copyBlockRecords[i].text=s}unregisterCopyBlock(t){const e=this.copyIndex.get(t);if(e!==void 0){this.copyBlockRecords.splice(e,1),this.copyIndex.delete(t);for(let s=e;s<this.copyBlockRecords.length;s++)this.copyIndex.set(this.copyBlockRecords[s].block,s)}}toolResultText(t){if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"content"in t){const e=t.content;if(typeof e=="string")return e;if(Array.isArray(e))return e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}try{const e=JSON.stringify(t);return typeof e=="string"?e:""}catch{return""}}pushTranscriptText(t){const e=t.trim();if(e==="")return;const s=[...new Set(kt(e).reverse())];if(s.length>0){const r=[...s,...this.transcriptDocRefs.filter(o=>!s.includes(o))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...r)}const i=Tt([e],this.cwd);if(i.length===0)return;const n=[...i,...this.transcriptFilePaths.filter(r=>!i.includes(r))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...n)}pushTranscriptValue(t){try{const e=typeof t=="string"?t:JSON.stringify(t);typeof e=="string"&&this.pushTranscriptText(e)}catch{}}userMessageText(t){const e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="text").map(s=>s.text).join(""):""}}export{me as ChatView};
@@ -2,7 +2,7 @@
2
2
  * live viewer state; a miss may schedule a fetch that re-renders later. */
3
3
  export interface DocLinkContext {
4
4
  /** The node this viewer is attached to. */
5
- selfNodeId: string;
5
+ selfNodeId: string | undefined;
6
6
  /** A node's display name, when known. */
7
7
  nodeName(nodeId: string): string | undefined;
8
8
  /** The browser URL of a document ref, absent on remote attach. */
@@ -1 +1 @@
1
- var v=Object.defineProperty;var n=(s,r)=>v(s,"name",{value:r,configurable:!0});import{APIError as E,isDaemonTransportApiError as M}from"../../../api/errors.js";const p=5e3,I=6e4,L="crtrd not responding \u2014 retrying";function x(s){return M(s)||s instanceof E&&s.status>=500}n(x,"isTransientDaemonFailure");function J(s,r){const{nodeId:w,canvasSource:f}=s;let o={},a,y=!1,i=0,S=0;const _=n(()=>{i===0&&r.setNotice(L,{sticky:!0}),i=Math.min(i+1,16)},"markStalled"),F=n(()=>{i!==0&&(i=0,r.setNotice("crtrd responding again"),D(p))},"markHealthy"),l=n((e,t)=>{if(S++,x(t)){_();return}const c=(t instanceof Error?t.message:t===void 0?"":String(t)).replace(/\s+/g," ").trim().slice(0,120);r.setNotice(c===""?`${e} delayed`:`${e} delayed \u2014 ${c}`)},"reportFailure"),N=n(e=>{JSON.stringify(e)!==JSON.stringify(o)&&(o=e,r.renderFooter())},"setAsks");let g=!1,d=!1;const u=n(()=>{d=!0,!g&&(g=!0,(async()=>{try{for(;d&&!r.isTornDown();){d=!1;const e=S;try{const t=await f.panelView?.(w);t!==void 0&&N(t.counts),await r.refreshRoster(t),S===e&&F()}catch(t){l("canvas panel refresh",t)}r.refreshGraph()}}finally{g=!1,d&&!r.isTornDown()&&u()}})().catch(e=>l("canvas chrome refresh",e)))},"refresh"),O=n(async e=>{let t=e;const c=new Set([t]);for(;;){const m=(await f.subscribersOf(t).catch(()=>[]))[0]?.node_id;if(m===void 0||c.has(m))break;c.add(m),t=m}return t},"climbRootFromSource"),T=n(()=>{u(),r.refreshIdentity(),r.renderExtensionWidgets(),r.pollGit(),r.refreshInFlightTools(),r.renderFooter(),f.panelView===void 0&&(async()=>{const e=await O(w),t=await f.ticketCountsForView(e);JSON.stringify(t)!==JSON.stringify(o)&&(o=t,u(),r.renderFooter())})().catch(e=>l("canvas attention refresh",e))},"pollChrome"),A=n(()=>i===0?p:Math.min(p*2**i,I),"nextDelay");function D(e){y||a===void 0||(clearTimeout(a),h(e))}n(D,"rearm");function h(e){a=setTimeout(()=>{y||r.isTornDown()||(T(),h(A()))},e),typeof a.unref=="function"&&a.unref()}return n(h,"schedule"),{refresh:u,asks:n(()=>o,"asks"),reportFailure:l,daemonStalled:n(()=>i>0,"daemonStalled"),start:n(()=>{T(),h(p)},"start"),stop:n(()=>{y=!0,a!==void 0&&clearTimeout(a)},"stop")}}n(J,"createChromeRefresh");export{L as DAEMON_STALLED_NOTICE,J as createChromeRefresh,x as isTransientDaemonFailure};
1
+ var D=Object.defineProperty;var n=(i,t)=>D(i,"name",{value:t,configurable:!0});import{APIError as I,isDaemonTransportApiError as v}from"../../../api/errors.js";const p=5e3,E=6e4,M="crtrd not responding \u2014 retrying";function L(i){return v(i)||i instanceof I&&i.status>=500}n(L,"isTransientDaemonFailure");function J(i,t){const{canvasSource:c}=i;let o={},a,y=!1,s=0,S=0;const T=n(()=>{s===0&&t.setNotice(M,{sticky:!0}),s=Math.min(s+1,16)},"markStalled"),_=n(()=>{s!==0&&(s=0,t.setNotice("crtrd responding again"),A(p))},"markHealthy"),d=n((e,r)=>{if(S++,L(r)){T();return}const f=(r instanceof Error?r.message:r===void 0?"":String(r)).replace(/\s+/g," ").trim().slice(0,120);t.setNotice(f===""?`${e} delayed`:`${e} delayed \u2014 ${f}`)},"reportFailure"),F=n(e=>{JSON.stringify(e)!==JSON.stringify(o)&&(o=e,t.renderFooter())},"setAsks");let g=!1,l=!1;const u=n(()=>{i.nodeId!==""&&(l=!0,!g&&(g=!0,(async()=>{try{for(;l&&!t.isTornDown();){l=!1;const e=S;try{const r=await c.panelView?.(i.nodeId);r!==void 0&&F(r.counts),await t.refreshRoster(r),S===e&&_()}catch(r){d("canvas panel refresh",r)}t.refreshGraph()}}finally{g=!1,l&&!t.isTornDown()&&u()}})().catch(e=>d("canvas chrome refresh",e))))},"refresh"),N=n(async e=>{let r=e;const f=new Set([r]);for(;;){const m=(await c.subscribersOf(r).catch(()=>[]))[0]?.node_id;if(m===void 0||f.has(m))break;f.add(m),r=m}return r},"climbRootFromSource"),w=n(()=>{u(),t.refreshIdentity(),t.renderExtensionWidgets(),t.pollGit(),t.refreshInFlightTools(),t.renderFooter(),c.panelView===void 0&&(async()=>{const e=await N(i.nodeId),r=await c.ticketCountsForView(e);JSON.stringify(r)!==JSON.stringify(o)&&(o=r,u(),t.renderFooter())})().catch(e=>d("canvas attention refresh",e))},"pollChrome"),O=n(()=>s===0?p:Math.min(p*2**s,E),"nextDelay");function A(e){y||a===void 0||(clearTimeout(a),h(e))}n(A,"rearm");function h(e){a=setTimeout(()=>{y||t.isTornDown()||(w(),h(O()))},e),typeof a.unref=="function"&&a.unref()}return n(h,"schedule"),{refresh:u,asks:n(()=>o,"asks"),reportFailure:d,daemonStalled:n(()=>s>0,"daemonStalled"),start:n(()=>{w(),h(p)},"start"),stop:n(()=>{y=!0,a!==void 0&&clearTimeout(a)},"stop")}}n(J,"createChromeRefresh");export{M as DAEMON_STALLED_NOTICE,J as createChromeRefresh,L as isTransientDaemonFailure};
@@ -20,6 +20,10 @@ export declare function resolveHelloRole(observer: boolean): ClientRole;
20
20
  * "attach does NOT launch the engine" contract. */
21
21
  export declare function preWaitForViewSocket(nodeId: string): Promise<void>;
22
22
  /** A connected viewer's transport facts, established before any UI exists. */
23
+ export interface BoundNode {
24
+ readonly meta: Pick<NodeMeta, 'cwd' | 'profile_id' | 'grantee'>;
25
+ readonly nodeIdentity: Pick<NodeMeta, 'kind' | 'mode' | 'lifecycle' | 'icon'> | undefined;
26
+ }
23
27
  export interface AttachConnection {
24
28
  /** THE single remote fact for the whole session (the node lives on another
25
29
  * canvas; local-host operations are off), derived ONCE here from `--canvas`. Every local disk/SQLite read or write keyed on the node id
@@ -27,12 +31,9 @@ export interface AttachConnection {
27
31
  readonly remote: boolean;
28
32
  /** Canvas read authority: an API source locally, a relayed source remotely. */
29
33
  readonly canvasSource: CanvasSource;
30
- /** Viewer-LOCAL concerns only — `cwd` drives theming and this pane's own git
31
- * status, and is the CLI's own cwd under `--canvas`. */
32
- readonly meta: Pick<NodeMeta, 'cwd' | 'profile_id' | 'grantee'>;
33
- /** The attached node's persona/lifecycle, when this canvas can tell us —
34
- * `undefined` for a remote attach until the viewer refetches it. */
35
- readonly nodeIdentity: Pick<NodeMeta, 'kind' | 'mode' | 'lifecycle' | 'icon'> | undefined;
34
+ /** Name the node to attach to and build its transport. Returns the viewer-LOCAL `meta` (`cwd` drives theming and this pane's own git
35
+ * status, and is the CLI's own cwd under `--canvas`) and the node's persona/lifecycle, `undefined` for a remote attach until the viewer refetches it. */
36
+ bind(nodeId: string, known?: NodeDetailDTO): Promise<BoundNode>;
36
37
  /** The one socket to the node's headless broker. Not connected until `dial()` settles. */
37
38
  readonly socket: BrokerClient;
38
39
  /** Revive the node if it is dormant (server-side) and connect `socket`, resolving once the transport is open. It does not send `hello`. Rejects with a plain `InputError`.
@@ -48,6 +49,6 @@ export interface ParkedSnapshot {
48
49
  source: string;
49
50
  }> | undefined;
50
51
  }
51
- /** Resolve the attach target and build the not-yet-connected socket. Rejects with
52
- * a plain `InputError` for an unknown node — no terminal has been taken over yet. */
53
- export declare function connectToNode(nodeId: string, canvasName?: string, wakeParked?: boolean, known?: NodeDetailDTO): Promise<AttachConnection>;
52
+ /** Build the not-yet-connected socket and canvas source. No node is resolved or dialed until `bind` names one: a viewer whose root is
53
+ * still being created paints first and binds when the create returns. `bind` rejects with a plain `InputError` for an unknown node. */
54
+ export declare function connectToNode(canvasName?: string, wakeParked?: boolean): AttachConnection;