@north-light/cli 0.3.706 → 0.3.708

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 (187) 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/human.d.ts +9 -6
  6. package/dist/api/dto/inbox.d.ts +2 -0
  7. package/dist/api/dto/review-comments.d.ts +12 -35
  8. package/dist/api/dto/reviews.d.ts +3 -10
  9. package/dist/api/routes.d.ts +0 -1
  10. package/dist/api/routes.js +1 -1
  11. package/dist/builtin-memory/05-kinds/review/companion/00-base.md +2 -2
  12. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  13. package/dist/clients/attach/chrome/canvas-panels.d.ts +1 -1
  14. package/dist/clients/attach/chrome/canvas-panels.js +1 -1
  15. package/dist/clients/attach/chrome/roster.js +6 -6
  16. package/dist/clients/attach/chrome/status-line.js +1 -1
  17. package/dist/clients/attach/chrome/ticket-panel.js +1 -1
  18. package/dist/clients/attach/input/controller.d.ts +0 -1
  19. package/dist/clients/attach/input/controller.js +3 -3
  20. package/dist/clients/attach/input/overlay-owner.d.ts +0 -1
  21. package/dist/clients/attach/input/overlay-owner.js +1 -1
  22. package/dist/clients/attach/session/keys.d.ts +0 -2
  23. package/dist/clients/attach/session/keys.js +1 -1
  24. package/dist/clients/attach/session/surface-host.d.ts +0 -5
  25. package/dist/clients/attach/session/surface-host.js +1 -1
  26. package/dist/clients/attach/viewer.js +545 -560
  27. package/dist/clients/editor-roundtrip.js +3 -0
  28. package/dist/clients/inbox/controller.d.ts +1 -6
  29. package/dist/clients/inbox/controller.js +1 -1
  30. package/dist/clients/inbox/dto-adapt.js +1 -1
  31. package/dist/clients/inbox/tui/page-body.js +1 -1
  32. package/dist/clients/inbox/tui/render.js +2 -2
  33. package/dist/clients/open-browser.d.ts +2 -0
  34. package/dist/clients/open-browser.js +1 -0
  35. package/dist/clients/surfaces/host.d.ts +0 -6
  36. package/dist/commands/human/review.js +1 -1
  37. package/dist/commands/sys/context/admin/shell.js +1 -1
  38. package/dist/core/canvas/schema-pg/025-review-anchors.sql +19 -0
  39. package/dist/core/canvas/schema-version.d.ts +1 -1
  40. package/dist/core/canvas/schema-version.js +1 -1
  41. package/dist/core/human/page-markdown.js +10 -12
  42. package/dist/core/human/tickets.js +1 -1
  43. package/dist/core/human/types.d.ts +4 -6
  44. package/dist/core/keybindings/attach-control.d.ts +0 -3
  45. package/dist/core/keybindings/attach-control.js +1 -1
  46. package/dist/core/keybindings/catalog.d.ts +1 -1
  47. package/dist/core/keybindings/catalog.js +1 -1
  48. package/dist/core/review/anchors.d.ts +28 -0
  49. package/dist/core/review/anchors.js +6 -0
  50. package/dist/core/review/comments.d.ts +2 -2
  51. package/dist/core/review/comments.js +7 -8
  52. package/dist/core/review/companion.d.ts +2 -1
  53. package/dist/core/review/companion.js +1 -1
  54. package/dist/core/review/document.d.ts +4 -17
  55. package/dist/core/review/document.js +1 -2
  56. package/dist/core/review/fork.js +2 -4
  57. package/dist/core/review/project.d.ts +1 -1
  58. package/dist/core/review/project.js +2 -2
  59. package/dist/core/review/realize.js +1 -1
  60. package/dist/core/review/stage.d.ts +2 -9
  61. package/dist/core/review/stage.js +1 -1
  62. package/dist/core/review/types.d.ts +16 -12
  63. package/dist/core/review/types.js +1 -1
  64. package/dist/core/runtime/broker/turn-replies.d.ts +1 -3
  65. package/dist/core/runtime/broker-cli.js +3 -3
  66. package/dist/core/runtime/broker-extension-render.js +1 -1
  67. package/dist/core/runtime/tmux-bindings.js +3 -3
  68. package/dist/daemon/api/canvas-host.js +1 -1
  69. package/dist/daemon/api/document-page.d.ts +12 -1
  70. package/dist/daemon/api/document-page.js +6 -6
  71. package/dist/daemon/api/handlers/inbox.js +1 -1
  72. package/dist/daemon/api/handlers/review-comments.js +1 -1
  73. package/dist/daemon/api/handlers/reviews.js +1 -1
  74. package/dist/daemon/api/map.js +2 -2
  75. package/dist/daemon/api/review-page.d.ts +3 -0
  76. package/dist/daemon/api/review-page.js +13 -0
  77. package/dist/daemon/broker-memory-cap.d.ts +9 -0
  78. package/dist/daemon/broker-memory-cap.js +2 -0
  79. package/dist/daemon/broker-signals/bus.d.ts +1 -1
  80. package/dist/daemon/broker-signals/bus.js +1 -1
  81. package/dist/daemon/crtrd.js +14 -14
  82. package/dist/daemon/machine-daemon.js +1 -1
  83. package/dist/daemon/review/comment-notify.js +2 -2
  84. package/dist/daemon/review/deliver.d.ts +2 -2
  85. package/dist/daemon/review/deliver.js +6 -2
  86. package/dist/daemon/review/finish.js +1 -1
  87. package/dist/doc-editor/Geist-Variable.woff2 +0 -0
  88. package/dist/doc-editor/GeistMono-Variable.woff2 +0 -0
  89. package/dist/doc-editor/editor.css +1 -1
  90. package/dist/doc-editor/review.css +2 -0
  91. package/dist/doc-editor/review.js +149 -0
  92. package/dist/pi-extensions/canvas-review-boundary.js +3 -3
  93. package/dist/shared/turn-replies.d.ts +3 -3
  94. package/dist/shared/turn-replies.js +3 -3
  95. package/docs/sdk/release-notes.md +6 -0
  96. package/package.json +13 -4
  97. package/packages/crouter-api/dist/api/client.js +0 -3
  98. package/packages/crouter-api/dist/api/contract.js +1 -1
  99. package/packages/crouter-api/dist/api/routes.js +0 -1
  100. package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +3 -3
  101. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +9 -20
  102. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -6
  103. package/packages/crouter-api/dist/clients/attach/chrome/ticket-panel.js +1 -1
  104. package/packages/crouter-api/dist/clients/attach/input/controller.js +0 -3
  105. package/packages/crouter-api/dist/clients/attach/input/overlay-owner.js +0 -7
  106. package/packages/crouter-api/dist/clients/attach/session/keys.js +0 -1
  107. package/packages/crouter-api/dist/clients/attach/session/surface-host.js +0 -17
  108. package/packages/crouter-api/dist/clients/attach/viewer.js +0 -37
  109. package/packages/crouter-api/dist/clients/{inbox/review/roundtrip.js → editor-roundtrip.js} +1 -1
  110. package/packages/crouter-api/dist/clients/inbox/controller.js +12 -31
  111. package/packages/crouter-api/dist/clients/inbox/dto-adapt.js +1 -0
  112. package/packages/crouter-api/dist/clients/inbox/tui/page-body.js +0 -7
  113. package/packages/crouter-api/dist/clients/inbox/tui/render.js +0 -7
  114. package/packages/crouter-api/dist/clients/open-browser.js +6 -0
  115. package/packages/crouter-api/dist/commands/human/review.js +17 -18
  116. package/packages/crouter-api/dist/commands/sys/context/admin/shell.js +1 -1
  117. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  118. package/packages/crouter-api/dist/core/human/page-markdown.js +2 -6
  119. package/packages/crouter-api/dist/core/human/tickets.js +2 -11
  120. package/packages/crouter-api/dist/core/keybindings/attach-control.js +0 -1
  121. package/packages/crouter-api/dist/core/keybindings/catalog.js +1 -3
  122. package/packages/crouter-api/dist/core/review/anchors.js +91 -0
  123. package/packages/crouter-api/dist/core/review/comments.js +27 -46
  124. package/packages/crouter-api/dist/core/review/companion.js +5 -9
  125. package/packages/crouter-api/dist/core/review/document.js +17 -89
  126. package/packages/crouter-api/dist/core/review/project.js +2 -1
  127. package/packages/crouter-api/dist/core/review/types.js +2 -2
  128. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +0 -5
  129. package/packages/crouter-api/dist/daemon/api/map.js +2 -6
  130. package/packages/crouter-api/dist/daemon/broker-signals/bus.js +1 -1
  131. package/packages/crouter-api/dist/daemon/review/deliver.js +4 -3
  132. package/packages/crouter-api/dist/daemon/review/finish.js +26 -47
  133. package/packages/crouter-api/dist/shared/turn-replies.js +9 -14
  134. package/packages/crouter-api/package.json +1 -1
  135. package/packages/crouter-identity/package.json +1 -1
  136. package/packages/crouter-plugin/package.json +3 -3
  137. package/runtime.lock.json +1740 -505
  138. package/dist/clients/attach/overlays/file-review.d.ts +0 -10
  139. package/dist/clients/attach/overlays/file-review.js +0 -2
  140. package/dist/clients/inbox/review/anchors.d.ts +0 -41
  141. package/dist/clients/inbox/review/anchors.js +0 -1
  142. package/dist/clients/inbox/review/comments-client.d.ts +0 -74
  143. package/dist/clients/inbox/review/comments-client.js +0 -1
  144. package/dist/clients/inbox/review/companion-pane.d.ts +0 -47
  145. package/dist/clients/inbox/review/companion-pane.js +0 -1
  146. package/dist/clients/inbox/review/document-surface.d.ts +0 -212
  147. package/dist/clients/inbox/review/document-surface.js +0 -2
  148. package/dist/clients/inbox/review/frame.d.ts +0 -57
  149. package/dist/clients/inbox/review/frame.js +0 -1
  150. package/dist/clients/inbox/review/keys.d.ts +0 -69
  151. package/dist/clients/inbox/review/keys.js +0 -1
  152. package/dist/clients/inbox/review/launch.d.ts +0 -16
  153. package/dist/clients/inbox/review/launch.js +0 -1
  154. package/dist/clients/inbox/review/live-source.d.ts +0 -24
  155. package/dist/clients/inbox/review/live-source.js +0 -1
  156. package/dist/clients/inbox/review/nvim.d.ts +0 -15
  157. package/dist/clients/inbox/review/nvim.js +0 -1
  158. package/dist/clients/inbox/review/remap.d.ts +0 -51
  159. package/dist/clients/inbox/review/remap.js +0 -1
  160. package/dist/clients/inbox/review/review-client.d.ts +0 -43
  161. package/dist/clients/inbox/review/review-client.js +0 -1
  162. package/dist/clients/inbox/review/roundtrip.js +0 -3
  163. package/dist/clients/inbox/review/state.d.ts +0 -153
  164. package/dist/clients/inbox/review/state.js +0 -4
  165. package/dist/clients/inbox/review-adapter.d.ts +0 -17
  166. package/dist/clients/inbox/review-adapter.js +0 -1
  167. package/dist/core/review/remap.d.ts +0 -24
  168. package/dist/core/review/remap.js +0 -19
  169. package/dist/core/review/signal.d.ts +0 -5
  170. package/dist/core/review/signal.js +0 -1
  171. package/packages/crouter-api/dist/clients/attach/overlays/file-review.js +0 -146
  172. package/packages/crouter-api/dist/clients/inbox/review/anchors.js +0 -89
  173. package/packages/crouter-api/dist/clients/inbox/review/comments-client.js +0 -103
  174. package/packages/crouter-api/dist/clients/inbox/review/companion-pane.js +0 -109
  175. package/packages/crouter-api/dist/clients/inbox/review/document-surface.js +0 -1268
  176. package/packages/crouter-api/dist/clients/inbox/review/frame.js +0 -309
  177. package/packages/crouter-api/dist/clients/inbox/review/keys.js +0 -133
  178. package/packages/crouter-api/dist/clients/inbox/review/launch.js +0 -170
  179. package/packages/crouter-api/dist/clients/inbox/review/live-source.js +0 -160
  180. package/packages/crouter-api/dist/clients/inbox/review/nvim.js +0 -43
  181. package/packages/crouter-api/dist/clients/inbox/review/remap.js +0 -157
  182. package/packages/crouter-api/dist/clients/inbox/review/review-client.js +0 -125
  183. package/packages/crouter-api/dist/clients/inbox/review/state.js +0 -315
  184. package/packages/crouter-api/dist/clients/inbox/review-adapter.js +0 -43
  185. package/packages/crouter-api/dist/core/review/signal.js +0 -12
  186. package/packages/crouter-api/dist/core/termrender/code-doc.js +0 -92
  187. /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 +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};
@@ -0,0 +1,19 @@
1
+ -- 025-review-anchors.sql — review comments anchor to rendered text (quote + prefix + suffix + offset) instead of line ranges, and are re-found on every read.
2
+ -- Reviews moved to the browser: every open review is canceled and every comment row dropped; none are carried. Destructive, so `schema_min_reader`
3
+ -- rises to 25 in the last statement.
4
+ DO $$ BEGIN DELETE FROM review_comment_events; DELETE FROM review_comments; END $$;
5
+ UPDATE human_requests SET state = 'settled', outcome = 'canceled', settled_at = to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
6
+ result_json = jsonb_build_object('schema', 'humanloop.cancel/v1', 'kind', 'canceled', 'canceledAt', to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
7
+ 'reason', 'Reviews moved to the browser; start a new review.')
8
+ WHERE kind = 'review' AND state IN ('open', 'binding');
9
+ DROP INDEX IF EXISTS idx_review_comments_review_line_seq;
10
+ ALTER TABLE review_comments
11
+ DROP COLUMN anchor_line, DROP COLUMN anchor_end_line, DROP COLUMN anchor_col_start, DROP COLUMN anchor_col_end,
12
+ DROP COLUMN anchor_line_text, DROP COLUMN anchor_doc_hash, DROP COLUMN anchor_state,
13
+ ADD COLUMN anchor_prefix text NOT NULL DEFAULT '', ADD COLUMN anchor_suffix text NOT NULL DEFAULT '', ADD COLUMN anchor_offset bigint NOT NULL DEFAULT 0;
14
+ ALTER TABLE review_comments ALTER COLUMN anchor_quote SET NOT NULL;
15
+ CREATE INDEX review_comments_review ON review_comments (review_id, created_seq);
16
+ ALTER TABLE review_comment_events DROP CONSTRAINT IF EXISTS review_comment_events_kind_check;
17
+ ALTER TABLE review_comment_events ADD CONSTRAINT review_comment_events_kind_check
18
+ CHECK (kind IN ('created', 'edited', 'resolved', 'reopened', 'deleted', 'notified', 'notify_failed'));
19
+ INSERT INTO canvas_meta (key, value) VALUES ('schema_min_reader', '25') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 24;
4
+ export declare const CANVAS_SCHEMA_VERSION = 25;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=24;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=25;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1,17 +1,15 @@
1
- var w=Object.defineProperty;var o=(n,r)=>w(n,"name",{value:r,configurable:!0});import{BUILTIN_KIND_BY_TAG as P,BUILTIN_PAGE_COMPONENT_TAGS as S,DISPLAY_PAGE_COMPONENT_TAGS as _,pageComponentTag as j}from"./page-catalog.js";import{evaluatePageTree as v}from"./page-eval.js";import{PageAuthoringError as I}from"./page-errors.js";import{compilePage as N}from"./page.js";const M=new Set(Object.keys(P)),B=new Set(["Page","Step","Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent","address","article","aside","blockquote","details","dialog","div","dl","dt","dd","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","summary","table","thead","tbody","tfoot","tr","th","td","ul"]);function p(n){return n.kind==="element"}o(p,"isElement");function T(n){return n.replace(/\s+/g," ").replace(/([\\`*_[\]<>#])/g,"\\$1")}o(T,"markdownText");function i(n){return n.replace(/[ \t]+\n/g,`
1
+ var w=Object.defineProperty;var c=(n,r)=>w(n,"name",{value:r,configurable:!0});import{BUILTIN_KIND_BY_TAG as P,BUILTIN_PAGE_COMPONENT_TAGS as S,DISPLAY_PAGE_COMPONENT_TAGS as _,pageComponentTag as j}from"./page-catalog.js";import{evaluatePageTree as v}from"./page-eval.js";import{PageAuthoringError as I}from"./page-errors.js";import{compilePage as N}from"./page.js";const M=new Set(Object.keys(P)),B=new Set(["Page","Step","Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent","address","article","aside","blockquote","details","dialog","div","dl","dt","dd","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","summary","table","thead","tbody","tfoot","tr","th","td","ul"]);function p(n){return n.kind==="element"}c(p,"isElement");function b(n){return n.replace(/\s+/g," ").replace(/([\\`*_[\]<>#])/g,"\\$1")}c(b,"markdownText");function i(n){return n.replace(/[ \t]+\n/g,`
2
2
  `).replace(/\n[ \t]+/g,`
3
- `).trim()}o(i,"cleanInline");function y(n,r){let t="";for(const e of n){if(!p(e)){t+=e.text;continue}r.slotTags.has(e.tag)||(t+=y(e.children,r))}return t}o(y,"rawText");function D(n){const r=n.replace(/\s+/g," ").trim();if(r==="")return"";const t=Math.max(0,...[...r.matchAll(/`+/g)].map(a=>a[0].length)),e="`".repeat(t+1),s=/^`|`$|^ | $/.test(r)?" ":"";return`${e}${s}${r}${s}${e}`}o(D,"inlineCode");function g(n,r){let t="";for(const e of n){if(!p(e)){t+=T(e.text);continue}if(r.slotTags.has(e.tag))continue;const s=o(()=>g(e.children,r),"body");switch(e.tag){case"br":t+=`
4
- `;break;case"code":t+=D(y(e.children,r));break;case"strong":case"b":{const a=i(s());a!==""&&(t+=`**${a}**`);break}case"em":case"i":{const a=i(s());a!==""&&(t+=`*${a}*`);break}case"del":case"s":{const a=i(s());a!==""&&(t+=`~~${a}~~`);break}case"a":{const a=i(s()),c=e.props.href;t+=typeof c=="string"&&c!==""?`[${a===""?T(c):a}](${c.replace(/([\\()])/g,"\\$1")})`:a;break}case"img":{const a=typeof e.props.alt=="string"?T(e.props.alt):"image",c=e.props.src;t+=typeof c=="string"&&c!==""?`![${a}](${c.replace(/([\\()])/g,"\\$1")})`:a;break}case"Badge":{const a=i(s());a!==""&&(t+=`**${a}**`);break}default:t+=s()}}return t}o(g,"inline");function C(n){return n.split(`
3
+ `).trim()}c(i,"cleanInline");function C(n,r){let t="";for(const e of n){if(!p(e)){t+=e.text;continue}r.slotTags.has(e.tag)||(t+=C(e.children,r))}return t}c(C,"rawText");function D(n){const r=n.replace(/\s+/g," ").trim();if(r==="")return"";const t=Math.max(0,...[...r.matchAll(/`+/g)].map(a=>a[0].length)),e="`".repeat(t+1),s=/^`|`$|^ | $/.test(r)?" ":"";return`${e}${s}${r}${s}${e}`}c(D,"inlineCode");function g(n,r){let t="";for(const e of n){if(!p(e)){t+=b(e.text);continue}if(r.slotTags.has(e.tag))continue;const s=c(()=>g(e.children,r),"body");switch(e.tag){case"br":t+=`
4
+ `;break;case"code":t+=D(C(e.children,r));break;case"strong":case"b":{const a=i(s());a!==""&&(t+=`**${a}**`);break}case"em":case"i":{const a=i(s());a!==""&&(t+=`*${a}*`);break}case"del":case"s":{const a=i(s());a!==""&&(t+=`~~${a}~~`);break}case"a":{const a=i(s()),o=e.props.href;t+=typeof o=="string"&&o!==""?`[${a===""?b(o):a}](${o.replace(/([\\()])/g,"\\$1")})`:a;break}case"img":{const a=typeof e.props.alt=="string"?b(e.props.alt):"image",o=e.props.src;t+=typeof o=="string"&&o!==""?`![${a}](${o.replace(/([\\()])/g,"\\$1")})`:a;break}case"Badge":{const a=i(s());a!==""&&(t+=`**${a}**`);break}default:t+=s()}}return t}c(g,"inline");function y(n){return n.split(`
5
5
  `).map(r=>r===""?">":`> ${r}`).join(`
6
- `)}o(C,"quote");function G(n){const r=[n.props.className],t=n.children.find(e=>p(e)&&e.tag==="code");t!==void 0&&r.push(t.props.className);for(const e of r){if(typeof e!="string")continue;const s=/(?:^|\s)language-([A-Za-z0-9_+-]+)/.exec(e)?.[1];if(s!==void 0)return s}return""}o(G,"languageFor");function O(n,r){const t=y(n.children,r).replace(/^\n/,"").replace(/\n$/,"");if(t==="")return"";const e=Math.max(0,...[...t.matchAll(/`+/g)].map(a=>a[0].length)),s="`".repeat(Math.max(3,e+1));return`${s}${G(n)}
6
+ `)}c(y,"quote");function G(n){const r=[n.props.className],t=n.children.find(e=>p(e)&&e.tag==="code");t!==void 0&&r.push(t.props.className);for(const e of r){if(typeof e!="string")continue;const s=/(?:^|\s)language-([A-Za-z0-9_+-]+)/.exec(e)?.[1];if(s!==void 0)return s}return""}c(G,"languageFor");function O(n,r){const t=C(n.children,r).replace(/^\n/,"").replace(/\n$/,"");if(t==="")return"";const e=Math.max(0,...[...t.matchAll(/`+/g)].map(a=>a[0].length)),s="`".repeat(Math.max(3,e+1));return`${s}${G(n)}
7
7
  ${t}
8
- ${s}`}o(O,"codeBlock");function k(n,r,t){return n.children.filter(s=>p(s)&&s.tag==="li").map((s,a)=>{const c=r?`${a+1}.`:"-",u=A(s.children,t);if(u==="")return"";const f=" ".repeat(c.length+1);return u.split(`
9
- `).map((m,$)=>$===0?`${c} ${m}`:m===""?"":`${f}${m}`).join(`
8
+ ${s}`}c(O,"codeBlock");function k(n,r,t){return n.children.filter(s=>p(s)&&s.tag==="li").map((s,a)=>{const o=r?`${a+1}.`:"-",u=A(s.children,t);if(u==="")return"";const f=" ".repeat(o.length+1);return u.split(`
9
+ `).map((m,$)=>$===0?`${o} ${m}`:m===""?"":`${f}${m}`).join(`
10
10
  `)}).filter(s=>s!=="").join(`
11
- `)}o(k,"list");function x(n,r){const t=[];let e="";const s=o(d=>{for(const l of d)if(!(!p(l)||r.slotTags.has(l.tag))){if(l.tag==="TableCaption"||l.tag==="caption"){e=i(g(l.children,r));continue}if(l.tag==="TableRow"||l.tag==="tr"){const b=l.children.filter(h=>p(h)&&["TableHead","TableCell","th","td"].includes(h.tag));b.length>0&&t.push({header:b.every(h=>h.tag==="TableHead"||h.tag==="th"),cells:b.map(h=>i(g(h.children,r)).replaceAll("|","\\|").replaceAll(`
12
- `,"<br>"))});continue}s(l.children)}},"visit");if(s(n.children),t.length===0)return A(n.children,r);const a=t.findIndex(d=>d.header),c=a===-1?t[0]:t[a],u=t.filter((d,l)=>l!==(a===-1?0:a)),f=Math.max(c.cells.length,...u.map(d=>d.cells.length)),m=o(d=>Array.from({length:f},(l,b)=>d[b]??""),"cells"),$=[`| ${m(c.cells).join(" | ")} |`,`| ${Array.from({length:f},()=>"---").join(" | ")} |`,...u.map(d=>`| ${m(d.cells).join(" | ")} |`)];return e!==""&&$.push("",`*${e}*`),$.join(`
13
- `)}o(x,"table");function E(n,r){if(r.slotTags.has(n.tag))return"";const t=o(()=>A(n.children,r),"contents");switch(n.tag){case"Page":return t();case"Step":{const e=n.props.title,s=t();return[typeof e=="string"&&e.trim()!==""?`## ${T(e.trim())}`:"",s].filter(c=>c!=="").join(`
11
+ `)}c(k,"list");function x(n,r){const t=[];let e="";const s=c(d=>{for(const l of d)if(!(!p(l)||r.slotTags.has(l.tag))){if(l.tag==="TableCaption"||l.tag==="caption"){e=i(g(l.children,r));continue}if(l.tag==="TableRow"||l.tag==="tr"){const T=l.children.filter(h=>p(h)&&["TableHead","TableCell","th","td"].includes(h.tag));T.length>0&&t.push({header:T.every(h=>h.tag==="TableHead"||h.tag==="th"),cells:T.map(h=>i(g(h.children,r)).replaceAll("|","\\|").replaceAll(`
12
+ `,"<br>"))});continue}s(l.children)}},"visit");if(s(n.children),t.length===0)return A(n.children,r);const a=t.findIndex(d=>d.header),o=a===-1?t[0]:t[a],u=t.filter((d,l)=>l!==(a===-1?0:a)),f=Math.max(o.cells.length,...u.map(d=>d.cells.length)),m=c(d=>Array.from({length:f},(l,T)=>d[T]??""),"cells"),$=[`| ${m(o.cells).join(" | ")} |`,`| ${Array.from({length:f},()=>"---").join(" | ")} |`,...u.map(d=>`| ${m(d.cells).join(" | ")} |`)];return e!==""&&$.push("",`*${e}*`),$.join(`
13
+ `)}c(x,"table");function E(n,r){if(r.slotTags.has(n.tag))return"";const t=c(()=>A(n.children,r),"contents");switch(n.tag){case"Page":return t();case"Step":return t();case"p":return i(g(n.children,r));case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":{const e=i(g(n.children,r)),s=Math.min(6,Number(n.tag[1])+1);return e===""?"":`${"#".repeat(s)} ${e}`}case"ul":return k(n,!1,r);case"ol":return k(n,!0,r);case"li":return i(t());case"pre":return O(n,r);case"blockquote":return y(t());case"hr":case"Separator":return"---";case"CardTitle":case"AlertTitle":{const e=i(g(n.children,r));return e===""?"":`**${e}**`}case"CardDescription":return i(g(n.children,r));case"Alert":{const e=t();return e===""?"":y(e)}case"AlertDescription":return t();case"Table":case"table":return x(n,r);case"TableRow":case"TableHead":case"TableCell":case"tr":case"th":case"td":return i(g(n.children,r));case"TabsTrigger":case"AccordionTrigger":case"summary":case"dt":{const e=i(g(n.children,r));return e===""?"":`**${e}**`}case"Progress":{const e=t(),s=n.props.value;return e!==""?e:typeof s=="number"||typeof s=="string"?`Progress: ${b(String(s))}%`:""}default:return t()}}c(E,"block");function A(n,r){const t=[];let e="";const s=c(()=>{const a=i(e);e="",a!==""&&t.push(a)},"flush");for(const a of n){if(!p(a)||!r.slotTags.has(a.tag)&&!B.has(a.tag)){e+=p(a)?g([a],r):b(a.text);continue}s();const o=E(a,r).trim();o!==""&&t.push(o)}return s(),t.join(`
14
14
 
15
- `)}case"p":return i(g(n.children,r));case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":{const e=i(g(n.children,r)),s=Math.min(6,Number(n.tag[1])+1);return e===""?"":`${"#".repeat(s)} ${e}`}case"ul":return k(n,!1,r);case"ol":return k(n,!0,r);case"li":return i(t());case"pre":return O(n,r);case"blockquote":return C(t());case"hr":case"Separator":return"---";case"CardTitle":case"AlertTitle":{const e=i(g(n.children,r));return e===""?"":`**${e}**`}case"CardDescription":return i(g(n.children,r));case"Alert":{const e=t();return e===""?"":C(e)}case"AlertDescription":return t();case"Table":case"table":return x(n,r);case"TableRow":case"TableHead":case"TableCell":case"tr":case"th":case"td":return i(g(n.children,r));case"TabsTrigger":case"AccordionTrigger":case"summary":case"dt":{const e=i(g(n.children,r));return e===""?"":`**${e}**`}case"Progress":{const e=t(),s=n.props.value;return e!==""?e:typeof s=="number"||typeof s=="string"?`Progress: ${T(String(s))}%`:""}default:return t()}}o(E,"block");function A(n,r){const t=[];let e="";const s=o(()=>{const a=i(e);e="",a!==""&&t.push(a)},"flush");for(const a of n){if(!p(a)||!r.slotTags.has(a.tag)&&!B.has(a.tag)){e+=p(a)?g([a],r):T(a.text);continue}s();const c=E(a,r).trim();c!==""&&t.push(c)}return s(),t.join(`
16
-
17
- `)}o(A,"flow");function K(n,r){if(r.dialect!=="jsx")return"";const t=new Set(r.slots.filter(u=>u.unvalidated===!0).map(u=>j(u.kind))),e=[...S,..._,...t],s=v(N(n),e),a=[],c=o(u=>{for(const f of u)p(f)&&(f.tag==="Page"&&a.push(f),c(f.children))},"collect");if(c(s),a.length!==1)throw new I(`page display projection expected one <Page> element; found ${a.length}`);return A(a[0].children,{slotTags:new Set([...M,...t])}).trim()}o(K,"projectPageDisplayMarkdown");export{K as projectPageDisplayMarkdown};
15
+ `)}c(A,"flow");function K(n,r){if(r.dialect!=="jsx")return"";const t=new Set(r.slots.filter(u=>u.unvalidated===!0).map(u=>j(u.kind))),e=[...S,..._,...t],s=v(N(n),e),a=[],o=c(u=>{for(const f of u)p(f)&&(f.tag==="Page"&&a.push(f),o(f.children))},"collect");if(o(s),a.length!==1)throw new I(`page display projection expected one <Page> element; found ${a.length}`);return A(a[0].children,{slotTags:new Set([...M,...t])}).trim()}c(K,"projectPageDisplayMarkdown");export{K as projectPageDisplayMarkdown};
@@ -1 +1 @@
1
- var b=Object.defineProperty;var s=(t,e)=>b(t,"name",{value:e,configurable:!0});import{mkdirSync as y,realpathSync as q}from"node:fs";import{basename as _,isAbsolute as P,resolve as k}from"node:path";import{z as n}from"zod";import{pageModulePath as R,pagePath as E}from"./convention.js";import{readPageManifest as d}from"./page.js";import{isBlobRequestPath as S,readRequestText as p}from"./request-files.js";import{validatePageResponses as x,validatePartialPageResponses as m}from"./page-schema.js";import{signalInboxActivity as g}from"./root.js";import{createPageRequest as j,getRequestByDirectory as l,presentationDir as f,publishPageRevisionTo as A,revisePageRequest as T,writeProgress as $}from"./requests.js";const I=n.object({id:n.string().min(1),line:n.number().int().positive(),endLine:n.number().int().positive(),quote:n.string().optional(),colStart:n.number().int().nonnegative().optional(),colEnd:n.number().int().nonnegative().optional(),lineText:n.string(),comment:n.string().min(1),createdAt:n.string().min(1)}).strict(),o=n.string().datetime({offset:!0}),L=n.object({file:n.string().min(1).refine(P,"file must be absolute").refine(t=>k(t)===t,"file must be canonical"),submitted:n.literal(!0),approved:n.boolean(),comments:n.array(I),submittedAt:o,savedAt:o,reviewId:n.string().optional(),changed:n.boolean().optional(),baselineSha256:n.string().optional(),approvedSha256:n.string().optional(),companionNodeId:n.string().optional(),commentsTotal:n.number().int().nonnegative().optional(),commentsUnresolved:n.number().int().nonnegative().optional()}).strict().superRefine((t,e)=>{t.comments.forEach((r,i)=>{r.endLine<r.line&&e.addIssue({code:"custom",message:"endLine must be >= line",path:["comments",i,"endLine"]}),r.colStart===void 0!=(r.colEnd===void 0)&&e.addIssue({code:"custom",message:"columns must be supplied together",path:["comments",i]}),r.line===r.endLine&&r.colStart!==void 0&&r.colEnd!==void 0&&r.colEnd<=r.colStart&&e.addIssue({code:"custom",message:"colEnd must exceed colStart",path:["comments",i,"colEnd"]})})}),w=n.record(n.string(),n.unknown()),O=n.object({schema:n.literal("crtr.page-response/v1"),kind:n.literal("page"),responses:n.record(n.string(),w),summary:n.string(),completedAt:o,actor:n.string().optional()}).strict(),te=n.object({kind:n.literal("page"),responses:n.record(n.string(),w),savedAt:o}).strict(),N=n.object({schema:n.literal("humanloop.review-response/v1"),kind:n.literal("review"),result:L,completedAt:o}).strict(),D=n.object({schema:n.literal("humanloop.cancel/v1"),kind:n.literal("canceled"),canceledAt:o,reason:n.string().optional(),actor:n.string().optional(),disposition:n.enum(["canceled","dismissed"]).optional()}).strict();async function ne(t){const e=await l(t);if(e===null)throw new Error(`unknown human request directory: ${t}`);if(e.state!=="settled"||e.result_json===null)return null;let r;try{r=JSON.parse(e.result_json)}catch(v){throw new Error(`corrupt human request result: ${e.request_id}`,{cause:v})}const i=O.safeParse(r);if(i.success)return i.data;const u=N.safeParse(r);if(u.success)return u.data;const a=D.safeParse(r);if(a.success)return a.data;throw new Error(`human request has an invalid terminal result: ${e.request_id}`)}s(ne,"readTicketResult");async function re(t,e){let r=t;S(t)||(y(t,{recursive:!0,mode:448}),r=q(t));const i=await l(r);if(i===null){const a=await j({request_id:_(r),prepared:e});return g(),{id:a.request_id,dir:a.request_dir,kind:"page",manifest:e.manifest}}const u=await A(r,e);if(!await T(i.request_id,{presentation_dir:u,specification_json:JSON.stringify(e.manifest),title:e.manifest.title,subtitle:e.manifest.subtitle??null,inbox_listed:e.manifest.delivery.inbox,settleable:e.manifest.delivery.inbox||e.manifest.delivery.reply}))throw new Error(`page request is not open: ${i.request_id}`);return g(),{id:i.request_id,dir:r,kind:"page",manifest:e.manifest}}s(re,"publishPage");async function c(t){const e=await l(t);if(e===null||e.kind!=="page")throw new Error(`unknown page request directory: ${t}`);return e}s(c,"pageRequest");async function H(t){return f(await c(t))}s(H,"selectedPageDir");async function J(t){return await d(await H(t))}s(J,"requirePage");async function h(t){const e=await J(t);if(!e.delivery.inbox&&!e.delivery.reply)throw new Error("page_has_no_response_lifecycle");return e}s(h,"requireSettleablePage");function M(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length===0}s(M,"isEmptyResponseMap");function B(t,e){return!t.delivery.reply&&M(e)?m(t,e):x(t,e)}s(B,"validateFinalPageResponses");async function C(t,e){return B(await h(t),e)}s(C,"validateFinalPageTicketResponses");async function ie(t,e){return await C(t,e)}s(ie,"validatePageTicketResponses");async function F(t){const e=await c(t);return e.settleable?e.state!=="settled"?"pending":e.outcome==="canceled"||e.outcome==="dismissed"?"canceled":"resolved":"passive"}s(F,"pageTicketState");async function se(t,e){const r=await c(t),i=m(await h(t),e);if(!await $(r.inbox_ticket_id,i))throw new Error(`page request is not open and settleable: ${r.request_id}`);return i}s(se,"writePageProgress");async function z(t){const e=await c(t);if(e.progress_json===null)return null;try{const r=JSON.parse(e.progress_json);if(r.kind!=="page")throw new Error("wrong kind");return r.responses}catch(r){throw new Error(`page progress is malformed for ${e.request_id}`,{cause:r})}}s(z,"readPageProgress");async function oe(t){const e=await c(t),r=f(e),i=await d(r);return{dir:e.request_dir,id:e.request_id,manifest:i,document:await p(E(r,i.dialect)),...i.dialect==="jsx"?{module:await p(R(r))}:{module:void 0},state:await F(e.request_dir),progress:i.delivery.inbox||i.delivery.reply?await z(e.request_dir):null}}s(oe,"readPageTicket");function ae(t,e,r,i={}){throw new Error("page completion must use settleHumanRequest")}s(ae,"completePage");function ce(t,e,r,i={}){throw new Error("page completion must use settleHumanRequest")}s(ce,"takeoverAndCompletePage");function ue(t,e={}){throw new Error("page cancellation must use settleHumanRequest")}s(ue,"cancelTicket");function le(t){throw new Error("review projection must use projectReviewResult")}s(le,"projectReviewOutput");export{ue as cancelTicket,ae as completePage,F as pageTicketState,le as projectReviewOutput,re as publishPage,z as readPageProgress,oe as readPageTicket,ne as readTicketResult,H as selectedPageDir,ce as takeoverAndCompletePage,B as validateFinalPageResponses,ie as validatePageTicketResponses,se as writePageProgress};
1
+ var h=Object.defineProperty;var s=(r,e)=>h(r,"name",{value:e,configurable:!0});import{mkdirSync as y,realpathSync as q}from"node:fs";import{basename as _,isAbsolute as P,resolve as k}from"node:path";import{z as t}from"zod";import{pageModulePath as R,pagePath as x}from"./convention.js";import{readPageManifest as d}from"./page.js";import{isBlobRequestPath as j,readRequestText as p}from"./request-files.js";import{validatePageResponses as S,validatePartialPageResponses as m}from"./page-schema.js";import{signalInboxActivity as g}from"./root.js";import{createPageRequest as E,getRequestByDirectory as u,presentationDir as f,publishPageRevisionTo as A,revisePageRequest as T,writeProgress as $}from"./requests.js";const O=t.object({id:t.string().min(1),quote:t.string().default(""),comment:t.string().min(1),createdAt:t.string().min(1),resolved:t.boolean().default(!1),detached:t.boolean().optional()}).passthrough(),o=t.string().datetime({offset:!0}),N=t.object({file:t.string().min(1).refine(P,"file must be absolute").refine(r=>k(r)===r,"file must be canonical"),submitted:t.literal(!0),approved:t.boolean(),comments:t.array(O),submittedAt:o,savedAt:o,document:t.object({id:t.string(),name:t.string(),base_revision:t.string().nullable(),approved_revision:t.string().nullable()}).nullable().optional(),reviewId:t.string().optional(),changed:t.boolean().optional(),baselineSha256:t.string().optional(),approvedSha256:t.string().optional(),companionNodeId:t.string().optional(),commentsTotal:t.number().int().nonnegative().optional(),commentsUnresolved:t.number().int().nonnegative().optional()}).strict(),w=t.record(t.string(),t.unknown()),D=t.object({schema:t.literal("crtr.page-response/v1"),kind:t.literal("page"),responses:t.record(t.string(),w),summary:t.string(),completedAt:o,actor:t.string().optional()}).strict(),te=t.object({kind:t.literal("page"),responses:t.record(t.string(),w),savedAt:o}).strict(),H=t.object({schema:t.literal("humanloop.review-response/v1"),kind:t.literal("review"),result:N,completedAt:o}).strict(),I=t.object({schema:t.literal("humanloop.cancel/v1"),kind:t.literal("canceled"),canceledAt:o,reason:t.string().optional(),actor:t.string().optional(),disposition:t.enum(["canceled","dismissed"]).optional()}).strict();async function re(r){const e=await u(r);if(e===null)throw new Error(`unknown human request directory: ${r}`);if(e.state!=="settled"||e.result_json===null)return null;let n;try{n=JSON.parse(e.result_json)}catch(b){throw new Error(`corrupt human request result: ${e.request_id}`,{cause:b})}const i=D.safeParse(n);if(i.success)return i.data;const l=H.safeParse(n);if(l.success)return l.data;const a=I.safeParse(n);if(a.success)return a.data;throw new Error(`human request has an invalid terminal result: ${e.request_id}`)}s(re,"readTicketResult");async function ne(r,e){let n=r;j(r)||(y(r,{recursive:!0,mode:448}),n=q(r));const i=await u(n);if(i===null){const a=await E({request_id:_(n),prepared:e});return g(),{id:a.request_id,dir:a.request_dir,kind:"page",manifest:e.manifest}}const l=await A(n,e);if(!await T(i.request_id,{presentation_dir:l,specification_json:JSON.stringify(e.manifest),title:e.manifest.title,subtitle:e.manifest.subtitle??null,inbox_listed:e.manifest.delivery.inbox,settleable:e.manifest.delivery.inbox||e.manifest.delivery.reply}))throw new Error(`page request is not open: ${i.request_id}`);return g(),{id:i.request_id,dir:n,kind:"page",manifest:e.manifest}}s(ne,"publishPage");async function c(r){const e=await u(r);if(e===null||e.kind!=="page")throw new Error(`unknown page request directory: ${r}`);return e}s(c,"pageRequest");async function J(r){return f(await c(r))}s(J,"selectedPageDir");async function M(r){return await d(await J(r))}s(M,"requirePage");async function v(r){const e=await M(r);if(!e.delivery.inbox&&!e.delivery.reply)throw new Error("page_has_no_response_lifecycle");return e}s(v,"requireSettleablePage");function B(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&Object.keys(r).length===0}s(B,"isEmptyResponseMap");function C(r,e){return!r.delivery.reply&&B(e)?m(r,e):S(r,e)}s(C,"validateFinalPageResponses");async function F(r,e){return C(await v(r),e)}s(F,"validateFinalPageTicketResponses");async function se(r,e){return await F(r,e)}s(se,"validatePageTicketResponses");async function z(r){const e=await c(r);return e.settleable?e.state!=="settled"?"pending":e.outcome==="canceled"||e.outcome==="dismissed"?"canceled":"resolved":"passive"}s(z,"pageTicketState");async function ie(r,e){const n=await c(r),i=m(await v(r),e);if(!await $(n.inbox_ticket_id,i))throw new Error(`page request is not open and settleable: ${n.request_id}`);return i}s(ie,"writePageProgress");async function U(r){const e=await c(r);if(e.progress_json===null)return null;try{const n=JSON.parse(e.progress_json);if(n.kind!=="page")throw new Error("wrong kind");return n.responses}catch(n){throw new Error(`page progress is malformed for ${e.request_id}`,{cause:n})}}s(U,"readPageProgress");async function oe(r){const e=await c(r),n=f(e),i=await d(n);return{dir:e.request_dir,id:e.request_id,manifest:i,document:await p(x(n,i.dialect)),...i.dialect==="jsx"?{module:await p(R(n))}:{module:void 0},state:await z(e.request_dir),progress:i.delivery.inbox||i.delivery.reply?await U(e.request_dir):null}}s(oe,"readPageTicket");function ae(r,e,n,i={}){throw new Error("page completion must use settleHumanRequest")}s(ae,"completePage");function ce(r,e,n,i={}){throw new Error("page completion must use settleHumanRequest")}s(ce,"takeoverAndCompletePage");function le(r,e={}){throw new Error("page cancellation must use settleHumanRequest")}s(le,"cancelTicket");function ue(r){throw new Error("review projection must use projectReviewResult")}s(ue,"projectReviewOutput");export{le as cancelTicket,ae as completePage,z as pageTicketState,ue as projectReviewOutput,ne as publishPage,U as readPageProgress,oe as readPageTicket,re as readTicketResult,J as selectedPageDir,ce as takeoverAndCompletePage,C as validateFinalPageResponses,se as validatePageTicketResponses,ie as writePageProgress};
@@ -11,14 +11,11 @@ export interface TicketSource {
11
11
  }
12
12
  export interface FeedbackComment {
13
13
  id: string;
14
- line: number;
15
- endLine: number;
16
- quote?: string;
17
- colStart?: number;
18
- colEnd?: number;
19
- lineText: string;
14
+ quote: string;
20
15
  comment: string;
21
16
  createdAt: string;
17
+ resolved: boolean;
18
+ detached?: boolean;
22
19
  }
23
20
  export interface FeedbackResult {
24
21
  file: string;
@@ -40,6 +37,7 @@ interface TicketSummaryBase {
40
37
  }
41
38
  export interface ReviewTicketSummary extends TicketSummaryBase {
42
39
  kind: 'review';
40
+ url?: string;
43
41
  file: string;
44
42
  output: string;
45
43
  }