@north-light/cli 0.3.650 → 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{existsSync as P,watch as F}from"node:fs";import{visibleWidth as C}from"@earendil-works/pi-tui";import{renderMarkdown as M}from"../../core/termrender/termrender.js";import{BOLD as L,CYAN as W,DIM as h,GRAY as q,RESET as a,YELLOW as k,clipLine as p,singleLine as O,wrap as E}from"./tui/ansi.js";import{buildInboxLines as N,recommendedLabel as H}from"./tui.js";import{inboxLayout as g}from"./layout.js";import{resolvePageComponents as T}from"../../core/config.js";import{watchInboxActivity as B}from"../../core/human/root.js";import{claimTicket as x,heartbeatClaim as _,releaseClaim as u}from"../../core/human/claim.js";import{claimPath as z,clearProgress as V}from"../../core/human/convention.js";import{emitEvent as j}from"../../core/events/emit.js";import{cliClient as f}from"../../commands/api-client.js";import{projectPageDisplayMarkdown as K}from"../../core/human/page-markdown.js";import{projectHtmlDocumentMarkdown as Y}from"../../core/human/page-html-markdown.js";import{pageBodyLines as G}from"./tui/page-body.js";import{docLinksRevision as b}from"../attach/render/doc-links.js";import{byNewestFirst as X,inboxRowFromDTO as J,pageViewFromDTO as y,settledStatusOf as $}from"./dto-adapt.js";import{PageAdapter as Q}from"./page-adapter.js";import{ReviewAdapter as U}from"./review-adapter.js";import{createReviewClient as Z}from"./review/review-client.js";import{editBufferInEditor as ee}from"./review/roundtrip.js";import{daemonErrorMessage as m,dismissTicketViaDaemon as te,resolveFailureKind as S,resolveTicketPage as I}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??ie,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&&V(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=N(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=`${q}\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-C(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: ${H(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await I(e.id,e.fastAction.responses),this.status=s}catch(n){this.status=S(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 Z().cancel(e.id,"Canceled from the inbox."):await te(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 Q({ticketId:e.inboxTicketId,page:s,productKinds:T(),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 U({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 I(t.id,e)}catch(s){this.submittingDir=void 0,this.status=m(s);const n=S(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);j({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:P(z(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=ee(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=[...E(O(i.title),Math.max(10,e-2)).map(r=>` ${L}${W}${r}${a}`),""];for(const r of M(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=B(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 ie(){const{tickets:d}=await f().listHumanInbox();return d.map(J).sort(X)}o(ie,"defaultScan");function A(d,e){const t=d.manifest.dialect==="html"?Y(d.document):K(d.document,d.manifest);return G(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,6 +1,6 @@
1
- var T=Object.defineProperty;var r=(e,t)=>T(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{defineBranch as q,defineLeaf as h}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{ExitCode as R}from"../../types.js";import{existsSync as D,mkdirSync as N,rmSync as E,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as I,bashJobCommandLine as B,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as p,jobStartedAtMs as L,newBashJobId as M,tailJobLog as S}from"../../core/bash-jobs.js";import{parseDurationMs as U}from"../../core/wake.js";import{cliClient as b,getNodeOrNull as u}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as J}from"../../core/preview-result-path.js";import{nodeInPane as A}from"../surface/node/placement.js";function c(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=A(n)),(o===void 0||o==="")&&(o=_()),o===void 0||o==="")throw new i({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}r(c,"resolveBashTarget");async function j(e,t,n){try{await b().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new i({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}r(j,"patchRunningJob");const C=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:r(async e=>{const t=e.command,n=_(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new i({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new i({error:"refused",message:l,next:"Run a different command."});const a=y(o,M());N(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[J]:g,...v}=process.env;try{await m(n,a,o,s,v)}catch(f){throw E(a.dir,{recursive:!0,force:!0}),f}const{recordBackgroundedJob:$}=await import("../../core/runtime/broker/daemon-ops.js");try{await $(n,a.jobId,{command:t}),e.quietOk===!0&&await b().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new i({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},R.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:r(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:r(async e=>{const{id:t}=c(e,"no node found for the bash handoff"),n=await u(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=I(n.paths.context_dir),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(L(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:r(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:r(async e=>{const{id:t}=c(e,"no node found for the bash job list"),n=await u(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=n.paths.context_dir,l=(await b().listBashJobs(n.node_id)).map(a=>{const m=y(d,a.job_id).jobLog,g=D(m)?m:null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:g,pgid:a.pgid,log_tail:g===null?null:S(g,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:r(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${B(n.command)}${n.purpose===null?"":`
1
+ var $=Object.defineProperty;var r=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{ExitCode as q}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as N,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as E,bashJobCommandLine as I,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as p,jobStartedAtMs as B,newBashJobId as L,tailJobLog as M}from"../../core/bash-jobs.js";import{parseDurationMs as S}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as U}from"../../core/preview-result-path.js";import{nodeInPane as J}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=J(n)),(o===void 0||o==="")&&(o=_()),o===void 0||o==="")throw new i({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}r(b,"resolveBashTarget");async function j(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new i({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}r(j,"patchRunningJob");const A=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:r(async e=>{const t=e.command,n=_(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new i({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new i({error:"refused",message:l,next:"Run a different command."});const a=y(o,L());D(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[U]:g,...v}=process.env;try{await m(n,a,o,s,v)}catch(f){throw N(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new i({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},q.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:r(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),C=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=E(n.paths.context_dir),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(B(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:r(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),P=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=n.paths.context_dir,l=(await u().listBashJobs(n.node_id)).map(a=>{const m=y(d,a.job_id).jobLog,g=R(m)?m:null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:g,pgid:a.pgid,log_tail:g===null?null:M(g,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:r(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${I(n.command)}${n.purpose===null?"":`
2
2
  purpose: ${n.purpose}`}${n.deadline_at===null?"":`
3
3
  cancels at: ${n.deadline_at}`}
4
4
  ${n.log_path===null?`log: not on this machine (the job runs in a sandbox); read its output with \`crtr node bash log ${n.job_id} --node ${e.node_id}\``:`log: ${n.log_path}`}`).join(`
5
- `)},"render")}),K=h({name:"log",description:"read a background bash job\u2019s output from the blob store, from any machine",whenToUse:"a job has exited or been killed, or its sandbox is gone, and you need what it printed \u2014 the wake and the job object name this command; for a job still running on this machine, `tail -f` on its log file shows more recent output",help:{name:"node bash log",summary:"read the stored output of one background bash job, last lines first bounded",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as named by the exit wake, `node bash list` or `node bash run`. Running and finished jobs both work."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID). A job another node started needs its owner here."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,constraint:"Return only this many trailing lines. Without it you get the last 256 KiB of output; either way at most 4 MiB."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"job_id",type:"string",required:!0,constraint:"The job."},{name:"output",type:"string",required:!0,constraint:"The stored output, empty when the job has written nothing yet. The broker uploads a running job\u2019s output every couple of seconds, so it can trail the live log slightly."},{name:"truncated",type:"boolean",required:!0,constraint:"True when earlier output exists that the bound left out."}],outputKind:"object",effects:["Reads the output chunks the job\u2019s broker uploaded to the blob store through the daemon; never the local log file, so it works from any machine and after the job\u2019s sandbox is deleted. Needs read access to the owning node. Changes nothing."]},run:r(async e=>{const{id:t}=c(e,"no node found for the bash job"),n=await u(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id named by the exit wake or `crtr node bash list`."});const s=e.tail===void 0?void 0:Math.trunc(Number(e.tail));if(s!==void 0&&!(s>=1))throw new i({error:"invalid_args",message:"--tail must be a positive number of lines",next:"Pass --tail 50, or omit it for the last 256 KiB."});try{const d=await b().readBashJobOutput(n.node_id,o,s===void 0?{}:{tail_lines:s});return{node_id:n.node_id,job_id:d.job_id,output:d.output,truncated:d.truncated}}catch(d){throw d instanceof x&&d.code==="job_not_found"?new i({error:"job_not_found",message:`no job ${o} owned by ${n.node_id}`,next:"A job another node started needs its owner: pass --node <owner>."}):d}},"run"),render:r(e=>`${e.truncated===!0?`[earlier output omitted]
6
- `:""}${String(e.output)}`,"render")}),X=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes, and cannot stop a descendant that detached and reparented before the snapshot.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:r(async e=>{const{id:t}=c(e,"no node found for the bash job"),n=await u(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await b().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled}},"run"),render:r(e=>`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),W=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:r(async e=>{const{id:t}=c(e,"no node found for the bash job"),n=await u(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await j(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:r(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),G=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:r(async e=>{const{id:t}=c(e,"no node found for the bash job"),n=await u(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new i({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await j(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=U(s);if(l===null||l<=0)throw new i({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await j(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:r(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),se=q({name:"bash",description:"start, list, read, stop, and extend your background bash jobs",whenToUse:"a command needs longer than one tool call \u2014 start it as a job and be woken with its exit code instead of using `&`, `nohup`, or a cron that polls a log \u2014 or you need to list, read the output of, stop, or extend the deadline of a job you already have",help:{name:"node bash",summary:"start, list, read, stop, and extend background bash jobs owned by a node",model:"Every bash call runs under a detached supervisor with its output in a log file, so a command that outlives its call keeps running as a job: a canvas object its node owns, readable and watchable with `crtr canvas`. `run` starts a job on purpose and it is never auto-canceled. A job that shows no activity for 15 minutes messages its node, and is never stopped for it. A foreground command still running after 5 minutes is moved to a job automatically, with a cancel deadline unless `extend` claims it."},children:[C,P,O,K,X,W,G]});export{se as nodeBash};
5
+ `)},"render")}),O=h({name:"log",description:"read a background bash job\u2019s output from the blob store, from any machine",whenToUse:"a job has exited or been killed, or its sandbox is gone, and you need what it printed \u2014 the wake and the job object name this command; for a job still running on this machine, `tail -f` on its log file shows more recent output",help:{name:"node bash log",summary:"read the stored output of one background bash job, last lines first bounded",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as named by the exit wake, `node bash list` or `node bash run`. Running and finished jobs both work."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID). A job another node started needs its owner here."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,constraint:"Return only this many trailing lines. Without it you get the last 256 KiB of output; either way at most 4 MiB."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"job_id",type:"string",required:!0,constraint:"The job."},{name:"output",type:"string",required:!0,constraint:"The stored output, empty when the job has written nothing yet. The broker uploads a running job\u2019s output every couple of seconds, so it can trail the live log slightly."},{name:"truncated",type:"boolean",required:!0,constraint:"True when earlier output exists that the bound left out."}],outputKind:"object",effects:["Reads the output chunks the job\u2019s broker uploaded to the blob store through the daemon; never the local log file, so it works from any machine and after the job\u2019s sandbox is deleted. Needs read access to the owning node. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id named by the exit wake or `crtr node bash list`."});const s=e.tail===void 0?void 0:Math.trunc(Number(e.tail));if(s!==void 0&&!(s>=1))throw new i({error:"invalid_args",message:"--tail must be a positive number of lines",next:"Pass --tail 50, or omit it for the last 256 KiB."});try{const d=await u().readBashJobOutput(n.node_id,o,s===void 0?{}:{tail_lines:s});return{node_id:n.node_id,job_id:d.job_id,output:d.output,truncated:d.truncated}}catch(d){throw d instanceof x&&d.code==="job_not_found"?new i({error:"job_not_found",message:`no job ${o} owned by ${n.node_id}`,next:"A job another node started needs its owner: pass --node <owner>."}):d}},"run"),render:r(e=>`${e.truncated===!0?`[earlier output omitted]
6
+ `:""}${String(e.output)}`,"render")}),K=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes, and cannot stop a descendant that detached and reparented before the snapshot.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await u().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled}},"run"),render:r(e=>`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),X=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await j(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:r(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),W=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!p(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new i({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await j(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=S(s);if(l===null||l<=0)throw new i({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await j(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:r(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),ae=T({name:"bash",description:"start, list, read, stop, and extend your background bash jobs",whenToUse:"a command needs longer than one tool call \u2014 start it as a job and be woken with its exit code instead of using `&`, `nohup`, or a cron that polls a log \u2014 or you need to list, read the output of, stop, or extend the deadline of a job you already have",help:{name:"node bash",summary:"start, list, read, stop, and extend background bash jobs owned by a node",model:"Every bash call runs under a detached supervisor with its output in a log file, so a command that outlives its call keeps running as a job: a canvas object its node owns, readable and watchable with `crtr canvas`. `run` starts a job on purpose and it is never auto-canceled. A job that shows no activity for 15 minutes messages its node, and is never stopped for it. A foreground command still running after 5 minutes is moved to a job automatically, with a cancel deadline unless `extend` claims it."},children:[A,C,P,O,K,X,W]});export{ae as nodeBash};
@@ -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};
@@ -28,7 +28,9 @@ export interface DirectoryToken {
28
28
  /** A `client_credentials` token for the runtime client. With `audience`, the
29
29
  * directory issues it for that audience (the storage service); without, for
30
30
  * the directory's own `/v1`. `expires_at` is epoch ms. */
31
- export declare function mintDirectoryToken(issuer: string, audience?: string): Promise<DirectoryToken>;
31
+ /** A token from the directory's `/token` for this runtime: its `/v1` token with no `audience`, else a token for `audience`. A shared
32
+ * (cloud-role) runtime names the person with `sub`; the directory grants it only for an account whose default runtime it is. */
33
+ export declare function mintDirectoryToken(issuer: string, audience?: string, sub?: string): Promise<DirectoryToken>;
32
34
  export type GrantSync = (options?: {
33
35
  fresh?: boolean;
34
36
  }) => Promise<void>;
@@ -1 +1 @@
1
- var x=Object.defineProperty;var r=(e,n)=>x(e,"name",{value:n,configurable:!0});import{createPrivateKey as $,randomUUID as O,sign as A}from"node:crypto";import{readFileSync as P}from"node:fs";import{join as T}from"node:path";import{crtrHome as N}from"../canvas/paths.js";import{withCanvasWrite as R}from"../canvas/db.js";import{isUnsandboxedMachine as v}from"../runtime/unsandboxed.js";import{emitEvent as l}from"../events/emit.js";import{describeOutboundFailure as G,outboundFetch as k,outboundJson as b,outboundRefusal as E}from"../events/outbound.js";import{dependenciesOf as J,inferenceEndpointOf as U,replaceGrants as B,teamsOf as C}from"./mirror.js";import{onGrantSync as D}from"./on-sync.js";import{hostedEndpointOf as F,paymentSetupUrlOf as I,storeHostedEndpoint as M}from"./hosted-endpoint.js";import{adoptInstallPerson as W}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as q,PersonUnresolvedError as L,personId as H,resolvePerson as z,retireLocalPerson as K,setPersonId as V}from"../canvas/person.js";const he=300;function Y(e,n){const t=Math.floor(Date.now()/1e3),o=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),p=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:O()})).toString("base64url"),i=`${o}.${p}`,s=A("sha256",Buffer.from(i),{key:$({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${i}.${s.toString("base64url")}`}r(Y,"assertion");function y(){const e=JSON.parse(P(T(N(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function we(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(we,"runtimeId");function Q(e){return`This machine was removed from your Northlight account. To use it again, create a join token at ${e.replace(/\/$/,"")}/account/machines, and run \`crtr sys join\` from a plain terminal.`}r(Q,"machineRevokedMessage");class S extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(Q(n)),this.name="MachineRevokedError"}}async function X(e,n){const t=y(),o=`${e.replace(/\/$/,"")}/token`,p=new URLSearchParams({grant_type:"client_credentials",client_id:t.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Y(t,o),...n===void 0?{}:{audience:n}}),i=await k("directory_token",o,{method:"POST",body:p,signal:AbortSignal.timeout(1e4)});if(!i.ok)throw i.status===401&&v()&&await Z(i)?new S(e):E("directory_token",o,`directory token request failed: ${i.status}`);const s=await b("directory_token",o,i);if(typeof s.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:s.access_token,expires_at:ee(s.access_token,s.expires_in)}}r(X,"mintDirectoryToken");async function Z(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(Z,"isInvalidClient");function ee(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(ee,"tokenExpiry");function te(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,o=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===o||v()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const s=e.revisions?.find(c=>c.rev===t.rev)?.approved_at;if(typeof s!="string")throw new TypeError("grant revision has no approval time");const f=t.payer==="app"?"app":"user";return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,revoked_at:t.revoked_at??null,approved_at:s,payer:f,dependencies:J(t.dependencies),inference_endpoint:f==="app"?U(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(te,"responseGrant");async function ne(){try{return{id:H(),late:null}}catch(n){if(n instanceof q)return null;if(!(n instanceof L))throw n}const e=await z();return e===null?null:{id:e.id,late:e}}r(ne,"pullPerson");async function re(e){V(e.id),await W(e.id);const n=await K();l({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),l({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(re,"bindLatePerson");let _;function ve(e){return _?_(e):Promise.resolve()}r(ve,"requestGrantSync");function ke(e,n=t=>{}){let t;const o=e.replace(/\/$/,""),p=r(async()=>{const c=y(),u=await X(o),m=await k("grant_sync",`${o}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${u.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw E("grant_sync",`${o}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const a=await b("grant_sync",`${o}/v1/runtime/grants`,m);if(!Array.isArray(a.grants)||typeof a.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in a||"payment_setup_url"in a?{hosted_endpoint:F(a.hosted_endpoint??null),payment_setup_url:I(a.payment_setup_url??null),synced_at:a.synced_at}:void 0,j=a.synced_at,h=a.grants.map(d=>te(d,c)),w=await R(async()=>{await B(h,j,o,C(a.teams));const d=await ne();return g&&d&&await M(g,d.id),d});l({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:a.synced_at}}),w?.late&&await re(w.late);try{await D(n)}catch(d){l({level:"error",event:"daemon.grants.on_sync_failed",error:d})}},"run");let i;const s=r(()=>{const c=p().catch(u=>{throw u instanceof S?l({level:"error",event:"daemon.grants.machine_revoked",error:u}):l({level:"error",event:"daemon.grants.sync_failed",error:u,fields:G(u)}),u}).finally(()=>{t===c&&(t=void 0)});return t=c,c},"start"),f=r((c={})=>t?c.fresh?(i??=t.catch(()=>{}).then(()=>(i=void 0,t??s())),i):t:s(),"sync");return _=f,f}r(ke,"createGrantSync");export{he as GRANT_SYNC_INTERVAL_S,S as MachineRevokedError,Y as assertion,ke as createGrantSync,Q as machineRevokedMessage,X as mintDirectoryToken,ve as requestGrantSync,y as runtimeClient,we as runtimeId};
1
+ var x=Object.defineProperty;var r=(e,n)=>x(e,"name",{value:n,configurable:!0});import{createPrivateKey as $,randomUUID as O,sign as A}from"node:crypto";import{readFileSync as P}from"node:fs";import{join as T}from"node:path";import{crtrHome as N}from"../canvas/paths.js";import{withCanvasWrite as R}from"../canvas/db.js";import{isUnsandboxedMachine as v}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as G,outboundFetch as k,outboundJson as b,outboundRefusal as E}from"../events/outbound.js";import{dependenciesOf as J,inferenceEndpointOf as U,replaceGrants as B,teamsOf as C}from"./mirror.js";import{onGrantSync as D}from"./on-sync.js";import{hostedEndpointOf as F,paymentSetupUrlOf as I,storeHostedEndpoint as M}from"./hosted-endpoint.js";import{adoptInstallPerson as W}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as q,PersonUnresolvedError as L,personId as H,resolvePerson as z,retireLocalPerson as K,setPersonId as V}from"../canvas/person.js";const he=300;function Y(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:O()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:$({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Y,"assertion");function y(){const e=JSON.parse(P(T(N(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function we(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(we,"runtimeId");function Q(e){return`This machine was removed from your Northlight account. To use it again, create a join token at ${e.replace(/\/$/,"")}/account/machines, and run \`crtr sys join\` from a plain terminal.`}r(Q,"machineRevokedMessage");class S extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(Q(n)),this.name="MachineRevokedError"}}async function X(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Y(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await k("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&v()&&await Z(o)?new S(e):E("directory_token",c,`directory token request failed: ${o.status}`);const a=await b("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:ee(a.access_token,a.expires_in)}}r(X,"mintDirectoryToken");async function Z(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(Z,"isInvalidClient");function ee(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(ee,"tokenExpiry");function te(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||v()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=t.payer==="app"?"app":"user";return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:J(t.dependencies),inference_endpoint:a==="app"?U(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(te,"responseGrant");async function ne(){try{return{id:H(),late:null}}catch(n){if(n instanceof q)return null;if(!(n instanceof L))throw n}const e=await z();return e===null?null:{id:e.id,late:e}}r(ne,"pullPerson");async function re(e){V(e.id),await W(e.id);const n=await K();f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(re,"bindLatePerson");let _;function ve(e){return _?_(e):Promise.resolve()}r(ve,"requestGrantSync");function ke(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await X(i),m=await k("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw E("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await b("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:F(s.hosted_endpoint??null),payment_setup_url:I(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,j=s.synced_at,h=s.grants.map(l=>te(l,d)),w=await R(async()=>{await B(h,j,i,C(s.teams));const l=await ne();return g&&l&&await M(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await re(w.late);try{await D(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof S?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:G(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(ke,"createGrantSync");export{he as GRANT_SYNC_INTERVAL_S,S as MachineRevokedError,Y as assertion,ke as createGrantSync,Q as machineRevokedMessage,X as mintDirectoryToken,ve as requestGrantSync,y as runtimeClient,we as runtimeId};
@@ -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';
@@ -54,6 +54,8 @@ export interface PeerDeps {
54
54
  version(): string;
55
55
  timeoutMs: number;
56
56
  startingBudgetMs: number;
57
+ /** The person a cloud role acts for (the peer token's `sub`); undefined on a machine with its own account. */
58
+ person?(): string | undefined;
57
59
  }
58
60
  export declare function createPeerCall(deps: PeerDeps): (machineId: string, request: PeerRequest, options?: PeerOptions) => Promise<PeerResult>;
59
61
  /** Call a machine of this account. Resolves reach through the directory (cached 5 min), authenticates with a peer call token for the callee's URL,
@@ -1 +1 @@
1
- var T=Object.defineProperty;var c=(e,r)=>T(e,"name",{value:r,configurable:!0});import{crtrVersion as p}from"../../shared/crtr-version.js";import{directory as $,normalizeMachineId as v}from"./directory.js";import{directoryIssuer as A}from"../directory/issuer.js";import{ENVELOPE_HEADER as N,encodeEnvelope as O}from"./envelope.js";import{peerTokens as P}from"./token.js";import{PEER_VERSION_FLOOR as y,PEER_VERSION_HEADER as x,peerVersionRefusal as U}from"./version.js";const k=12e4,B=6e4,S={first:1e3,max:8e3},M=16*1024*1024,L=new Set(["GET","PUT","DELETE"]),K=c(e=>"unreachable"in e,"isUnreachable"),i=c((e,r)=>({unreachable:{reason:e,message:r}}),"unreachable");function I(e){const r=e?.error;if(typeof r=="string")return r;const s=r?.code;return typeof s=="string"?s:null}c(I,"errorCode");async function D(e){if(Number(e.headers.get("content-length")??"0")>M)throw new RangeError("the peer answer is too large");const s=new Uint8Array(await e.arrayBuffer());if(s.byteLength>M)throw new RangeError("the peer answer is too large");const o=new TextDecoder().decode(s);if(o==="")return null;try{return JSON.parse(o)}catch{return o}}c(D,"readBody");function C(e,r){const s=new URL(`${e.url}${r.path.startsWith("/")?"":"/"}${r.path}`),o=r.query instanceof URLSearchParams?r.query:Object.entries(r.query??{});for(const[u,l]of o instanceof URLSearchParams?o.entries():o)l!==void 0&&s.searchParams.append(u,String(l));return s.toString()}c(C,"targetUrl");function V(e){return c(async function(s,o,u={}){const l=e.issuer();if(l===null)return i("no_directory","this machine is not joined to a Northlight account, so it has no peers");let t;try{t=await e.directory.reach(s)}catch(a){return i("directory_unreachable",a instanceof Error?a.message:String(a))}if(t===null)return i("unknown_machine",`No machine ${v(s)} on your account.`);if(t.kind==="device"&&u.device!==!0)return i("not_a_crtr_peer",`${t.name} is a device, not a crtr peer.`);const w=t.crtr_version===null?null:U(t.crtr_version,y,e.version());if(w!==null)return{status:426,headers:{},body:{error:{code:w.code,message:`${t.name} runs crtr ${t.crtr_version}; peers below ${y} cannot take part. Update it with \`crtr sys update\`.`,details:{peer_version:t.crtr_version,floor:y,receiver_version:e.version()}}}};const R=C(t,o),h=e.now();let m=S.first,b=!1,d=!1;for(;;){let a;try{const n=await e.tokens.get(l,t.url);a=await e.fetch(R,{method:o.method,redirect:"manual",headers:{authorization:`Bearer ${n}`,[x]:e.version(),...u.envelope?{[N]:O(u.envelope)}:{},...o.body===void 0?{}:{"content-type":"application/json"}},...o.body===void 0?{}:{body:JSON.stringify(o.body)},signal:AbortSignal.any([AbortSignal.timeout(d?Math.max(1e3,Math.min(e.timeoutMs,e.startingBudgetMs-(e.now()-h))):e.timeoutMs),...u.signal?[u.signal]:[]])})}catch(n){return n instanceof Error&&(n.name==="TimeoutError"||n.name==="AbortError")?i("timeout",`${t.name} did not answer within ${Math.round(e.timeoutMs/1e3)} s.`):n instanceof Error&&/directory/.test(n.message)?i("directory_unreachable",n.message):i("network",`${t.name} could not be reached: ${n instanceof Error?n.message:String(n)}`)}let E;try{E=await D(a)}catch(n){return n instanceof Error&&(n.name==="TimeoutError"||n.name==="AbortError")?i("timeout",`${t.name} did not finish its answer within ${Math.round(e.timeoutMs/1e3)} s.`):i("network",`${t.name}'s answer could not be read: ${n instanceof Error?n.message:String(n)}`)}const _=I(E),g=Object.fromEntries(a.headers.entries());if(a.status===401&&!b){b=!0,e.tokens.drop(l,t.url);continue}if(a.status===503&&_==="machine_offline")return i("machine_offline",`${t.name} is offline.`);if(a.status===504)return i("timeout",`${t.name} did not answer in time.`);if(a.status===503&&_==="runtime_starting"){if(e.now()-h+m>e.startingBudgetMs)return i("runtime_starting",`${t.name} is still starting.`);await e.sleep(m),m=Math.min(m*2,S.max),d=!0;continue}const f=Number(g["retry-after"]);if(a.status===503&&_==="runtime_unreachable"&&L.has(o.method)&&g["retry-after"]!==void 0&&Number.isFinite(f)&&f>=0&&e.now()-h+f*1e3<=e.startingBudgetMs){await e.sleep(f*1e3),d=!0;continue}return{status:a.status,headers:g,body:E}}},"peerCall")}c(V,"createPeerCall");const W=V({issuer:A,directory:$,tokens:P,fetch:c((e,r)=>fetch(e,r),"fetch"),sleep:c(e=>new Promise(r=>setTimeout(r,e)),"sleep"),now:Date.now,version:p,timeoutMs:k,startingBudgetMs:B});export{M as MAX_PEER_RESPONSE_BYTES,k as PEER_CALL_TIMEOUT_MS,S as RUNTIME_STARTING_BACKOFF_MS,B as RUNTIME_STARTING_RETRY_BUDGET_MS,V as createPeerCall,K as isUnreachable,W as peerCall};
1
+ var T=Object.defineProperty;var c=(e,r)=>T(e,"name",{value:r,configurable:!0});import{crtrVersion as $}from"../../shared/crtr-version.js";import{actingPerson as v,directory as A,normalizeMachineId as N}from"./directory.js";import{directoryIssuer as O}from"../directory/issuer.js";import{ENVELOPE_HEADER as P,encodeEnvelope as x}from"./envelope.js";import{peerTokens as U}from"./token.js";import{PEER_VERSION_FLOOR as y,PEER_VERSION_HEADER as k,peerVersionRefusal as B}from"./version.js";const L=12e4,I=6e4,M={first:1e3,max:8e3},R=16*1024*1024,D=new Set(["GET","PUT","DELETE"]),X=c(e=>"unreachable"in e,"isUnreachable"),i=c((e,r)=>({unreachable:{reason:e,message:r}}),"unreachable");function C(e){const r=e?.error;if(typeof r=="string")return r;const s=r?.code;return typeof s=="string"?s:null}c(C,"errorCode");async function V(e){if(Number(e.headers.get("content-length")??"0")>R)throw new RangeError("the peer answer is too large");const s=new Uint8Array(await e.arrayBuffer());if(s.byteLength>R)throw new RangeError("the peer answer is too large");const o=new TextDecoder().decode(s);if(o==="")return null;try{return JSON.parse(o)}catch{return o}}c(V,"readBody");function j(e,r){const s=new URL(`${e.url}${r.path.startsWith("/")?"":"/"}${r.path}`),o=r.query instanceof URLSearchParams?r.query:Object.entries(r.query??{});for(const[u,l]of o instanceof URLSearchParams?o.entries():o)l!==void 0&&s.searchParams.append(u,String(l));return s.toString()}c(j,"targetUrl");function F(e){return c(async function(s,o,u={}){const l=e.issuer();if(l===null)return i("no_directory","this machine is not joined to a Northlight account, so it has no peers");let t;try{t=await e.directory.reach(s)}catch(a){return i("directory_unreachable",a instanceof Error?a.message:String(a))}if(t===null)return i("unknown_machine",`No machine ${N(s)} on your account.`);if(t.kind==="device"&&u.device!==!0)return i("not_a_crtr_peer",`${t.name} is a device, not a crtr peer.`);const w=t.crtr_version===null?null:B(t.crtr_version,y,e.version());if(w!==null)return{status:426,headers:{},body:{error:{code:w.code,message:`${t.name} runs crtr ${t.crtr_version}; peers below ${y} cannot take part. Update it with \`crtr sys update\`.`,details:{peer_version:t.crtr_version,floor:y,receiver_version:e.version()}}}};const p=j(t,o),b=e.person?.(),h=e.now();let m=M.first,S=!1,d=!1;for(;;){let a;try{const n=await e.tokens.get(l,t.url,b);a=await e.fetch(p,{method:o.method,redirect:"manual",headers:{authorization:`Bearer ${n}`,[k]:e.version(),...u.envelope?{[P]:x(u.envelope)}:{},...o.body===void 0?{}:{"content-type":"application/json"}},...o.body===void 0?{}:{body:JSON.stringify(o.body)},signal:AbortSignal.any([AbortSignal.timeout(d?Math.max(1e3,Math.min(e.timeoutMs,e.startingBudgetMs-(e.now()-h))):e.timeoutMs),...u.signal?[u.signal]:[]])})}catch(n){return n instanceof Error&&(n.name==="TimeoutError"||n.name==="AbortError")?i("timeout",`${t.name} did not answer within ${Math.round(e.timeoutMs/1e3)} s.`):n instanceof Error&&/directory/.test(n.message)?i("directory_unreachable",n.message):i("network",`${t.name} could not be reached: ${n instanceof Error?n.message:String(n)}`)}let E;try{E=await V(a)}catch(n){return n instanceof Error&&(n.name==="TimeoutError"||n.name==="AbortError")?i("timeout",`${t.name} did not finish its answer within ${Math.round(e.timeoutMs/1e3)} s.`):i("network",`${t.name}'s answer could not be read: ${n instanceof Error?n.message:String(n)}`)}const _=C(E),g=Object.fromEntries(a.headers.entries());if(a.status===401&&!S){S=!0,e.tokens.drop(l,t.url,b);continue}if(a.status===503&&_==="machine_offline")return i("machine_offline",`${t.name} is offline.`);if(a.status===504)return i("timeout",`${t.name} did not answer in time.`);if(a.status===503&&_==="runtime_starting"){if(e.now()-h+m>e.startingBudgetMs)return i("runtime_starting",`${t.name} is still starting.`);await e.sleep(m),m=Math.min(m*2,M.max),d=!0;continue}const f=Number(g["retry-after"]);if(a.status===503&&_==="runtime_unreachable"&&D.has(o.method)&&g["retry-after"]!==void 0&&Number.isFinite(f)&&f>=0&&e.now()-h+f*1e3<=e.startingBudgetMs){await e.sleep(f*1e3),d=!0;continue}return{status:a.status,headers:g,body:E}}},"peerCall")}c(F,"createPeerCall");const Q=F({issuer:O,directory:A,tokens:U,fetch:c((e,r)=>fetch(e,r),"fetch"),sleep:c(e=>new Promise(r=>setTimeout(r,e)),"sleep"),now:Date.now,version:$,timeoutMs:L,startingBudgetMs:I,person:v});export{R as MAX_PEER_RESPONSE_BYTES,L as PEER_CALL_TIMEOUT_MS,M as RUNTIME_STARTING_BACKOFF_MS,I as RUNTIME_STARTING_RETRY_BUDGET_MS,F as createPeerCall,X as isUnreachable,Q as peerCall};
@@ -41,9 +41,13 @@ export interface DirectoryDeps {
41
41
  tokens: TokenCache;
42
42
  fetch: typeof fetch;
43
43
  now(): number;
44
+ /** The person a list or reach is for: the request's person on a cloud role, else undefined (the runtime's own account). */
45
+ person?(): string | undefined;
44
46
  }
47
+ /** The person a shared (cloud-role) runtime acts for; undefined on a machine with its own account. */
48
+ export declare function actingPerson(): string | undefined;
45
49
  export interface DirectoryClient {
46
- /** Every live machine of the account. Refreshes the reach cache. */
50
+ /** Every live machine of the account (on a cloud role, the request's person's account). Refreshes the reach cache. */
47
51
  list(): Promise<Machine[]>;
48
52
  /** The last `list()` answer, however old; null before the first one. For a caller that can use a stale list when the directory is down. */
49
53
  lastList(): Machine[] | null;