@north-light/cli 0.3.651 → 0.3.653

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 (41) hide show
  1. package/dist/build-root.js +1 -1
  2. package/dist/clients/attach/chrome/ticket-panel.js +1 -1
  3. package/dist/clients/attach/viewer.js +487 -489
  4. package/dist/clients/inbox/controller.d.ts +6 -6
  5. package/dist/clients/inbox/controller.js +1 -1
  6. package/dist/clients/inbox/tui.js +1 -1
  7. package/dist/commands/human/queue.js +1 -1
  8. package/dist/commands/sys/daemon.js +1 -1
  9. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -1
  10. package/dist/core/canvas/managed-worktree-sweep-candidates.js +1 -1
  11. package/dist/core/canvas/schema-pg/017-machine-worktree-ops.sql +7 -0
  12. package/dist/core/canvas/schema-version.d.ts +1 -1
  13. package/dist/core/canvas/schema-version.js +1 -1
  14. package/dist/core/command-plugins/compose.d.ts +5 -1
  15. package/dist/core/command-plugins/compose.js +1 -1
  16. package/dist/core/human/convention.d.ts +1 -3
  17. package/dist/core/human/convention.js +2 -2
  18. package/dist/core/human/types.d.ts +0 -7
  19. package/dist/core/runtime/runner/machine/call.d.ts +2 -1
  20. package/dist/core/runtime/runner/machine/call.js +2 -2
  21. package/dist/core/runtime/runner/machine/executor.d.ts +1 -1
  22. package/dist/core/runtime/runner/machine/ops.d.ts +59 -1
  23. package/dist/core/runtime/runner/machine/ops.js +1 -1
  24. package/dist/core/runtime/spawn.js +2 -2
  25. package/dist/core/worktree-close.d.ts +27 -0
  26. package/dist/core/worktree-close.js +6 -6
  27. package/dist/core/worktree-machine.d.ts +27 -0
  28. package/dist/core/worktree-machine.js +1 -0
  29. package/dist/core/worktree-mutation-async.d.ts +31 -0
  30. package/dist/core/worktree-mutation-async.js +7 -7
  31. package/dist/daemon/api/handlers/human-requests.js +1 -1
  32. package/dist/daemon/api/handlers/nodes.js +1 -1
  33. package/dist/daemon/api/handlers/reports.js +5 -5
  34. package/dist/daemon/api/handlers/worktree.js +1 -1
  35. package/dist/daemon/machine-daemon.js +1 -1
  36. package/dist/daemon/manage.js +3 -3
  37. package/package.json +2 -2
  38. package/packages/crouter-identity/package.json +1 -1
  39. package/runtime.lock.json +13 -13
  40. package/dist/core/human/claim.d.ts +0 -23
  41. package/dist/core/human/claim.js +0 -3
@@ -27,7 +27,7 @@ export interface InboxControllerOptions {
27
27
  profile?: InboxProfileScope;
28
28
  }
29
29
  type Screen = 'list' | 'detail';
30
- /** Host-agnostic model for scanning, stable selection, claims, and rendering. */
30
+ /** Host-agnostic model for scanning, stable selection, and rendering. */
31
31
  export declare class InboxController {
32
32
  private readonly options;
33
33
  private readonly host;
@@ -49,7 +49,8 @@ export declare class InboxController {
49
49
  private adapter;
50
50
  private reviewAdapter;
51
51
  private focusingSource;
52
- private claim;
52
+ /** The ticket open on the detail screen. */
53
+ private open;
53
54
  private submittingDir;
54
55
  private cancelConfirmation;
55
56
  private cols;
@@ -59,7 +60,6 @@ export declare class InboxController {
59
60
  private refreshError;
60
61
  private watchers;
61
62
  private selectedWatcher;
62
- private heartbeat;
63
63
  private started;
64
64
  private closed;
65
65
  /** The selected page's projection, kept across frames because fetching it is
@@ -155,7 +155,7 @@ export declare class InboxController {
155
155
  * the held projection, so activity on an unrelated ticket costs no re-wrap. */
156
156
  private schedulePreview;
157
157
  /** The request record is the settlement authority: a settled page publishes
158
- * no file, so a claim would still succeed on its directory. An unreachable
158
+ * no file in its directory. An unreachable
159
159
  * daemon reads as "not known to be settled" — the settle attempt that
160
160
  * follows is the one that fails loudly. */
161
161
  private requestOrNull;
@@ -166,8 +166,8 @@ export declare class InboxController {
166
166
  private withStatus;
167
167
  private markDirty;
168
168
  private watchRoots;
169
- /** The request directory still carries the claim and progress files other
170
- * inboxes write. Its page content lives in the daemon-selected revision,
169
+ /** The request directory still carries the progress file other inboxes
170
+ * write. Its page content lives in the daemon-selected revision,
171
171
  * which `invalidate` re-reads over the API. */
172
172
  private watchSelected;
173
173
  }
@@ -1 +1 @@
1
- var R=Object.defineProperty;var o=(d,e)=>R(d,"name",{value:e,configurable:!0});import{watch as F}from"node:fs";import{visibleWidth as P}from"@earendil-works/pi-tui";import{renderMarkdown as C}from"../../core/termrender/termrender.js";import{BOLD as M,CYAN as L,DIM as h,GRAY as W,RESET as a,YELLOW as k,clipLine as p,singleLine as q,wrap as O}from"./tui/ansi.js";import{buildInboxLines as E,recommendedLabel as N}from"./tui.js";import{inboxLayout as g}from"./layout.js";import{resolvePageComponents as H}from"../../core/config.js";import{watchInboxActivity as T}from"../../core/human/root.js";import{claimExists as B,claimTicket as x,heartbeatClaim as _,releaseClaim as u}from"../../core/human/claim.js";import{clearProgress as z}from"../../core/human/convention.js";import{emitEvent as V}from"../../core/events/emit.js";import{cliClient as f}from"../../commands/api-client.js";import{projectPageDisplayMarkdown as j}from"../../core/human/page-markdown.js";import{projectHtmlDocumentMarkdown as K}from"../../core/human/page-html-markdown.js";import{pageBodyLines as Y}from"./tui/page-body.js";import{docLinksRevision as b}from"../attach/render/doc-links.js";import{byNewestFirst as G,inboxRowFromDTO as X,pageViewFromDTO as y,settledStatusOf as $}from"./dto-adapt.js";import{PageAdapter as J}from"./page-adapter.js";import{ReviewAdapter as Q}from"./review-adapter.js";import{createReviewClient as U}from"./review/review-client.js";import{editBufferInEditor as Z}from"./review/roundtrip.js";import{daemonErrorMessage as m,dismissTicketViaDaemon as ee,resolveFailureKind as I,resolveTicketPage as S}from"./resolve.js";class Ie{static{o(this,"InboxController")}options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??te,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.claim;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&&z(e),e!==this.submittingDir&&(this.status=s?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}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(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&_(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==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=g(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${k}Resize terminal to at least 60\xD718 to use inbox.${a}`];const t=E(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=[],n=`${W}\u2502${a}`;for(let r=0;r<e.height;r++){const l=p(t[r]??"",e.listWidth),c=p(i[r]??"",e.detailWidth),v=" ".repeat(Math.max(0,e.listWidth-P(l)));s.push(`${l}${v}${n}${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(D(t)){this.status=w(t),await this.rescan();return}const i=x(e.dir);if(i===null){this.status="ticket is being edited by another inbox";return}const s=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${N(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await S(e.id,e.fastAction.responses),this.status=s}catch(n){this.status=I(n)==="already_settled"?w(await this.requestOrNull(e.id)):m(n)}finally{u(e.dir,i.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await U().cancel(e.id,"Canceled from the inbox."):await ee(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"){await this.activateReview(e);return}const t=await this.requestOrNull(e.id);if(this.closed)return;if(D(t)){this.status=w(t),await this.rescan();return}const i=x(e.dir);if(i===null){this.status="ticket is being edited by another inbox";return}let s,n;try{const r=await f().getHumanInboxPage(e.inboxTicketId);if(r.state==="resolved"||r.state==="canceled"){u(e.dir,i.token),this.status=$(r),await this.rescan();return}s=y(r),n=r.revision}catch{u(e.dir,i.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){u(e.dir,i.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:i.token},this.screen="detail",this.adapter=new J({ticketId:e.inboxTicketId,page:s,productKinds:H(),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=n,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new Q({reviewId:e.id,host:this.host});let t=!1;try{t=await this.reviewAdapter.start()}catch(i){this.status=m(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.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{const t=await f().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;t.revision!==this.openRevision&&(this.openRevision=t.revision,this.adapter.reload(y(t)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);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.claim;if(t===void 0)return;this.submittingDir=t.dir;try{await S(t.id,e)}catch(s){this.submittingDir=void 0,this.status=m(s);const n=I(s);if(n==="unreachable"||n==="other"){this.markDirty();return}n==="already_settled"&&(this.status=w(await this.requestOrNull(t.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();const i=this.items.some(s=>s.dir===t.dir);V({level:i?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:t.id,request_settled:D(await this.requestOrNull(t.id)),still_listed:i,claim_left_behind:B(t.dir)}}),this.markDirty()}editActivePageInput(){const e=this.adapter?.inputBuffer();if(e===void 0)return;const t=this.host.suspendForChild();let i={text:e};try{i=Z(e)}finally{t(),this.adapter?.setInputBuffer(i.text),i.error!==void 0&&(this.status=i.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&u(this.claim.dir,this.claim.token),this.claim=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=g(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${a} chat`:"",n=i.kind==="page"&&i.fastAction!==void 0?` ${h}s${a} ${i.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",r=i.kind==="page"?[` ${h}Enter${a} opens the full page ${h}\u2191\u2193/jk${a} select${n} ${h}x${a} cancel`,` ${h}Page:${a} c comment u/d scroll${s} ${h}q${a} close`]:[` ${h}Enter${a} opens the full review ${h}\u2191\u2193/jk${a} select ${h}x${a} cancel`,` ${s} ${h}q${a} close`],l=Math.max(0,t-r.length),c=this.passiveDetailLines(e,l);for(;c.length<l;)c.push("");return[...c,...r.map(v=>p(v,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){const e=this.screen==="detail"?this.claim?.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===b())return i.lines;const s=A(i.view,t);return this.preview={...i,width:t,links:b(),lines:s},s}return this.schedulePreview(e),this.previewFailed===e.dir?[`${h}page could not be read${a}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,f().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=y(t),s=this.preview?.width??g(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:t.revision,view:i,width:s,links:b(),lines:A(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 f().getHumanRequest(e)}catch{return}}passiveDetailLines(e,t){const i=this.currentRow();if(i===void 0)return[` ${h}Select a pending interaction.${a}`];const s=[...O(q(i.title),Math.max(10,e-2)).map(r=>` ${M}${L}${r}${a}`),""];for(const r of C(i.subtitle,Math.max(1,e-2)))s.push(` ${r}`);const n=i.kind==="page"?this.pagePreviewBody(i,e):[`${h}1 file to review${a}`];if(n.length>0){s.push("");const r=Math.max(0,t-s.length),l=n.length<=r?n:n.slice(0,Math.max(0,r-1));for(const c of l)s.push(` ${c}`);l.length<n.length&&s.push(` ${h}\u2026 +${n.length-l.length} more lines${a}`)}return s.map(r=>p(r,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]=`${k}${t}${a}`,i}markDirty(){this.options.onDirty()}watchRoots(){const e=T(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=F(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}}async function te(){const{tickets:d}=await f().listHumanInbox();return d.map(X).sort(G)}o(te,"defaultScan");function A(d,e){const t=d.manifest.dialect==="html"?K(d.document):j(d.document,d.manifest);return Y(d.manifest,t,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}o(A,"previewLines");function D(d){return d!==void 0&&d.state!=="pending"}o(D,"isSettled");function w(d){return d?.page===void 0?"ticket was already resolved":$(d.page)}o(w,"settledStatus");export{Ie as InboxController};
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 +1 @@
1
- var y=Object.defineProperty;var l=(n,e)=>y(n,"name",{value:e,configurable:!0});import{RESET as r,BOLD as b,DIM as $,ITALIC as m,CYAN as w,RED as x,GRAY as L,YELLOW as M,truncateRow as g}from"./tui/ansi.js";function I(n,e){switch(e){case"gray":return`${L}${n}${r}`;case"cyan":return`${w}${n}${r}`;case"red":return`${x}${n}${r}`;case"yellow":return`${M}${n}${r}`;default:return n}}l(I,"ansiColor");const R={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},k={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function v(n){const e=Math.floor((Date.now()-new Date(n).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}l(v,"formatTimeAgo");function T(n,e,d,t,o=Number.MAX_SAFE_INTEGER){const i=[` ${b}${n.length} pending${r} ${$}\xB7 ${t.label}${r}`];if(t.hint!==void 0&&i.push(` ${$}${t.hint}${r}`),i.push(""),n.length===0)return[...i,` ${$}${m}No pending interactions${r}`];const u=e-4,f=n.map((a,h)=>A(a,h,d,u)),s=E(f,d,Math.max(1,o-i.length)),c=[...i];s.start>0&&c.push(` ${$}\u2191 ${s.start} above${r}`);for(let a=s.start;a<s.end;a++)c.push(...f[a]);return s.end<n.length&&c.push(` ${$}\u2193 ${n.length-s.end} below${r}`),c}l(T,"buildInboxLines");function A(n,e,d,t){const o=n.kind==="page"?n.awaitsResponse===!1?"display":"rich":n.kind,i=R[o]??"\xB7",u=v(n.kind==="page"?n.emittedAt:n.blockedSince),f=e===d?`${w}\u25B8${r} `:" ",s=Math.max(1,t-u.length-6),c=`${f}${I(i,k[o]??"cyan")} ${b}${g(n.title||`(${n.id.slice(0,8)})`,s)}${r} ${$}${u}${r}`,a=n.claim?`claimed by ${n.claim.owner} \xB7 ${n.subtitle}`:n.subtitle,h=[c,` ${$}${g(a,t-6)}${r}`],p=D(n);return p!==void 0&&h.push(` ${$}Recommended: ${g(p,Math.max(1,t-19))}${r}`),h}l(A,"buildItemLines");function D(n){if(!(n.kind!=="page"||n.recommendedOptions.length===0))return n.recommendedOptions.map(e=>e.label).join(" \xB7 ")}l(D,"recommendedLabel");function E(n,e,d){let t=Math.max(0,Math.min(e,n.length-1)),o=t+1,i=!0;for(;;){const u=o<n.length?{start:t,end:o+1}:void 0,f=t>0?{start:t-1,end:o}:void 0,c=(i?[u,f]:[f,u]).find(a=>a!==void 0&&N(n,a.start,a.end)<=d);if(c===void 0)break;t=c.start,o=c.end,i=!i}return{start:t,end:o}}l(E,"visibleWindow");function N(n,e,d){let t=e>0?1:0;for(let o=e;o<d;o++)t+=n[o].length;return d<n.length&&t++,t}l(N,"windowHeight");export{k as KIND_COLOR,R as KIND_ICON,T as buildInboxLines,v as formatTimeAgo,D as recommendedLabel};
1
+ var y=Object.defineProperty;var $=(n,e)=>y(n,"name",{value:e,configurable:!0});import{RESET as r,BOLD as p,DIM as l,ITALIC as b,CYAN as w,RED as m,GRAY as x,YELLOW as L,truncateRow as g}from"./tui/ansi.js";function M(n,e){switch(e){case"gray":return`${x}${n}${r}`;case"cyan":return`${w}${n}${r}`;case"red":return`${m}${n}${r}`;case"yellow":return`${L}${n}${r}`;default:return n}}$(M,"ansiColor");const I={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},R={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function k(n){const e=Math.floor((Date.now()-new Date(n).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}$(k,"formatTimeAgo");function C(n,e,c,t,o=Number.MAX_SAFE_INTEGER){const a=[` ${p}${n.length} pending${r} ${l}\xB7 ${t.label}${r}`];if(t.hint!==void 0&&a.push(` ${l}${t.hint}${r}`),a.push(""),n.length===0)return[...a,` ${l}${b}No pending interactions${r}`];const u=e-4,f=n.map((i,h)=>v(i,h,c,u)),d=D(f,c,Math.max(1,o-a.length)),s=[...a];d.start>0&&s.push(` ${l}\u2191 ${d.start} above${r}`);for(let i=d.start;i<d.end;i++)s.push(...f[i]);return d.end<n.length&&s.push(` ${l}\u2193 ${n.length-d.end} below${r}`),s}$(C,"buildInboxLines");function v(n,e,c,t){const o=n.kind==="page"?n.awaitsResponse===!1?"display":"rich":n.kind,a=I[o]??"\xB7",u=k(n.kind==="page"?n.emittedAt:n.blockedSince),f=e===c?`${w}\u25B8${r} `:" ",d=Math.max(1,t-u.length-6),i=[`${f}${M(a,R[o]??"cyan")} ${p}${g(n.title||`(${n.id.slice(0,8)})`,d)}${r} ${l}${u}${r}`,` ${l}${g(n.subtitle,t-6)}${r}`],h=A(n);return h!==void 0&&i.push(` ${l}Recommended: ${g(h,Math.max(1,t-19))}${r}`),i}$(v,"buildItemLines");function A(n){if(!(n.kind!=="page"||n.recommendedOptions.length===0))return n.recommendedOptions.map(e=>e.label).join(" \xB7 ")}$(A,"recommendedLabel");function D(n,e,c){let t=Math.max(0,Math.min(e,n.length-1)),o=t+1,a=!0;for(;;){const u=o<n.length?{start:t,end:o+1}:void 0,f=t>0?{start:t-1,end:o}:void 0,s=(a?[u,f]:[f,u]).find(i=>i!==void 0&&E(n,i.start,i.end)<=c);if(s===void 0)break;t=s.start,o=s.end,a=!a}return{start:t,end:o}}$(D,"visibleWindow");function E(n,e,c){let t=e>0?1:0;for(let o=e;o<c;o++)t+=n[o].length;return c<n.length&&t++,t}$(E,"windowHeight");export{R as KIND_COLOR,I as KIND_ICON,C as buildInboxLines,k as formatTimeAgo,A as recommendedLabel};
@@ -1 +1 @@
1
- var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{ApiError as h}from"../../api/index.js";import{defineLeaf as u}from"../../core/command.js";import{InputError as c}from"../../core/io.js";import{paginate as y}from"../../core/pagination.js";import{cliClient as d,rethrowAsCliError as p}from"../api-client.js";async function b(){return(await d().listNodes()).map(e=>({node_id:e.node_id,name:e.name,cwd:e.cwd,parent:e.parent,status:e.status}))}s(b,"fetchNodeRefs");function q(e,t){if(e===void 0)return;const n=new Map(t.map(r=>[r.node_id,r]));let i=e;const o=new Set;for(;i.parent!==null&&!o.has(i.node_id);){o.add(i.node_id);const r=n.get(i.parent);if(r===void 0)break;i=r}return i}s(q,"resolveConversation");function v(e){const t=e?.sessionName?.trim();if(t!==void 0&&t!=="")return t;const n=e?.askedBy?.trim();return n===""?void 0:n}s(v,"readableSourceLabel");function x(e,t,n){const i=e.source.nodeId===void 0?void 0:n.get(e.source.nodeId),o=q(i,t),r=v(e.source);return{ticket_id:e.request_id,dir:e.request_dir,title:e.title,subtitle:e.subtitle??"",kind:e.kind,...e.kind==="page"?{emitted_at:e.emitted_at}:{blocked_since:e.blocked_since},...r===void 0?{}:{source_label:r},...i===void 0?{}:{asking_node_id:i.node_id,asking_node_name:i.name,cwd:i.cwd},...o===void 0?{}:{conversation_id:o.node_id,conversation_title:o.name}}}s(x,"summarizeTicket");async function k(e){try{const n=await d().getHumanRequest(e);return{request_id:n.request_id,kind:n.kind}}catch(n){(!(n instanceof h)||n.status!==404)&&p(n)}const t=(await d().listHumanInbox()).tickets.find(n=>n.request_id===e);if(t===void 0)throw new c({error:"not_found",message:`no interaction ticket: ${e}`,field:"ticket_id",next:"Pass a ticket_id from `crtr human list`."});return{request_id:t.request_id,kind:t.kind}}s(k,"requireInteraction");function g(e){return e instanceof h&&e.status===409&&(e.code==="already_settled"||e.code==="review_terminal_conflict")}s(g,"isAlreadySettled");const A=u({name:"list",description:"enumerate pending interactions",whenToUse:"discovering what is blocked on the user",help:{name:"human list",summary:"paginated list of pending interactions, oldest first",params:[{kind:"flag",name:"limit",type:"int",required:!1,default:20,constraint:"Default 20, max 100."},{kind:"flag",name:"cursor",type:"string",required:!1,constraint:"Opaque token from a previous response's next_cursor. Omit on first call."}],output:[{name:"items",type:"object[]",required:!0,constraint:"Each: {ticket_id, dir, title, subtitle, kind, emitted_at? | blocked_since?}; pages use emitted_at, reviews use blocked_since. Enriched when derivable with claim_owner, source_label, asking_node_id/name, conversation_id/title. Oldest first."},{name:"next_cursor",type:"string | null",required:!0,constraint:"Pass on the next call to continue. null means no more items."},{name:"total",type:"integer | null",required:!0,constraint:"Total pending interactions."}],outputKind:"object",effects:["None. Read-only."]},run:s(async e=>{const t=Math.min(Math.max(1,e.limit),100),n=await b(),i=new Map(n.map(a=>[a.node_id,a])),o=(await d().listHumanInbox()).tickets.map(a=>x(a,n,i)).sort((a,l)=>{const m=`${a.emitted_at??a.blocked_since}|${a.ticket_id}`,f=`${l.emitted_at??l.blocked_since}|${l.ticket_id}`;return m<f?-1:m>f?1:0}),r=y(o,{limit:t,cursor:e.cursor},{defaultLimit:20,maxLimit:100,keyOf:s(a=>`${a.emitted_at??a.blocked_since}|${a.ticket_id}`,"keyOf"),total:"count"});return{items:r.items,next_cursor:r.next_cursor,total:r.total}},"run")});function $(e){let t;try{t=JSON.parse(e)}catch(n){throw new c({error:"invalid_json",message:`stdin is not valid JSON: ${String(n)}`,field:"stdin",next:'Pass {"responses":{"<component_id>":{...}}} on stdin.'})}if(typeof t.responses!="object"||t.responses===null||Array.isArray(t.responses))throw new c({error:"invalid_field",message:"responses must be an object keyed by the id of a response-bearing component",field:"responses",next:'Pass {"responses":{"<component_id>":{...}}}, or {"responses":{}} to acknowledge a page with no response-bearing components.'});return t.responses}s($,"parseResolveBody");const L=u({name:"resolve",description:"resolve one human page from stdin answers",whenToUse:"an API client or local tool is submitting answers for a pending human interaction.",tier:"hidden",help:{name:"human resolve",summary:"resolve a pending page with the given answers",params:[{kind:"positional",name:"ticket_id",type:"string",required:!0,constraint:"page_id from human send, or a page ticket_id from human list."},{kind:"stdin",name:"body",required:!0,constraint:"JSON {responses:{<component_id>:{...}}} \u2014 one typed response object per response-bearing component of the page."}],output:[{name:"resolved",type:"boolean",required:!0,constraint:"True when this call completed the page."},{name:"ticket_id",type:"string",required:!0,constraint:"Interaction request id."},{name:"reason",type:"string",required:!1,constraint:"already_settled when resolved is false."}],outputKind:"object",effects:["The daemon settles the request and directly delivers a reply-bearing completion to its asking node."]},run:s(async e=>{const t=e.ticket_id,n=await k(t);if(n.kind!=="page")throw new c({error:"not_found",message:`no page for interaction: ${t}`,field:"ticket_id",next:"Pass a pending page ticket_id from `crtr human list`."});try{await d().respondHumanRequest(n.request_id,{responses:$(e.body),actor:_()??"human"})}catch(i){if(g(i))return{resolved:!1,ticket_id:t,reason:"already_settled"};p(i)}return{resolved:!0,ticket_id:t}},"run")}),P=u({name:"cancel",description:"retract a pending page/review",whenToUse:"a page or review went stale before the user completed it",help:{name:"human cancel",summary:"retract a pending page or review",params:[{kind:"positional",name:"ticket_id",type:"string",required:!0,constraint:"page_id returned by human send, or ticket_id returned by human list."},{kind:"flag",name:"reason",type:"string",required:!1,constraint:"Optional short note delivered to the asking node explaining why it was retracted."}],output:[{name:"canceled",type:"boolean",required:!0,constraint:"True when the interaction was retracted; false when it was already terminal."},{name:"ticket_id",type:"string",required:!0,constraint:"The interaction request id."},{name:"reason",type:"string",required:!1,constraint:"already_settled when canceled is false."}],outputKind:"object",effects:["The daemon removes the request from the human inbox and directly notifies its asking node when it has one."]},run:s(async e=>{const t=e.ticket_id,n=await k(t),i=e.reason,o={...i===void 0||i===""?{}:{reason:i},actor:_()??"human"};try{n.kind==="review"?await d().cancelReview(n.request_id,o):await d().cancelHumanRequest(n.request_id,o)}catch(r){if(g(r))return{canceled:!1,ticket_id:t,reason:"already_settled"};p(r)}return{canceled:!0,ticket_id:t}},"run"),render:s(e=>e.canceled===!0?`Canceled human interaction ${e.ticket_id} \u2014 it left the human inbox.`:`Nothing to cancel for ${e.ticket_id} \u2014 ${e.reason??"nothing to cancel"}.`,"render")});export{P as humanCancel,A as humanList,L as humanResolve};
1
+ var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{ApiError as h}from"../../api/index.js";import{defineLeaf as l}from"../../core/command.js";import{InputError as c}from"../../core/io.js";import{paginate as y}from"../../core/pagination.js";import{cliClient as d,rethrowAsCliError as p}from"../api-client.js";async function b(){return(await d().listNodes()).map(e=>({node_id:e.node_id,name:e.name,cwd:e.cwd,parent:e.parent,status:e.status}))}s(b,"fetchNodeRefs");function q(e,t){if(e===void 0)return;const n=new Map(t.map(r=>[r.node_id,r]));let i=e;const o=new Set;for(;i.parent!==null&&!o.has(i.node_id);){o.add(i.node_id);const r=n.get(i.parent);if(r===void 0)break;i=r}return i}s(q,"resolveConversation");function v(e){const t=e?.sessionName?.trim();if(t!==void 0&&t!=="")return t;const n=e?.askedBy?.trim();return n===""?void 0:n}s(v,"readableSourceLabel");function x(e,t,n){const i=e.source.nodeId===void 0?void 0:n.get(e.source.nodeId),o=q(i,t),r=v(e.source);return{ticket_id:e.request_id,dir:e.request_dir,title:e.title,subtitle:e.subtitle??"",kind:e.kind,...e.kind==="page"?{emitted_at:e.emitted_at}:{blocked_since:e.blocked_since},...r===void 0?{}:{source_label:r},...i===void 0?{}:{asking_node_id:i.node_id,asking_node_name:i.name,cwd:i.cwd},...o===void 0?{}:{conversation_id:o.node_id,conversation_title:o.name}}}s(x,"summarizeTicket");async function k(e){try{const n=await d().getHumanRequest(e);return{request_id:n.request_id,kind:n.kind}}catch(n){(!(n instanceof h)||n.status!==404)&&p(n)}const t=(await d().listHumanInbox()).tickets.find(n=>n.request_id===e);if(t===void 0)throw new c({error:"not_found",message:`no interaction ticket: ${e}`,field:"ticket_id",next:"Pass a ticket_id from `crtr human list`."});return{request_id:t.request_id,kind:t.kind}}s(k,"requireInteraction");function g(e){return e instanceof h&&e.status===409&&(e.code==="already_settled"||e.code==="review_terminal_conflict")}s(g,"isAlreadySettled");const A=l({name:"list",description:"enumerate pending interactions",whenToUse:"discovering what is blocked on the user",help:{name:"human list",summary:"paginated list of pending interactions, oldest first",params:[{kind:"flag",name:"limit",type:"int",required:!1,default:20,constraint:"Default 20, max 100."},{kind:"flag",name:"cursor",type:"string",required:!1,constraint:"Opaque token from a previous response's next_cursor. Omit on first call."}],output:[{name:"items",type:"object[]",required:!0,constraint:"Each: {ticket_id, dir, title, subtitle, kind, emitted_at? | blocked_since?}; pages use emitted_at, reviews use blocked_since. Enriched when derivable with source_label, asking_node_id/name, conversation_id/title. Oldest first."},{name:"next_cursor",type:"string | null",required:!0,constraint:"Pass on the next call to continue. null means no more items."},{name:"total",type:"integer | null",required:!0,constraint:"Total pending interactions."}],outputKind:"object",effects:["None. Read-only."]},run:s(async e=>{const t=Math.min(Math.max(1,e.limit),100),n=await b(),i=new Map(n.map(a=>[a.node_id,a])),o=(await d().listHumanInbox()).tickets.map(a=>x(a,n,i)).sort((a,u)=>{const m=`${a.emitted_at??a.blocked_since}|${a.ticket_id}`,f=`${u.emitted_at??u.blocked_since}|${u.ticket_id}`;return m<f?-1:m>f?1:0}),r=y(o,{limit:t,cursor:e.cursor},{defaultLimit:20,maxLimit:100,keyOf:s(a=>`${a.emitted_at??a.blocked_since}|${a.ticket_id}`,"keyOf"),total:"count"});return{items:r.items,next_cursor:r.next_cursor,total:r.total}},"run")});function $(e){let t;try{t=JSON.parse(e)}catch(n){throw new c({error:"invalid_json",message:`stdin is not valid JSON: ${String(n)}`,field:"stdin",next:'Pass {"responses":{"<component_id>":{...}}} on stdin.'})}if(typeof t.responses!="object"||t.responses===null||Array.isArray(t.responses))throw new c({error:"invalid_field",message:"responses must be an object keyed by the id of a response-bearing component",field:"responses",next:'Pass {"responses":{"<component_id>":{...}}}, or {"responses":{}} to acknowledge a page with no response-bearing components.'});return t.responses}s($,"parseResolveBody");const L=l({name:"resolve",description:"resolve one human page from stdin answers",whenToUse:"an API client or local tool is submitting answers for a pending human interaction.",tier:"hidden",help:{name:"human resolve",summary:"resolve a pending page with the given answers",params:[{kind:"positional",name:"ticket_id",type:"string",required:!0,constraint:"page_id from human send, or a page ticket_id from human list."},{kind:"stdin",name:"body",required:!0,constraint:"JSON {responses:{<component_id>:{...}}} \u2014 one typed response object per response-bearing component of the page."}],output:[{name:"resolved",type:"boolean",required:!0,constraint:"True when this call completed the page."},{name:"ticket_id",type:"string",required:!0,constraint:"Interaction request id."},{name:"reason",type:"string",required:!1,constraint:"already_settled when resolved is false."}],outputKind:"object",effects:["The daemon settles the request and directly delivers a reply-bearing completion to its asking node."]},run:s(async e=>{const t=e.ticket_id,n=await k(t);if(n.kind!=="page")throw new c({error:"not_found",message:`no page for interaction: ${t}`,field:"ticket_id",next:"Pass a pending page ticket_id from `crtr human list`."});try{await d().respondHumanRequest(n.request_id,{responses:$(e.body),actor:_()??"human"})}catch(i){if(g(i))return{resolved:!1,ticket_id:t,reason:"already_settled"};p(i)}return{resolved:!0,ticket_id:t}},"run")}),P=l({name:"cancel",description:"retract a pending page/review",whenToUse:"a page or review went stale before the user completed it",help:{name:"human cancel",summary:"retract a pending page or review",params:[{kind:"positional",name:"ticket_id",type:"string",required:!0,constraint:"page_id returned by human send, or ticket_id returned by human list."},{kind:"flag",name:"reason",type:"string",required:!1,constraint:"Optional short note delivered to the asking node explaining why it was retracted."}],output:[{name:"canceled",type:"boolean",required:!0,constraint:"True when the interaction was retracted; false when it was already terminal."},{name:"ticket_id",type:"string",required:!0,constraint:"The interaction request id."},{name:"reason",type:"string",required:!1,constraint:"already_settled when canceled is false."}],outputKind:"object",effects:["The daemon removes the request from the human inbox and directly notifies its asking node when it has one."]},run:s(async e=>{const t=e.ticket_id,n=await k(t),i=e.reason,o={...i===void 0||i===""?{}:{reason:i},actor:_()??"human"};try{n.kind==="review"?await d().cancelReview(n.request_id,o):await d().cancelHumanRequest(n.request_id,o)}catch(r){if(g(r))return{canceled:!1,ticket_id:t,reason:"already_settled"};p(r)}return{canceled:!0,ticket_id:t}},"run"),render:s(e=>e.canceled===!0?`Canceled human interaction ${e.ticket_id} \u2014 it left the human inbox.`:`Nothing to cancel for ${e.ticket_id} \u2014 ${e.reason??"nothing to cancel"}.`,"render")});export{P as humanCancel,A as humanList,L as humanResolve};
@@ -1 +1 @@
1
- var w=Object.defineProperty;var o=(n,e)=>w(n,"name",{value:e,configurable:!0});import{defineLeaf as u,defineBranch as f}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as g}from"../../core/wake.js";import{DaemonNotPreparedError as y,probeDaemonHealth as p,probeErrorMessage as b,spawnDaemon as h,stopDaemonProcess as v,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as l,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{localClient as c}from"../../api/node-transport.js";import{defineSysBranch as q}from"./branch.js";import{selectedGeneration as x}from"./shared.js";const I=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."},{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.","Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async n=>{try{return await h({targetPhase:n.prepare===!0?"prepared":"ready",ignoreJoinLock:n.force===!0})}catch(e){throw e instanceof y?new d({error:"daemon_not_prepared",message:e.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):e}},"run")}),D=100;async function S(n,e){const t=Date.now(),a=t+e;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<a;){try{const r=await p(Math.min(1e3,Math.max(1,a-Date.now())));if(s=r.startup_phase,i=r.startup_blocked??`daemon is ${r.startup_phase}`,r.startup_phase==="blocked")throw new d({error:"startup_blocked",message:r.startup_blocked??"daemon startup is blocked",received:r.startup_phase,field:"phase",next:"Repair the reported blocker paths with `crtr sys migrate`, then retry the await."});if(r.startup_phase===n)return{startup_phase:n,waited_ms:Date.now()-t};if(n==="prepared"&&r.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:r.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(r){if(r instanceof d)throw r;i=r instanceof Error?r.message:String(r)}await new Promise(r=>setTimeout(r,Math.min(D,Math.max(0,a-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${e}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(S,"awaitDaemonPhase");const E=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async n=>{const e=n.timeout,t=g(e);if(t===null||t<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${e}`,received:e,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return S(n.phase,t)},"run")}),R=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async n=>await c({autostart:!1}).admitDaemon(),"run")});async function P(){try{return(await c({autostart:!1}).status()).generation_id??void 0}catch{return}}o(P,"servingGenerationId");const A=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async n=>{const e=l();if(!(e!==null&&m(e)))return{running:!1};try{const a=await p(),s=await P(),i=x().generation?.id;return{running:!0,serving:a.ok,pid:e,...a.startup_phase===void 0?{}:{startup_phase:a.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(a){return{running:!0,serving:!1,pid:e,probe_error:b(a)}}},"run")}),j=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async n=>{const e=T({local:!0});if(!k()){const t=await h();return{restarted:!1,started:t.started,...t.pid!==void 0?{pid:t.pid}:{},...t.existing_pid!==void 0?{pid:t.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}try{const t=await e.restartDaemon();return{restarted:t.accepted,pid:t.predecessor_pid,grace_ms:t.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(t){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${t.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),U=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async n=>{const e=l(),t=e!==null&&m(e);try{let a=!1;t&&(a=await v(e)==="killed");const s=_(null);return!t&&s.length===0?{stopped:!1}:{stopped:!0,...t?{pid:e}:{},...s.length>0?{strays_killed:s}:{},...a?{force_killed:!0}:{}}}catch(a){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${t?` pid ${e}`:""}: ${a.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),L=f({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[I,E,R,j,A,U]});function W(){return q([L])}o(W,"registerDaemonControlSys");export{L as daemonBranch,W as registerDaemonControlSys};
1
+ var f=Object.defineProperty;var o=(n,t)=>f(n,"name",{value:t,configurable:!0});import{defineLeaf as u,defineBranch as g}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as y}from"../../core/wake.js";import{DaemonNotPreparedError as b,probeDaemonHealth as l,probeErrorMessage as v,spawnDaemon as p,stopDaemonProcess as c,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as h,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{readMachineConfig as q}from"../../daemon/machine-link/config.js";import{localClient as w}from"../../api/node-transport.js";import{defineSysBranch as x}from"./branch.js";import{selectedGeneration as I}from"./shared.js";const D=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."},{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.","Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async n=>{try{return await p({targetPhase:n.prepare===!0?"prepared":"ready",ignoreJoinLock:n.force===!0})}catch(t){throw t instanceof b?new d({error:"daemon_not_prepared",message:t.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):t}},"run")}),S=100;async function E(n,t){const e=Date.now(),r=e+t;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<r;){try{const a=await l(Math.min(1e3,Math.max(1,r-Date.now())));if(s=a.startup_phase,i=a.startup_blocked??`daemon is ${a.startup_phase}`,a.startup_phase==="blocked")throw new d({error:"startup_blocked",message:a.startup_blocked??"daemon startup is blocked",received:a.startup_phase,field:"phase",next:"Repair the reported blocker paths with `crtr sys migrate`, then retry the await."});if(a.startup_phase===n)return{startup_phase:n,waited_ms:Date.now()-e};if(n==="prepared"&&a.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:a.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(a){if(a instanceof d)throw a;i=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,Math.min(S,Math.max(0,r-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${t}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(E,"awaitDaemonPhase");const R=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async n=>{const t=n.timeout,e=y(t);if(e===null||e<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${t}`,received:t,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return E(n.phase,e)},"run")}),P=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async n=>await w({autostart:!1}).admitDaemon(),"run")});async function A(){try{return(await w({autostart:!1}).status()).generation_id??void 0}catch{return}}o(A,"servingGenerationId");const j=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async n=>{const t=h();if(!(t!==null&&m(t)))return{running:!1};try{const r=await l(),s=await A(),i=I().generation?.id;return{running:!0,serving:r.ok,pid:t,...r.startup_phase===void 0?{}:{startup_phase:r.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(r){return{running:!0,serving:!1,pid:t,probe_error:v(r)}}},"run")}),M=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async n=>{const t=T({local:!0});if(!k()){const e=await p();return{restarted:!1,started:e.started,...e.pid!==void 0?{pid:e.pid}:{},...e.existing_pid!==void 0?{pid:e.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}if(q()!==void 0){const e=h();e!==null&&await c(e);const r=await p(),s=r.pid??r.existing_pid;return{restarted:!0,...s!==void 0?{pid:s}:{},note:"Machine-role daemon replaced on the selected runtime generation. Its brokers kept running; no node was interrupted."}}try{const e=await t.restartDaemon();return{restarted:e.accepted,pid:e.predecessor_pid,grace_ms:e.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(e){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${e.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),U=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async n=>{const t=h(),e=t!==null&&m(t);try{let r=!1;e&&(r=await c(t)==="killed");const s=_(null);return!e&&s.length===0?{stopped:!1}:{stopped:!0,...e?{pid:t}:{},...s.length>0?{strays_killed:s}:{},...r?{force_killed:!0}:{}}}catch(r){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${e?` pid ${t}`:""}: ${r.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),L=g({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[D,R,P,M,j,U]});function J(){return x([L])}o(J,"registerDaemonControlSys");export{L as daemonBranch,J as registerDaemonControlSys};
@@ -1,5 +1,6 @@
1
1
  /** Find only terminal nodes with an unreconciled, explicitly disposable worktree. A node that ever ran in a Blaxel sandbox
2
- * is never a candidate: its sandbox is its worktree and the control plane has no checkout to sweep (D102).
2
+ * is never a candidate: its sandbox is its worktree and the control plane has no checkout to sweep (D102). Nor is a node that
3
+ * ever ran on an imported Mac: its checkout is on that Mac, and the sweep runs Git on this host.
3
4
  * Keep due-time parsing in JS: Date.parse accepts more than SQLite's date
4
5
  * functions, and malformed dates are due rather than permanently skipped. */
5
6
  export declare function managedWorktreeSweepCandidates(now: number): Promise<string[]>;
@@ -5,7 +5,7 @@ var d=Object.defineProperty;var s=(t,o)=>d(t,"name",{value:o,configurable:!0});i
5
5
  JOIN nodes n ON n.node_id = w.node_id
6
6
  WHERE n.status IN ('done', 'dead', 'canceled')
7
7
  AND n.node_id NOT IN (SELECT node_id FROM warm_pool)
8
- AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.runner = 'blaxel')
8
+ AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.runner IN ('blaxel', 'machine'))
9
9
  AND w.state IN ('open', 'closed')
10
10
  AND (w.state = 'open' OR w.cleanup_state IS NULL OR w.cleanup_state != 'complete')
11
11
  AND (w.state = 'closed' OR (n.status = 'done' AND n.final_report IS NOT NULL))
@@ -0,0 +1,7 @@
1
+ -- 017-machine-worktree-ops.sql — the managed-worktree ops a control plane sends an imported Mac over its link (`worktree.create`,
2
+ -- `worktree.rollback`, `worktree.close`, `worktree.abandon`, `worktree.finalize`). One transaction, additions only: `schema_min_reader`
3
+ -- is not touched, so the previous release (version 16) still opens the result. Widening a CHECK is rollback-safe (008 did the same for
4
+ -- `executions_runner_check`): the previous build never writes these ops.
5
+ ALTER TABLE machine_calls DROP CONSTRAINT IF EXISTS machine_calls_op_check;
6
+ ALTER TABLE machine_calls ADD CONSTRAINT machine_calls_op_check CHECK (op IN ('start', 'wake', 'stop', 'status', 'delete', 'viewer', 'cron.run', 'cron.cancel',
7
+ 'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize'));
@@ -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 = 16;
4
+ export declare const CANVAS_SCHEMA_VERSION = 17;
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=16;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=17;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};
@@ -7,5 +7,9 @@ import type { ValidatedContribution, ValidatedCoreMount } from './discovery.js';
7
7
  export declare function composeSandboxProviderSubtrees(providers: readonly (ProviderToolDescription | UnavailableProviderToolDescription)[], reserved: ReadonlySet<string>): BranchDef[];
8
8
  export declare function adaptPluginContributions(contributions: ValidatedContribution[]): CommandRegistrySnapshot;
9
9
  export declare function adaptPluginCoreMounts(mounts: ValidatedCoreMount[]): CoreBranchMount[];
10
- export declare function composeExternalSubtrees(snapshot: CommandRegistrySnapshot): BranchDef[];
10
+ /** The tools a provider's help lists, by provider id. */
11
+ export type ProviderToolsLookup = (providerId: string) => Promise<ReadonlySet<string>>;
12
+ /** `allowedTools` replaces the per-provider `GET /v1/providers/<id>/tools` behind each provider branch's help, for a caller that
13
+ * already holds the provider catalog (`GET /v1/providers/tools`) from this invocation. */
14
+ export declare function composeExternalSubtrees(snapshot: CommandRegistrySnapshot, allowedTools?: ProviderToolsLookup): BranchDef[];
11
15
  export declare function composeCoreBranchMounts(mounts: readonly CoreBranchMount[], parent: string[]): (BranchDef | LeafDef)[];
@@ -1 +1 @@
1
- var b=Object.defineProperty;var o=(n,e)=>b(n,"name",{value:e,configurable:!0});import{resolve as _}from"node:path";import{ExitCode as j}from"../../types.js";import{envNodeId as A}from"../../shared/env.js";import{cliClient as f}from"../../commands/api-client.js";import{apiErrorToCliError as h}from"../io.js";import{ApiError as l}from"../../api/index.js";import{defineBranch as y,defineLeaf as L}from"../command.js";import{qualifiedTopLevelCommandName as M,resolveCommandRegistry as N}from"../command-manifests/registry.js";import{executeExternalLeaf as S}from"./transport/exec-invoke.js";import{invokeHttpLeaf as U}from"./transport/http-invoke.js";import{readPathParam as P}from"./transport/http-plan.js";import{sha256Hex as H,signedHeaderDigest as R}from"./transport/sign.js";import{needsAppToken as K}from"../plugin-objects-manifest.js";async function $(n){const e=await f().request("GET",`/v1/providers/${encodeURIComponent(n)}/tools`);return new Set(e.groups.flatMap(a=>a.leaves.map(t=>t.tool)))}o($,"allowedProviderTools");function g(n,e,a){return n.children.some(t=>t.kind==="leaf"?a.has([...e,t.name].join(" ")):g(t,[...e,t.name],a))}o(g,"hasAllowedLeaf");function I(n,e,a){return n.children.filter(t=>t.tier!=="hidden"&&(t.kind==="leaf"?a.has([...e,t.name].join(" ")):g(t,[...e,t.name],a))).length}o(I,"visibleChildCount");function E(n,e,a){return async()=>{if(!A())return n.help;const t=await a();return{...n.help,listing:n.help.listing?.flatMap(d=>{const i=n.children.find(c=>c.name===d.name);if(i?.kind==="leaf")return t.has([...e,i.name].join(" "))?[d]:[];if(i?.kind!=="branch")return[];const s=[...e,i.name];if(!g(i,s,t))return[];const p=I(i,s,t);return[{...d,...d.subCount!==void 0?{subCount:p}:{}}]})}}}o(E,"providerHelp");const O="Runs on one of your devices. Add `--machine <machine_id>` to pick which; without it the call goes to your only device, and with several the answer is `machine_required` listing each one's machine_id. The `runtime:` prefix on the id is optional.";function w(n,e,a,t=!1){return{outputKind:"object",...t?{machineSelector:!0}:{},run:o(async(d,i)=>{const s={...d};for(const p of a.params){if(!("type"in p))continue;const c=p.name.replace(/-([a-z])/g,(u,m)=>m.toUpperCase()),r=s[c];p.type==="file"&&typeof r=="string"?s[c]=_(r):p.type==="path"&&r!==void 0&&(s[c]=P(`provider command \`${n} ${e}\``,p,r))}try{return await f({timeoutMs:0}).request("POST","/v1/provider/call",{provider:n,tool:e,arguments:s,...i?.machine===void 0?{}:{machine:i.machine}},{timeout:0})}catch(p){throw p instanceof l?h(p,void 0,{providerCall:!0}):p}},"run")}}o(w,"providerLeafAdapter");function k(n,e){return/^[A-Za-z0-9_-]{1,64}$/.test(n)&&n!=="crtr"&&!e.has(n)}o(k,"validRootName");function re(n,e){const a=[],t=[];for(const i of n){const{provider:s,commands:p}=i;if(!Array.isArray(p)||i.status!=="available"&&!k(s,e))continue;if(i.status!=="available"){const r=i.error??"bundle installation pending",u=`Unavailable (${i.status}): ${r}`,m=y({name:s,rootEntry:{concept:i.display_name,desc:u,useWhen:u},help:{name:s,summary:u},children:[],refusal:{code:"provider_unavailable",message:u,exit:j.NETWORK,next:"The daemon retries bundle installation on grant sync; retry after the provider becomes available."}});t.push(m);continue}const c=o(r=>r.kind==="branch"?{...r,children:r.children.map(c)}:{...r,rest:{method:"GET",path:"/",params:{}}},"helpNode");for(const r of p){if(r.kind!=="branch"||!Array.isArray(r.children)||!k(r.name,e))continue;const u=c(r);a.push({contributor:{name:s,scope:"user"},manifestName:r.name,node:i.groups.length===0?{...u,rootEntry:void 0}:u,adaptLeaf:o((m,T)=>w(s,T.slice(1).join(" "),m,i.transport==="machine"),"adaptLeaf")})}}const d=D(N(a,e));for(const i of d){const s=n.find(r=>r.status==="available"&&r.commands.some(u=>u.name===i.name||M({name:r.provider},u.name)===i.name));if(s?.status!=="available")continue;const p=new Set(s.groups.flatMap(r=>r.leaves.map(u=>u.tool))),c=o((r,u)=>{r.effectiveHelp=E(r,u,async()=>p);for(const m of r.children)m.kind==="branch"&&c(m,[...u,m.name])},"attachHelp");c(i,[])}return[...d,...t]}o(re,"composeSandboxProviderSubtrees");async function q(n){try{const{token:e,socket:a}=await f().plugins.appToken(n);return{CRTR_APP_TOKEN:e,CRTR_DAEMON_SOCKET:a}}catch(e){if(e instanceof l&&(e.status===404||e.status===403))return;throw e instanceof l?h(e):e}}o(q,"appEnvFor");function x(n,e){return(a,t)=>{const d=n.transport,i=e(t);if(n.provider!==void 0)return w(n.provider.id,i.slice(1).join(" "),a,d.kind==="machine");if(d.kind==="exec"){const p=d.executable;if(p===void 0)throw new Error(`exec plugin "${n.plugin.name}" has an executable leaf without transport.executable`);return{outputKind:"object",run:o(async c=>{const r=K(n.plugin.manifest)?await q(n.plugin.name):void 0;return S({plugin:n.plugin,executable:p,commandPath:i,output:a.output,...r!==void 0?{appEnv:r}:{}},c)},"run")}}if(d.kind==="machine")throw new Error(`machine plugin "${n.plugin.name}" is not a capability provider`);const s=a;return{outputKind:s.rest.streaming===!0?"jsonl":"object",run:o((p,c)=>U({registration:{name:n.plugin.name,endpoint:d.endpoint,...d.authEnv!==void 0?{authEnv:d.authEnv}:{}},...n.manifest?.baseUrl!==void 0?{baseUrl:n.manifest.baseUrl}:{},...n.manifest?.timeouts!==void 0?{timeouts:n.manifest.timeouts}:{},params:s.params,rest:s.rest,output:s.output,commandPath:i},p,c,{callHeaders:o(r=>f().plugins.callHeaders(n.plugin.name,{method:r.method,url:r.url.href,body_sha256:H(r.body),...R(r.headers)}).then(u=>u.headers,u=>{throw u instanceof l?h(u):u}),"callHeaders")}),"run")}}}o(x,"adaptLeaf");function te(n){return{contributions:n.map(e=>({contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,manifestName:e.manifestName,adaptLeaf:x(e,a=>[e.manifestName,...a.slice(1)]),...e.provider!==void 0?{provider:e.provider}:{}})),coreMounts:[],issues:[]}}o(te,"adaptPluginContributions");function ie(n){return n.map(e=>({parent:e.parent,plugin:e.plugin.name,contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,...e.provider!==void 0?{provider:e.provider}:{},adaptLeaf:x({...e,manifestName:e.node.name},a=>e.provider===void 0?[...a]:[e.provider.id,...a.slice(e.parent.length)])}))}o(ie,"adaptPluginCoreMounts");function D(n){return n.contributions.map(e=>v(e,e.node,[e.node.name]))}o(D,"composeExternalSubtrees");function se(n,e){return n.filter(a=>a.parent.join("\0")===e.join("\0")).map(a=>a.node.kind==="branch"?v(a,a.node,[...e,a.node.name],a.provider===void 0?1:e.length):C(a,a.node,[...e,a.node.name]))}o(se,"composeCoreBranchMounts");function v(n,e,a,t=1){const d=e.rootEntry===void 0?void 0:{concept:e.rootEntry.concept,desc:e.rootEntry.description,useWhen:e.rootEntry.whenToUse},i=y({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...d!==void 0?{rootEntry:d}:{},help:{name:a.join(" "),summary:e.summary,...e.model!==void 0?{model:e.model}:{},...a.length===1&&n.extensionIssue!==void 0?{extensionIssue:n.extensionIssue}:{}},...e.passthrough!==void 0?{passthrough:e.passthrough}:{},children:e.children.map(s=>s.kind==="branch"?v(n,s,[...a,s.name],t):C(n,s,[...a,s.name]))});return n.provider!==void 0&&(i.effectiveHelp=E(i,a.slice(t),()=>$(n.provider.id))),i}o(v,"buildBranch");function C(n,e,a){const t=n.adaptLeaf(e,a);return L({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...t.machineSelector===!0?{machineSelector:!0}:{},help:{name:a.join(" "),summary:e.summary,...t.machineSelector===!0?{guide:O}:{},params:e.params,output:e.output,outputKind:t.outputKind,effects:[...e.effects]},run:t.run})}o(C,"buildLeaf");export{te as adaptPluginContributions,ie as adaptPluginCoreMounts,se as composeCoreBranchMounts,D as composeExternalSubtrees,re as composeSandboxProviderSubtrees};
1
+ var _=Object.defineProperty;var u=(n,e)=>_(n,"name",{value:e,configurable:!0});import{resolve as j}from"node:path";import{ExitCode as A}from"../../types.js";import{envNodeId as L}from"../../shared/env.js";import{cliClient as f}from"../../commands/api-client.js";import{apiErrorToCliError as h}from"../io.js";import{ApiError as l}from"../../api/index.js";import{defineBranch as y,defineLeaf as M}from"../command.js";import{qualifiedTopLevelCommandName as N,resolveCommandRegistry as S}from"../command-manifests/registry.js";import{executeExternalLeaf as U}from"./transport/exec-invoke.js";import{invokeHttpLeaf as P}from"./transport/http-invoke.js";import{readPathParam as H}from"./transport/http-plan.js";import{sha256Hex as R,signedHeaderDigest as K}from"./transport/sign.js";import{needsAppToken as $}from"../plugin-objects-manifest.js";async function E(n){const e=await f().request("GET",`/v1/providers/${encodeURIComponent(n)}/tools`);return new Set(e.groups.flatMap(a=>a.leaves.map(t=>t.tool)))}u(E,"allowedProviderTools");function g(n,e,a){return n.children.some(t=>t.kind==="leaf"?a.has([...e,t.name].join(" ")):g(t,[...e,t.name],a))}u(g,"hasAllowedLeaf");function I(n,e,a){return n.children.filter(t=>t.tier!=="hidden"&&(t.kind==="leaf"?a.has([...e,t.name].join(" ")):g(t,[...e,t.name],a))).length}u(I,"visibleChildCount");function w(n,e,a){return async()=>{if(!L())return n.help;const t=await a();return{...n.help,listing:n.help.listing?.flatMap(d=>{const i=n.children.find(c=>c.name===d.name);if(i?.kind==="leaf")return t.has([...e,i.name].join(" "))?[d]:[];if(i?.kind!=="branch")return[];const o=[...e,i.name];if(!g(i,o,t))return[];const s=I(i,o,t);return[{...d,...d.subCount!==void 0?{subCount:s}:{}}]})}}}u(w,"providerHelp");const O="Runs on one of your devices. Add `--machine <machine_id>` to pick which; without it the call goes to your only device, and with several the answer is `machine_required` listing each one's machine_id. The `runtime:` prefix on the id is optional.";function k(n,e,a,t=!1){return{outputKind:"object",...t?{machineSelector:!0}:{},run:u(async(d,i)=>{const o={...d};for(const s of a.params){if(!("type"in s))continue;const c=s.name.replace(/-([a-z])/g,(p,m)=>m.toUpperCase()),r=o[c];s.type==="file"&&typeof r=="string"?o[c]=j(r):s.type==="path"&&r!==void 0&&(o[c]=H(`provider command \`${n} ${e}\``,s,r))}try{return await f({timeoutMs:0}).request("POST","/v1/provider/call",{provider:n,tool:e,arguments:o,...i?.machine===void 0?{}:{machine:i.machine}},{timeout:0})}catch(s){throw s instanceof l?h(s,void 0,{providerCall:!0}):s}},"run")}}u(k,"providerLeafAdapter");function x(n,e){return/^[A-Za-z0-9_-]{1,64}$/.test(n)&&n!=="crtr"&&!e.has(n)}u(x,"validRootName");function re(n,e){const a=[],t=[];for(const i of n){const{provider:o,commands:s}=i;if(!Array.isArray(s)||i.status!=="available"&&!x(o,e))continue;if(i.status!=="available"){const r=i.error??"bundle installation pending",p=`Unavailable (${i.status}): ${r}`,m=y({name:o,rootEntry:{concept:i.display_name,desc:p,useWhen:p},help:{name:o,summary:p},children:[],refusal:{code:"provider_unavailable",message:p,exit:A.NETWORK,next:"The daemon retries bundle installation on grant sync; retry after the provider becomes available."}});t.push(m);continue}const c=u(r=>r.kind==="branch"?{...r,children:r.children.map(c)}:{...r,rest:{method:"GET",path:"/",params:{}}},"helpNode");for(const r of s){if(r.kind!=="branch"||!Array.isArray(r.children)||!x(r.name,e))continue;const p=c(r);a.push({contributor:{name:o,scope:"user"},manifestName:r.name,node:i.groups.length===0?{...p,rootEntry:void 0}:p,adaptLeaf:u((m,b)=>k(o,b.slice(1).join(" "),m,i.transport==="machine"),"adaptLeaf")})}}const d=D(S(a,e));for(const i of d){const o=n.find(r=>r.status==="available"&&r.commands.some(p=>p.name===i.name||N({name:r.provider},p.name)===i.name));if(o?.status!=="available")continue;const s=new Set(o.groups.flatMap(r=>r.leaves.map(p=>p.tool))),c=u((r,p)=>{r.effectiveHelp=w(r,p,async()=>s);for(const m of r.children)m.kind==="branch"&&c(m,[...p,m.name])},"attachHelp");c(i,[])}return[...d,...t]}u(re,"composeSandboxProviderSubtrees");async function q(n){try{const{token:e,socket:a}=await f().plugins.appToken(n);return{CRTR_APP_TOKEN:e,CRTR_DAEMON_SOCKET:a}}catch(e){if(e instanceof l&&(e.status===404||e.status===403))return;throw e instanceof l?h(e):e}}u(q,"appEnvFor");function C(n,e){return(a,t)=>{const d=n.transport,i=e(t);if(n.provider!==void 0)return k(n.provider.id,i.slice(1).join(" "),a,d.kind==="machine");if(d.kind==="exec"){const s=d.executable;if(s===void 0)throw new Error(`exec plugin "${n.plugin.name}" has an executable leaf without transport.executable`);return{outputKind:"object",run:u(async c=>{const r=$(n.plugin.manifest)?await q(n.plugin.name):void 0;return U({plugin:n.plugin,executable:s,commandPath:i,output:a.output,...r!==void 0?{appEnv:r}:{}},c)},"run")}}if(d.kind==="machine")throw new Error(`machine plugin "${n.plugin.name}" is not a capability provider`);const o=a;return{outputKind:o.rest.streaming===!0?"jsonl":"object",run:u((s,c)=>P({registration:{name:n.plugin.name,endpoint:d.endpoint,...d.authEnv!==void 0?{authEnv:d.authEnv}:{}},...n.manifest?.baseUrl!==void 0?{baseUrl:n.manifest.baseUrl}:{},...n.manifest?.timeouts!==void 0?{timeouts:n.manifest.timeouts}:{},params:o.params,rest:o.rest,output:o.output,commandPath:i},s,c,{callHeaders:u(r=>f().plugins.callHeaders(n.plugin.name,{method:r.method,url:r.url.href,body_sha256:R(r.body),...K(r.headers)}).then(p=>p.headers,p=>{throw p instanceof l?h(p):p}),"callHeaders")}),"run")}}}u(C,"adaptLeaf");function te(n){return{contributions:n.map(e=>({contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,manifestName:e.manifestName,adaptLeaf:C(e,a=>[e.manifestName,...a.slice(1)]),...e.provider!==void 0?{provider:e.provider}:{}})),coreMounts:[],issues:[]}}u(te,"adaptPluginContributions");function ie(n){return n.map(e=>({parent:e.parent,plugin:e.plugin.name,contributor:{name:e.plugin.name,scope:e.plugin.scope,sourceMarketplace:e.plugin.sourceMarketplace},node:e.node,...e.provider!==void 0?{provider:e.provider}:{},adaptLeaf:C({...e,manifestName:e.node.name},a=>e.provider===void 0?[...a]:[e.provider.id,...a.slice(e.parent.length)])}))}u(ie,"adaptPluginCoreMounts");function D(n,e=E){return n.contributions.map(a=>v(a,a.node,[a.node.name],1,e))}u(D,"composeExternalSubtrees");function se(n,e){return n.filter(a=>a.parent.join("\0")===e.join("\0")).map(a=>a.node.kind==="branch"?v(a,a.node,[...e,a.node.name],a.provider===void 0?1:e.length):T(a,a.node,[...e,a.node.name]))}u(se,"composeCoreBranchMounts");function v(n,e,a,t=1,d=E){const i=e.rootEntry===void 0?void 0:{concept:e.rootEntry.concept,desc:e.rootEntry.description,useWhen:e.rootEntry.whenToUse},o=y({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...i!==void 0?{rootEntry:i}:{},help:{name:a.join(" "),summary:e.summary,...e.model!==void 0?{model:e.model}:{},...a.length===1&&n.extensionIssue!==void 0?{extensionIssue:n.extensionIssue}:{}},...e.passthrough!==void 0?{passthrough:e.passthrough}:{},children:e.children.map(s=>s.kind==="branch"?v(n,s,[...a,s.name],t,d):T(n,s,[...a,s.name]))});return n.provider!==void 0&&(o.effectiveHelp=w(o,a.slice(t),()=>d(n.provider.id))),o}u(v,"buildBranch");function T(n,e,a){const t=n.adaptLeaf(e,a);return M({name:e.name,description:e.description,whenToUse:e.whenToUse,...e.tier!==void 0?{tier:e.tier}:{},...n.plugin!==void 0?{plugin:n.plugin}:{},...t.machineSelector===!0?{machineSelector:!0}:{},help:{name:a.join(" "),summary:e.summary,...t.machineSelector===!0?{guide:O}:{},params:e.params,output:e.output,outputKind:t.outputKind,effects:[...e.effects]},run:t.run})}u(T,"buildLeaf");export{te as adaptPluginContributions,ie as adaptPluginCoreMounts,se as composeCoreBranchMounts,D as composeExternalSubtrees,re as composeSandboxProviderSubtrees};
@@ -8,6 +8,7 @@ export declare function pageManifestPath(dir: string): string;
8
8
  export declare function reviewPath(dir: string): string;
9
9
  export declare function responsePath(dir: string): string;
10
10
  export declare function progressPath(dir: string): string;
11
+ /** A presenter claim older inboxes wrote; kept only so review validation tolerates one left in a request directory. */
11
12
  export declare function claimPath(dir: string): string;
12
13
  export declare function replyRoutePath(dir: string): string;
13
14
  /** The frozen completion-action binding, written once at request creation. */
@@ -20,10 +21,7 @@ export interface TicketReplyRoute {
20
21
  * representation of a standalone page. */
21
22
  export declare function readTicketReplyRoute(dir: string): TicketReplyRoute | null;
22
23
  export declare function bindTicketReplyRoute(dir: string, bridgeNodeId: string): void;
23
- export type InteractionState = 'pending' | 'claimed' | 'resolved' | 'missing';
24
- export declare function interactionState(dir: string): InteractionState;
25
24
  export declare function isResolved(dir: string): boolean;
26
- export declare function isClaimed(dir: string): boolean;
27
25
  /** Resolve and verify a ticket directory without a registry. */
28
26
  export declare function requireTicket(dir: string): string;
29
27
  /** Publish one immutable JSON record without replacing an existing winner. */
@@ -1,2 +1,2 @@
1
- var d=Object.defineProperty;var t=(r,e)=>d(r,"name",{value:e,configurable:!0});import{existsSync as n,linkSync as x,mkdirSync as h,readFileSync as m,realpathSync as g,unlinkSync as c,writeFileSync as y}from"node:fs";import{dirname as $}from"node:path";import{atomicWriteJson as u,atomicWriteText as w}from"../fs-utils.js";function E(r,e="jsx"){return`${r}/page.${e==="jsx"?"tsx":"html"}`}t(E,"pagePath");function b(r){return`${r}/page.js`}t(b,"pageModulePath");function s(r){return`${r}/page.json`}t(s,"pageManifestPath");function a(r){return`${r}/review.json`}t(a,"reviewPath");function p(r){return`${r}/response.json`}t(p,"responsePath");function S(r){return`${r}/progress.json`}t(S,"progressPath");function l(r){return`${r}/claim.json`}t(l,"claimPath");function f(r){return`${r}/reply-route.json`}t(f,"replyRoutePath");function R(r){return`${r}/action.json`}t(R,"actionBindingPath");function T(r){const e=f(r);if(!n(e))return null;let o;try{o=JSON.parse(m(e,"utf8"))}catch{throw new Error(`invalid ticket reply route: ${e}`)}const i=o?.bridge_node_id;if(typeof i!="string"||i==="")throw new Error(`invalid ticket reply route: ${e}`);return{bridge_node_id:i}}t(T,"readTicketReplyRoute");function _(r,e){u(f(r),{bridge_node_id:e})}t(_,"bindTicketReplyRoute");function N(r){return!n(s(r))&&!n(a(r))?"missing":n(p(r))?"resolved":n(l(r))?"claimed":"pending"}t(N,"interactionState");function J(r){return n(p(r))}t(J,"isResolved");function M(r){return n(l(r))}t(M,"isClaimed");function O(r){const e=g(r);if(!n(s(e))&&!n(a(e)))throw new Error("ticket directory has no page or review");return e}t(O,"requireTicket");function F(r,e){const o=`${r}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;h($(r),{recursive:!0,mode:448}),y(o,`${JSON.stringify(e,null,2)}
2
- `,{mode:384});try{return x(o,r),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}finally{c(o)}}t(F,"publishJsonExclusive");function I(r){try{c(S(r))}catch(e){if(e.code!=="ENOENT")throw e}}t(I,"clearProgress");export{R as actionBindingPath,u as atomicWriteJson,w as atomicWriteText,_ as bindTicketReplyRoute,l as claimPath,I as clearProgress,N as interactionState,M as isClaimed,J as isResolved,s as pageManifestPath,b as pageModulePath,E as pagePath,S as progressPath,F as publishJsonExclusive,T as readTicketReplyRoute,f as replyRoutePath,O as requireTicket,p as responsePath,a as reviewPath};
1
+ var s=Object.defineProperty;var t=(r,e)=>s(r,"name",{value:e,configurable:!0});import{existsSync as i,linkSync as a,mkdirSync as l,readFileSync as d,realpathSync as f,unlinkSync as c,writeFileSync as x}from"node:fs";import{dirname as h}from"node:path";import{atomicWriteJson as u,atomicWriteText as y}from"../fs-utils.js";function v(r,e="jsx"){return`${r}/page.${e==="jsx"?"tsx":"html"}`}t(v,"pagePath");function E(r){return`${r}/page.js`}t(E,"pageModulePath");function g(r){return`${r}/page.json`}t(g,"pageManifestPath");function m(r){return`${r}/review.json`}t(m,"reviewPath");function $(r){return`${r}/response.json`}t($,"responsePath");function w(r){return`${r}/progress.json`}t(w,"progressPath");function b(r){return`${r}/claim.json`}t(b,"claimPath");function p(r){return`${r}/reply-route.json`}t(p,"replyRoutePath");function R(r){return`${r}/action.json`}t(R,"actionBindingPath");function T(r){const e=p(r);if(!i(e))return null;let n;try{n=JSON.parse(d(e,"utf8"))}catch{throw new Error(`invalid ticket reply route: ${e}`)}const o=n?.bridge_node_id;if(typeof o!="string"||o==="")throw new Error(`invalid ticket reply route: ${e}`);return{bridge_node_id:o}}t(T,"readTicketReplyRoute");function _(r,e){u(p(r),{bridge_node_id:e})}t(_,"bindTicketReplyRoute");function N(r){return i($(r))}t(N,"isResolved");function J(r){const e=f(r);if(!i(g(e))&&!i(m(e)))throw new Error("ticket directory has no page or review");return e}t(J,"requireTicket");function M(r,e){const n=`${r}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;l(h(r),{recursive:!0,mode:448}),x(n,`${JSON.stringify(e,null,2)}
2
+ `,{mode:384});try{return a(n,r),!0}catch(o){if(o.code==="EEXIST")return!1;throw o}finally{c(n)}}t(M,"publishJsonExclusive");function O(r){try{c(w(r))}catch(e){if(e.code!=="ENOENT")throw e}}t(O,"clearProgress");export{R as actionBindingPath,u as atomicWriteJson,y as atomicWriteText,_ as bindTicketReplyRoute,b as claimPath,O as clearProgress,N as isResolved,g as pageManifestPath,E as pageModulePath,v as pagePath,w as progressPath,M as publishJsonExclusive,T as readTicketReplyRoute,p as replyRoutePath,J as requireTicket,$ as responsePath,m as reviewPath};
@@ -28,11 +28,6 @@ export interface FeedbackResult {
28
28
  submittedAt?: string;
29
29
  savedAt: string;
30
30
  }
31
- export interface ClaimSummary {
32
- owner: string;
33
- claimedAt: string;
34
- heartbeatAt: string;
35
- }
36
31
  interface TicketSummaryBase {
37
32
  dir: string;
38
33
  id: string;
@@ -42,7 +37,6 @@ interface TicketSummaryBase {
42
37
  subtitle: string;
43
38
  blockedSince: string;
44
39
  source: TicketSource;
45
- claim?: ClaimSummary;
46
40
  }
47
41
  export interface ReviewTicketSummary extends TicketSummaryBase {
48
42
  kind: 'review';
@@ -60,7 +54,6 @@ export interface PageTicketSummary {
60
54
  subtitle: string;
61
55
  source: import('./page-schema.js').PageSource;
62
56
  emittedAt: string;
63
- claim?: ClaimSummary;
64
57
  /** Present on resolved history entries; the stored one-line response digest. */
65
58
  answerDigest?: string;
66
59
  dialect: 'jsx' | 'html';
@@ -1,5 +1,6 @@
1
1
  import { type MachineOp, type MachineOpTable } from './ops.js';
2
- /** Seconds a caller waits: `start` 60, every other op 15 (design). */
2
+ /** Seconds a caller waits: `start` 60, every other op 15 (design). The `worktree.*` ops run Git under a repository lock that waits up to
3
+ * 25 s, so they get 60 too (`worktree.finalize` also asks origin, bounded at 10 s). */
3
4
  export declare const MACHINE_CALL_TIMEOUT_S: Record<MachineOp, number>;
4
5
  export interface CallMachineOptions {
5
6
  timeoutMs?: number;
@@ -1,3 +1,3 @@
1
- var d=Object.defineProperty;var s=(e,n)=>d(e,"name",{value:n,configurable:!0});import{randomUUID as E}from"node:crypto";import{openDb as f,withCanvasWrite as h}from"../../../canvas/db.js";import{MachineCallFailedError as p,MachineLostError as l,MachineOfflineError as o}from"./ops.js";const S={start:60,wake:15,stop:15,status:15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15},m=1e3;async function M(e,n,r,c={}){const i=E(),u=new Date().toISOString();if(!await h(async a=>await a.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,u)===void 0?!1:(await a.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(i,e,n,JSON.stringify(r),u),await a.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new o(e,"no live link");const w=Date.now()+(c.timeoutMs??S[n]*1e3);for(;;){const a=await(await f()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(i);if(a===void 0)throw new l(e,i);if(a.state==="done")return a.result_json===null?null:JSON.parse(a.result_json);if(a.state==="failed"){const t=a.result_json===null?{}:JSON.parse(a.result_json);throw t.code==="machine_offline"?new o(e,t.message,t.sent===!0):t.code==="machine_lost"?new l(e,i):new p(e,n,t.message??"unknown")}if(a.claimed_generation!==null&&a.lease_expires_at!==null&&a.lease_expires_at<=new Date().toISOString()){if(await _(i,"lease expired")===void 0)continue;throw new l(e,i)}if(Date.now()>=w){const t=await _(i,"timed out");if(t===void 0)continue;throw t===null?new o(e,"no holder claimed the call"):new l(e,i)}await new Promise(t=>setTimeout(t,c.rereadMs??m))}}s(M,"callMachine");async function _(e,n){const r=await(await f()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
1
+ var d=Object.defineProperty;var o=(e,n)=>d(e,"name",{value:n,configurable:!0});import{randomUUID as E}from"node:crypto";import{openDb as f,withCanvasWrite as h}from"../../../canvas/db.js";import{MachineCallFailedError as p,MachineLostError as l,MachineOfflineError as s}from"./ops.js";const S={start:60,wake:15,stop:15,status:15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60},m=1e3;async function T(e,n,r,c={}){const i=E(),w=new Date().toISOString();if(!await h(async a=>await a.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,w)===void 0?!1:(await a.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(i,e,n,JSON.stringify(r),w),await a.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new s(e,"no live link");const _=Date.now()+(c.timeoutMs??S[n]*1e3);for(;;){const a=await(await f()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(i);if(a===void 0)throw new l(e,i);if(a.state==="done")return a.result_json===null?null:JSON.parse(a.result_json);if(a.state==="failed"){const t=a.result_json===null?{}:JSON.parse(a.result_json);throw t.code==="machine_offline"?new s(e,t.message,t.sent===!0):t.code==="machine_lost"?new l(e,i):new p(e,n,t.message??"unknown")}if(a.claimed_generation!==null&&a.lease_expires_at!==null&&a.lease_expires_at<=new Date().toISOString()){if(await u(i,"lease expired")===void 0)continue;throw new l(e,i)}if(Date.now()>=_){const t=await u(i,"timed out");if(t===void 0)continue;throw t===null?new s(e,"no holder claimed the call"):new l(e,i)}await new Promise(t=>setTimeout(t,c.rereadMs??m))}}o(T,"callMachine");async function u(e,n){const r=await(await f()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
2
2
  result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
3
- WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return r===void 0?void 0:r.claimed_generation===null?null:Number(r.claimed_generation)}s(_,"failOpenCall");export{S as MACHINE_CALL_TIMEOUT_S,M as callMachine};
3
+ WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return r===void 0?void 0:r.claimed_generation===null?null:Number(r.claimed_generation)}o(u,"failOpenCall");export{S as MACHINE_CALL_TIMEOUT_S,T as callMachine};
@@ -38,5 +38,5 @@ export declare function machineBrokerEnv(bundle: StartBundleDTO, deps: Pick<Mach
38
38
  * SIGKILL, so the caller never reports stopped while something of this home may still run. */
39
39
  export declare function stopAllBrokers(graceMs?: number): Promise<void>;
40
40
  export declare function createMachineExecutor(deps: MachineExecutorDeps): {
41
- [O in Exclude<keyof MachineOpTable, 'cron.run' | 'cron.cancel'>]: (args: MachineOpTable[O]['args'], signal?: AbortSignal) => Promise<MachineOpTable[O]['result']>;
41
+ [O in Exclude<keyof MachineOpTable, 'cron.run' | 'cron.cancel' | `worktree.${string}`>]: (args: MachineOpTable[O]['args'], signal?: AbortSignal) => Promise<MachineOpTable[O]['result']>;
42
42
  };
@@ -1,5 +1,9 @@
1
+ import type { ManagedWorktree } from '../../../canvas/types.js';
2
+ import type { AutoDroppedWorktree, AbandonManagedWorktreeResult } from '../../../worktree.js';
3
+ import type { CloseOnHostOutcome } from '../../../worktree-close.js';
4
+ import type { AbandonOutcome, FinalizeWorktreeOutcome } from '../../../worktree-mutation-async.js';
1
5
  import type { RunnerExecution, RunnerStartInput, RunnerStatus, RunnerStopOptions, RunnerStopResult, RunnerViewerAddress, RunnerWakeResult } from '../types.js';
2
- export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "delete", "viewer", "cron.run", "cron.cancel"];
6
+ export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "delete", "viewer", "cron.run", "cron.cancel", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize"];
3
7
  export type MachineOp = (typeof MACHINE_OPS)[number];
4
8
  /** A `start` call carries the whole start input and the node token the control plane minted: the Mac has no database, so it cannot mint one.
5
9
  * The token sits in `machine_calls.args_json` until the row is deleted a day after it finishes; the execution's token row holds its hash. */
@@ -61,6 +65,40 @@ export interface MachineCronCancelArgs {
61
65
  export interface MachineCronCancelResult {
62
66
  canceled: boolean;
63
67
  }
68
+ /** A `worktree.*` op's answer: its value, or the typed refusal (a `WorktreeError`) the Mac raised. A refusal travels as data because
69
+ * a failed call carries only a message, and the caller needs the refusal's code, next step and Git detail. */
70
+ export type MachineWorktreeAnswer<T> = {
71
+ value: T;
72
+ } | {
73
+ refused: {
74
+ code: string;
75
+ message: string;
76
+ next: string;
77
+ detail?: string;
78
+ };
79
+ };
80
+ export interface MachineWorktreeCreateArgs {
81
+ cwd: string;
82
+ nodeId: string;
83
+ baseRef?: string;
84
+ }
85
+ export interface MachineWorktreeRollbackArgs {
86
+ worktree: ManagedWorktree;
87
+ }
88
+ export interface MachineWorktreeCloseArgs {
89
+ nodeId: string;
90
+ worktree: ManagedWorktree;
91
+ }
92
+ export interface MachineWorktreeAbandonArgs {
93
+ nodeId: string;
94
+ worktree: ManagedWorktree;
95
+ by: string;
96
+ }
97
+ export interface MachineWorktreeFinalizeArgs {
98
+ nodeId: string;
99
+ worktree: ManagedWorktree;
100
+ }
101
+ export type { AutoDroppedWorktree, AbandonManagedWorktreeResult };
64
102
  export interface MachineOpTable {
65
103
  start: {
66
104
  args: MachineStartArgs;
@@ -96,6 +134,26 @@ export interface MachineOpTable {
96
134
  args: MachineCronCancelArgs;
97
135
  result: MachineCronCancelResult;
98
136
  };
137
+ 'worktree.create': {
138
+ args: MachineWorktreeCreateArgs;
139
+ result: MachineWorktreeAnswer<ManagedWorktree>;
140
+ };
141
+ 'worktree.rollback': {
142
+ args: MachineWorktreeRollbackArgs;
143
+ result: MachineWorktreeAnswer<null>;
144
+ };
145
+ 'worktree.close': {
146
+ args: MachineWorktreeCloseArgs;
147
+ result: MachineWorktreeAnswer<CloseOnHostOutcome>;
148
+ };
149
+ 'worktree.abandon': {
150
+ args: MachineWorktreeAbandonArgs;
151
+ result: MachineWorktreeAnswer<AbandonOutcome>;
152
+ };
153
+ 'worktree.finalize': {
154
+ args: MachineWorktreeFinalizeArgs;
155
+ result: MachineWorktreeAnswer<FinalizeWorktreeOutcome>;
156
+ };
99
157
  }
100
158
  /** No live link row for the environment: the caller leaves its work pending and retries on its own backoff. */
101
159
  export declare class MachineOfflineError extends Error {
@@ -1 +1 @@
1
- var o=Object.defineProperty;var t=(n,e)=>o(n,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","delete","viewer","cron.run","cron.cancel"];class c extends Error{static{t(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,s=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=s}}class l extends c{static{t(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{t(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{t(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,s){super(`${r} on machine ${e} failed: ${s}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};
1
+ var s=Object.defineProperty;var n=(t,e)=>s(t,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","delete","viewer","cron.run","cron.cancel","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize"];class c extends Error{static{n(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,o=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=o}}class l extends c{static{n(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{n(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{n(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,o){super(`${r} on machine ${e} failed: ${o}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};