@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
@@ -0,0 +1,3 @@
1
+ var l=Object.defineProperty;var s=(r,e)=>l(r,"name",{value:e,configurable:!0});import{readFileSync as a,unlinkSync as c,writeFileSync as d}from"node:fs";import{spawnSync as m}from"node:child_process";import{randomUUID as u}from"node:crypto";import{tmpdir as $}from"node:os";import{join as p}from"node:path";import{announceFallbackEditor as E,NO_EDITOR_MESSAGE as h,resolveEditor as x}from"../core/editor-resolver.js";function R(r){const e=p($(),`crtr-input-${u()}.txt`),o=x();if(o===null)return{text:r,error:h};const i=o.command;try{d(e,r),E(o);const t=m("/bin/sh",["-c",`${i} "$1"`,"sh",e],{stdio:"inherit"});if(t.error)return{text:r,error:`$EDITOR ("${i}") failed to launch: ${t.error.message}`};if(t.signal!==null)return{text:r,error:`$EDITOR ("${i}") was killed by signal ${t.signal}`};if(t.status===127||t.status===126)return{text:r,error:`$EDITOR ("${i}") failed to launch (shell exit ${t.status})`};if(t.status!==0)return{text:r,error:`$EDITOR ("${i}") exited with status ${t.status}`};let n=a(e,"utf8");return n.endsWith(`
2
+ `)&&!r.endsWith(`
3
+ `)&&(n=n.slice(0,-1)),{text:n}}catch(t){return{text:r,error:`$EDITOR round-trip failed: ${t instanceof Error?t.message:String(t)}`}}finally{try{c(e)}catch{}}}s(R,"editBufferInEditor");export{R as editBufferInEditor};
@@ -47,7 +47,6 @@ export declare class InboxController {
47
47
  private selectedIndex;
48
48
  private screen;
49
49
  private adapter;
50
- private reviewAdapter;
51
50
  private focusingSource;
52
51
  /** The ticket open on the detail screen. */
53
52
  private open;
@@ -120,11 +119,7 @@ export declare class InboxController {
120
119
  * whichever one the selected row actually is. */
121
120
  private cancelFromInbox;
122
121
  activate(): Promise<void>;
123
- /** A review opens in its own tmux window, which tmux selects at once, so
124
- * the inbox left behind in this pane has nothing more to do: it closes,
125
- * and returning to this window lands on the conversation beneath it. The
126
- * inbox stays up only when the window could not be opened, so its notice
127
- * is read where the person is looking. */
122
+ /** A review opens in the browser at its canvas page; a runtime with no canvas host has none. */
128
123
  private activateReview;
129
124
  /** Seat the selection on a ticket dir, when present in the current list. */
130
125
  selectDir(dir: string): void;
@@ -1 +1 @@
1
- var I=Object.defineProperty;var o=(a,e)=>I(a,"name",{value:e,configurable:!0});import{watch as A}from"node:fs";import{visibleWidth as R}from"@earendil-works/pi-tui";import{renderMarkdown as F}from"../../core/termrender/termrender.js";import{BOLD as P,CYAN as M,DIM as h,GRAY as C,RESET as n,YELLOW as D,clipLine as m,singleLine as L,wrap as W}from"./tui/ansi.js";import{buildInboxLines as q,recommendedLabel as O}from"./tui.js";import{inboxLayout as v}from"./layout.js";import{resolvePageComponents as E}from"../../core/config.js";import{watchInboxActivity as N}from"../../core/human/root.js";import{clearProgress as H}from"../../core/human/convention.js";import{emitEvent as B}from"../../core/events/emit.js";import{cliClient as u}from"../../commands/api-client.js";import{projectPageDisplayMarkdown as T}from"../../core/human/page-markdown.js";import{projectHtmlDocumentMarkdown as z}from"../../core/human/page-html-markdown.js";import{pageBodyLines as V}from"./tui/page-body.js";import{docLinksRevision as g}from"../attach/render/doc-links.js";import{byNewestFirst as _,inboxRowFromDTO as j,pageViewFromDTO as b,settledStatusOf as k}from"./dto-adapt.js";import{PageAdapter as K}from"./page-adapter.js";import{ReviewAdapter as Y}from"./review-adapter.js";import{createReviewClient as G}from"./review/review-client.js";import{editBufferInEditor as X}from"./review/roundtrip.js";import{daemonErrorMessage as f,dismissTicketViaDaemon as J,resolveFailureKind as x,resolveTicketPage as $}from"./resolve.js";class ye{static{o(this,"InboxController")}options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;open;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??Q,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){const e=this.selectedDir,t=this.open;try{this.items=await this.scan()}catch(s){if(this.closed)return;this.status=f(s),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){const s=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(s)}if(!(e!==void 0&&this.items.some(s=>s.dir===e))&&this.adapter!==void 0&&e!==void 0&&t!==void 0){const s=(await this.requestOrNull(t.id))?.state==="canceled";if(this.closed)return;s&&H(e),e!==this.submittingDir&&(this.status=s?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail()}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}const e=this.profile.members();this.visible=this.items.filter(t=>{const i=t.source.nodeId;return i!==void 0&&e.has(i)})}reseatSelection(){const e=this.selectedDir===void 0?-1:this.visible.findIndex(t=>t.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(t=>t.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){const e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots())}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.open!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,t){this.cols=e,this.rows=t,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){const e=v(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${D}Resize terminal to at least 60\xD718 to use inbox.${n}`];const t=q(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),i=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(t);if(e.mode==="detail")return this.withStatus(i);const s=[],r=`${C}\u2502${n}`;for(let d=0;d<e.height;d++){const l=m(t[d]??"",e.listWidth),c=m(i[d]??"",e.detailWidth),w=" ".repeat(Math.max(0,e.listWidth-R(l)));s.push(`${l}${w}${r}${c}`)}return this.withStatus(s)}handleKey(e,t){if(t.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()&&!this.adapter.hasShortcut(e)){this.focusSelectedSource();return}this.adapter.handleKey(e,t),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){const i=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(i)}else(e==="n"||e==="N"||t.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){const i=this.currentRow();i!==void 0&&(this.cancelConfirmation={item:i},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(t.escape||e==="q"){this.close();return}e==="j"||t.downArrow?this.select(this.selectedIndex+1):e==="k"||t.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(t.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){const e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}const t=await this.requestOrNull(e.id);if(y(t)){this.status=p(t),await this.rescan();return}const i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${O(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await $(e.id,e.fastAction.responses),this.status=i}catch(s){this.status=x(s)==="already_settled"?p(await this.requestOrNull(e.id)):f(s)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await G().cancel(e.id,"Canceled from the inbox."):await J(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(t){this.status=f(t)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){const e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}const t=await this.requestOrNull(e.id);if(this.closed)return;if(y(t)){this.status=p(t),await this.rescan();return}let i,s;try{const r=await u().getHumanInboxPage(e.inboxTicketId);if(r.state==="resolved"||r.state==="canceled"){this.status=k(r),await this.rescan();return}i=b(r),s=r.revision}catch{this.status="page could not be read",await this.invalidate();return}this.closed||this.open!==void 0||this.adapter!==void 0||(this.open={dir:e.dir,id:e.id,ticketId:e.inboxTicketId},this.screen="detail",this.adapter=new K({ticketId:e.inboxTicketId,page:i,productKinds:E(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:o(()=>this.markDirty(),"onDirty"),onEditorRequest:o(()=>this.editActivePageInput(),"onEditorRequest"),onBack:o(()=>{this.leaveDetail(),this.markDirty()},"onBack"),onComplete:o(r=>{this.complete(r)},"onComplete")}),this.openRevision=s,this.watchSelected(e.dir),this.markDirty())}async activateReview(e){this.reviewAdapter=new Y({reviewId:e.id,host:this.host});let t=!1;try{t=await this.reviewAdapter.start()}catch(i){this.status=f(i)}finally{this.reviewAdapter=void 0}if(t){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let t=this.visible.findIndex(i=>i.dir===e);return t<0&&this.items.some(i=>i.dir===e)&&(this.filter="all",this.recomputeVisible(),t=this.visible.findIndex(i=>i.dir===e)),t<0?!1:(this.select(t),!0)}async reloadSelectedPage(){const e=this.open;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{const t=await u().getHumanInboxPage(e.ticketId);if(this.closed||this.open!==e||this.adapter===void 0)return;t.revision!==this.openRevision&&(this.openRevision=t.revision,this.adapter.reload(b(t)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.reviewAdapter?.stop(),this.leaveDetail();for(const e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){const t=this.open;if(t===void 0)return;this.submittingDir=t.dir;try{await $(t.id,e)}catch(s){this.submittingDir=void 0,this.status=f(s);const r=x(s);if(r==="unreachable"||r==="other"){this.markDirty();return}r==="already_settled"&&(this.status=p(await this.requestOrNull(t.id))),this.leaveDetail(),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(),await this.rescan();const i=this.items.some(s=>s.dir===t.dir);B({level:i?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:t.id,request_settled:y(await this.requestOrNull(t.id)),still_listed:i}}),this.markDirty()}editActivePageInput(){const e=this.adapter?.inputBuffer();if(e===void 0)return;const t=this.host.suspendForChild();let i={text:e};try{i=X(e)}finally{t(),this.adapter?.setInputBuffer(i.text),i.error!==void 0&&(this.status=i.error),this.markDirty()}}leaveDetail(){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.open=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){const e=v(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,t){if(this.adapter!==void 0)return this.adapter.render();const i=this.currentRow();if(i===void 0)return this.passiveDetailLines(e,t);const s=this.focusAvailable(i.dir)?` ${h}g${n} chat`:"",r=i.kind==="page"&&i.fastAction!==void 0?` ${h}s${n} ${i.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",d=i.kind==="page"?[` ${h}Enter${n} opens the full page ${h}\u2191\u2193/jk${n} select${r} ${h}x${n} cancel`,` ${h}Page:${n} c comment u/d scroll${s} ${h}q${n} close`]:[` ${h}Enter${n} opens the full review ${h}\u2191\u2193/jk${n} select ${h}x${n} cancel`,` ${s} ${h}q${n} close`],l=Math.max(0,t-d.length),c=this.passiveDetailLines(e,l);for(;c.length<l;)c.push("");return[...c,...d.map(w=>m(w,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){const e=this.screen==="detail"?this.open?.dir:this.currentRow()?.dir,t=e===void 0?void 0:this.items.find(s=>s.dir===e);if(t===void 0||this.focusingSource)return;const i=t.source.nodeId;if(i===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(i)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,t){const i=this.preview;if(i!==void 0&&i.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),i.width===t&&i.links===g())return i.lines;const s=S(i.view,t);return this.preview={...i,width:t,links:g(),lines:s},s}return this.schedulePreview(e),this.previewFailed===e.dir?[`${h}page could not be read${n}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,u().getHumanInboxPage(e.inboxTicketId).then(t=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===t.revision))return;const i=b(t),s=this.preview?.width??v(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:t.revision,view:i,width:s,links:g(),lines:S(i,s)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await u().getHumanRequest(e)}catch{return}}passiveDetailLines(e,t){const i=this.currentRow();if(i===void 0)return[` ${h}Select a pending interaction.${n}`];const s=[...W(L(i.title),Math.max(10,e-2)).map(d=>` ${P}${M}${d}${n}`),""];for(const d of F(i.subtitle,Math.max(1,e-2)))s.push(` ${d}`);const r=i.kind==="page"?this.pagePreviewBody(i,e):[`${h}1 file to review${n}`];if(r.length>0){s.push("");const d=Math.max(0,t-s.length),l=r.length<=d?r:r.slice(0,Math.max(0,d-1));for(const c of l)s.push(` ${c}`);l.length<r.length&&s.push(` ${h}\u2026 +${r.length-l.length} more lines${n}`)}return s.map(d=>m(d,e)).slice(0,Math.max(1,t))}withStatus(e){const t=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(t===void 0||this.rows<1)return e;const i=[...e];for(;i.length<this.rows;)i.push("");return i[this.rows-1]=`${D}${t}${n}`,i}markDirty(){this.options.onDirty()}watchRoots(){const e=N(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=A(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}}async function Q(){const{tickets:a}=await u().listHumanInbox();return a.map(j).sort(_)}o(Q,"defaultScan");function S(a,e){const t=a.manifest.dialect==="html"?z(a.document):T(a.document,a.manifest);return V(a.manifest,t,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}o(S,"previewLines");function y(a){return a!==void 0&&a.state!=="pending"}o(y,"isSettled");function p(a){return a?.page===void 0?"ticket was already resolved":k(a.page)}o(p,"settledStatus");export{ye as InboxController};
1
+ var I=Object.defineProperty;var h=(a,e)=>I(a,"name",{value:e,configurable:!0});import{watch as R}from"node:fs";import{visibleWidth as F}from"@earendil-works/pi-tui";import{renderMarkdown as P}from"../../core/termrender/termrender.js";import{BOLD as M,CYAN as A,DIM as o,GRAY as C,RESET as n,YELLOW as D,clipLine as f,singleLine as L,wrap as W}from"./tui/ansi.js";import{buildInboxLines as q,recommendedLabel as O}from"./tui.js";import{inboxLayout as v}from"./layout.js";import{resolvePageComponents as E}from"../../core/config.js";import{watchInboxActivity as N}from"../../core/human/root.js";import{clearProgress as B}from"../../core/human/convention.js";import{emitEvent as H}from"../../core/events/emit.js";import{cliClient as u}from"../../commands/api-client.js";import{projectPageDisplayMarkdown as T}from"../../core/human/page-markdown.js";import{projectHtmlDocumentMarkdown as z}from"../../core/human/page-html-markdown.js";import{pageBodyLines as V}from"./tui/page-body.js";import{docLinksRevision as g}from"../attach/render/doc-links.js";import{byNewestFirst as _,inboxRowFromDTO as j,pageViewFromDTO as b,settledStatusOf as k}from"./dto-adapt.js";import{PageAdapter as K}from"./page-adapter.js";import{editBufferInEditor as Y}from"../editor-roundtrip.js";import{openBrowser as G}from"../open-browser.js";import{daemonErrorMessage as m,dismissTicketViaDaemon as X,resolveFailureKind as x,resolveTicketPage as $}from"./resolve.js";class ge{static{h(this,"InboxController")}options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;focusingSource=!1;open;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??J,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){const e=this.selectedDir,t=this.open;try{this.items=await this.scan()}catch(s){if(this.closed)return;this.status=m(s),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){const s=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(s)}if(!(e!==void 0&&this.items.some(s=>s.dir===e))&&this.adapter!==void 0&&e!==void 0&&t!==void 0){const s=(await this.requestOrNull(t.id))?.state==="canceled";if(this.closed)return;s&&B(e),e!==this.submittingDir&&(this.status=s?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail()}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}const e=this.profile.members();this.visible=this.items.filter(t=>{const i=t.source.nodeId;return i!==void 0&&e.has(i)})}reseatSelection(){const e=this.selectedDir===void 0?-1:this.visible.findIndex(t=>t.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(t=>t.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){const e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots())}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.open!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,t){this.cols=e,this.rows=t,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){const e=v(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${D}Resize terminal to at least 60\xD718 to use inbox.${n}`];const t=q(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),i=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(t);if(e.mode==="detail")return this.withStatus(i);const s=[],r=`${C}\u2502${n}`;for(let d=0;d<e.height;d++){const l=f(t[d]??"",e.listWidth),c=f(i[d]??"",e.detailWidth),w=" ".repeat(Math.max(0,e.listWidth-F(l)));s.push(`${l}${w}${r}${c}`)}return this.withStatus(s)}handleKey(e,t){if(t.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()&&!this.adapter.hasShortcut(e)){this.focusSelectedSource();return}this.adapter.handleKey(e,t),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){const i=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(i)}else(e==="n"||e==="N"||t.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){const i=this.currentRow();i!==void 0&&(this.cancelConfirmation={item:i},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(t.escape||e==="q"){this.close();return}e==="j"||t.downArrow?this.select(this.selectedIndex+1):e==="k"||t.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(t.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){const e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}const t=await this.requestOrNull(e.id);if(y(t)){this.status=p(t),await this.rescan();return}const i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${O(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await $(e.id,e.fastAction.responses),this.status=i}catch(s){this.status=x(s)==="already_settled"?p(await this.requestOrNull(e.id)):m(s)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await u().cancelReview(e.id,{reason:"Canceled from the inbox."}):await X(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(t){this.status=m(t)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){const e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){this.activateReview(e);return}const t=await this.requestOrNull(e.id);if(this.closed)return;if(y(t)){this.status=p(t),await this.rescan();return}let i,s;try{const r=await u().getHumanInboxPage(e.inboxTicketId);if(r.state==="resolved"||r.state==="canceled"){this.status=k(r),await this.rescan();return}i=b(r),s=r.revision}catch{this.status="page could not be read",await this.invalidate();return}this.closed||this.open!==void 0||this.adapter!==void 0||(this.open={dir:e.dir,id:e.id,ticketId:e.inboxTicketId},this.screen="detail",this.adapter=new K({ticketId:e.inboxTicketId,page:i,productKinds:E(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:h(()=>this.markDirty(),"onDirty"),onEditorRequest:h(()=>this.editActivePageInput(),"onEditorRequest"),onBack:h(()=>{this.leaveDetail(),this.markDirty()},"onBack"),onComplete:h(r=>{this.complete(r)},"onComplete")}),this.openRevision=s,this.watchSelected(e.dir),this.markDirty())}activateReview(e){e.url===void 0?this.status="Reviews open on canvas.northlight.ai; this runtime has no canvas host":(G(e.url),this.status="opened the review in your browser"),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let t=this.visible.findIndex(i=>i.dir===e);return t<0&&this.items.some(i=>i.dir===e)&&(this.filter="all",this.recomputeVisible(),t=this.visible.findIndex(i=>i.dir===e)),t<0?!1:(this.select(t),!0)}async reloadSelectedPage(){const e=this.open;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{const t=await u().getHumanInboxPage(e.ticketId);if(this.closed||this.open!==e||this.adapter===void 0)return;t.revision!==this.openRevision&&(this.openRevision=t.revision,this.adapter.reload(b(t)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.leaveDetail();for(const e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){const t=this.open;if(t===void 0)return;this.submittingDir=t.dir;try{await $(t.id,e)}catch(s){this.submittingDir=void 0,this.status=m(s);const r=x(s);if(r==="unreachable"||r==="other"){this.markDirty();return}r==="already_settled"&&(this.status=p(await this.requestOrNull(t.id))),this.leaveDetail(),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(),await this.rescan();const i=this.items.some(s=>s.dir===t.dir);H({level:i?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:t.id,request_settled:y(await this.requestOrNull(t.id)),still_listed:i}}),this.markDirty()}editActivePageInput(){const e=this.adapter?.inputBuffer();if(e===void 0)return;const t=this.host.suspendForChild();let i={text:e};try{i=Y(e)}finally{t(),this.adapter?.setInputBuffer(i.text),i.error!==void 0&&(this.status=i.error),this.markDirty()}}leaveDetail(){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.open=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){const e=v(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,t){if(this.adapter!==void 0)return this.adapter.render();const i=this.currentRow();if(i===void 0)return this.passiveDetailLines(e,t);const s=this.focusAvailable(i.dir)?` ${o}g${n} chat`:"",r=i.kind==="page"&&i.fastAction!==void 0?` ${o}s${n} ${i.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",d=i.kind==="page"?[` ${o}Enter${n} opens the full page ${o}\u2191\u2193/jk${n} select${r} ${o}x${n} cancel`,` ${o}Page:${n} c comment u/d scroll${s} ${o}q${n} close`]:[` ${o}Enter${n} opens the review in your browser ${o}\u2191\u2193/jk${n} select ${o}x${n} cancel`,` ${s} ${o}q${n} close`],l=Math.max(0,t-d.length),c=this.passiveDetailLines(e,l);for(;c.length<l;)c.push("");return[...c,...d.map(w=>f(w,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){const e=this.screen==="detail"?this.open?.dir:this.currentRow()?.dir,t=e===void 0?void 0:this.items.find(s=>s.dir===e);if(t===void 0||this.focusingSource)return;const i=t.source.nodeId;if(i===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(i)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,t){const i=this.preview;if(i!==void 0&&i.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),i.width===t&&i.links===g())return i.lines;const s=S(i.view,t);return this.preview={...i,width:t,links:g(),lines:s},s}return this.schedulePreview(e),this.previewFailed===e.dir?[`${o}page could not be read${n}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,u().getHumanInboxPage(e.inboxTicketId).then(t=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===t.revision))return;const i=b(t),s=this.preview?.width??v(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:t.revision,view:i,width:s,links:g(),lines:S(i,s)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await u().getHumanRequest(e)}catch{return}}passiveDetailLines(e,t){const i=this.currentRow();if(i===void 0)return[` ${o}Select a pending interaction.${n}`];const s=[...W(L(i.title),Math.max(10,e-2)).map(d=>` ${M}${A}${d}${n}`),""];for(const d of P(i.subtitle,Math.max(1,e-2)))s.push(` ${d}`);const r=i.kind==="page"?this.pagePreviewBody(i,e):[`${o}1 file to review${n}`];if(r.length>0){s.push("");const d=Math.max(0,t-s.length),l=r.length<=d?r:r.slice(0,Math.max(0,d-1));for(const c of l)s.push(` ${c}`);l.length<r.length&&s.push(` ${o}\u2026 +${r.length-l.length} more lines${n}`)}return s.map(d=>f(d,e)).slice(0,Math.max(1,t))}withStatus(e){const t=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(t===void 0||this.rows<1)return e;const i=[...e];for(;i.length<this.rows;)i.push("");return i[this.rows-1]=`${D}${t}${n}`,i}markDirty(){this.options.onDirty()}watchRoots(){const e=N(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=R(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}}async function J(){const{tickets:a}=await u().listHumanInbox();return a.map(j).sort(_)}h(J,"defaultScan");function S(a,e){const t=a.manifest.dialect==="html"?z(a.document):T(a.document,a.manifest);return V(a.manifest,t,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}h(S,"previewLines");function y(a){return a!==void 0&&a.state!=="pending"}h(y,"isSettled");function p(a){return a?.page===void 0?"ticket was already resolved":k(a.page)}h(p,"settledStatus");export{ge as InboxController};
@@ -1 +1 @@
1
- var r=Object.defineProperty;var t=(e,i)=>r(e,"name",{value:i,configurable:!0});import{validatePageManifest as a}from"../../core/human/page-schema.js";function p(e){return e}t(p,"responsesFromDTO");function l(e){return{dir:e.request_dir,id:e.request_id,inboxTicketId:e.ticket_id,kind:"page",title:e.title,subtitle:e.subtitle??"",dialect:e.dialect,placement:e.placement,inbox:e.inbox,steps:e.steps,slotKinds:e.slot_kinds,awaitsResponse:e.awaits_response,source:e.source,emittedAt:e.emitted_at,recommendedOptions:(e.recommended_options??[]).map(i=>({slotId:i.slot_id,optionId:i.option_id,label:i.label})),...e.fast_action===void 0?{}:{fastAction:{kind:e.fast_action.kind,responses:e.fast_action.responses}},state:e.state,...e.answer_digest===void 0?{}:{answerDigest:e.answer_digest}}}t(l,"pageRowFromDTO");function u(e){return{dir:e.request_dir,id:e.request_id,inboxTicketId:e.ticket_id,kind:"review",title:e.title,subtitle:e.subtitle,blockedSince:e.blocked_since,source:e.source}}t(u,"reviewRowFromDTO");function d(e){return e.kind==="page"?l(e):u(e)}t(d,"inboxRowFromDTO");function m(e){return{manifest:a(e.page),document:e.source_document,progress:e.progress===null?null:e.progress.responses,state:e.state,revision:e.revision}}t(m,"pageViewFromDTO");function f(e){const i=e.result;if(!(i===null||i.kind!=="page"))return i.summary.replace(/\s+/g," ").trim()}t(f,"answerDigestOf");function k(e){const i=e.result;return i!==null&&i.kind==="canceled"?"ticket was already canceled":i!==null&&i.kind==="page"?"ticket was already resolved: page submitted":"ticket was already resolved"}t(k,"settledStatusOf");function _(e,i){const n=t(s=>s.kind==="page"?s.emittedAt:s.blockedSince,"time");return n(i).localeCompare(n(e))||e.id.localeCompare(i.id)}t(_,"byNewestFirst");export{f as answerDigestOf,_ as byNewestFirst,d as inboxRowFromDTO,m as pageViewFromDTO,k as settledStatusOf};
1
+ var r=Object.defineProperty;var n=(e,i)=>r(e,"name",{value:i,configurable:!0});import{validatePageManifest as a}from"../../core/human/page-schema.js";function p(e){return e}n(p,"responsesFromDTO");function l(e){return{dir:e.request_dir,id:e.request_id,inboxTicketId:e.ticket_id,kind:"page",title:e.title,subtitle:e.subtitle??"",dialect:e.dialect,placement:e.placement,inbox:e.inbox,steps:e.steps,slotKinds:e.slot_kinds,awaitsResponse:e.awaits_response,source:e.source,emittedAt:e.emitted_at,recommendedOptions:(e.recommended_options??[]).map(i=>({slotId:i.slot_id,optionId:i.option_id,label:i.label})),...e.fast_action===void 0?{}:{fastAction:{kind:e.fast_action.kind,responses:e.fast_action.responses}},state:e.state,...e.answer_digest===void 0?{}:{answerDigest:e.answer_digest}}}n(l,"pageRowFromDTO");function u(e){return{dir:e.request_dir,id:e.request_id,inboxTicketId:e.ticket_id,kind:"review",title:e.title,subtitle:e.subtitle,blockedSince:e.blocked_since,source:e.source,...e.url===void 0?{}:{url:e.url}}}n(u,"reviewRowFromDTO");function d(e){return e.kind==="page"?l(e):u(e)}n(d,"inboxRowFromDTO");function m(e){return{manifest:a(e.page),document:e.source_document,progress:e.progress===null?null:e.progress.responses,state:e.state,revision:e.revision}}n(m,"pageViewFromDTO");function f(e){const i=e.result;if(!(i===null||i.kind!=="page"))return i.summary.replace(/\s+/g," ").trim()}n(f,"answerDigestOf");function k(e){const i=e.result;return i!==null&&i.kind==="canceled"?"ticket was already canceled":i!==null&&i.kind==="page"?"ticket was already resolved: page submitted":"ticket was already resolved"}n(k,"settledStatusOf");function _(e,i){const t=n(s=>s.kind==="page"?s.emittedAt:s.blockedSince,"time");return t(i).localeCompare(t(e))||e.id.localeCompare(i.id)}n(_,"byNewestFirst");export{f as answerDigestOf,_ as byNewestFirst,d as inboxRowFromDTO,m as pageViewFromDTO,k as settledStatusOf};
@@ -1 +1 @@
1
- var L=Object.defineProperty;var $=(s,r)=>L(s,"name",{value:r,configurable:!0});import{renderMarkdownBlockAwareLines as M}from"../../../core/termrender/termrender.js";import{describeSlot as w,tableMarkdown as S,terminalAnswerable as x}from"./slots.js";import{rewriteMarkdownDocLinks as y}from"../../attach/render/markdown-source.js";import{BOLD as b,DIM as l,RESET as o,sanitize as n,singleLine as d,truncate as k,wrap as u}from"./ansi.js";function N(s,r,f,m){const p=$(t=>M(y(t),f,m),"md");if(s.dialect==="html")return r===""?[`${l}HTML page \u2014 open in Northlight to read this${o}`]:p(r);const e=r===""?[]:p(r);let a=-1;for(const t of s.slots){s.steps>1&&t.step!==a&&(e.length>0&&e.push(""),e.push(`${b}Step ${t.step+1}/${s.steps}${o}`),a=t.step),e.length>0&&e.push("");for(const i of u(d(w(t)),f))e.push(`${b}${i}${o}`);const h=t.config.body;if(typeof h=="string"&&h!==""&&e.push(...p(h)),!x(t)){e.push(`${l}${n(t.kind)} \u2014 open in Northlight to answer this${o}`);continue}if(t.kind==="text")e.push(...p(t.config.initialText));else if(t.kind==="table")e.push(...p(S(t.config)));else if(t.kind==="cards"){for(const i of t.config.cards??[])if(e.push(` \u2022 ${k(n(d(i.subtitle===void 0?i.title:`${i.title} \u2014 ${i.subtitle}`)),Math.max(10,f-4))}`),i.body!==void 0)for(const c of u(n(i.body),Math.max(10,f-6)))e.push(` ${l}${c}${o}`)}else if(t.kind==="options"){for(const i of t.config.options)if(e.push(` \u2022 ${k(n(d(i.label)),Math.max(10,f-4))}`),i.description!==void 0)for(const c of u(n(i.description),Math.max(10,f-6)))e.push(` ${l}${c}${o}`)}else if(t.kind==="chart"){const i=t.config,c=i.title??`${i.x??""} vs ${(i.y??[]).map(g=>g.label??g.field).join(", ")}`;e.push(`${l}chart \u2014 ${n(i.kind??"chart")}: ${n(c)}${o}`)}}return e}$(N,"pageBodyLines");export{N as pageBodyLines};
1
+ var m=Object.defineProperty;var p=(d,e)=>m(d,"name",{value:e,configurable:!0});import{renderMarkdownBlockAwareLines as k}from"../../../core/termrender/termrender.js";import{describeSlot as L,tableMarkdown as M,terminalAnswerable as w}from"./slots.js";import{rewriteMarkdownDocLinks as x}from"../../attach/render/markdown-source.js";import{BOLD as y,DIM as l,RESET as r,sanitize as n,singleLine as $,truncate as g,wrap as a}from"./ansi.js";function N(d,e,s,b){const f=p(t=>k(x(t),s,b),"md");if(d.dialect==="html")return e===""?[`${l}HTML page \u2014 open in Northlight to read this${r}`]:f(e);const o=e===""?[]:f(e);for(const t of d.slots){o.length>0&&o.push("");for(const i of a($(L(t)),s))o.push(`${y}${i}${r}`);const h=t.config.body;if(typeof h=="string"&&h!==""&&o.push(...f(h)),!w(t)){o.push(`${l}${n(t.kind)} \u2014 open in Northlight to answer this${r}`);continue}if(t.kind==="text")o.push(...f(t.config.initialText));else if(t.kind==="table")o.push(...f(M(t.config)));else if(t.kind==="cards"){for(const i of t.config.cards??[])if(o.push(` \u2022 ${g(n($(i.subtitle===void 0?i.title:`${i.title} \u2014 ${i.subtitle}`)),Math.max(10,s-4))}`),i.body!==void 0)for(const c of a(n(i.body),Math.max(10,s-6)))o.push(` ${l}${c}${r}`)}else if(t.kind==="options"){for(const i of t.config.options)if(o.push(` \u2022 ${g(n($(i.label)),Math.max(10,s-4))}`),i.description!==void 0)for(const c of a(n(i.description),Math.max(10,s-6)))o.push(` ${l}${c}${r}`)}else if(t.kind==="chart"){const i=t.config,c=i.title??`${i.x??""} vs ${(i.y??[]).map(u=>u.label??u.field).join(", ")}`;o.push(`${l}chart \u2014 ${n(i.kind??"chart")}: ${n(c)}${r}`)}}return o}p(N,"pageBodyLines");export{N as pageBodyLines};
@@ -1,2 +1,2 @@
1
- var U=Object.defineProperty;var a=(n,s)=>U(n,"name",{value:s,configurable:!0});import R from"string-width";import{isResponseBearingSlot as v}from"../../../core/human/page-schema.js";import{answerCommentAnchorLabel as X,describePageAnswer as Z}from"../../../core/human/answer.js";import{renderMarkdownBlockAwareLines as nn}from"../../../core/termrender/termrender.js";import{rewriteMarkdownDocLinks as en}from"../../attach/render/markdown-source.js";import{commentAnchors as tn,describeSlot as C,pageComplete as sn,slotActions as on,slotAnswered as B,tableMarkdown as rn,terminalAnswerable as N}from"./slots.js";import{RESET as r,BOLD as w,DIM as $,GREEN as A,YELLOW as S,CYAN as E,REVERSE as T,sanitize as x,singleLine as y,truncate as H,hline as I,wrap as g,centerHorizontal as D,clipLine as P,panLine as ln,visibleWidth as L}from"./ansi.js";const cn=8,W=a((n,s,t)=>nn(en(n),s,t),"mdLines");function z(n){return Z(n.manifest,Object.fromEntries(n.responses),{completedAt:""})}a(z,"pageAnswer");function fn(n,s){return s.id===void 0?void 0:n.slots.find(t=>t.id===s.id)}a(fn,"answerSlot");function F(n){if(n===void 0||n.state==="unanswered")return"unanswered";if(n.raw!==void 0)return"custom response";const s=n.text!==void 0?[n.text.edited?"edited":"accepted"]:n.groups.map(t=>t.picked.length===0?"none":t.picked.map(e=>e.label).join(", "));return n.freetext!==void 0&&s.push(n.freetext),n.comments.length>0&&s.push(`${n.comments.length} comment${n.comments.length===1?"":"s"}`),s.join("; ")||"answered"}a(F,"answerSummary");function Y(n,s){return X(n,s)}a(Y,"commentLabel");function kn(n,s,t){const e=Math.min(Math.max(20,s-4),120),o=Math.max(20,s-4),l=["",...j(y(n.manifest.title),e,"",0,`${w}${E}`)];if(n.manifest.subtitle)for(const h of g(x(n.manifest.subtitle),e))l.push(` ${$}${h}${r}`);if(n.displayMarkdown!==""){l.push("");for(const h of W(n.displayMarkdown,e,o))l.push(` ${h}`)}else n.manifest.dialect==="html"&&l.push("",` ${$}HTML page \u2014 open in Northlight to read this${r}`);const i=n.slots.length>0;i&&l.push(` ${$}${I(e)}${r}`,"");const f=z(n);let c=-1,u;for(let h=0;h<n.slots.length;h++){const p=n.slots[h];n.manifest.steps>1&&p.step!==c&&(c!==-1&&l.push(""),l.push(` ${w}Step ${p.step+1}/${n.manifest.steps}${r}`),c=p.step);const k=p.id===void 0?void 0:n.responses.get(p.id),M=v(p)?B(n,p)?`${A}\u2713${r}`:`${$}\u25CB${r}`:`${$}\xB7${r}`,b=h===n.currentIndex?`${E}\u25B8${r} `:" ";h===n.currentIndex&&(u=l.length),l.push(` ${b}${M} ${H(y(C(p)),Math.max(10,s-16))}`),k!==void 0&&l.push(` ${$}${H(y(F(fn(f,p))),Math.max(10,s-10))}${r}`)}if(n.manifest.slots.some(h=>v(h)&&!N(h))){l.push("");for(const h of g("This page must be answered in Northlight. Leaving it here keeps it in your inbox; x on the list cancels it.",e-2))l.push(` ${S}${h}${r}`)}i&&l.push(""),l.push(` ${$}${I(e)}${r}`);const d=!n.manifest.slots.some(v)?` ${$}u/d${r} scroll ${$}q${r} dismiss`:` ${$}enter${r} review ${$}\u2191\u2193/jk${r} navigate ${$}u/d${r} scroll ${$}q${r} close`;return K(l,d,n,s,t,e+2,n.followSelection?u:void 0)}a(kn,"renderOverview");function $n(n,s,t){const e=[...n],o=Math.max(0,Math.min(s,e.length)),l=G(n,t);let i=0;for(let u=0;u<l.length;u++)l[u].start<=o&&(i=u);const f=l.map((u,m)=>{if(m!==i)return e.slice(u.start,u.end).join("");const d=e.slice(u.start,o).join(""),h=o<u.end?e[o]:" ",p=o<u.end?e.slice(o+1,u.end).join(""):"";return`${d}${T}${h}${r}${p}`}),c=l[i];return o===c.end&&R(e.slice(c.start,c.end).join(""))>=t&&(f[i]=e.slice(c.start,c.end).join(""),f.splice(i+1,0,`${T} ${r}`)),f}a($n,"renderInputBuffer");function bn(n,s){const t=[...n];let e=Math.max(0,Math.min(s,t.length));for(;e>0&&/\s/.test(t[e-1]);)e--;for(;e>0&&!/\s/.test(t[e-1]);)e--;return e}a(bn,"wordLeftIndex");function On(n,s){const t=[...n];let e=Math.max(0,Math.min(s,t.length));for(;e<t.length&&/\s/.test(t[e]);)e++;for(;e<t.length&&!/\s/.test(t[e]);)e++;return e}a(On,"wordRightIndex");function G(n,s){const t=[...n],e=Math.max(1,s),o=[];let l=0,i=0;for(let f=0;f<t.length;f++){const c=t[f];if(c===`
2
- `){o.push({start:l,end:f}),l=f+1,i=0;continue}const u=R(c);i+u>e?(o.push({start:l,end:f}),l=f,i=u):i+=u}return o.push({start:l,end:t.length}),o}a(G,"wrappedRowBounds");function yn(n,s,t,e){const o=G(n,e),l=Math.max(0,Math.min(s,[...n].length));let i=0;for(let c=0;c<o.length;c++)o[c].start<=l&&(i=c);const f=o[i+t];return f===void 0?l:Math.min(f.start+(l-o[i].start),f.end)}a(yn,"verticalCursor");function un(n,s){return s.id===void 0?[]:n.responses.get(s.id)?.comments??[]}a(un,"responseComments");function j(n,s,t,e,o){return g(n,Math.max(10,s-e)).map((l,i)=>` ${i===0?t:" ".repeat(e)}${o}${l}${r}`)}a(j,"hangingWrap");function dn(n,s,t,e){if(s.id===void 0)return!1;const o=n.responses.get(s.id);return t==="option"?o?.selectedOptionIds?.includes(e)===!0:t==="card"?o?.selectedCardIds?.includes(e)===!0:t==="row"?o?.selectedRowIds?.includes(e)===!0:o?.selectedColumnIds?.includes(e)===!0}a(dn,"selected");function V(n,s){const t=n.slots[n.currentIndex],e=Math.min(Math.max(20,s-4),120),o=Math.max(20,s-4),l=`[${n.currentIndex+1}/${n.slots.length}]`,i=["",...j(y(n.manifest.title),e,`${w}${E}${l}${r} `,R(l)+2,$),` ${$}${I(e)}${r}`,"",...j(y(C(t)),e,"",0,w)],f=t.config.body;if(typeof f=="string"&&f.length>0){i.push("");for(const m of W(f,e,o))i.push(` ${m}`)}if(N(t)){if(t.kind==="chart"){const m=t.config,d=m.title??`${m.x} vs ${(m.y??[]).map(h=>h.label??h.field).join(", ")}`;i.push("",` ${$}chart \u2014 ${x(m.kind)}: ${x(d)}${r}`)}else if(t.kind==="table"){i.push("");for(const d of W(rn(t.config),e,o))i.push(` ${d}`);const m=t.config.label;m&&i.push(` ${$}${x(m)}${r}`)}else if(t.kind==="text"){const d=(t.id===void 0?void 0:n.responses.get(t.id))?.text??t.config.initialText;i.push("");for(const h of W(d,e,o))i.push(` ${h}`)}}else{i.push("");for(const m of g(`${x(t.kind)} \u2014 must be answered in Northlight; the terminal cannot submit this page`,Math.max(10,e-2)))i.push(` ${S}${m}${r}`);i.push(` ${$}q leaves it in your inbox; x on the list cancels it${r}`)}i.push("",` ${$}${I(e)}${r}`);let c;if(n.inputMode!==null){const m=n.inputMode.kind==="comment"?`Comment on ${Y(t,n.inputMode.anchor)}`:n.inputMode.kind==="text"?"Edit text":"Other response";i.push(` ${w}${m}${r}`);for(const d of $n(n.inputMode.buffer,n.inputMode.cursor,Math.max(10,e-4)))i.push(` ${d}`);c=` ${$}enter save esc cancel${n.editorAvailable?" ^o editor":""}${r}`}else{on(t).forEach((d,h)=>{const p=h===n.selectedAction?`${E}\u25B8${r}`:" ";if(d.kind==="select"){const k=dn(n,t,d.group,d.id);let M;d.mode==="multi"?M=`[${k?`${A}\u2713${r}`:" "}] ${d.shortcut?`[${d.shortcut}] `:""}`:M=`[${k?`${A}\u2713${r}`:d.shortcut??" "}] `;const b=L(M);if(g(x(d.label),Math.max(10,e-2-b)).forEach((O,Q)=>i.push(Q===0?` ${p} ${M}${O}`:`${" ".repeat(4+b)}${O}`)),d.description)for(const O of g(x(d.description),Math.max(10,e-6)))i.push(` ${$}${O}${r}`)}else{const k=d.kind==="freetext"?"r":d.kind==="edit"?"e":"a";g(x(d.label),Math.max(10,e-6)).forEach((M,b)=>i.push(b===0?` ${p} [${k}] ${M}`:` ${M}`))}});for(const d of un(n,t))for(const h of g(`attached: ${Y(t,d.anchor)} \u2014 ${x(d.text)}`,Math.max(10,e-2)))i.push(` ${$}${h}${r}`);n.hint&&i.push(` ${S}${x(n.hint)}${r}`),c=` ${$}n/p next/previous \u2191\u2193/jk actions${tn(t).length>0?" c comment":""} u/d scroll \u2190\u2192/hl pan q close${r}`}const u=Math.max(0,...i.map(L));return{lines:i,footer:c,maxW:e,maxH:Math.max(0,u-Math.max(1,s))}}a(V,"itemLines");function In(n,s,t){if(n.slots[n.currentIndex]===void 0){n.scrollOffset=0,n.hscrollOffset=0,n.hscrollMax=0;return}const e=V(n,s);n.hscrollMax=e.maxH,n.hscrollOffset=Math.max(0,Math.min(n.hscrollOffset,n.hscrollMax)),n.scrollOffset=Math.max(0,Math.min(n.scrollOffset,Math.max(0,e.lines.length-q(t))))}a(In,"clampItemReviewScroll");function Sn(n,s){n.hscrollOffset=Math.max(0,Math.min(n.hscrollMax,n.hscrollOffset+s*cn))}a(Sn,"panItemReview");function En(n,s,t){const e=V(n,s),o=q(t),l=n.scrollOffset,i=e.lines.slice(l,l+o);for(;i.length<o;)i.push("");const f=n.hscrollOffset>0?i.map(u=>ln(u,n.hscrollOffset,s)):i,c=Math.min(s,e.maxW+2);return o<t&&f.push(J(e.footer,_(l,o,e.lines.length),e.maxW+2)),D(f.map(u=>P(u,s)),s,c)}a(En,"renderItemReview");function vn(n,s,t){const e=Math.min(Math.max(20,s-4),120),o=["",...j(`${y(n.manifest.title)} \u2014 Summary`,e,"",0,`${w}${E}`),` ${$}${I(e)}${r}`,""],l=z(n);for(const c of l.slots){const u=n.manifest.slots.find(h=>h.id===c.id),d=u!==void 0&&B(n,u)?`${A}\u2713${r}`:`${S}\u25CB${r}`;o.push(` ${d} ${w}${x(u===void 0?c.kind:C(u))}${r} ${$}${x(F(c))}${r}`)}const i=sn(n);if(!i){o.push("",` ${S}Cannot submit yet.${r}`);for(const c of n.slots.filter(v))B(n,c)||(o.push(` ${$}${c.id??c.kind} is unanswered${r}`),N(c)||o.push(` ${$}${c.id} must be answered in Northlight${r}`))}o.push("",` ${$}${I(e)}${r}`);const f=i?` ${$}enter${r} submit ${$}u/d${r} scroll ${$}q${r} back`:` ${$}u/d${r} scroll ${$}q${r} back`;return K(o,f,n,s,t,e+2)}a(vn,"renderFinal");function q(n){return n>=2?n-1:n}a(q,"bodyRows");function _(n,s,t){if(s<=0||t<=s)return{marks:"",full:""};const e=Math.min(t,n+s),o=`${n>0?"\u25B4":" "}${e<t?"\u25BE":" "}`;return{marks:`${$}${o}${r}`,full:`${$}${o} ${n+1}\u2013${e}/${t}${r}`}}a(_,"scrollBadge");function J(n,s,t){if(s.full==="")return n;const e=a(o=>t-L(n)-L(o)-2,"room");for(const o of[s.full,s.marks])if(e(o)>=2)return`${n}${" ".repeat(e(o))}${o}`;return` ${s.marks} ${n.trimStart()}`}a(J,"pinnedFooter");function K(n,s,t,e,o,l,i){const f=q(o),c=Math.max(0,n.length-f);t.scrollOffset=Math.max(0,Math.min(t.scrollOffset,c)),i!==void 0&&f>0&&(i<t.scrollOffset?t.scrollOffset=i:i>=t.scrollOffset+f&&(t.scrollOffset=Math.min(c,i-f+1)));const u=n.slice(t.scrollOffset,t.scrollOffset+f);for(;u.length<f;)u.push("");return f<o&&u.push(J(s,_(t.scrollOffset,f,n.length),l)),D(u.map(m=>P(m,e)),e,Math.min(e,l))}a(K,"centeredWindow");export{In as clampItemReviewScroll,Sn as panItemReview,vn as renderFinal,$n as renderInputBuffer,En as renderItemReview,kn as renderOverview,yn as verticalCursor,bn as wordLeftIndex,On as wordRightIndex,G as wrappedRowBounds};
1
+ var U=Object.defineProperty;var h=(n,s)=>U(n,"name",{value:s,configurable:!0});import R from"string-width";import{isResponseBearingSlot as A}from"../../../core/human/page-schema.js";import{answerCommentAnchorLabel as X,describePageAnswer as Z}from"../../../core/human/answer.js";import{renderMarkdownBlockAwareLines as nn}from"../../../core/termrender/termrender.js";import{rewriteMarkdownDocLinks as en}from"../../attach/render/markdown-source.js";import{commentAnchors as tn,describeSlot as C,pageComplete as sn,slotActions as on,slotAnswered as B,tableMarkdown as rn,terminalAnswerable as N}from"./slots.js";import{RESET as i,BOLD as b,DIM as u,GREEN as L,YELLOW as I,CYAN as E,REVERSE as T,sanitize as p,singleLine as O,truncate as H,hline as y,wrap as M,centerHorizontal as D,clipLine as P,panLine as cn,visibleWidth as S}from"./ansi.js";const ln=8,W=h((n,s,t)=>nn(en(n),s,t),"mdLines");function z(n){return Z(n.manifest,Object.fromEntries(n.responses),{completedAt:""})}h(z,"pageAnswer");function fn(n,s){return s.id===void 0?void 0:n.slots.find(t=>t.id===s.id)}h(fn,"answerSlot");function F(n){if(n===void 0||n.state==="unanswered")return"unanswered";if(n.raw!==void 0)return"custom response";const s=n.text!==void 0?[n.text.edited?"edited":"accepted"]:n.groups.map(t=>t.picked.length===0?"none":t.picked.map(e=>e.label).join(", "));return n.freetext!==void 0&&s.push(n.freetext),n.comments.length>0&&s.push(`${n.comments.length} comment${n.comments.length===1?"":"s"}`),s.join("; ")||"answered"}h(F,"answerSummary");function Y(n,s){return X(n,s)}h(Y,"commentLabel");function kn(n,s,t){const e=Math.min(Math.max(20,s-4),120),r=Math.max(20,s-4),l=["",...j(O(n.manifest.title),e,"",0,`${b}${E}`)];if(n.manifest.subtitle)for(const c of M(p(n.manifest.subtitle),e))l.push(` ${u}${c}${i}`);if(n.displayMarkdown!==""){l.push("");for(const c of W(n.displayMarkdown,e,r))l.push(` ${c}`)}else n.manifest.dialect==="html"&&l.push("",` ${u}HTML page \u2014 open in Northlight to read this${i}`);const o=n.slots.length>0;o&&l.push(` ${u}${y(e)}${i}`,"");const f=z(n);let $;for(let c=0;c<n.slots.length;c++){const m=n.slots[c],g=m.id===void 0?void 0:n.responses.get(m.id),w=A(m)?B(n,m)?`${L}\u2713${i}`:`${u}\u25CB${i}`:`${u}\xB7${i}`,x=c===n.currentIndex?`${E}\u25B8${i} `:" ";c===n.currentIndex&&($=l.length),l.push(` ${x}${w} ${H(O(C(m)),Math.max(10,s-16))}`),g!==void 0&&l.push(` ${u}${H(O(F(fn(f,m))),Math.max(10,s-10))}${i}`)}if(n.manifest.slots.some(c=>A(c)&&!N(c))){l.push("");for(const c of M("This page must be answered in Northlight. Leaving it here keeps it in your inbox; x on the list cancels it.",e-2))l.push(` ${I}${c}${i}`)}o&&l.push(""),l.push(` ${u}${y(e)}${i}`);const a=!n.manifest.slots.some(A)?` ${u}u/d${i} scroll ${u}q${i} dismiss`:` ${u}enter${i} review ${u}\u2191\u2193/jk${i} navigate ${u}u/d${i} scroll ${u}q${i} close`;return K(l,a,n,s,t,e+2,n.followSelection?$:void 0)}h(kn,"renderOverview");function $n(n,s,t){const e=[...n],r=Math.max(0,Math.min(s,e.length)),l=G(n,t);let o=0;for(let d=0;d<l.length;d++)l[d].start<=r&&(o=d);const f=l.map((d,a)=>{if(a!==o)return e.slice(d.start,d.end).join("");const c=e.slice(d.start,r).join(""),m=r<d.end?e[r]:" ",g=r<d.end?e.slice(r+1,d.end).join(""):"";return`${c}${T}${m}${i}${g}`}),$=l[o];return r===$.end&&R(e.slice($.start,$.end).join(""))>=t&&(f[o]=e.slice($.start,$.end).join(""),f.splice(o+1,0,`${T} ${i}`)),f}h($n,"renderInputBuffer");function bn(n,s){const t=[...n];let e=Math.max(0,Math.min(s,t.length));for(;e>0&&/\s/.test(t[e-1]);)e--;for(;e>0&&!/\s/.test(t[e-1]);)e--;return e}h(bn,"wordLeftIndex");function On(n,s){const t=[...n];let e=Math.max(0,Math.min(s,t.length));for(;e<t.length&&/\s/.test(t[e]);)e++;for(;e<t.length&&!/\s/.test(t[e]);)e++;return e}h(On,"wordRightIndex");function G(n,s){const t=[...n],e=Math.max(1,s),r=[];let l=0,o=0;for(let f=0;f<t.length;f++){const $=t[f];if($===`
2
+ `){r.push({start:l,end:f}),l=f+1,o=0;continue}const d=R($);o+d>e?(r.push({start:l,end:f}),l=f,o=d):o+=d}return r.push({start:l,end:t.length}),r}h(G,"wrappedRowBounds");function yn(n,s,t,e){const r=G(n,e),l=Math.max(0,Math.min(s,[...n].length));let o=0;for(let $=0;$<r.length;$++)r[$].start<=l&&(o=$);const f=r[o+t];return f===void 0?l:Math.min(f.start+(l-r[o].start),f.end)}h(yn,"verticalCursor");function un(n,s){return s.id===void 0?[]:n.responses.get(s.id)?.comments??[]}h(un,"responseComments");function j(n,s,t,e,r){return M(n,Math.max(10,s-e)).map((l,o)=>` ${o===0?t:" ".repeat(e)}${r}${l}${i}`)}h(j,"hangingWrap");function dn(n,s,t,e){if(s.id===void 0)return!1;const r=n.responses.get(s.id);return t==="option"?r?.selectedOptionIds?.includes(e)===!0:t==="card"?r?.selectedCardIds?.includes(e)===!0:t==="row"?r?.selectedRowIds?.includes(e)===!0:r?.selectedColumnIds?.includes(e)===!0}h(dn,"selected");function V(n,s){const t=n.slots[n.currentIndex],e=Math.min(Math.max(20,s-4),120),r=Math.max(20,s-4),l=`[${n.currentIndex+1}/${n.slots.length}]`,o=["",...j(O(n.manifest.title),e,`${b}${E}${l}${i} `,R(l)+2,u),` ${u}${y(e)}${i}`,"",...j(O(C(t)),e,"",0,b)],f=t.config.body;if(typeof f=="string"&&f.length>0){o.push("");for(const a of W(f,e,r))o.push(` ${a}`)}if(N(t)){if(t.kind==="chart"){const a=t.config,c=a.title??`${a.x} vs ${(a.y??[]).map(m=>m.label??m.field).join(", ")}`;o.push("",` ${u}chart \u2014 ${p(a.kind)}: ${p(c)}${i}`)}else if(t.kind==="table"){o.push("");for(const c of W(rn(t.config),e,r))o.push(` ${c}`);const a=t.config.label;a&&o.push(` ${u}${p(a)}${i}`)}else if(t.kind==="text"){const c=(t.id===void 0?void 0:n.responses.get(t.id))?.text??t.config.initialText;o.push("");for(const m of W(c,e,r))o.push(` ${m}`)}}else{o.push("");for(const a of M(`${p(t.kind)} \u2014 must be answered in Northlight; the terminal cannot submit this page`,Math.max(10,e-2)))o.push(` ${I}${a}${i}`);o.push(` ${u}q leaves it in your inbox; x on the list cancels it${i}`)}o.push("",` ${u}${y(e)}${i}`);let $;if(n.inputMode!==null){const a=n.inputMode.kind==="comment"?`Comment on ${Y(t,n.inputMode.anchor)}`:n.inputMode.kind==="text"?"Edit text":"Other response";o.push(` ${b}${a}${i}`);for(const c of $n(n.inputMode.buffer,n.inputMode.cursor,Math.max(10,e-4)))o.push(` ${c}`);$=` ${u}enter save esc cancel${n.editorAvailable?" ^o editor":""}${i}`}else{on(t).forEach((c,m)=>{const g=m===n.selectedAction?`${E}\u25B8${i}`:" ";if(c.kind==="select"){const w=dn(n,t,c.group,c.id);let x;c.mode==="multi"?x=`[${w?`${L}\u2713${i}`:" "}] ${c.shortcut?`[${c.shortcut}] `:""}`:x=`[${w?`${L}\u2713${i}`:c.shortcut??" "}] `;const v=S(x);if(M(p(c.label),Math.max(10,e-2-v)).forEach((k,Q)=>o.push(Q===0?` ${g} ${x}${k}`:`${" ".repeat(4+v)}${k}`)),c.description)for(const k of M(p(c.description),Math.max(10,e-6)))o.push(` ${u}${k}${i}`)}else{const w=c.kind==="freetext"?"r":c.kind==="edit"?"e":"a";M(p(c.label),Math.max(10,e-6)).forEach((x,v)=>o.push(v===0?` ${g} [${w}] ${x}`:` ${x}`))}});for(const c of un(n,t))for(const m of M(`attached: ${Y(t,c.anchor)} \u2014 ${p(c.text)}`,Math.max(10,e-2)))o.push(` ${u}${m}${i}`);n.hint&&o.push(` ${I}${p(n.hint)}${i}`),$=` ${u}n/p next/previous \u2191\u2193/jk actions${tn(t).length>0?" c comment":""} u/d scroll \u2190\u2192/hl pan q close${i}`}const d=Math.max(0,...o.map(S));return{lines:o,footer:$,maxW:e,maxH:Math.max(0,d-Math.max(1,s))}}h(V,"itemLines");function In(n,s,t){if(n.slots[n.currentIndex]===void 0){n.scrollOffset=0,n.hscrollOffset=0,n.hscrollMax=0;return}const e=V(n,s);n.hscrollMax=e.maxH,n.hscrollOffset=Math.max(0,Math.min(n.hscrollOffset,n.hscrollMax)),n.scrollOffset=Math.max(0,Math.min(n.scrollOffset,Math.max(0,e.lines.length-q(t))))}h(In,"clampItemReviewScroll");function En(n,s){n.hscrollOffset=Math.max(0,Math.min(n.hscrollMax,n.hscrollOffset+s*ln))}h(En,"panItemReview");function vn(n,s,t){const e=V(n,s),r=q(t),l=n.scrollOffset,o=e.lines.slice(l,l+r);for(;o.length<r;)o.push("");const f=n.hscrollOffset>0?o.map(d=>cn(d,n.hscrollOffset,s)):o,$=Math.min(s,e.maxW+2);return r<t&&f.push(J(e.footer,_(l,r,e.lines.length),e.maxW+2)),D(f.map(d=>P(d,s)),s,$)}h(vn,"renderItemReview");function An(n,s,t){const e=Math.min(Math.max(20,s-4),120),r=["",...j(`${O(n.manifest.title)} \u2014 Summary`,e,"",0,`${b}${E}`),` ${u}${y(e)}${i}`,""],l=z(n);for(const $ of l.slots){const d=n.manifest.slots.find(m=>m.id===$.id),c=d!==void 0&&B(n,d)?`${L}\u2713${i}`:`${I}\u25CB${i}`;r.push(` ${c} ${b}${p(d===void 0?$.kind:C(d))}${i} ${u}${p(F($))}${i}`)}const o=sn(n);if(!o){r.push("",` ${I}Cannot submit yet.${i}`);for(const $ of n.slots.filter(A))B(n,$)||(r.push(` ${u}${$.id??$.kind} is unanswered${i}`),N($)||r.push(` ${u}${$.id} must be answered in Northlight${i}`))}r.push("",` ${u}${y(e)}${i}`);const f=o?` ${u}enter${i} submit ${u}u/d${i} scroll ${u}q${i} back`:` ${u}u/d${i} scroll ${u}q${i} back`;return K(r,f,n,s,t,e+2)}h(An,"renderFinal");function q(n){return n>=2?n-1:n}h(q,"bodyRows");function _(n,s,t){if(s<=0||t<=s)return{marks:"",full:""};const e=Math.min(t,n+s),r=`${n>0?"\u25B4":" "}${e<t?"\u25BE":" "}`;return{marks:`${u}${r}${i}`,full:`${u}${r} ${n+1}\u2013${e}/${t}${i}`}}h(_,"scrollBadge");function J(n,s,t){if(s.full==="")return n;const e=h(r=>t-S(n)-S(r)-2,"room");for(const r of[s.full,s.marks])if(e(r)>=2)return`${n}${" ".repeat(e(r))}${r}`;return` ${s.marks} ${n.trimStart()}`}h(J,"pinnedFooter");function K(n,s,t,e,r,l,o){const f=q(r),$=Math.max(0,n.length-f);t.scrollOffset=Math.max(0,Math.min(t.scrollOffset,$)),o!==void 0&&f>0&&(o<t.scrollOffset?t.scrollOffset=o:o>=t.scrollOffset+f&&(t.scrollOffset=Math.min($,o-f+1)));const d=n.slice(t.scrollOffset,t.scrollOffset+f);for(;d.length<f;)d.push("");return f<r&&d.push(J(s,_(t.scrollOffset,f,n.length),l)),D(d.map(a=>P(a,e)),e,Math.min(e,l))}h(K,"centeredWindow");export{In as clampItemReviewScroll,En as panItemReview,An as renderFinal,$n as renderInputBuffer,vn as renderItemReview,kn as renderOverview,yn as verticalCursor,bn as wordLeftIndex,On as wordRightIndex,G as wrappedRowBounds};
@@ -0,0 +1,2 @@
1
+ /** Open a URL in the person's browser (best-effort, fire-and-forget). */
2
+ export declare function openBrowser(url: string): void;
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty;var r=(o,e)=>t(o,"name",{value:e,configurable:!0});import{execFile as p}from"node:child_process";function c(o){const e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";p(e,[o],{timeout:5e3},()=>{})}r(c,"openBrowser");export{c as openBrowser};
@@ -42,12 +42,6 @@ export interface SurfaceHost {
42
42
  suspendForChild(): () => void;
43
43
  /** Bring a node's viewer to the front; failures are reported through notice and never reject. */
44
44
  focusNode(nodeId: string): Promise<boolean>;
45
- /** Mount the shared review-file picker and resolve to its chosen path or null on cancellation. */
46
- pickReviewFile(spec: {
47
- candidates: readonly string[];
48
- cwd: string;
49
- title?: string;
50
- }): Promise<string | null>;
51
45
  /** Capability facts resolved once by the host for this session. */
52
46
  readonly capabilities: {
53
47
  /** True when this viewer is attached to a remote session. */
@@ -1 +1 @@
1
- var y=Object.defineProperty;var o=(e,t)=>y(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{randomUUID as q}from"node:crypto";import{defineBranch as w,defineLeaf as s}from"../../core/command.js";import{InputError as l}from"../../core/io.js";import{cliClient as r}from"../api-client.js";function d(){const e=_();return e===void 0||e===""?null:e}o(d,"nodeActor");function x(){const e=d();if(e!==null)return e;throw new l({error:"review_origin_unavailable",message:"a review must be filed from a node with a live or resumable session",field:"CRTR_NODE_ID",next:"Run this from the node whose document context should be forked for the review."})}o(x,"requireOriginNode");function b(e){if(typeof e=="string"&&e.trim()!=="")return e.trim();throw new l({error:"missing_parameter",message:"a non-empty subtitle is required",field:"subtitle",next:"Run `crtr human review new -h` and provide one plain-English sentence explaining the review needed and why it matters."})}o(b,"requireSubtitle");function v(e,t){if(typeof e=="string"&&e.trim()!=="")return e;throw new l({error:"missing_parameter",message:"non-empty comment text is required on stdin",field:"text",next:`Run \`crtr human review comment ${t} -h\` and pipe the comment text on stdin.`})}o(v,"requireCommentText");function h(e,t){if(!(t?.providedParams.has("deliver")??e.deliver!==void 0))return;const i=e.deliver;return i==="wake"||i==="quiet"?i:void 0}o(h,"explicitDeliver");function f(e,t=!0){const{comment:n}=e;return{comment_id:n.comment_id,status:n.status,revision:n.revision,...t?{anchor:n.anchor}:{},author:n.author,text:n.text,changed:e.changed,delivery:e.delivery??null}}o(f,"mutationOutput");function k(e){return{comment_id:e.comment_id,status:e.status,revision:e.revision,anchor:{line:e.anchor.line,end_line:e.anchor.end_line},anchor_state:e.anchor_state,author:e.author,updated_by:e.updated_by,created_at:e.created_at,updated_at:e.updated_at,text_preview:e.text.slice(0,200)}}o(k,"commentPreview");const C=s({name:"new",description:"queue a document review with a collaborating companion agent",whenToUse:"filing a live document for a person to review alongside a companion agent.",help:{name:"human review new",summary:"queue a live document review and return its ticket handle immediately",guide:"The person reviews the document in the attach viewer alongside a collaborating companion agent. The daemon reads the document as you and snapshots its current revision into the review. When the person submits, their edits are saved as a new revision of the document and the approval is pushed to your inbox. If the document gets a new revision while the review is open, the save is refused as `stale_revision` and the review stays open; do not edit a document while it is under review.",params:[{kind:"positional",name:"document",type:"string",required:!0,constraint:"The document to review: a name, `<owner>/<name>` or id, `[[ ]]` optional. It must have one head; merge several heads first."},{kind:"flag",name:"subtitle",type:"string",required:!0,constraint:"One plain-English sentence stating the review needed and why it matters."}],output:[{name:"review_id",type:"string",required:!0,constraint:"Daemon-owned review id for the document, comments, and companion."},{name:"document",type:"string",required:!0,constraint:"The reviewed document's `<owner>/<name>`."},{name:"review_dir",type:"string",required:!0,constraint:"Directory containing the review's document.md snapshot and immutable result.json."},{name:"result_path",type:"string",required:!0,constraint:"The immutable terminal result path: <review_dir>/result.json."},{name:"follow_up",type:"string",required:!0,constraint:"The review remains live for the person and companion; approval is delivered to the origin inbox."}],outputKind:"object",effects:["Records your read of the document and creates the durable review, its `document.md` snapshot, and the companion session fork.","On submit, a changed snapshot becomes a new revision authored by the person; this command does not submit an approval."]},run:o(async e=>{const t=b(e.subtitle),n=await r().createReview({origin_kind:"ticket",origin_node_id:x(),document:e.document,idempotency_key:q(),subtitle:t});return{review_id:n.review_id,document:n.document??null,review_dir:n.review_dir,result_path:`${n.review_dir}/result.json`,follow_up:"The review is live for the person in the attach viewer with its companion agent. Approval is pushed to the origin inbox when submitted."}},"run")}),R=s({name:"create",description:"add an anchored review comment",whenToUse:"recording a new finding or instruction against one or more document lines.",help:{name:"human review comment create",summary:"add a daemon-owned comment anchored to document lines",guide:"Without --review, the daemon targets the calling companion node's open review. Comment text is supplied on stdin; agent comments use whole-line anchors.",params:[{kind:"flag",name:"review",type:"string",required:!1,constraint:"Review id. Omit only to target the calling companion node's open review."},{kind:"flag",name:"line",type:"int",required:!0,constraint:"First 1-based document line in the anchor."},{kind:"flag",name:"end-line",type:"int",required:!1,constraint:"Last 1-based document line in the anchor. Default: --line."},{kind:"flag",name:"deliver",type:"enum",choices:["wake","quiet"],required:!1,constraint:"wake interrupts the companion now; quiet leaves a durable message for its next turn. Default: wake unless the caller is the companion."},{kind:"stdin",name:"text",required:!0,constraint:"Non-empty comment text."}],output:[{name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id."},{name:"status",type:"string",required:!0,constraint:"Current comment status: open, resolved, or deleted."},{name:"revision",type:"integer",required:!0,constraint:"Current per-comment revision."},{name:"author",type:"object",required:!0,constraint:"Daemon-derived human or node attribution."},{name:"text",type:"string",required:!0,constraint:"Stored full comment text."},{name:"changed",type:"boolean",required:!0,constraint:"Whether this invocation changed the comment."},{name:"delivery",type:"object | null",required:!0,constraint:"Best-effort companion notification outcome, or null when no notification was needed."}],outputKind:"object",effects:["Creates a daemon-owned comment and audit event, then best-effort notifies the companion."]},run:o(async(e,t)=>{const n=e.review,i=e.line,a=e.endLine,u=await r().createReviewComment(n,{text:v(e.text,"create"),anchor:{line:i,end_line:a??i},actor_node_id:d(),...h(e,t)===void 0?{}:{deliver:h(e,t)}});return f(u,!1)},"run")}),j=s({name:"list",description:"list review comments in render order",whenToUse:"choosing a comment to inspect or checking the current anchored comment set.",help:{name:"human review comment list",summary:"list render-ordered review comments with short text previews",guide:"Without --review, the daemon targets the calling companion node's open review. Use show for full comment text and audit history.",params:[{kind:"flag",name:"review",type:"string",required:!1,constraint:"Review id. Omit only to target the calling companion node's open review."},{kind:"flag",name:"status",type:"enum",choices:["open","resolved","deleted","all"],required:!1,default:"open",constraint:"Comment statuses to include. Default: open."}],output:[{name:"review_id",type:"string",required:!0,constraint:"Resolved daemon-owned review id."},{name:"comments",type:"object[]",required:!0,constraint:"Comments in render order with status, anchor, attribution, and a 200-character text_preview."},{name:"follow_up",type:"string",required:!0,constraint:"Points to show for full text and per-comment history."}],outputKind:"object",effects:["None. Read-only."]},run:o(async e=>{const t=e.review,n=e.status,i=await r().listReviewComments(t,t===void 0?{status:n,actor_node_id:d()}:{status:n});return{review_id:i.review_id,comments:i.comments.map(k),follow_up:"Use `crtr human review comment show <comment_id>` for full comment text and event history."}},"run")}),T=s({name:"show",description:"read one comment and its event history",whenToUse:"you need a comment's full text or complete per-comment audit history.",help:{name:"human review comment show",summary:"read one full review comment and its event history",params:[{kind:"positional",name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id from comment list."}],output:[{name:"comment",type:"object",required:!0,constraint:"Full daemon-owned comment projection, including text and attribution."},{name:"events",type:"object[]",required:!0,constraint:"Complete append-only event history for this comment, in event sequence order."}],outputKind:"object",effects:["None. Read-only."]},run:o(async e=>{const t=await r().getReviewComment(e.comment_id);return{comment:t.comment,events:t.events}},"run")});function c(e){const t=e==="edit";return s({name:e,description:e==="edit"?"replace a comment's text":`${e} one review comment`,whenToUse:e==="edit"?"changing the stored text of an existing open or resolved comment.":`${e==="resolve"?"marking a comment addressed":e==="reopen"?"returning a resolved comment to open":"retaining a terminal comment tombstone while removing it from active work"}.`,help:{name:`human review comment ${e}`,summary:e==="edit"?"replace a review comment's full text":`${e} a review comment`,guide:t?"Replacement comment text is supplied on stdin.":void 0,params:[{kind:"positional",name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id from comment list."},{kind:"flag",name:"deliver",type:"enum",choices:["wake","quiet"],required:!1,constraint:`wake interrupts the companion now; quiet leaves a durable message for its next turn. Default: ${e==="resolve"||e==="delete"?"quiet":"wake"} unless the caller is the companion.`},...t?[{kind:"stdin",name:"text",required:!0,constraint:"Non-empty replacement comment text."}]:[]],output:[{name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id."},{name:"status",type:"string",required:!0,constraint:"Current comment status: open, resolved, or deleted."},{name:"revision",type:"integer",required:!0,constraint:"Current per-comment revision."},{name:"anchor",type:"object",required:!0,constraint:"Current whole-line anchor."},{name:"author",type:"object",required:!0,constraint:"Daemon-derived human or node attribution."},{name:"text",type:"string",required:!0,constraint:"Stored full comment text."},{name:"changed",type:"boolean",required:!0,constraint:"Whether this invocation changed the comment."},{name:"delivery",type:"object | null",required:!0,constraint:"Best-effort companion notification outcome, or null when no notification was needed."}],outputKind:"object",effects:["Mutates the daemon-owned comment and appends an audit event when its state changes; notification is best-effort."]},run:o(async(n,i)=>{const a=n.comment_id,u=d(),p=h(n,i),m={actor_node_id:u,...p===void 0?{}:{deliver:p}},g=e==="edit"?await r().editReviewComment(a,{...m,text:v(n.text,"edit")}):e==="resolve"?await r().resolveReviewComment(a,m):e==="reopen"?await r().reopenReviewComment(a,m):await r().deleteReviewComment(a,m);return f(g)},"run")})}o(c,"commentMutationLeaf");const D=w({name:"comment",description:"create, inspect, and update daemon-owned review comments",whenToUse:"working with the anchored comments on a document review.",help:{name:"human review comment",summary:"operate on daemon-owned anchored review comments",model:"create and list address a review; all other verbs address one comment id. Create, edit, and reopen default to wake, while resolve and delete default to quiet."},children:[R,j,T,c("edit"),c("resolve"),c("reopen"),c("delete")]}),K=w({name:"review",description:"queue a document review or operate on its anchored comments",whenToUse:"a person and companion agent should collaborate on a live document review, or you need to work with that review's anchored comments.",help:{name:"human review",summary:"queue live document reviews and manage their daemon-owned comments",model:"new creates the durable review, ticket, and companion. comment contains the operations on the review's shared anchored comments."},children:[C,D]});export{K as humanReviewBranch};
1
+ var y=Object.defineProperty;var o=(e,t)=>y(e,"name",{value:t,configurable:!0});import{envNodeId as q}from"../../shared/env.js";import{randomUUID as x}from"node:crypto";import{defineBranch as p,defineLeaf as a}from"../../core/command.js";import{InputError as u}from"../../core/io.js";import{cliClient as i}from"../api-client.js";function d(){const e=q();return e===void 0||e===""?null:e}o(d,"nodeActor");function _(){const e=d();if(e!==null)return e;throw new u({error:"review_origin_unavailable",message:"a review must be filed from a node with a live or resumable session",field:"CRTR_NODE_ID",next:"Run this from the node whose document context should be forked for the review."})}o(_,"requireOriginNode");function k(e){if(typeof e=="string"&&e.trim()!=="")return e.trim();throw new u({error:"missing_parameter",message:"a non-empty subtitle is required",field:"subtitle",next:"Run `crtr human review new -h` and provide one plain-English sentence explaining the review needed and why it matters."})}o(k,"requireSubtitle");function w(e,t){if(typeof e=="string"&&e.trim()!=="")return e;throw new u({error:"missing_parameter",message:"non-empty comment text is required on stdin",field:"text",next:`Run \`crtr human review comment ${t} -h\` and pipe the comment text on stdin.`})}o(w,"requireCommentText");function l(e,t){if(!(t?.providedParams.has("deliver")??e.deliver!==void 0))return;const r=e.deliver;return r==="wake"||r==="quiet"?r:void 0}o(l,"explicitDeliver");function f(e,t=!0){const{comment:n}=e;return{comment_id:n.comment_id,status:n.status,revision:n.revision,...t?{anchor:n.anchor}:{},author:n.author,text:n.text,changed:e.changed,delivery:e.delivery??null}}o(f,"mutationOutput");function b(e){return{comment_id:e.comment_id,status:e.status,revision:e.revision,quote:e.anchor.quote,detached:e.location===null,author:e.author,updated_by:e.updated_by,created_at:e.created_at,updated_at:e.updated_at,text_preview:e.text.slice(0,200)}}o(b,"commentPreview");const R=a({name:"new",description:"queue a document review with a collaborating companion agent",whenToUse:"filing a live document for a person to review alongside a companion agent.",help:{name:"human review new",summary:"queue a live document review and return its ticket handle immediately",guide:"The person reviews the document in the browser at the canvas host, with a companion agent that edits the document itself while they comment; there is no file or snapshot to review. Needs a cloud runtime with a canvas host, otherwise it fails with `no_canvas_host`. When the person approves, the approval, with the comments and their quotes, is pushed to your inbox.",params:[{kind:"positional",name:"document",type:"string",required:!0,constraint:"The document to review: a name, `<owner>/<name>` or id, `[[ ]]` optional. It must have one head; merge several heads first."},{kind:"flag",name:"subtitle",type:"string",required:!0,constraint:"One plain-English sentence stating the review needed and why it matters."}],output:[{name:"review_id",type:"string",required:!0,constraint:"Daemon-owned review id for the document, comments, and companion."},{name:"document",type:"string",required:!0,constraint:"The reviewed document's `<owner>/<name>`."},{name:"result_path",type:"string",required:!0,constraint:"The immutable terminal result path: <review_dir>/result.json."}],outputKind:"object",effects:["Records your read of the document as the review base and creates the durable review and the companion session fork.","This command does not submit an approval."]},run:o(async e=>{const t=k(e.subtitle),n=await i().createReview({origin_kind:"ticket",origin_node_id:_(),document:e.document,idempotency_key:x(),subtitle:t});return{review_id:n.review_id,document:n.document??null,result_path:`${n.review_dir}/result.json`}},"run")}),C=a({name:"create",description:"add an anchored review comment",whenToUse:"recording a new finding or instruction against a passage of the document.",help:{name:"human review comment create",summary:"add a daemon-owned comment anchored to quoted document text",guide:"Without --review, the daemon targets the calling companion node's open review. Comment text is supplied on stdin; the quote is matched against the document's rendered text, whitespace collapsed.",params:[{kind:"flag",name:"review",type:"string",required:!1,constraint:"Review id. Omit only to target the calling companion node's open review."},{kind:"flag",name:"quote",type:"string",required:!0,constraint:"Text to anchor to; it must occur in the current rendered document. When it occurs more than once, the error lists each occurrence with its context: pass --prefix or --suffix."},{kind:"flag",name:"prefix",type:"string",required:!1,constraint:"Up to 32 characters immediately before the quote."},{kind:"flag",name:"suffix",type:"string",required:!1,constraint:"Up to 32 characters immediately after the quote."},{kind:"flag",name:"deliver",type:"enum",choices:["wake","quiet"],required:!1,constraint:"wake interrupts the companion now; quiet leaves a durable message for its next turn. Default: wake unless the caller is the companion."},{kind:"stdin",name:"text",required:!0,constraint:"Non-empty comment text."}],output:[{name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id."},{name:"status",type:"string",required:!0,constraint:"Current comment status: open, resolved, or deleted."},{name:"revision",type:"integer",required:!0,constraint:"Current per-comment revision."},{name:"author",type:"object",required:!0,constraint:"Daemon-derived human or node attribution."},{name:"text",type:"string",required:!0,constraint:"Stored full comment text."},{name:"changed",type:"boolean",required:!0,constraint:"Whether this invocation changed the comment."},{name:"delivery",type:"object | null",required:!0,constraint:"Best-effort companion notification outcome, or null when no notification was needed."}],outputKind:"object",effects:["Creates a daemon-owned comment and audit event, then best-effort notifies the companion."]},run:o(async(e,t)=>{const n=e.review,r=await i().createReviewComment(n,{text:w(e.text,"create"),anchor:{quote:e.quote,...typeof e.prefix=="string"?{prefix:e.prefix}:{},...typeof e.suffix=="string"?{suffix:e.suffix}:{}},actor_node_id:d(),...l(e,t)===void 0?{}:{deliver:l(e,t)}});return f(r,!1)},"run")}),j=a({name:"list",description:"list review comments in render order",whenToUse:"choosing a comment to inspect or checking the current anchored comment set.",help:{name:"human review comment list",summary:"list render-ordered review comments with short text previews",guide:"Without --review, the daemon targets the calling companion node's open review. Use show for full comment text and audit history.",params:[{kind:"flag",name:"review",type:"string",required:!1,constraint:"Review id. Omit only to target the calling companion node's open review."},{kind:"flag",name:"status",type:"enum",choices:["open","resolved","deleted","all"],required:!1,default:"open",constraint:"Comment statuses to include. Default: open."}],output:[{name:"review_id",type:"string",required:!0,constraint:"Resolved daemon-owned review id."},{name:"comments",type:"object[]",required:!0,constraint:"Comments in render order with status, anchor, attribution, and a 200-character text_preview."},{name:"follow_up",type:"string",required:!0,constraint:"Points to show for full text and per-comment history."}],outputKind:"object",effects:["None. Read-only."]},run:o(async e=>{const t=e.review,n=e.status,r=await i().listReviewComments(t,t===void 0?{status:n,actor_node_id:d()}:{status:n});return{review_id:r.review_id,comments:r.comments.map(b),follow_up:"Use `crtr human review comment show <comment_id>` for full comment text and event history."}},"run")}),T=a({name:"show",description:"read one comment and its event history",whenToUse:"you need a comment's full text or complete per-comment audit history.",help:{name:"human review comment show",summary:"read one full review comment and its event history",params:[{kind:"positional",name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id from comment list."}],output:[{name:"comment",type:"object",required:!0,constraint:"Full daemon-owned comment projection, including text and attribution."},{name:"events",type:"object[]",required:!0,constraint:"Complete append-only event history for this comment, in event sequence order."}],outputKind:"object",effects:["None. Read-only."]},run:o(async e=>{const t=await i().getReviewComment(e.comment_id);return{comment:t.comment,events:t.events}},"run")});function c(e){const t=e==="edit";return a({name:e,description:e==="edit"?"replace a comment's text":`${e} one review comment`,whenToUse:e==="edit"?"changing the stored text of an existing open or resolved comment.":`${e==="resolve"?"marking a comment addressed":e==="reopen"?"returning a resolved comment to open":"retaining a terminal comment tombstone while removing it from active work"}.`,help:{name:`human review comment ${e}`,summary:e==="edit"?"replace a review comment's full text":`${e} a review comment`,guide:t?"Replacement comment text is supplied on stdin.":void 0,params:[{kind:"positional",name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id from comment list."},{kind:"flag",name:"deliver",type:"enum",choices:["wake","quiet"],required:!1,constraint:`wake interrupts the companion now; quiet leaves a durable message for its next turn. Default: ${e==="resolve"||e==="delete"?"quiet":"wake"} unless the caller is the companion.`},...t?[{kind:"stdin",name:"text",required:!0,constraint:"Non-empty replacement comment text."}]:[]],output:[{name:"comment_id",type:"string",required:!0,constraint:"Daemon-owned comment id."},{name:"status",type:"string",required:!0,constraint:"Current comment status: open, resolved, or deleted."},{name:"revision",type:"integer",required:!0,constraint:"Current per-comment revision."},{name:"anchor",type:"object",required:!0,constraint:"Quoted text anchor."},{name:"author",type:"object",required:!0,constraint:"Daemon-derived human or node attribution."},{name:"text",type:"string",required:!0,constraint:"Stored full comment text."},{name:"changed",type:"boolean",required:!0,constraint:"Whether this invocation changed the comment."},{name:"delivery",type:"object | null",required:!0,constraint:"Best-effort companion notification outcome, or null when no notification was needed."}],outputKind:"object",effects:["Mutates the daemon-owned comment and appends an audit event when its state changes; notification is best-effort."]},run:o(async(n,r)=>{const s=n.comment_id,v=d(),h=l(n,r),m={actor_node_id:v,...h===void 0?{}:{deliver:h}},g=e==="edit"?await i().editReviewComment(s,{...m,text:w(n.text,"edit")}):e==="resolve"?await i().resolveReviewComment(s,m):e==="reopen"?await i().reopenReviewComment(s,m):await i().deleteReviewComment(s,m);return f(g)},"run")})}o(c,"commentMutationLeaf");const D=p({name:"comment",description:"create, inspect, and update daemon-owned review comments",whenToUse:"working with the anchored comments on a document review.",help:{name:"human review comment",summary:"operate on daemon-owned anchored review comments",model:"create and list address a review; all other verbs address one comment id. Create, edit, and reopen default to wake, while resolve and delete default to quiet."},children:[C,j,T,c("edit"),c("resolve"),c("reopen"),c("delete")]}),K=p({name:"review",description:"queue a document review or operate on its anchored comments",whenToUse:"a person and companion agent should collaborate on a live document review, or you need to work with that review's anchored comments.",help:{name:"human review",summary:"queue live document reviews and manage their daemon-owned comments",model:"new creates the durable review, ticket, and companion. comment contains the operations on the review's shared anchored comments."},children:[R,D]});export{K as humanReviewBranch};
@@ -1,7 +1,3 @@
1
- var p=Object.defineProperty;var o=(e,n)=>p(e,"name",{value:n,configurable:!0});import{envNodeId as m,envProfileId as g}from"../../shared/env.js";import{defineBranch as y,defineLeaf as u}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{requireScope as _}from"../../core/errors.js";import{parseWhen as b}from"../../core/wake.js";import{cliClient as h,getNodeOrNull as x,rethrowAsCliError as f}from"../api-client.js";import{shellQuote as v}from"../surface/node/placement.js";function k(){const e=m();if(e===void 0||e==="")throw new i({error:"no_node",message:"no node to anchor a deadline cron (CRTR_NODE_ID unset)",next:"Run from inside a node."});return e}o(k,"armerId");function I(e,n){return n!==void 0&&n.trim()!==""?{tz:n,now:e}:{now:e}}o(I,"parseOpts");function T(e){const n={wake_in_past:'Pick a future instant \u2014 a positive duration ("5m","2h") or an ISO time later than now.',bad_when:'Use a duration ("5m","1h30m"), a zoned ISO ("2026-06-07T09:00:00Z"), or a bare ISO ("2026-06-07T09:00").',bad_cadence:'Use a duration ("6h"), a 5-field cron ("0 9 * * *"), or an @alias ("@daily").',unknown_zone:'Pass --tz with an IANA zone name (e.g. "America/New_York").',cadence_too_fast:'Use a cadence of at least 60s (e.g. "1m","5m","1h").'};throw new i({error:e.code,message:e.message,received:e.received,next:n[e.code]??"Fix the time value and retry."})}o(T,"throwTimeError");function $(e,n){const t=new Date(e).getTime()-n.getTime();if(!Number.isFinite(t)||t<=0)return"";const r=Math.round(t/6e4);if(r<60)return` (~${r}m)`;const a=Math.round(t/36e5);return a<48?` (~${a}h)`:` (~${Math.round(t/864e5)}d)`}o($,"etaHint");function D(e,n){let t="CRTR_DEADLINE",r=0;const a=new Set(e.split(`
2
- `));for(;a.has(t);)t=`CRTR_DEADLINE_${++r}`;return`crtr cron cancel "$CRTR_CRON_ID"
3
- crtr node message send --to ${v(n)} --tier urgent <<'${t}'
4
- ${e}
5
- ${t}`}o(D,"deadlineHeredoc");const R=u({name:"deadline",description:"race this node\u2019s next wake against one urgent deadline cron",whenToUse:"you are waiting on an event nothing can push for, so a self-scheduled deadline must settle the wait",help:{name:"node wait deadline",summary:"arm one cancel-on-wake deadline cron for this node",params:[{kind:"stdin",name:"body",required:!0,constraint:"Policy delivered urgently to this node if the deadline fires first."},{kind:"flag",name:"until",type:"string",required:!0,constraint:"Future duration, zoned ISO timestamp, or bare ISO timestamp interpreted in --tz or host-local time."},{kind:"flag",name:"tz",type:"string",required:!1,constraint:"IANA timezone for a bare ISO --until value."}],output:[{name:"id",type:"string",required:!0,constraint:"The armed cron id."},{name:"name",type:"string",required:!0,constraint:"The cron label."},{name:"fires_at",type:"string",required:!0,constraint:"Absolute UTC deadline."},{name:"guidance",type:"string",required:!0,constraint:"How to inspect the cron and dorm."}],outputKind:"object",effects:["Arms one anchored cancel-on-wake cron. Any wake of this node cancels it; otherwise it urgently sends the body to this node at the deadline.","Re-arming replaces this node\u2019s pending deadline rather than stacking a second."]},run:o(async e=>{_("crtr:schedule","crtr node wait deadline");const n=k(),t=typeof e.body=="string"?e.body.trim():"";if(t==="")throw new i({error:"empty_body",message:"a deadline body is required",field:"body",next:"Pass the timeout policy on stdin."});const r=typeof e.until=="string"?e.until.trim():"";if(r==="")throw new i({error:"missing_until",message:"--until is required",field:"until",next:"Pass a future duration or timestamp."});const a=typeof e.tz=="string"&&e.tz.trim()!==""?e.tz:void 0,c=new Date,s=b(r,I(c,a));"error"in s&&T(s.error);const l=g(),d=await h().armCron({name:`deadline:${n}`,command:D(t,n),fire_at:s.fireAt,recur:null,tz:a??null,created_by:n,cwd:process.cwd(),profile:l!==void 0&&l!==""?l:null,scope:"profile",on_output:"on-failure",sink:null,tier:"normal",expires_at:null,anchor_node:n,cancel_on_wake:!0,run_timeout_s:300,overlap:"skip"}).catch(f),w=`Deadline cron armed for ${d.fire_at}${$(d.fire_at,c)}. End your turn to dorm; any earlier wake cancels it. Inspect pending schedules with \`crtr cron list\`.`;return{id:d.cron_id,name:d.name,fires_at:d.fire_at,guidance:w}},"run"),render:o(e=>`Deadline cron armed \u2014 ${e.name} (${e.id}), fires ${e.fires_at}.
1
+ var p=Object.defineProperty;var r=(e,n)=>p(e,"name",{value:n,configurable:!0});import{envNodeId as m,envProfileId as y}from"../../shared/env.js";import{defineBranch as g,defineLeaf as u}from"../../core/command.js";import{InputError as a}from"../../core/io.js";import{requireScope as _}from"../../core/errors.js";import{parseWhen as b}from"../../core/wake.js";import{cliClient as h,getNodeOrNull as x,rethrowAsCliError as f}from"../api-client.js";function v(){const e=m();if(e===void 0||e==="")throw new a({error:"no_node",message:"no node to anchor a deadline cron (CRTR_NODE_ID unset)",next:"Run from inside a node."});return e}r(v,"armerId");function k(e,n){return n!==void 0&&n.trim()!==""?{tz:n,now:e}:{now:e}}r(k,"parseOpts");function I(e){const n={wake_in_past:'Pick a future instant \u2014 a positive duration ("5m","2h") or an ISO time later than now.',bad_when:'Use a duration ("5m","1h30m"), a zoned ISO ("2026-06-07T09:00:00Z"), or a bare ISO ("2026-06-07T09:00").',bad_cadence:'Use a duration ("6h"), a 5-field cron ("0 9 * * *"), or an @alias ("@daily").',unknown_zone:'Pass --tz with an IANA zone name (e.g. "America/New_York").',cadence_too_fast:'Use a cadence of at least 60s (e.g. "1m","5m","1h").'};throw new a({error:e.code,message:e.message,received:e.received,next:n[e.code]??"Fix the time value and retry."})}r(I,"throwTimeError");function T(e,n){const t=new Date(e).getTime()-n.getTime();if(!Number.isFinite(t)||t<=0)return"";const o=Math.round(t/6e4);if(o<60)return` (~${o}m)`;const i=Math.round(t/36e5);return i<48?` (~${i}h)`:` (~${Math.round(t/864e5)}d)`}r(T,"etaHint");const q=u({name:"deadline",description:"race this node\u2019s next wake against one urgent deadline cron",whenToUse:"you are waiting on an event nothing can push for, so a self-scheduled deadline must settle the wait",help:{name:"node wait deadline",summary:"arm one cancel-on-wake deadline cron for this node",params:[{kind:"stdin",name:"body",required:!0,constraint:"Policy delivered urgently to this node if the deadline fires first."},{kind:"flag",name:"until",type:"string",required:!0,constraint:"Future duration, zoned ISO timestamp, or bare ISO timestamp interpreted in --tz or host-local time."},{kind:"flag",name:"tz",type:"string",required:!1,constraint:"IANA timezone for a bare ISO --until value."}],output:[{name:"id",type:"string",required:!0,constraint:"The armed cron id."},{name:"name",type:"string",required:!0,constraint:"The cron label."},{name:"fires_at",type:"string",required:!0,constraint:"Absolute UTC deadline."},{name:"guidance",type:"string",required:!0,constraint:"How to inspect the cron and dorm."}],outputKind:"object",effects:["Arms one anchored cancel-on-wake cron. Any wake of this node cancels it; otherwise it urgently sends the body to this node at the deadline.","Re-arming replaces this node\u2019s pending deadline rather than stacking a second."]},run:r(async e=>{_("crtr:schedule","crtr node wait deadline");const n=v(),t=typeof e.body=="string"?e.body.trim():"";if(t==="")throw new a({error:"empty_body",message:"a deadline body is required",field:"body",next:"Pass the timeout policy on stdin."});const o=typeof e.until=="string"?e.until.trim():"";if(o==="")throw new a({error:"missing_until",message:"--until is required",field:"until",next:"Pass a future duration or timestamp."});const i=typeof e.tz=="string"&&e.tz.trim()!==""?e.tz:void 0,c=new Date,s=b(o,k(c,i));"error"in s&&I(s.error);const l=y(),d=await h().armCron({name:`deadline:${n}`,command:"",deadline_body:t,fire_at:s.fireAt,recur:null,tz:i??null,created_by:n,cwd:process.cwd(),profile:l!==void 0&&l!==""?l:null,scope:"profile",on_output:"on-failure",sink:null,tier:"normal",expires_at:null,anchor_node:n,cancel_on_wake:!0,run_timeout_s:300,overlap:"skip"}).catch(f),w=`Deadline cron armed for ${d.fire_at}${T(d.fire_at,c)}. End your turn to dorm; any earlier wake cancels it. Inspect pending schedules with \`crtr cron list\`.`;return{id:d.cron_id,name:d.name,fires_at:d.fire_at,guidance:w}},"run"),render:r(e=>`Deadline cron armed \u2014 ${e.name} (${e.id}), fires ${e.fires_at}.
6
2
 
7
- ${e.guidance}`,"render")}),N=u({name:"controller",description:"wait durably for a named controller message",whenToUse:"you are a terminal node blocked on one specific live parent or controller and have no managed-child subscription whose report will wake you",help:{name:"node wait controller",summary:"declare that your next stop may dorm only until one live controller delivers an inbox message",params:[{kind:"positional",name:"controller",type:"string",required:!0,constraint:"Live node id expected to send the message. It may be your parent or another named controller, but cannot be yourself."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The terminal node that declared the wait."}],outputKind:"object",effects:["Durably records the controller on this node. The stop guard permits dormancy only while that controller remains active or idle; its next inbox delivery clears the record before the delivery wakes this node."]},run:o(async e=>{const n=m();if(n===void 0||n==="")throw new i({error:"no_node",message:"no node to wait (CRTR_NODE_ID unset)",next:"Run from inside the terminal node that is blocked."});const t=await x(n);if(t===null)throw new i({error:"not_found",message:`no node: ${n}`,next:"Run from a live canvas node."});if(t.lifecycle!=="terminal")throw new i({error:"resident_node",message:`node ${n} is resident and may already dorm on its inbox`,next:"Use this only from a terminal node that needs the stop guard to recognize a controller dependency."});const r=String(e.controller).trim();if(r===n)throw new i({error:"self_controller",message:"a node cannot wait for its own message",field:"controller",next:"Name the parent or external controller expected to send the message."});return await h().waitNode(n,{controller:r}).catch(a=>f(a)),{node_id:n}},"run"),render:o(()=>"Waiting for the controller. End your turn to dorm; its next message wakes you and clears this wait.","render")}),P=y({name:"wait",description:"declare a durable controller or deadline wait",whenToUse:"a terminal node must dorm for one named controller, or race its inbox against a self-scheduled deadline",help:{name:"node wait",summary:"declare durable wait state; choose the event that settles it",model:"Both waits belong to the calling terminal node and settle on one future event. A controller wait records an existing node as the wake source; a deadline wait arms an urgent one-shot cron that races any earlier inbox delivery and is canceled when that delivery wins."},children:[N,R]});export{P as nodeWaitBranch};
3
+ ${e.guidance}`,"render")}),z=u({name:"controller",description:"wait durably for a named controller message",whenToUse:"you are a terminal node blocked on one specific live parent or controller and have no managed-child subscription whose report will wake you",help:{name:"node wait controller",summary:"declare that your next stop may dorm only until one live controller delivers an inbox message",params:[{kind:"positional",name:"controller",type:"string",required:!0,constraint:"Live node id expected to send the message. It may be your parent or another named controller, but cannot be yourself."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The terminal node that declared the wait."}],outputKind:"object",effects:["Durably records the controller on this node. The stop guard permits dormancy only while that controller remains active or idle; its next inbox delivery clears the record before the delivery wakes this node."]},run:r(async e=>{const n=m();if(n===void 0||n==="")throw new a({error:"no_node",message:"no node to wait (CRTR_NODE_ID unset)",next:"Run from inside the terminal node that is blocked."});const t=await x(n);if(t===null)throw new a({error:"not_found",message:`no node: ${n}`,next:"Run from a live canvas node."});if(t.lifecycle!=="terminal")throw new a({error:"resident_node",message:`node ${n} is resident and may already dorm on its inbox`,next:"Use this only from a terminal node that needs the stop guard to recognize a controller dependency."});const o=String(e.controller).trim();if(o===n)throw new a({error:"self_controller",message:"a node cannot wait for its own message",field:"controller",next:"Name the parent or external controller expected to send the message."});return await h().waitNode(n,{controller:o}).catch(i=>f(i)),{node_id:n}},"run"),render:r(()=>"Waiting for the controller. End your turn to dorm; its next message wakes you and clears this wait.","render")}),U=g({name:"wait",description:"declare a durable controller or deadline wait",whenToUse:"a terminal node must dorm for one named controller, or race its inbox against a self-scheduled deadline",help:{name:"node wait",summary:"declare durable wait state; choose the event that settles it",model:"Both waits belong to the calling terminal node and settle on one future event. A controller wait records an existing node as the wake source; a deadline wait arms an urgent one-shot cron that races any earlier inbox delivery and is canceled when that delivery wins."},children:[z,q]});export{U as nodeWaitBranch};
@@ -1 +1 @@
1
- var z=Object.defineProperty;var l=(u,e)=>z(u,"name",{value:e,configurable:!0});import{Input as A,matchesKey as s,truncateToWidth as b,visibleWidth as w}from"@earendil-works/pi-tui";import{formatGesture as C,matchesPiTuiInput as N}from"../../../../core/keybindings/index.js";import{writeClipboardTextEverywhere as T}from"../../../../core/clipboard-text.js";import{runTuiPage as O}from"../../../../core/tui/page-host.js";import{PAGE_CHROME_ROWS as F,columns as x,framed as W,pageFrame as L,theme as h}from"../../../../core/tui/panel.js";import{editBufferInEditor as G}from"../../../../clients/inbox/review/roundtrip.js";import{PLANNED_EVENTS as m}from"../resolve.js";import{moveDoc as H,readBody as k,readOnlyReason as I,toggleUnlisted as P,writeBody as B,writePreview as U,writeRules as v}from"./actions.js";import{axesOf as j,cycleAxis as $,cycleFacet as V,facetsOf as K,payloadRowOf as X,railEnter as D,railRowKey as M,railRowsOf as J,renderRail as Q,setTypedAxis as Y,typedAxisValue as Z}from"./rail-panel.js";import{ContextDetailPanel as ee}from"./detail-panel.js";import{ContextDocsPanel as te,buildRows as ie}from"./docs-panel.js";import{NO_FILTERS as se}from"./list-view.js";import{DELIVER_LEVELS as g,PlanSet as ne,describeRule as re,plural as S}from"./model.js";function oe(u){return u!=="boot"&&u!=="workspace-open"}l(oe,"needsMatch");const le={boot:"","workspace-open":"","file-read":"absolute path glob, or ./ for this document\u2019s own directory","document-read":"document name glob",command:"command-path glob, e.g. node new","pre-command":"command-path glob, e.g. node new","slash-command":"slash command name glob"},a=26,de=86,he=112,q=6,ce=48,ue=100,ae=.45;function fe(u){const e=Math.max(1,u-a-q);return Math.max(ce,Math.min(ue,Math.floor(e*ae)))}l(fe,"docsWidthFor");class pe{static{l(this,"ContextAdminShell")}tui;terminalRows;bindings;suspendForChild;profiles;snapshot;plans;zone="rail";railIndex=0;filters=se;rows=[];searching=!1;docs;detail=new ee;modal;notice;busy;edited=new Set;bodies=new Map;_focused=!1;onCancel;onSubmit;constructor(e,t,i,n,r,o){this.tui=t,this.terminalRows=i,this.bindings=n,this.suspendForChild=r,this.profiles=o,this.snapshot=e,this.plans=new ne(e,()=>{this.refreshRows(),this.tui.requestRender()}),this.docs=new te(()=>this.tui.requestRender()),this.rebuild()}set focused(e){this._focused=e}get focused(){return this._focused}invalidate(){}dispose(){this.plans.dispose()}rebuild(){this.refreshRows(),this.plans.warm(this.snapshot.event)}refreshRows(){this.rows=ie(this.plans,this.snapshot.event),this.docs.setRows(this.rows,this.snapshot.event),this.syncDetail()}setFilters(e){this.filters=e,this.docs.setFilters(e),this.syncDetail()}syncDetail(){const e=this.docs.selected,t=e===void 0?null:I(e.anchor),i=this.plans.peek(this.snapshot.event)?.subject??null;this.detail.setContext(e,this.snapshot.event,t,i,e===void 0?void 0:this.bodies.get(e.key))}setSnapshot(e){const t=this.railRows()[this.railIndex];this.snapshot=e,this.plans.setSnapshot(e),this.notice=void 0,this.rebuild(),this.holdRail(t)}holdRail(e){if(e===void 0)return;const t=this.railRows(),i=M(e),n=t.findIndex(r=>M(r)===i);this.railIndex=Math.max(0,n>=0?n:t.findIndex(r=>r.kind==="event"&&r.event.dialled))}matches(e,t){return N(this.bindings,e,t,(i,n)=>s(i,n))}label(e,t){const i=this.bindings.gestures(e);return i.length===0?t:C(i[0].split(" > ").pop())}isDown(e){return s(e,"j")||s(e,"down")||this.matches("crtr.setup.list-down",e)}isUp(e){return s(e,"k")||s(e,"up")||this.matches("crtr.setup.list-up",e)}isDescend(e){return s(e,"l")||s(e,"right")||s(e,"enter")||this.matches("crtr.setup.advance",e)}isAscend(e){return s(e,"h")||s(e,"left")}cyclesEvent(e){const t=s(e,"right")||s(e,"left");return s(e,"tab")||!t&&this.matches("crtr.setup.tab-next",e)?1:s(e,"shift+tab")||!t&&this.matches("crtr.setup.tab-previous",e)?-1:0}handleInput(e){if(this.busy!==void 0)return;if(this.modal!==void 0){this.handleModal(e);return}if(this.searching){this.handleSearch(e);return}const t=this.cyclesEvent(e);if(t!==0){this.setSnapshot($(this.snapshot,"event",t,this.profiles));return}if(!(this.zone==="detail"&&!this.detail.editing&&s(e,"ctrl+d"))&&(s(e,"q")||this.matches("crtr.setup.cancel",e))){this.close();return}this.zone==="rail"?this.handleRail(e):this.zone==="docs"?this.handleDocs(e):this.handleDetail(e)}eventRows(){return m.map(e=>{const t=this.plans.peek(e);return{event:e,delivers:t===void 0?void 0:t.docs.filter(i=>i.finalRung!=="none").length,dialled:e===this.snapshot.event}})}railRows(){return J(this.eventRows(),X(this.snapshot),j(this.snapshot,this.profileName()),K(this.filters))}profileName(){const e=this.snapshot.profileId;return e===null?"none":this.profiles.find(t=>t.id===e)?.name??e}handleRail(e){const t=this.railRows();this.railIndex=Math.max(0,Math.min(this.railIndex,t.length-1));const i=t[this.railIndex],n=l(o=>{i!==void 0&&(i.kind==="event"?this.setSnapshot({...this.snapshot,event:i.event.event}):i.kind==="axis"?i.axis.typed?this.openAxisField(i.axis.id,i.axis.label):this.setSnapshot($(this.snapshot,i.axis.id,o,this.profiles)):i.facet.typed?this.openSearch():this.setFilters(V(this.filters,i.facet.id,o)))},"change"),r=D(i);this.isDown(e)?this.railIndex=Math.min(t.length-1,this.railIndex+1):this.isUp(e)?this.railIndex=Math.max(0,this.railIndex-1):s(e,"space")||this.matches("crtr.setup.toggle",e)?n(1):this.isDescend(e)?s(e,"enter")&&r!=="documents"?n(1):this.zone="docs":s(e,"escape")&&this.close()}handleDocs(e){e==="/"||s(e,"/")?this.openSearch():s(e,"y")?this.yankId():this.isDown(e)?(this.docs.move(1),this.syncDetail()):this.isUp(e)?(this.docs.move(-1),this.syncDetail()):s(e,"space")||this.matches("crtr.setup.toggle",e)?(this.docs.toggleGroup(),this.syncDetail()):this.isDescend(e)?this.docs.onGroup?(this.docs.toggleGroup(),this.syncDetail()):this.docs.selected!==void 0&&(this.zone="detail"):s(e,"escape")&&this.filters.query!==""?this.setFilters({...this.filters,query:""}):(this.isAscend(e)||s(e,"escape"))&&(this.zone="rail")}openSearch(){this.searching=!0,this.zone="docs",this.tui.requestRender()}handleSearch(e){s(e,"escape")?(this.searching=!1,this.setFilters({...this.filters,query:""})):s(e,"enter")?this.searching=!1:s(e,"backspace")?this.setFilters({...this.filters,query:this.filters.query.slice(0,-1)}):e.length===1&&e.charCodeAt(0)>=32&&this.setFilters({...this.filters,query:this.filters.query+e}),this.tui.requestRender()}handleDetail(e){s(e,"y")?this.yankId():this.detail.editing?this.handleEdit(e):this.handleRead(e)}yankId(){const e=this.docs.selected;if(e===void 0)return;const{system:t,tmux:i}=T(e.key);this.notice=t||i?{text:`Copied ${e.key}${t?"":" to the tmux buffer"}`,ok:!0}:{text:"No clipboard tool available \u2014 nothing copied",ok:!1},this.tui.requestRender()}handleRead(e){this.isDown(e)?this.detail.move(1):this.isUp(e)?this.detail.move(-1):s(e,"ctrl+d")?this.detail.page(1):s(e,"ctrl+u")?this.detail.page(-1):e==="G"||s(e,"shift+g")?this.detail.jump("bottom"):e==="g"||s(e,"g")?this.detail.jump("top"):e==="e"||s(e,"e")?this.detail.edit():this.isDescend(e)?this.openBody():(this.isAscend(e)||s(e,"escape"))&&(this.detail.back()||(this.zone="docs"))}openBody(){const e=this.docs.selected;if(e===void 0||!this.detail.openBody()||this.bodies.has(e.key))return;const t=e.key;k(e.anchor.doc).then(i=>{this.bodies.set(t,i),this.syncDetail(),this.tui.requestRender()},i=>{this.notice={text:i instanceof Error?i.message:String(i),ok:!1},this.detail.back(),this.tui.requestRender()})}handleEdit(e){if(this.isDown(e)){this.detail.move(1);return}if(this.isUp(e)){this.detail.move(-1);return}if(this.isAscend(e)||s(e,"escape")){this.detail.back();return}const t=this.writeGesture(e);t!==void 0&&(t.document&&this.refusesWrite()||t.start())}writeGesture(e){const t=l(i=>({start:i,document:!0}),"doc");if(s(e,"enter")||s(e,"space")||this.matches("crtr.setup.toggle",e))return this.detail.selected===void 0?void 0:t(()=>this.activate());if(s(e,"m"))return{start:l(()=>this.explainLimit(),"start"),document:!1};if(s(e,"b"))return t(()=>this.editBody());if(s(e,"x"))return t(()=>this.removeRule());if(s(e,"e"))return t(()=>this.composeRule());if(s(e,"u"))return t(()=>this.flipUnlisted());if(s(e,"r"))return t(()=>this.editMove());if(s(e,"w"))return t(()=>this.editPreview())}refusesWrite(){const e=this.record;if(e===void 0)return!1;const t=I(e);return t===null?!1:(this.notice={text:t,ok:!1},this.tui.requestRender(),!0)}activate(){const e=this.detail.selected;if(e!==void 0)switch(e.kind){case"rule":return this.cycleRuleLevel(e.at);case"add-rule":return this.composeRule();case"preview":return this.editPreview();case"unlisted":return this.flipUnlisted();case"body":return this.editBody();case"move":return this.editMove()}}get record(){return this.docs.selected?.anchor}apply(e){this.busy="writing\u2026",this.tui.requestRender(),e.then(t=>{this.busy=void 0,this.notice={text:t.message,ok:t.ok},t.ok&&(t.name!==void 0&&this.edited.add(t.name),this.bodies.clear(),this.plans.refresh(),this.rebuild()),this.tui.requestRender()})}cycleRuleLevel(e){const t=this.record,i=t?.doc.rules[e];if(t===void 0||i===void 0)return;const r=g[(g.indexOf(i.deliver)+1)%g.length],o=t.doc.rules.map((d,p)=>p===e?{...d,deliver:r}:d);this.apply(v(t,o,`${t.doc.displayName} now delivers ${r} on ${i.on}.`))}removeRule(){const e=this.record,t=this.detail.selectedRule;if(e===void 0||t===void 0){this.notice={text:"Select a delivery rule to remove.",ok:!1};return}const i=e.doc.rules[t],n=e.doc.rules.filter((r,o)=>o!==t);this.modal={kind:"confirm",title:"Remove delivery rule",message:`${e.doc.displayName} will stop delivering on ${i.on} (${re(i)}).`,submit:l(()=>this.apply(v(e,n,`Removed the ${i.on} rule from ${e.doc.displayName}.`)),"submit")}}composeRule(){const e=this.record;e!==void 0&&(this.modal={kind:"choice",title:"New rule \u2014 activity",options:[...m],index:m.indexOf(this.snapshot.event),submit:l(t=>{const i=t,n=l(r=>{this.modal={kind:"choice",title:"New rule \u2014 deliver",options:[...g],index:0,submit:l(o=>{this.modal=void 0;const d={on:i,...r===""?{}:{match:[r]},deliver:o};this.apply(v(e,[...e.doc.rules,d],`${e.doc.displayName} now delivers ${o} on ${i}.`))},"submit")}},"chooseLevel");if(!oe(i)){n("");return}this.modal={kind:"field",title:`New rule \u2014 ${i} match`,hint:le[i],input:y(""),submit:l(r=>{const o=r.trim();if(o===""){this.modal=void 0,this.notice={text:`A ${i} rule needs a match glob.`,ok:!1};return}n(o)},"submit")}},"submit")})}flipUnlisted(){const e=this.record;e!==void 0&&this.apply(P(e))}editPreview(){const e=this.record;e!==void 0&&(this.modal={kind:"field",title:"Preview",hint:"the one line a reader decides to open the document on",input:y(e.doc.preview),submit:l(t=>{this.modal=void 0,this.apply(U(e,t))},"submit")})}editBody(){const e=this.record;e!==void 0&&(this.busy="reading the body\u2026",this.tui.requestRender(),k(e.doc).then(t=>{this.busy=void 0;const i=this.suspendForChild();let n;try{n=G(t)}finally{i()}if(n.error!==void 0)this.notice={text:n.error,ok:!1};else if(n.text===t)this.notice={text:`${e.doc.displayName} came back unchanged \u2014 nothing written.`,ok:!1};else{this.apply(B(e,n.text));return}this.tui.requestRender()},t=>{this.busy=void 0,this.notice={text:t instanceof Error?t.message:String(t),ok:!1},this.tui.requestRender()}))}editMove(){const e=this.record;e!==void 0&&(this.modal={kind:"field",title:"Rename",hint:"the new name under this document\u2019s own owner",input:y(e.doc.displayName),submit:l(t=>{this.modal=void 0,this.apply(H(e,t))},"submit")})}explainLimit(){this.notice={text:"Delivery limits are per owner on the profile; set one with `crtr profile project limit`.",ok:!1},this.tui.requestRender()}openAxisField(e,t){this.modal={kind:"field",title:t,hint:e==="cwd"?"absolute directory the project stores resolve from":"value the planner should match against",input:y(Z(this.snapshot,e)),submit:l(i=>{this.modal=void 0,this.setSnapshot(Y(this.snapshot,e,i))},"submit")}}close(){if(this.edited.size===0){this.onCancel?.();return}this.onSubmit?.({edited:[...this.edited]})}handleModal(e){const t=this.modal;if(t!==void 0){if(s(e,"escape")){this.modal=void 0;return}if(t.kind==="choice"){this.isDown(e)?t.index=Math.min(t.options.length-1,t.index+1):this.isUp(e)?t.index=Math.max(0,t.index-1):s(e,"enter")&&t.submit(t.options[t.index]);return}if(t.kind==="confirm"){s(e,"y")||s(e,"enter")?(this.modal=void 0,t.submit()):s(e,"n")&&(this.modal=void 0);return}s(e,"enter")?t.submit(t.input.getValue()):t.input.handleInput(e)}}renderModal(e,t){const i=this.modal;if(i===void 0)return[];let n;i.kind==="choice"?n=[h.fg("accent",h.bold(i.title)),"",...i.options.map((o,d)=>`${d===i.index?h.fg("accent","\u25B6"):" "} ${o}`)]:i.kind==="confirm"?n=[h.fg("warning",h.bold(i.title)),"",...ge(i.message,Math.max(1,e-6))]:n=[h.fg("accent",h.bold(i.title)),h.fg("dim",i.hint),"",i.input.render(Math.max(1,e-6))[0]??""];const r=W(n,e);for(;r.length<t;)r.push("");return r.slice(0,t)}footer(e,t){if(this.busy!==void 0)return h.fg("warning",this.busy);if(this.modal?.kind==="choice")return h.fg("dim","\u2191\u2193/jk choose \xB7 enter apply \xB7 esc cancel");if(this.modal?.kind==="confirm")return h.fg("dim","y/enter confirm \xB7 n/esc cancel");if(this.modal?.kind==="field")return h.fg("dim","type \xB7 enter apply \xB7 esc cancel");if(this.searching)return h.fg("dim","type to search names \xB7 enter keep \xB7 esc clear");if(this.notice===void 0&&this.plans.error!==void 0)return h.fg("warning",b(`dry run refused: ${this.plans.error}`,e));if(this.notice!==void 0)return h.fg(this.notice.ok?"success":"warning",b(this.notice.text,e));const i=`${this.label("crtr.setup.list-down","j")}/${this.label("crtr.setup.list-up","k")}`,n=this.zone==="rail"?`${i} row \xB7 ${me(t)}`:this.zone==="docs"?`${i} row \xB7 ${this.docsGesture()} \xB7 / search \xB7 y id`:this.detail.editing?`${i} field \xB7 enter edit \xB7 e add \xB7 x remove \xB7 w preview \xB7 b body \xB7 u unlisted \xB7 m limit \xB7 r rename \xB7 y id \xB7 esc read`:this.detail.bodyOpen?`${i} scroll \xB7 ctrl-d/u page \xB7 g/G ends \xB7 y id \xB7 esc collapse`:`${i} scroll \xB7 enter body \xB7 e edit \xB7 y id \xB7 esc list`,r=`${this.label("crtr.setup.tab-next","tab")} event \xB7 ${this.label("crtr.setup.cancel","q")} close`,o=e-w(n)-w(r);return o>=2?`${h.fg("dim",n)}${" ".repeat(o)}${h.fg("dim",r)}`:h.fg("dim",b(`${n} \xB7 ${this.label("crtr.setup.cancel","q")} close`,e))}docsGesture(){return this.docs.onGroup?"space/enter open":"enter dossier"}render(e){const t=this.terminalRows(),i=Math.max(1,t-F),n=e>=de,r=this.railRows();this.railIndex=Math.max(0,Math.min(this.railIndex,r.length-1));const o=l(c=>Q({rows:r,index:this.railIndex,width:c,height:i,focused:this.zone==="rail",matched:this.docs.visibleCount,total:this.rows.length}),"rail");let d;if(e>=he){const c=fe(e),f=Math.max(1,e-a-c-q),_=x(this.docs.render(c,i,this.zone==="docs"),c,this.modal===void 0?this.detail.render(f,i,this.zone==="detail"):this.renderModal(f,i),f);d=x(o(a),a,_,e-a-3)}else if(n){const c=e-a-3,f=this.modal!==void 0?this.renderModal(c,i):this.zone==="detail"?this.detail.render(c,i,!0):this.docs.render(c,i,this.zone==="docs");d=x(o(a),a,f,c)}else this.modal!==void 0?d=this.renderModal(e,i):this.zone==="rail"?d=o(e):this.zone==="detail"?d=this.detail.render(e,i,!0):d=this.docs.render(e,i,!0);const p=m.filter(c=>this.plans.peek(c)===void 0).length,R=this.plans.peek(this.snapshot.event)?.docs.filter(c=>c.finalRung!=="none").length,E=[this.snapshot.event,R===void 0?"":`${R} delivered`,p>0?`${S(p,"event","events")} planning`:"all events planned",this.edited.size>0?`${S(this.edited.size,"doc","docs")} edited`:""].filter(c=>c!=="").join(" \xB7 ");return L({width:e,height:t,title:"crouter context",meta:E,body:d,footer:this.footer(e,r[this.railIndex])})}}function me(u){switch(D(u)){case"dial":return"space/enter dial \xB7 l documents";case"edit":return"space/enter edit \xB7 l documents";default:return"space change \xB7 enter documents"}}l(me,"railGesture");function y(u){const e=new A;return e.setValue(u),e.handleInput(""),e.focused=!0,e}l(y,"seeded");function ge(u,e){const t=[];let i="";for(const n of u.trim().split(/\s+/)){const r=i===""?n:`${i} ${n}`;w(r)<=e?i=r:(i!==""&&t.push(i),i=n)}return i!==""&&t.push(i),t}l(ge,"wrap");async function _e(u,e){return O(({tui:t,terminal:i,bindings:n,suspendForChild:r},o)=>{const d=new pe(u,t,()=>i.rows,n,r,e);return d.onCancel=o.cancel,d.onSubmit=o.submit,d})}l(_e,"runContextAdmin");export{pe as ContextAdminShell,_e as runContextAdmin};
1
+ var z=Object.defineProperty;var l=(u,e)=>z(u,"name",{value:e,configurable:!0});import{Input as A,matchesKey as s,truncateToWidth as b,visibleWidth as w}from"@earendil-works/pi-tui";import{formatGesture as C,matchesPiTuiInput as N}from"../../../../core/keybindings/index.js";import{writeClipboardTextEverywhere as T}from"../../../../core/clipboard-text.js";import{runTuiPage as O}from"../../../../core/tui/page-host.js";import{PAGE_CHROME_ROWS as F,columns as x,framed as W,pageFrame as L,theme as h}from"../../../../core/tui/panel.js";import{editBufferInEditor as G}from"../../../../clients/editor-roundtrip.js";import{PLANNED_EVENTS as m}from"../resolve.js";import{moveDoc as H,readBody as k,readOnlyReason as I,toggleUnlisted as P,writeBody as B,writePreview as U,writeRules as v}from"./actions.js";import{axesOf as j,cycleAxis as $,cycleFacet as V,facetsOf as K,payloadRowOf as X,railEnter as D,railRowKey as M,railRowsOf as J,renderRail as Q,setTypedAxis as Y,typedAxisValue as Z}from"./rail-panel.js";import{ContextDetailPanel as ee}from"./detail-panel.js";import{ContextDocsPanel as te,buildRows as ie}from"./docs-panel.js";import{NO_FILTERS as se}from"./list-view.js";import{DELIVER_LEVELS as g,PlanSet as ne,describeRule as re,plural as S}from"./model.js";function oe(u){return u!=="boot"&&u!=="workspace-open"}l(oe,"needsMatch");const le={boot:"","workspace-open":"","file-read":"absolute path glob, or ./ for this document\u2019s own directory","document-read":"document name glob",command:"command-path glob, e.g. node new","pre-command":"command-path glob, e.g. node new","slash-command":"slash command name glob"},a=26,de=86,he=112,q=6,ce=48,ue=100,ae=.45;function fe(u){const e=Math.max(1,u-a-q);return Math.max(ce,Math.min(ue,Math.floor(e*ae)))}l(fe,"docsWidthFor");class pe{static{l(this,"ContextAdminShell")}tui;terminalRows;bindings;suspendForChild;profiles;snapshot;plans;zone="rail";railIndex=0;filters=se;rows=[];searching=!1;docs;detail=new ee;modal;notice;busy;edited=new Set;bodies=new Map;_focused=!1;onCancel;onSubmit;constructor(e,t,i,n,r,o){this.tui=t,this.terminalRows=i,this.bindings=n,this.suspendForChild=r,this.profiles=o,this.snapshot=e,this.plans=new ne(e,()=>{this.refreshRows(),this.tui.requestRender()}),this.docs=new te(()=>this.tui.requestRender()),this.rebuild()}set focused(e){this._focused=e}get focused(){return this._focused}invalidate(){}dispose(){this.plans.dispose()}rebuild(){this.refreshRows(),this.plans.warm(this.snapshot.event)}refreshRows(){this.rows=ie(this.plans,this.snapshot.event),this.docs.setRows(this.rows,this.snapshot.event),this.syncDetail()}setFilters(e){this.filters=e,this.docs.setFilters(e),this.syncDetail()}syncDetail(){const e=this.docs.selected,t=e===void 0?null:I(e.anchor),i=this.plans.peek(this.snapshot.event)?.subject??null;this.detail.setContext(e,this.snapshot.event,t,i,e===void 0?void 0:this.bodies.get(e.key))}setSnapshot(e){const t=this.railRows()[this.railIndex];this.snapshot=e,this.plans.setSnapshot(e),this.notice=void 0,this.rebuild(),this.holdRail(t)}holdRail(e){if(e===void 0)return;const t=this.railRows(),i=M(e),n=t.findIndex(r=>M(r)===i);this.railIndex=Math.max(0,n>=0?n:t.findIndex(r=>r.kind==="event"&&r.event.dialled))}matches(e,t){return N(this.bindings,e,t,(i,n)=>s(i,n))}label(e,t){const i=this.bindings.gestures(e);return i.length===0?t:C(i[0].split(" > ").pop())}isDown(e){return s(e,"j")||s(e,"down")||this.matches("crtr.setup.list-down",e)}isUp(e){return s(e,"k")||s(e,"up")||this.matches("crtr.setup.list-up",e)}isDescend(e){return s(e,"l")||s(e,"right")||s(e,"enter")||this.matches("crtr.setup.advance",e)}isAscend(e){return s(e,"h")||s(e,"left")}cyclesEvent(e){const t=s(e,"right")||s(e,"left");return s(e,"tab")||!t&&this.matches("crtr.setup.tab-next",e)?1:s(e,"shift+tab")||!t&&this.matches("crtr.setup.tab-previous",e)?-1:0}handleInput(e){if(this.busy!==void 0)return;if(this.modal!==void 0){this.handleModal(e);return}if(this.searching){this.handleSearch(e);return}const t=this.cyclesEvent(e);if(t!==0){this.setSnapshot($(this.snapshot,"event",t,this.profiles));return}if(!(this.zone==="detail"&&!this.detail.editing&&s(e,"ctrl+d"))&&(s(e,"q")||this.matches("crtr.setup.cancel",e))){this.close();return}this.zone==="rail"?this.handleRail(e):this.zone==="docs"?this.handleDocs(e):this.handleDetail(e)}eventRows(){return m.map(e=>{const t=this.plans.peek(e);return{event:e,delivers:t===void 0?void 0:t.docs.filter(i=>i.finalRung!=="none").length,dialled:e===this.snapshot.event}})}railRows(){return J(this.eventRows(),X(this.snapshot),j(this.snapshot,this.profileName()),K(this.filters))}profileName(){const e=this.snapshot.profileId;return e===null?"none":this.profiles.find(t=>t.id===e)?.name??e}handleRail(e){const t=this.railRows();this.railIndex=Math.max(0,Math.min(this.railIndex,t.length-1));const i=t[this.railIndex],n=l(o=>{i!==void 0&&(i.kind==="event"?this.setSnapshot({...this.snapshot,event:i.event.event}):i.kind==="axis"?i.axis.typed?this.openAxisField(i.axis.id,i.axis.label):this.setSnapshot($(this.snapshot,i.axis.id,o,this.profiles)):i.facet.typed?this.openSearch():this.setFilters(V(this.filters,i.facet.id,o)))},"change"),r=D(i);this.isDown(e)?this.railIndex=Math.min(t.length-1,this.railIndex+1):this.isUp(e)?this.railIndex=Math.max(0,this.railIndex-1):s(e,"space")||this.matches("crtr.setup.toggle",e)?n(1):this.isDescend(e)?s(e,"enter")&&r!=="documents"?n(1):this.zone="docs":s(e,"escape")&&this.close()}handleDocs(e){e==="/"||s(e,"/")?this.openSearch():s(e,"y")?this.yankId():this.isDown(e)?(this.docs.move(1),this.syncDetail()):this.isUp(e)?(this.docs.move(-1),this.syncDetail()):s(e,"space")||this.matches("crtr.setup.toggle",e)?(this.docs.toggleGroup(),this.syncDetail()):this.isDescend(e)?this.docs.onGroup?(this.docs.toggleGroup(),this.syncDetail()):this.docs.selected!==void 0&&(this.zone="detail"):s(e,"escape")&&this.filters.query!==""?this.setFilters({...this.filters,query:""}):(this.isAscend(e)||s(e,"escape"))&&(this.zone="rail")}openSearch(){this.searching=!0,this.zone="docs",this.tui.requestRender()}handleSearch(e){s(e,"escape")?(this.searching=!1,this.setFilters({...this.filters,query:""})):s(e,"enter")?this.searching=!1:s(e,"backspace")?this.setFilters({...this.filters,query:this.filters.query.slice(0,-1)}):e.length===1&&e.charCodeAt(0)>=32&&this.setFilters({...this.filters,query:this.filters.query+e}),this.tui.requestRender()}handleDetail(e){s(e,"y")?this.yankId():this.detail.editing?this.handleEdit(e):this.handleRead(e)}yankId(){const e=this.docs.selected;if(e===void 0)return;const{system:t,tmux:i}=T(e.key);this.notice=t||i?{text:`Copied ${e.key}${t?"":" to the tmux buffer"}`,ok:!0}:{text:"No clipboard tool available \u2014 nothing copied",ok:!1},this.tui.requestRender()}handleRead(e){this.isDown(e)?this.detail.move(1):this.isUp(e)?this.detail.move(-1):s(e,"ctrl+d")?this.detail.page(1):s(e,"ctrl+u")?this.detail.page(-1):e==="G"||s(e,"shift+g")?this.detail.jump("bottom"):e==="g"||s(e,"g")?this.detail.jump("top"):e==="e"||s(e,"e")?this.detail.edit():this.isDescend(e)?this.openBody():(this.isAscend(e)||s(e,"escape"))&&(this.detail.back()||(this.zone="docs"))}openBody(){const e=this.docs.selected;if(e===void 0||!this.detail.openBody()||this.bodies.has(e.key))return;const t=e.key;k(e.anchor.doc).then(i=>{this.bodies.set(t,i),this.syncDetail(),this.tui.requestRender()},i=>{this.notice={text:i instanceof Error?i.message:String(i),ok:!1},this.detail.back(),this.tui.requestRender()})}handleEdit(e){if(this.isDown(e)){this.detail.move(1);return}if(this.isUp(e)){this.detail.move(-1);return}if(this.isAscend(e)||s(e,"escape")){this.detail.back();return}const t=this.writeGesture(e);t!==void 0&&(t.document&&this.refusesWrite()||t.start())}writeGesture(e){const t=l(i=>({start:i,document:!0}),"doc");if(s(e,"enter")||s(e,"space")||this.matches("crtr.setup.toggle",e))return this.detail.selected===void 0?void 0:t(()=>this.activate());if(s(e,"m"))return{start:l(()=>this.explainLimit(),"start"),document:!1};if(s(e,"b"))return t(()=>this.editBody());if(s(e,"x"))return t(()=>this.removeRule());if(s(e,"e"))return t(()=>this.composeRule());if(s(e,"u"))return t(()=>this.flipUnlisted());if(s(e,"r"))return t(()=>this.editMove());if(s(e,"w"))return t(()=>this.editPreview())}refusesWrite(){const e=this.record;if(e===void 0)return!1;const t=I(e);return t===null?!1:(this.notice={text:t,ok:!1},this.tui.requestRender(),!0)}activate(){const e=this.detail.selected;if(e!==void 0)switch(e.kind){case"rule":return this.cycleRuleLevel(e.at);case"add-rule":return this.composeRule();case"preview":return this.editPreview();case"unlisted":return this.flipUnlisted();case"body":return this.editBody();case"move":return this.editMove()}}get record(){return this.docs.selected?.anchor}apply(e){this.busy="writing\u2026",this.tui.requestRender(),e.then(t=>{this.busy=void 0,this.notice={text:t.message,ok:t.ok},t.ok&&(t.name!==void 0&&this.edited.add(t.name),this.bodies.clear(),this.plans.refresh(),this.rebuild()),this.tui.requestRender()})}cycleRuleLevel(e){const t=this.record,i=t?.doc.rules[e];if(t===void 0||i===void 0)return;const r=g[(g.indexOf(i.deliver)+1)%g.length],o=t.doc.rules.map((d,p)=>p===e?{...d,deliver:r}:d);this.apply(v(t,o,`${t.doc.displayName} now delivers ${r} on ${i.on}.`))}removeRule(){const e=this.record,t=this.detail.selectedRule;if(e===void 0||t===void 0){this.notice={text:"Select a delivery rule to remove.",ok:!1};return}const i=e.doc.rules[t],n=e.doc.rules.filter((r,o)=>o!==t);this.modal={kind:"confirm",title:"Remove delivery rule",message:`${e.doc.displayName} will stop delivering on ${i.on} (${re(i)}).`,submit:l(()=>this.apply(v(e,n,`Removed the ${i.on} rule from ${e.doc.displayName}.`)),"submit")}}composeRule(){const e=this.record;e!==void 0&&(this.modal={kind:"choice",title:"New rule \u2014 activity",options:[...m],index:m.indexOf(this.snapshot.event),submit:l(t=>{const i=t,n=l(r=>{this.modal={kind:"choice",title:"New rule \u2014 deliver",options:[...g],index:0,submit:l(o=>{this.modal=void 0;const d={on:i,...r===""?{}:{match:[r]},deliver:o};this.apply(v(e,[...e.doc.rules,d],`${e.doc.displayName} now delivers ${o} on ${i}.`))},"submit")}},"chooseLevel");if(!oe(i)){n("");return}this.modal={kind:"field",title:`New rule \u2014 ${i} match`,hint:le[i],input:y(""),submit:l(r=>{const o=r.trim();if(o===""){this.modal=void 0,this.notice={text:`A ${i} rule needs a match glob.`,ok:!1};return}n(o)},"submit")}},"submit")})}flipUnlisted(){const e=this.record;e!==void 0&&this.apply(P(e))}editPreview(){const e=this.record;e!==void 0&&(this.modal={kind:"field",title:"Preview",hint:"the one line a reader decides to open the document on",input:y(e.doc.preview),submit:l(t=>{this.modal=void 0,this.apply(U(e,t))},"submit")})}editBody(){const e=this.record;e!==void 0&&(this.busy="reading the body\u2026",this.tui.requestRender(),k(e.doc).then(t=>{this.busy=void 0;const i=this.suspendForChild();let n;try{n=G(t)}finally{i()}if(n.error!==void 0)this.notice={text:n.error,ok:!1};else if(n.text===t)this.notice={text:`${e.doc.displayName} came back unchanged \u2014 nothing written.`,ok:!1};else{this.apply(B(e,n.text));return}this.tui.requestRender()},t=>{this.busy=void 0,this.notice={text:t instanceof Error?t.message:String(t),ok:!1},this.tui.requestRender()}))}editMove(){const e=this.record;e!==void 0&&(this.modal={kind:"field",title:"Rename",hint:"the new name under this document\u2019s own owner",input:y(e.doc.displayName),submit:l(t=>{this.modal=void 0,this.apply(H(e,t))},"submit")})}explainLimit(){this.notice={text:"Delivery limits are per owner on the profile; set one with `crtr profile project limit`.",ok:!1},this.tui.requestRender()}openAxisField(e,t){this.modal={kind:"field",title:t,hint:e==="cwd"?"absolute directory the project stores resolve from":"value the planner should match against",input:y(Z(this.snapshot,e)),submit:l(i=>{this.modal=void 0,this.setSnapshot(Y(this.snapshot,e,i))},"submit")}}close(){if(this.edited.size===0){this.onCancel?.();return}this.onSubmit?.({edited:[...this.edited]})}handleModal(e){const t=this.modal;if(t!==void 0){if(s(e,"escape")){this.modal=void 0;return}if(t.kind==="choice"){this.isDown(e)?t.index=Math.min(t.options.length-1,t.index+1):this.isUp(e)?t.index=Math.max(0,t.index-1):s(e,"enter")&&t.submit(t.options[t.index]);return}if(t.kind==="confirm"){s(e,"y")||s(e,"enter")?(this.modal=void 0,t.submit()):s(e,"n")&&(this.modal=void 0);return}s(e,"enter")?t.submit(t.input.getValue()):t.input.handleInput(e)}}renderModal(e,t){const i=this.modal;if(i===void 0)return[];let n;i.kind==="choice"?n=[h.fg("accent",h.bold(i.title)),"",...i.options.map((o,d)=>`${d===i.index?h.fg("accent","\u25B6"):" "} ${o}`)]:i.kind==="confirm"?n=[h.fg("warning",h.bold(i.title)),"",...ge(i.message,Math.max(1,e-6))]:n=[h.fg("accent",h.bold(i.title)),h.fg("dim",i.hint),"",i.input.render(Math.max(1,e-6))[0]??""];const r=W(n,e);for(;r.length<t;)r.push("");return r.slice(0,t)}footer(e,t){if(this.busy!==void 0)return h.fg("warning",this.busy);if(this.modal?.kind==="choice")return h.fg("dim","\u2191\u2193/jk choose \xB7 enter apply \xB7 esc cancel");if(this.modal?.kind==="confirm")return h.fg("dim","y/enter confirm \xB7 n/esc cancel");if(this.modal?.kind==="field")return h.fg("dim","type \xB7 enter apply \xB7 esc cancel");if(this.searching)return h.fg("dim","type to search names \xB7 enter keep \xB7 esc clear");if(this.notice===void 0&&this.plans.error!==void 0)return h.fg("warning",b(`dry run refused: ${this.plans.error}`,e));if(this.notice!==void 0)return h.fg(this.notice.ok?"success":"warning",b(this.notice.text,e));const i=`${this.label("crtr.setup.list-down","j")}/${this.label("crtr.setup.list-up","k")}`,n=this.zone==="rail"?`${i} row \xB7 ${me(t)}`:this.zone==="docs"?`${i} row \xB7 ${this.docsGesture()} \xB7 / search \xB7 y id`:this.detail.editing?`${i} field \xB7 enter edit \xB7 e add \xB7 x remove \xB7 w preview \xB7 b body \xB7 u unlisted \xB7 m limit \xB7 r rename \xB7 y id \xB7 esc read`:this.detail.bodyOpen?`${i} scroll \xB7 ctrl-d/u page \xB7 g/G ends \xB7 y id \xB7 esc collapse`:`${i} scroll \xB7 enter body \xB7 e edit \xB7 y id \xB7 esc list`,r=`${this.label("crtr.setup.tab-next","tab")} event \xB7 ${this.label("crtr.setup.cancel","q")} close`,o=e-w(n)-w(r);return o>=2?`${h.fg("dim",n)}${" ".repeat(o)}${h.fg("dim",r)}`:h.fg("dim",b(`${n} \xB7 ${this.label("crtr.setup.cancel","q")} close`,e))}docsGesture(){return this.docs.onGroup?"space/enter open":"enter dossier"}render(e){const t=this.terminalRows(),i=Math.max(1,t-F),n=e>=de,r=this.railRows();this.railIndex=Math.max(0,Math.min(this.railIndex,r.length-1));const o=l(c=>Q({rows:r,index:this.railIndex,width:c,height:i,focused:this.zone==="rail",matched:this.docs.visibleCount,total:this.rows.length}),"rail");let d;if(e>=he){const c=fe(e),f=Math.max(1,e-a-c-q),_=x(this.docs.render(c,i,this.zone==="docs"),c,this.modal===void 0?this.detail.render(f,i,this.zone==="detail"):this.renderModal(f,i),f);d=x(o(a),a,_,e-a-3)}else if(n){const c=e-a-3,f=this.modal!==void 0?this.renderModal(c,i):this.zone==="detail"?this.detail.render(c,i,!0):this.docs.render(c,i,this.zone==="docs");d=x(o(a),a,f,c)}else this.modal!==void 0?d=this.renderModal(e,i):this.zone==="rail"?d=o(e):this.zone==="detail"?d=this.detail.render(e,i,!0):d=this.docs.render(e,i,!0);const p=m.filter(c=>this.plans.peek(c)===void 0).length,R=this.plans.peek(this.snapshot.event)?.docs.filter(c=>c.finalRung!=="none").length,E=[this.snapshot.event,R===void 0?"":`${R} delivered`,p>0?`${S(p,"event","events")} planning`:"all events planned",this.edited.size>0?`${S(this.edited.size,"doc","docs")} edited`:""].filter(c=>c!=="").join(" \xB7 ");return L({width:e,height:t,title:"crouter context",meta:E,body:d,footer:this.footer(e,r[this.railIndex])})}}function me(u){switch(D(u)){case"dial":return"space/enter dial \xB7 l documents";case"edit":return"space/enter edit \xB7 l documents";default:return"space change \xB7 enter documents"}}l(me,"railGesture");function y(u){const e=new A;return e.setValue(u),e.handleInput(""),e.focused=!0,e}l(y,"seeded");function ge(u,e){const t=[];let i="";for(const n of u.trim().split(/\s+/)){const r=i===""?n:`${i} ${n}`;w(r)<=e?i=r:(i!==""&&t.push(i),i=n)}return i!==""&&t.push(i),t}l(ge,"wrap");async function _e(u,e){return O(({tui:t,terminal:i,bindings:n,suspendForChild:r},o)=>{const d=new pe(u,t,()=>i.rows,n,r,e);return d.onCancel=o.cancel,d.onSubmit=o.submit,d})}l(_e,"runContextAdmin");export{pe as ContextAdminShell,_e as runContextAdmin};
@@ -39,8 +39,7 @@ export interface BrokerClient {
39
39
  off(event: 'close', listener: () => void): this;
40
40
  }
41
41
  export declare class BrokerClient extends EventEmitter {
42
- private readonly nodeId;
43
- private readonly transport;
42
+ private transport;
44
43
  private closeEmitted;
45
44
  /** Tracks live connect↔close state so {@link request} can fail fast on a
46
45
  * dead/absent connection rather than parking a promise the reply will
@@ -56,7 +55,11 @@ export declare class BrokerClient extends EventEmitter {
56
55
  * Resolved by the matching `data` frame / rejected by the matching `error`
57
56
  * frame in {@link onFrame}, the request's timeout, or transport teardown. */
58
57
  private pending;
59
- constructor(nodeId: string, options?: BrokerClientOptions);
58
+ /** `nodeId` is undefined only for a viewer whose node is still being created: it holds no transport until {@link bindTransport}, so
59
+ * every send is a no-op and every request rejects until then. */
60
+ constructor(nodeId: string | undefined, options?: BrokerClientOptions);
61
+ /** Wire the transport once the node it reaches is known. */
62
+ bindTransport(transport: Transport): void;
60
63
  /** Issue a correlated read-op and resolve with the broker's `data` reply (or
61
64
  * reject on the correlated `error`, a timeout, or transport teardown). Mints
62
65
  * the `id`, sends `{...frame, id}`, and parks a resolver consumed by
@@ -1 +1 @@
1
- var c=Object.defineProperty;var i=(n,t)=>c(n,"name",{value:t,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as k}from"./transport.js";import{SocketTransport as x}from"./transport-socket.js";import{RelayTransport as w}from"./transport-relay.js";const d=1e4;function f(n){return n===null||n.status==="done"&&n.final_report!=null}i(f,"reconnectShouldGiveUp");class g extends l{static{i(this,"BrokerClient")}nodeId;transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(t,e={}){super(),this.nodeId=t,this.transport=e.transport??new a(t),this.transport.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),this.transport.on("frame",r=>this.onFrame(r)),this.transport.on("error",r=>{this.lastTransportError=r.message,this.emitError(r)}),this.transport.on("close",()=>this.onClose())}request(t){const e=p();return new Promise((r,o)=>{if(!this.connected){o(new Error(`cannot issue '${t.type}': no live broker connection`));return}const s=setTimeout(()=>{this.pending.delete(e),o(new Error(`request '${t.type}' timed out after ${d}ms`))},d);typeof s.unref=="function"&&s.unref(),this.pending.set(e,{resolve:r,reject:o,timer:s}),this.send({...t,id:e})})}rejectAllPending(t){for(const{reject:e,timer:r}of this.pending.values())clearTimeout(r),e(new Error(t));this.pending.clear()}connect(){this.transport.connect()}redial(t){return this.transport.redial(t)}send(t){this.transport.send(t)}close(){this.transport.destroy()}onFrame(t){if(t.type==="data"){const e=typeof t.id=="string"?this.pending.get(t.id):void 0;e&&(this.pending.delete(t.id),clearTimeout(e.timer),e.resolve(t));return}if(t.type==="error"&&typeof t.id=="string"&&this.pending.has(t.id)){const e=this.pending.get(t.id);this.pending.delete(t.id),clearTimeout(e.timer),e.reject(new Error(t.message||`request failed: ${t.code}`));return}this.emit("frame",t)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(t){this.listenerCount("error")>0&&this.emit("error",t)}}export{g as BrokerClient,k as BrokerUnavailableError,w as RelayTransport,x as SocketTransport,f as reconnectShouldGiveUp};
1
+ var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as w}from"./transport.js";import{SocketTransport as v}from"./transport-socket.js";import{RelayTransport as U}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(new Error(e.message||`request failed: ${e.code}`));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,w as BrokerUnavailableError,U as RelayTransport,v as SocketTransport,E as reconnectShouldGiveUp};
@@ -41,6 +41,11 @@ export interface Cron {
41
41
  expires_at: string | null;
42
42
  anchor_node: string | null;
43
43
  cancel_on_wake: boolean;
44
+ /** A node deadline (`crtr node wait deadline`): the message the cron lane sends the anchor, urgently, when the row falls
45
+ * due. Such a row runs no command. Null for every other cron. */
46
+ deadline_body: string | null;
47
+ /** How many times the cron has fired (a hosted cron ends after HOSTED_CRON_MAX_FIRES). */
48
+ fires: number;
44
49
  cwd: string;
45
50
  env_json: string | null;
46
51
  profile: string | null;
@@ -102,6 +107,7 @@ export interface ArmCronSpec {
102
107
  expires_at: string | null;
103
108
  anchor_node: string | null;
104
109
  cancel_on_wake: boolean;
110
+ deadline_body?: string | null;
105
111
  cwd: string;
106
112
  env_json: string | null;
107
113
  profile: string | null;
@@ -194,6 +200,10 @@ export declare function deleteCronsForProfile(profileId: string, anchorNodeIds:
194
200
  export declare function cronIdsForProfileDetach(profileId: string): Promise<string[]>;
195
201
  /** Preserve matching crons while removing their deleted profile dependency. */
196
202
  export declare function globalizeCronsForProfile(profileId: string): Promise<string[]>;
203
+ /** A hosted cron ends after this many fires; no flag raises it (NL-1110). */
204
+ export declare const HOSTED_CRON_MAX_FIRES = 64;
205
+ /** Idle crons that have used all `max` fires; the due pass ends them whether paused or not (NL-1110). */
206
+ export declare function cappedIdleCrons(max: number): Promise<Cron[]>;
197
207
  /** DELETE one cron by id — one-shot consumption after its run settles.
198
208
  * Returns whether a live row was removed, so a consumer racing an explicit
199
209
  * cancel can no-op instead of double-settling. */
@@ -243,7 +253,7 @@ export declare function dueClockCrons(nowIso: string): Promise<Cron[]>;
243
253
  *
244
254
  * `outOfBand` stamps the lease as a `cron run` (manual verification) so the
245
255
  * overlap pass leaves it alone — see `dueOverlapCrons`. */
246
- export declare function acquireCronRunLease(cron_id: string, leaseOwner: string, startedAtIso: string, outOfBand: boolean, executionId?: string | null): Promise<boolean>;
256
+ export declare function acquireCronRunLease(cron_id: string, leaseOwner: string, startedAtIso: string, outOfBand: boolean, executionId?: string | null, maxFires?: number | null): Promise<boolean>;
247
257
  /** Attach the launcher's pid only to the run that claimed this lease. */
248
258
  export declare function attachCronRunPid(cron_id: string, leaseOwner: string, startedAtIso: string, pid: number): Promise<boolean>;
249
259
  /** What a settling run does with the row's `held` state, applied in the SAME