@north-light/cli 0.3.651 → 0.3.652

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.
@@ -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};
@@ -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,3 +1,3 @@
1
- var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as V}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as k,join as E}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as H,lstatSync as ee,mkdirSync as te,openSync as U,closeSync as j,fstatSync as K,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as O}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as D,isPidAlive as f}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as G}from"./startup-policy.js";import{exclusiveLockOwnerPid as se}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ce}from"../core/canvas/paths.js";import{envNoDaemonAutostart as ue}from"../shared/env.js";import{awaitJoinLockRelease as le,joinInProgress as de,joinInProgressError as pe,joinLockHolder as fe}from"../core/directory/join-lock.js";import{waitForDaemonAvailability as me}from"../api/index.js";import{localClient as he}from"../api/node-transport.js";const we=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function M(){const e={...process.env};for(const t of we)delete e[t];return e}o(M,"sanitizedDaemonEnv");function _e(){for(let e=k(Z(import.meta.url));;e=k(e)){if(H(E(e,"bin","runtime-generation-manifest.mjs")))return e;if(k(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(_e,"generationRoot");async function A(){const e=_e(),t=I(E(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(E(r(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,E(e,"src","daemon","crtrd-cli.ts")]}const n=I(E(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),c=a("daemon");if(!c.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${c.error}`);return[c.runtime.entryPath]}o(A,"resolveDaemonLaunch");function Ee(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(Ee,"daemonCommandDeclaresCanvasHome");function De(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&Ee(a,t)&&n!==process.pid&&r.push(n);return r}o(De,"findDaemonPids");function xe(e){const t=De().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>f(n));)V("sleep",["0.1"]);for(const n of t)if(f(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(xe,"sweepStrayDaemons");async function Qe(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=O(),r=await A();return e(t,[t,...r,"--canvas-home",g()],M())}o(Qe,"execDaemon");async function R(e){const t=await A(),r=B(O(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:M()});let n="",a="";r.stdout.setEncoding("utf8").on("data",u=>{n+=u}),r.stderr.setEncoding("utf8").on("data",u=>{a+=u});const c=await new Promise((u,m)=>{r.once("error",m),r.once("close",p=>u(p))});if(c!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${c}`);const s=n.trim().split(`
2
- `).at(-1)??"";return JSON.parse(s)}o(R,"runDaemonEntry");function Ze(){return R(["export-sqlite"])}o(Ze,"runDaemonExportSqlite");function et(e,t){return R(["import-dump",e,t])}o(et,"runDaemonImportDump");function tt(e){return R(["import-dump",e,"bodies"])}o(tt,"runDaemonBodiesDump");function rt(){return R(["import-dump","","install-id"])}o(rt,"runDaemonInstallId");const ye=3*6e4,z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return he({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function ge(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(ge,"probeErrorMessage");async function J(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=D()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(J,"probeDaemonServing");async function nt(){try{return await J(),!0}catch{return!1}}o(nt,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
- ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Se(e,t=G,r={},n="ready"){const a=r.readPidfile??D,c=r.isPidAlive??f,s=r.childExited,u=r.isDaemonServing,m=r.probeDaemonServing??(async w=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await J(w)}),p=r.probeDaemonHealth??L,x=r.sleepMs??$,y=r.now??Date.now;let i=null,l=null;return await me({windowMs:t,pollIntervalMs:N,now:y,sleep:x,retry:o(w=>w!==l,"retry"),probe:o(async w=>{const h=a();if(h===null||!c(h)){const d=s?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await m(w)}catch(d){throw d instanceof v&&(l=d),d}i=h;return}const _=await p(w);if(_.startup_phase==="prepared"){i=h;return}throw _.startup_phase==="blocked"?(l=new v(h,_.startup_blocked??"on-disk migration is blocked"),l):_.startup_phase==="ready"?(l=new F(h,_.startup_phase),l):new Error(`daemon ${h} is ${_.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),i===e?null:i}o(Se,"verifyDaemonStartup");async function Re(e,t=z,r={}){const n=r.readPidfile??D,a=r.isPidAlive??f,c=r.sleepMs??$,s=r.now??Date.now,u=s()+t;for(;s()<=u;){if(!a(e)&&n()!==e)return;await c(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(Re,"waitForDaemonExit");const ve=2e3,Te=5e3;async function X(e,t=z,r={}){const n=r.isPidAlive??f,a=r.sleepMs??$,c=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await Re(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const s=c()+ve;for(;c()<=s;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(X,"stopDaemonProcess");async function ot(){const e=D(),t=e!==null&&f(e),r=t&&await X(e)==="killed",n=xe(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(ot,"stopAllDaemons");function be(e,t,r=2048){let n;try{n=U(e,"r");const{size:a}=K(n),c=Math.max(t,a-r),s=a-c;if(s<=0)return"";const u=Buffer.alloc(s);return re(n,u,0,s,c),u.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{j(n)}catch{}}}o(be,"readLogTailFrom");async function ke(e={}){if(process.platform==="linux"&&H("/run/crtr/launcher.sock")&&!f(D()??-1))throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=D();if(r!==null&&f(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:ge(i)}}te(g(),{recursive:!0});const n=await A().catch(i=>{throw new Y(i)});e.waitForJoinLock===!0&&await le(ye);const a=fe();if(a!==null&&a!==process.pid&&e.ignoreJoinLock!==!0)throw pe(a);const c=E(g(),"crtrd.err"),s=U(c,"a"),u=(()=>{try{return K(s).size}catch{return 0}})();ae()===void 0&&oe();const m=B(O(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:M()});j(s);const p=m.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let x=null;m.once("exit",(i,l)=>{x={code:i,signal:l}}),m.unref();let y;try{y=await Se(p,G,{childExited:o(()=>x,"childExited"),childStderrTail:o(()=>be(c,u),"childStderrTail")},t)}catch(i){const l=se(ce())===p;if(x===null&&!l&&!(i instanceof v))try{await X(p,Te)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(ke,"spawnDaemon");function Ie(){return ue()||process.argv.includes("--no-autostart")}o(Ie,"autostartDisabled");const Oe=5e3,Me=6e4;let W=!1,S,T=0,b=0;function Ae(e){return Math.min(Oe*2**(e-1),Me)}o(Ae,"autostartBackoffMs");function Ne(){S=void 0,T=0,b=0}o(Ne,"resetDaemonAutostart");function at(){return S}o(at,"daemonAutostartStartupFailure");function it(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??ke,n=e.now??Date.now;if(!Ie()&&!de()&&!W&&!(n()<b)){if(t()){Ne();return}S=void 0,W=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof Y)&&(S=a.message),T+=1,b=n()+Ae(T)}).finally(()=>{W=!1})}}o(it,"ensureDaemon");export{we as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,Ie as autostartDisabled,at as daemonAutostartStartupFailure,Ee as daemonCommandDeclaresCanvasHome,it as ensureDaemon,Qe as execDaemon,De as findDaemonPids,nt as isDaemonServing,L as probeDaemonHealth,J as probeDaemonServing,ge as probeErrorMessage,Ne as resetDaemonAutostart,tt as runDaemonBodiesDump,Ze as runDaemonExportSqlite,et as runDaemonImportDump,rt as runDaemonInstallId,M as sanitizedDaemonEnv,ke as spawnDaemon,ot as stopAllDaemons,X as stopDaemonProcess,xe as sweepStrayDaemons,Se as verifyDaemonStartup,Re as waitForDaemonExit};
1
+ var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as V}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as k,join as E}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as H,lstatSync as ee,mkdirSync as te,openSync as U,closeSync as j,fstatSync as K,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as M}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as D,isPidAlive as f}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as G}from"./startup-policy.js";import{readMachineConfig as se}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ce}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ue}from"../core/canvas/paths.js";import{envNoDaemonAutostart as le}from"../shared/env.js";import{awaitJoinLockRelease as de,joinInProgress as pe,joinInProgressError as fe,joinLockHolder as me}from"../core/directory/join-lock.js";import{waitForDaemonAvailability as he}from"../api/index.js";import{localClient as we}from"../api/node-transport.js";const _e=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function O(){const e={...process.env};for(const t of _e)delete e[t];return e}o(O,"sanitizedDaemonEnv");function Ee(){for(let e=k(Z(import.meta.url));;e=k(e)){if(H(E(e,"bin","runtime-generation-manifest.mjs")))return e;if(k(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Ee,"generationRoot");async function A(){const e=Ee(),t=I(E(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(E(r(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,E(e,"src","daemon","crtrd-cli.ts")]}const n=I(E(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),c=a("daemon");if(!c.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${c.error}`);return[c.runtime.entryPath]}o(A,"resolveDaemonLaunch");function De(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(De,"daemonCommandDeclaresCanvasHome");function xe(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&De(a,t)&&n!==process.pid&&r.push(n);return r}o(xe,"findDaemonPids");function ye(e){const t=xe().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>f(n));)V("sleep",["0.1"]);for(const n of t)if(f(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(ye,"sweepStrayDaemons");async function et(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=M(),r=await A();return e(t,[t,...r,"--canvas-home",g()],O())}o(et,"execDaemon");async function R(e){const t=await A(),r=B(M(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:O()});let n="",a="";r.stdout.setEncoding("utf8").on("data",u=>{n+=u}),r.stderr.setEncoding("utf8").on("data",u=>{a+=u});const c=await new Promise((u,m)=>{r.once("error",m),r.once("close",p=>u(p))});if(c!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${c}`);const s=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(s)}o(R,"runDaemonEntry");function tt(){return R(["export-sqlite"])}o(tt,"runDaemonExportSqlite");function rt(e,t){return R(["import-dump",e,t])}o(rt,"runDaemonImportDump");function nt(e){return R(["import-dump",e,"bodies"])}o(nt,"runDaemonBodiesDump");function ot(){return R(["import-dump","","install-id"])}o(ot,"runDaemonInstallId");const ge=3*6e4,z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return we({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function Se(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(Se,"probeErrorMessage");async function J(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=D()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(J,"probeDaemonServing");async function at(){try{return await J(),!0}catch{return!1}}o(at,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Re(e,t=G,r={},n="ready"){const a=r.readPidfile??D,c=r.isPidAlive??f,s=r.childExited,u=r.isDaemonServing,m=r.probeDaemonServing??(async w=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await J(w)}),p=r.probeDaemonHealth??L,x=r.sleepMs??$,y=r.now??Date.now;let i=null,l=null;return await he({windowMs:t,pollIntervalMs:N,now:y,sleep:x,retry:o(w=>w!==l,"retry"),probe:o(async w=>{const h=a();if(h===null||!c(h)){const d=s?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await m(w)}catch(d){throw d instanceof v&&(l=d),d}i=h;return}const _=await p(w);if(_.startup_phase==="prepared"){i=h;return}throw _.startup_phase==="blocked"?(l=new v(h,_.startup_blocked??"on-disk migration is blocked"),l):_.startup_phase==="ready"?(l=new F(h,_.startup_phase),l):new Error(`daemon ${h} is ${_.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),i===e?null:i}o(Re,"verifyDaemonStartup");async function ve(e,t=z,r={}){const n=r.readPidfile??D,a=r.isPidAlive??f,c=r.sleepMs??$,s=r.now??Date.now,u=s()+t;for(;s()<=u;){if(!a(e)&&n()!==e)return;await c(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(ve,"waitForDaemonExit");const Te=2e3,be=5e3;async function X(e,t=z,r={}){const n=r.isPidAlive??f,a=r.sleepMs??$,c=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await ve(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const s=c()+Te;for(;c()<=s;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(X,"stopDaemonProcess");async function it(){const e=D(),t=e!==null&&f(e),r=t&&await X(e)==="killed",n=ye(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(it,"stopAllDaemons");function ke(e,t,r=2048){let n;try{n=U(e,"r");const{size:a}=K(n),c=Math.max(t,a-r),s=a-c;if(s<=0)return"";const u=Buffer.alloc(s);return re(n,u,0,s,c),u.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{j(n)}catch{}}}o(ke,"readLogTailFrom");async function Ie(e={}){if(process.platform==="linux"&&H("/run/crtr/launcher.sock")&&!f(D()??-1)&&se()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=D();if(r!==null&&f(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:Se(i)}}te(g(),{recursive:!0});const n=await A().catch(i=>{throw new Y(i)});e.waitForJoinLock===!0&&await de(ge);const a=me();if(a!==null&&a!==process.pid&&e.ignoreJoinLock!==!0)throw fe(a);const c=E(g(),"crtrd.err"),s=U(c,"a"),u=(()=>{try{return K(s).size}catch{return 0}})();ae()===void 0&&oe();const m=B(M(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:O()});j(s);const p=m.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let x=null;m.once("exit",(i,l)=>{x={code:i,signal:l}}),m.unref();let y;try{y=await Re(p,G,{childExited:o(()=>x,"childExited"),childStderrTail:o(()=>ke(c,u),"childStderrTail")},t)}catch(i){const l=ce(ue())===p;if(x===null&&!l&&!(i instanceof v))try{await X(p,be)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(Ie,"spawnDaemon");function Me(){return le()||process.argv.includes("--no-autostart")}o(Me,"autostartDisabled");const Oe=5e3,Ae=6e4;let W=!1,S,T=0,b=0;function Ne(e){return Math.min(Oe*2**(e-1),Ae)}o(Ne,"autostartBackoffMs");function Pe(){S=void 0,T=0,b=0}o(Pe,"resetDaemonAutostart");function st(){return S}o(st,"daemonAutostartStartupFailure");function ct(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??Ie,n=e.now??Date.now;if(!Me()&&!pe()&&!W&&!(n()<b)){if(t()){Pe();return}S=void 0,W=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof Y)&&(S=a.message),T+=1,b=n()+Ne(T)}).finally(()=>{W=!1})}}o(ct,"ensureDaemon");export{_e as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,Me as autostartDisabled,st as daemonAutostartStartupFailure,De as daemonCommandDeclaresCanvasHome,ct as ensureDaemon,et as execDaemon,xe as findDaemonPids,at as isDaemonServing,L as probeDaemonHealth,J as probeDaemonServing,Se as probeErrorMessage,Pe as resetDaemonAutostart,nt as runDaemonBodiesDump,tt as runDaemonExportSqlite,rt as runDaemonImportDump,ot as runDaemonInstallId,O as sanitizedDaemonEnv,Ie as spawnDaemon,it as stopAllDaemons,X as stopDaemonProcess,ye as sweepStrayDaemons,Re as verifyDaemonStartup,ve as waitForDaemonExit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.651",
3
+ "version": "0.3.652",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.651",
148
+ "@north-light/identity": "0.3.652",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.651",
3
+ "version": "0.3.652",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.651",
3
+ "version": "0.3.652",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.651",
9
+ "version": "0.3.652",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.651",
31
+ "@north-light/identity": "0.3.652",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.651",
11959
+ "version": "0.3.652",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.651",
11964
+ "version": "0.3.652",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.651",
11969
+ "version": "0.3.652",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.651",
11977
+ "version": "0.3.652",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.651",
11981
- "@north-light/identity": "0.3.651"
11980
+ "@north-light/api": "0.3.652",
11981
+ "@north-light/identity": "0.3.652"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.651",
11986
+ "version": "0.3.652",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.651",
11990
- "@north-light/identity": "0.3.651",
11991
- "@north-light/plugin": "0.3.651",
11989
+ "@north-light/api": "0.3.652",
11990
+ "@north-light/identity": "0.3.652",
11991
+ "@north-light/plugin": "0.3.652",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {
@@ -1,23 +0,0 @@
1
- export interface TicketClaim {
2
- token: string;
3
- host: string;
4
- pid: number;
5
- claimedAt: string;
6
- heartbeatAt: string;
7
- tmuxClient?: string;
8
- }
9
- export interface ClaimOptions {
10
- host?: string;
11
- pid?: number;
12
- tmuxClient?: string;
13
- now?: Date;
14
- }
15
- export declare function readTicketClaim(dir: string): TicketClaim | null;
16
- export declare function isStaleClaim(claim: TicketClaim, now?: number, localHost?: string): boolean;
17
- /** Exclude another live presenter; the daemon owns whether the request can settle. */
18
- export declare function claimTicket(ticketDir: string, opts?: ClaimOptions): TicketClaim | null;
19
- export declare function heartbeatClaim(ticketDir: string, token: string, now?: Date): boolean;
20
- export declare function releaseClaimLocked(ticketDir: string, token: string): boolean;
21
- export declare function releaseClaim(dir: string, token: string): boolean;
22
- export declare function claimExists(dir: string): boolean;
23
- export declare function withTicketLock<T>(dir: string, operation: () => T): T;
@@ -1,3 +0,0 @@
1
- var y=Object.defineProperty;var n=(e,t)=>y(e,"name",{value:t,configurable:!0});import{existsSync as h,mkdirSync as S,renameSync as b,unlinkSync as k,writeFileSync as x}from"node:fs";import{join as g}from"node:path";import{hostname as m}from"node:os";import{randomUUID as C}from"node:crypto";import{claimPath as l}from"./convention.js";import{readJsonOrNull as A}from"../fs-utils.js";import{withExclusiveDirectoryLock as u}from"../exclusive-lock.js";import{runtimeRoot as w}from"../layout.js";import{isBlobRequestPath as $}from"./request-files.js";function o(e){if(!$(e))return e;const t=g(w(),"ticket-claims",e);return S(t,{recursive:!0}),t}n(o,"claimDir");const D=3e4;function L(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.token!="string"||typeof t.host!="string"||!Number.isInteger(t.pid)||typeof t.claimedAt!="string"||typeof t.heartbeatAt!="string"?null:{token:t.token,host:t.host,pid:t.pid,claimedAt:t.claimedAt,heartbeatAt:t.heartbeatAt,...typeof t.tmuxClient=="string"?{tmuxClient:t.tmuxClient}:{}}}n(L,"parseClaim");function s(e){return L(A(l(o(e))))}n(s,"readTicketClaim");function O(e){try{return process.kill(e,0),!0}catch{return!1}}n(O,"isLiveLocalPid");function E(e,t=Date.now(),i=m()){if(e.host===i)return!O(e.pid);const r=Date.parse(e.heartbeatAt);return!Number.isFinite(r)||t-r>D}n(E,"isStaleClaim");function U(e,t={}){const i=o(e);return u(`${i}/.ticket-lock`,()=>{const r=l(i),c=s(i);if(c!==null&&!E(c,Date.now(),t.host??m()))return null;h(r)&&k(r);const a=t.host??m(),d=t.pid??process.pid,f=(t.now??new Date).toISOString(),p={token:C(),host:a,pid:d,claimedAt:f,heartbeatAt:f,...t.tmuxClient?{tmuxClient:t.tmuxClient}:{}};return x(r,`${JSON.stringify(p)}
2
- `,{flag:"wx",mode:384}),p})}n(U,"claimTicket");function q(e,t,i=new Date){const r=o(e);return u(`${r}/.ticket-lock`,()=>{const c=s(r);if(c===null||c.token!==t)return!1;const a=`${l(r)}.${t}.heartbeat`;return x(a,`${JSON.stringify({...c,heartbeatAt:i.toISOString()})}
3
- `,{flag:"wx",mode:384}),b(a,l(r)),!0})}n(q,"heartbeatClaim");function N(e,t){const i=s(e);return i===null||i.token!==t?!1:(k(l(o(e))),!0)}n(N,"releaseClaimLocked");function B(e,t){return u(`${o(e)}/.ticket-lock`,()=>N(e,t))}n(B,"releaseClaim");function z(e){return h(l(o(e)))}n(z,"claimExists");function G(e,t){return u(`${o(e)}/.ticket-lock`,t)}n(G,"withTicketLock");export{z as claimExists,U as claimTicket,q as heartbeatClaim,E as isStaleClaim,s as readTicketClaim,B as releaseClaim,N as releaseClaimLocked,G as withTicketLock};