@north-light/cli 0.3.650 → 0.3.651

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.
@@ -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 R=Object.defineProperty;var o=(d,e)=>R(d,"name",{value:e,configurable:!0});import{watch as F}from"node:fs";import{visibleWidth as P}from"@earendil-works/pi-tui";import{renderMarkdown as C}from"../../core/termrender/termrender.js";import{BOLD as M,CYAN as L,DIM as h,GRAY as W,RESET as a,YELLOW as k,clipLine as p,singleLine as q,wrap as O}from"./tui/ansi.js";import{buildInboxLines as E,recommendedLabel as N}from"./tui.js";import{inboxLayout as g}from"./layout.js";import{resolvePageComponents as H}from"../../core/config.js";import{watchInboxActivity as T}from"../../core/human/root.js";import{claimExists as B,claimTicket as x,heartbeatClaim as _,releaseClaim as u}from"../../core/human/claim.js";import{clearProgress as z}from"../../core/human/convention.js";import{emitEvent as V}from"../../core/events/emit.js";import{cliClient as f}from"../../commands/api-client.js";import{projectPageDisplayMarkdown as j}from"../../core/human/page-markdown.js";import{projectHtmlDocumentMarkdown as K}from"../../core/human/page-html-markdown.js";import{pageBodyLines as Y}from"./tui/page-body.js";import{docLinksRevision as b}from"../attach/render/doc-links.js";import{byNewestFirst as G,inboxRowFromDTO as X,pageViewFromDTO as y,settledStatusOf as $}from"./dto-adapt.js";import{PageAdapter as J}from"./page-adapter.js";import{ReviewAdapter as Q}from"./review-adapter.js";import{createReviewClient as U}from"./review/review-client.js";import{editBufferInEditor as Z}from"./review/roundtrip.js";import{daemonErrorMessage as m,dismissTicketViaDaemon as ee,resolveFailureKind as I,resolveTicketPage as S}from"./resolve.js";class Ie{static{o(this,"InboxController")}options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??te,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){const e=this.selectedDir,t=this.claim;try{this.items=await this.scan()}catch(s){if(this.closed)return;this.status=m(s),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){const s=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(s)}if(!(e!==void 0&&this.items.some(s=>s.dir===e))&&this.adapter!==void 0&&e!==void 0&&t!==void 0){const s=(await this.requestOrNull(t.id))?.state==="canceled";if(this.closed)return;s&&z(e),e!==this.submittingDir&&(this.status=s?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}const e=this.profile.members();this.visible=this.items.filter(t=>{const i=t.source.nodeId;return i!==void 0&&e.has(i)})}reseatSelection(){const e=this.selectedDir===void 0?-1:this.visible.findIndex(t=>t.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(t=>t.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){const e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&_(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,t){this.cols=e,this.rows=t,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){const e=g(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${k}Resize terminal to at least 60\xD718 to use inbox.${a}`];const t=E(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),i=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(t);if(e.mode==="detail")return this.withStatus(i);const s=[],n=`${W}\u2502${a}`;for(let r=0;r<e.height;r++){const l=p(t[r]??"",e.listWidth),c=p(i[r]??"",e.detailWidth),v=" ".repeat(Math.max(0,e.listWidth-P(l)));s.push(`${l}${v}${n}${c}`)}return this.withStatus(s)}handleKey(e,t){if(t.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()&&!this.adapter.hasShortcut(e)){this.focusSelectedSource();return}this.adapter.handleKey(e,t),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){const i=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(i)}else(e==="n"||e==="N"||t.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){const i=this.currentRow();i!==void 0&&(this.cancelConfirmation={item:i},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(t.escape||e==="q"){this.close();return}e==="j"||t.downArrow?this.select(this.selectedIndex+1):e==="k"||t.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(t.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){const e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}const t=await this.requestOrNull(e.id);if(D(t)){this.status=w(t),await this.rescan();return}const i=x(e.dir);if(i===null){this.status="ticket is being edited by another inbox";return}const s=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${N(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await S(e.id,e.fastAction.responses),this.status=s}catch(n){this.status=I(n)==="already_settled"?w(await this.requestOrNull(e.id)):m(n)}finally{u(e.dir,i.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await U().cancel(e.id,"Canceled from the inbox."):await ee(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(t){this.status=m(t)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){const e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}const t=await this.requestOrNull(e.id);if(this.closed)return;if(D(t)){this.status=w(t),await this.rescan();return}const i=x(e.dir);if(i===null){this.status="ticket is being edited by another inbox";return}let s,n;try{const r=await f().getHumanInboxPage(e.inboxTicketId);if(r.state==="resolved"||r.state==="canceled"){u(e.dir,i.token),this.status=$(r),await this.rescan();return}s=y(r),n=r.revision}catch{u(e.dir,i.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){u(e.dir,i.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:i.token},this.screen="detail",this.adapter=new J({ticketId:e.inboxTicketId,page:s,productKinds:H(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:o(()=>this.markDirty(),"onDirty"),onEditorRequest:o(()=>this.editActivePageInput(),"onEditorRequest"),onBack:o(()=>{this.leaveDetail(),this.markDirty()},"onBack"),onComplete:o(r=>{this.complete(r)},"onComplete")}),this.openRevision=n,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new Q({reviewId:e.id,host:this.host});let t=!1;try{t=await this.reviewAdapter.start()}catch(i){this.status=m(i)}finally{this.reviewAdapter=void 0}if(t){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let t=this.visible.findIndex(i=>i.dir===e);return t<0&&this.items.some(i=>i.dir===e)&&(this.filter="all",this.recomputeVisible(),t=this.visible.findIndex(i=>i.dir===e)),t<0?!1:(this.select(t),!0)}async reloadSelectedPage(){const e=this.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{const t=await f().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;t.revision!==this.openRevision&&(this.openRevision=t.revision,this.adapter.reload(y(t)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);for(const e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){const t=this.claim;if(t===void 0)return;this.submittingDir=t.dir;try{await S(t.id,e)}catch(s){this.submittingDir=void 0,this.status=m(s);const n=I(s);if(n==="unreachable"||n==="other"){this.markDirty();return}n==="already_settled"&&(this.status=w(await this.requestOrNull(t.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();const i=this.items.some(s=>s.dir===t.dir);V({level:i?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:t.id,request_settled:D(await this.requestOrNull(t.id)),still_listed:i,claim_left_behind:B(t.dir)}}),this.markDirty()}editActivePageInput(){const e=this.adapter?.inputBuffer();if(e===void 0)return;const t=this.host.suspendForChild();let i={text:e};try{i=Z(e)}finally{t(),this.adapter?.setInputBuffer(i.text),i.error!==void 0&&(this.status=i.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&u(this.claim.dir,this.claim.token),this.claim=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){const e=g(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,t){if(this.adapter!==void 0)return this.adapter.render();const i=this.currentRow();if(i===void 0)return this.passiveDetailLines(e,t);const s=this.focusAvailable(i.dir)?` ${h}g${a} chat`:"",n=i.kind==="page"&&i.fastAction!==void 0?` ${h}s${a} ${i.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",r=i.kind==="page"?[` ${h}Enter${a} opens the full page ${h}\u2191\u2193/jk${a} select${n} ${h}x${a} cancel`,` ${h}Page:${a} c comment u/d scroll${s} ${h}q${a} close`]:[` ${h}Enter${a} opens the full review ${h}\u2191\u2193/jk${a} select ${h}x${a} cancel`,` ${s} ${h}q${a} close`],l=Math.max(0,t-r.length),c=this.passiveDetailLines(e,l);for(;c.length<l;)c.push("");return[...c,...r.map(v=>p(v,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){const e=this.screen==="detail"?this.claim?.dir:this.currentRow()?.dir,t=e===void 0?void 0:this.items.find(s=>s.dir===e);if(t===void 0||this.focusingSource)return;const i=t.source.nodeId;if(i===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(i)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,t){const i=this.preview;if(i!==void 0&&i.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),i.width===t&&i.links===b())return i.lines;const s=A(i.view,t);return this.preview={...i,width:t,links:b(),lines:s},s}return this.schedulePreview(e),this.previewFailed===e.dir?[`${h}page could not be read${a}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,f().getHumanInboxPage(e.inboxTicketId).then(t=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===t.revision))return;const i=y(t),s=this.preview?.width??g(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:t.revision,view:i,width:s,links:b(),lines:A(i,s)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await f().getHumanRequest(e)}catch{return}}passiveDetailLines(e,t){const i=this.currentRow();if(i===void 0)return[` ${h}Select a pending interaction.${a}`];const s=[...O(q(i.title),Math.max(10,e-2)).map(r=>` ${M}${L}${r}${a}`),""];for(const r of C(i.subtitle,Math.max(1,e-2)))s.push(` ${r}`);const n=i.kind==="page"?this.pagePreviewBody(i,e):[`${h}1 file to review${a}`];if(n.length>0){s.push("");const r=Math.max(0,t-s.length),l=n.length<=r?n:n.slice(0,Math.max(0,r-1));for(const c of l)s.push(` ${c}`);l.length<n.length&&s.push(` ${h}\u2026 +${n.length-l.length} more lines${a}`)}return s.map(r=>p(r,e)).slice(0,Math.max(1,t))}withStatus(e){const t=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(t===void 0||this.rows<1)return e;const i=[...e];for(;i.length<this.rows;)i.push("");return i[this.rows-1]=`${k}${t}${a}`,i}markDirty(){this.options.onDirty()}watchRoots(){const e=T(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=F(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}}async function te(){const{tickets:d}=await f().listHumanInbox();return d.map(X).sort(G)}o(te,"defaultScan");function A(d,e){const t=d.manifest.dialect==="html"?K(d.document):j(d.document,d.manifest);return Y(d.manifest,t,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}o(A,"previewLines");function D(d){return d!==void 0&&d.state!=="pending"}o(D,"isSettled");function w(d){return d?.page===void 0?"ticket was already resolved":$(d.page)}o(w,"settledStatus");export{Ie as InboxController};
@@ -1,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};
@@ -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};
@@ -15,9 +15,9 @@ export interface ClaimOptions {
15
15
  export declare function readTicketClaim(dir: string): TicketClaim | null;
16
16
  export declare function isStaleClaim(claim: TicketClaim, now?: number, localHost?: string): boolean;
17
17
  /** Exclude another live presenter; the daemon owns whether the request can settle. */
18
- export declare function claimTicket(dir: string, opts?: ClaimOptions): TicketClaim | null;
19
- export declare function heartbeatClaim(dir: string, token: string, now?: Date): boolean;
20
- export declare function releaseClaimLocked(dir: string, token: string): boolean;
18
+ export declare function claimTicket(ticketDir: string, opts?: ClaimOptions): TicketClaim | null;
19
+ export declare function heartbeatClaim(ticketDir: string, token: string, now?: Date): boolean;
20
+ export declare function releaseClaimLocked(ticketDir: string, token: string): boolean;
21
21
  export declare function releaseClaim(dir: string, token: string): boolean;
22
22
  export declare function claimExists(dir: string): boolean;
23
23
  export declare function withTicketLock<T>(dir: string, operation: () => T): T;
@@ -1,3 +1,3 @@
1
- var x=Object.defineProperty;var n=(t,e)=>x(t,"name",{value:e,configurable:!0});import{existsSync as f,renameSync as y,unlinkSync as p,writeFileSync as h}from"node:fs";import{hostname as l}from"node:os";import{randomUUID as g}from"node:crypto";import{claimPath as o}from"./convention.js";import{readJsonOrNull as S}from"../fs-utils.js";import{withExclusiveDirectoryLock as a}from"../exclusive-lock.js";const b=3e4;function C(t){if(typeof t!="object"||t===null)return null;const e=t;return typeof e.token!="string"||typeof e.host!="string"||!Number.isInteger(e.pid)||typeof e.claimedAt!="string"||typeof e.heartbeatAt!="string"?null:{token:e.token,host:e.host,pid:e.pid,claimedAt:e.claimedAt,heartbeatAt:e.heartbeatAt,...typeof e.tmuxClient=="string"?{tmuxClient:e.tmuxClient}:{}}}n(C,"parseClaim");function u(t){return C(S(o(t)))}n(u,"readTicketClaim");function d(t){try{return process.kill(t,0),!0}catch{return!1}}n(d,"isLiveLocalPid");function A(t,e=Date.now(),r=l()){if(t.host===r)return!d(t.pid);const i=Date.parse(t.heartbeatAt);return!Number.isFinite(i)||e-i>b}n(A,"isStaleClaim");function I(t,e={}){return a(`${t}/.ticket-lock`,()=>{const r=o(t),i=u(t);if(i!==null&&!A(i,Date.now(),e.host??l()))return null;f(r)&&p(r);const c=e.host??l(),k=e.pid??process.pid,s=(e.now??new Date).toISOString(),m={token:g(),host:c,pid:k,claimedAt:s,heartbeatAt:s,...e.tmuxClient?{tmuxClient:e.tmuxClient}:{}};return h(r,`${JSON.stringify(m)}
2
- `,{flag:"wx",mode:384}),m})}n(I,"claimTicket");function J(t,e,r=new Date){return a(`${t}/.ticket-lock`,()=>{const i=u(t);if(i===null||i.token!==e)return!1;const c=`${o(t)}.${e}.heartbeat`;return h(c,`${JSON.stringify({...i,heartbeatAt:r.toISOString()})}
3
- `,{flag:"wx",mode:384}),y(c,o(t)),!0})}n(J,"heartbeatClaim");function w(t,e){const r=u(t);return r===null||r.token!==e?!1:(p(o(t)),!0)}n(w,"releaseClaimLocked");function _(t,e){return a(`${t}/.ticket-lock`,()=>w(t,e))}n(_,"releaseClaim");function v(t){return f(o(t))}n(v,"claimExists");function F(t,e){return a(`${t}/.ticket-lock`,e)}n(F,"withTicketLock");export{v as claimExists,I as claimTicket,J as heartbeatClaim,A as isStaleClaim,u as readTicketClaim,_ as releaseClaim,w as releaseClaimLocked,F as withTicketLock};
1
+ var y=Object.defineProperty;var n=(e,t)=>y(e,"name",{value:t,configurable:!0});import{existsSync as h,mkdirSync as S,renameSync as b,unlinkSync as k,writeFileSync as x}from"node:fs";import{join as g}from"node:path";import{hostname as m}from"node:os";import{randomUUID as C}from"node:crypto";import{claimPath as l}from"./convention.js";import{readJsonOrNull as A}from"../fs-utils.js";import{withExclusiveDirectoryLock as u}from"../exclusive-lock.js";import{runtimeRoot as w}from"../layout.js";import{isBlobRequestPath as $}from"./request-files.js";function o(e){if(!$(e))return e;const t=g(w(),"ticket-claims",e);return S(t,{recursive:!0}),t}n(o,"claimDir");const D=3e4;function L(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.token!="string"||typeof t.host!="string"||!Number.isInteger(t.pid)||typeof t.claimedAt!="string"||typeof t.heartbeatAt!="string"?null:{token:t.token,host:t.host,pid:t.pid,claimedAt:t.claimedAt,heartbeatAt:t.heartbeatAt,...typeof t.tmuxClient=="string"?{tmuxClient:t.tmuxClient}:{}}}n(L,"parseClaim");function s(e){return L(A(l(o(e))))}n(s,"readTicketClaim");function O(e){try{return process.kill(e,0),!0}catch{return!1}}n(O,"isLiveLocalPid");function E(e,t=Date.now(),i=m()){if(e.host===i)return!O(e.pid);const r=Date.parse(e.heartbeatAt);return!Number.isFinite(r)||t-r>D}n(E,"isStaleClaim");function U(e,t={}){const i=o(e);return u(`${i}/.ticket-lock`,()=>{const r=l(i),c=s(i);if(c!==null&&!E(c,Date.now(),t.host??m()))return null;h(r)&&k(r);const a=t.host??m(),d=t.pid??process.pid,f=(t.now??new Date).toISOString(),p={token:C(),host:a,pid:d,claimedAt:f,heartbeatAt:f,...t.tmuxClient?{tmuxClient:t.tmuxClient}:{}};return x(r,`${JSON.stringify(p)}
2
+ `,{flag:"wx",mode:384}),p})}n(U,"claimTicket");function q(e,t,i=new Date){const r=o(e);return u(`${r}/.ticket-lock`,()=>{const c=s(r);if(c===null||c.token!==t)return!1;const a=`${l(r)}.${t}.heartbeat`;return x(a,`${JSON.stringify({...c,heartbeatAt:i.toISOString()})}
3
+ `,{flag:"wx",mode:384}),b(a,l(r)),!0})}n(q,"heartbeatClaim");function N(e,t){const i=s(e);return i===null||i.token!==t?!1:(k(l(o(e))),!0)}n(N,"releaseClaimLocked");function B(e,t){return u(`${o(e)}/.ticket-lock`,()=>N(e,t))}n(B,"releaseClaim");function z(e){return h(l(o(e)))}n(z,"claimExists");function G(e,t){return u(`${o(e)}/.ticket-lock`,t)}n(G,"withTicketLock");export{z as claimExists,U as claimTicket,q as heartbeatClaim,E as isStaleClaim,s as readTicketClaim,B as releaseClaim,N as releaseClaimLocked,G as withTicketLock};
@@ -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;
@@ -1 +1 @@
1
- var x=Object.defineProperty;var s=(t,e)=>x(t,"name",{value:e,configurable:!0});import{normalizeMachineId as m,rememberMachineName as p}from"./names.js";import{openDb as _}from"../canvas/db.js";import{directoryIssuer as g}from"../directory/issuer.js";import{runtimeClient as E}from"../grants/sync.js";import{crtrVersion as M}from"../../shared/crtr-version.js";import{installedPluginIds as C}from"../directory/join.js";import{peerTokens as I}from"./token.js";const R=5*6e4,S=1e4;class c extends Error{static{s(this,"DirectoryError")}status;constructor(e,i){super(i),this.status=e,this.name="DirectoryError"}}function T(t){if(!t||typeof t!="object")return null;const{kind:e,relay:i}=t;return e==="stable"?{kind:"stable"}:e==="relay"&&typeof i=="string"?{kind:"relay",relay:i}:null}s(T,"asReach");function k(t){const e=t,i=T(e?.reach);if(!e||typeof e.machine_id!="string"||typeof e.url!="string"||i===null)throw new c(502,"the directory answered a machine record with a missing machine_id, url or reach");return{machine_id:e.machine_id,name:typeof e.name=="string"?e.name:e.machine_id,url:e.url.replace(/\/$/,""),reach:i,crtr_version:typeof e.crtr_version=="string"?e.crtr_version:null,last_seen:typeof e.last_seen=="string"?e.last_seen:null,kind:e.kind==="device"?"device":"runtime",plugins:Array.isArray(e.plugins)?e.plugins.filter(u=>typeof u=="string"):[],...typeof e.is_default=="boolean"?{is_default:e.is_default}:{}}}s(k,"asMachine");function A(t,e){const i=new Map;let u=null;async function d(o,a,r){const n=t.issuer();if(n===null)throw new c(0,"this daemon has no directory");const f=n.replace(/\/$/,"");for(let y=0;;y++){let l;try{const h=await t.tokens.get(f);l=await t.fetch(`${f}${a}`,{method:o,headers:{authorization:`Bearer ${h}`,...r===void 0?{}:{"content-type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},signal:AbortSignal.timeout(S)})}catch(h){throw new c(0,`the directory could not be reached: ${h instanceof Error?h.message:String(h)}`)}if(l.status===401&&y===0){t.tokens.drop(f);continue}if(!l.ok)throw new c(l.status,`directory ${o} ${a} answered ${l.status}`);try{return await l.json()}catch{throw new c(502,`directory ${o} ${a} answered a body that is not JSON`)}}}return s(d,"call"),{async list(){const o=await d("GET","/v1/machines");if(!Array.isArray(o))throw new c(502,"the directory answered a machine list that is not an array");const a=o.map(k),r=t.now();for(const n of a)i.set(n.machine_id,{machine:n,at:r}),p(n.machine_id,n.name);return u={machines:a,at:r},a},lastList(){return u===null?null:u.machines},async reach(o){const a=m(o),r=i.get(a);if(r&&t.now()-r.at<R)return r.machine;try{const n=k(await d("GET",`/v1/machines/${encodeURIComponent(a)}/reach`));return i.set(a,{machine:n,at:t.now()}),p(n.machine_id,n.name),n}catch(n){if(n instanceof c&&n.status===404)return i.delete(a),null;if(r&&n instanceof c&&n.status===0)return r.machine;throw n}},async status(o){const a=e(),r=await d("PUT",`/v1/machines/${encodeURIComponent(a)}/status`,o);if(!r||typeof r.machine_id!="string"||typeof r.url!="string")throw new c(502,"the directory answered a status record with a missing machine_id or url");return{machine_id:r.machine_id,url:r.url.replace(/\/$/,""),reach:T(r.reach)}},invalidate(o){o===void 0?(i.clear(),u=null):i.delete(m(o))}}}s(A,"createDirectoryClient");function $(){return m(E().runtime)}s($,"ownMachineId");const w=A({issuer:g,tokens:I,fetch:s((t,e)=>fetch(t,e),"fetch"),now:Date.now},$),z=s(()=>w.list(),"listMachines"),F=s(t=>w.reach(t),"machineReach"),v="machine_url";async function G(){return(await(await _()).prepare("SELECT value FROM runtime_state WHERE key = ?").get(v))?.value??null}s(G,"machineUrl");async function b(t){await(await _()).prepare("INSERT INTO runtime_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(v,t)}s(b,"storeMachineUrl");async function J(t=w){if(g()===null)return null;try{E()}catch{return null}const e=await t.status({plugins:C(),crtr_version:M()});if(e.machine_id!==$())throw new c(502,"the directory answered a status for another machine");return await b(e.url),e}s(J,"reportMachineStatus");export{S as DIRECTORY_CALL_TIMEOUT_MS,c as DirectoryError,R as REACH_TTL_MS,A as createDirectoryClient,w as directory,z as listMachines,F as machineReach,G as machineUrl,m as normalizeMachineId,$ as ownMachineId,J as reportMachineStatus};
1
+ var C=Object.defineProperty;var o=(t,e)=>C(t,"name",{value:e,configurable:!0});import{normalizeMachineId as m,rememberMachineName as g}from"./names.js";import{openDb as E}from"../canvas/db.js";import{directoryIssuer as $}from"../directory/issuer.js";import{runtimeClient as M}from"../grants/sync.js";import{crtrVersion as I}from"../../shared/crtr-version.js";import{installedPluginIds as R}from"../directory/join.js";import{peerTokens as S}from"./token.js";import{isCloudRole as A,requestPersonId as O}from"../canvas/person-state.js";const U=5*6e4,b=1e4;class u extends Error{static{o(this,"DirectoryError")}status;constructor(e,s){super(s),this.status=e,this.name="DirectoryError"}}function D(){return A()?O():void 0}o(D,"actingPerson");function T(t){if(!t||typeof t!="object")return null;const{kind:e,relay:s}=t;return e==="stable"?{kind:"stable"}:e==="relay"&&typeof s=="string"?{kind:"relay",relay:s}:null}o(T,"asReach");function k(t){const e=t,s=T(e?.reach);if(!e||typeof e.machine_id!="string"||typeof e.url!="string"||s===null)throw new u(502,"the directory answered a machine record with a missing machine_id, url or reach");return{machine_id:e.machine_id,name:typeof e.name=="string"?e.name:e.machine_id,url:e.url.replace(/\/$/,""),reach:s,crtr_version:typeof e.crtr_version=="string"?e.crtr_version:null,last_seen:typeof e.last_seen=="string"?e.last_seen:null,kind:e.kind==="device"?"device":"runtime",plugins:Array.isArray(e.plugins)?e.plugins.filter(f=>typeof f=="string"):[],...typeof e.is_default=="boolean"?{is_default:e.is_default}:{}}}o(k,"asMachine");function L(t,e){const s=new Map,f=new Map,y=o(n=>{let r=s.get(n??"");return r||(r=new Map,s.set(n??"",r)),r},"reachOf"),_=o((n,r)=>r===void 0?n:`${n}?user_id=${encodeURIComponent(r)}`,"forPerson");async function w(n,r,i){const l=t.issuer();if(l===null)throw new u(0,"this daemon has no directory");const c=l.replace(/\/$/,"");for(let a=0;;a++){let h;try{const d=await t.tokens.get(c);h=await t.fetch(`${c}${r}`,{method:n,headers:{authorization:`Bearer ${d}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:JSON.stringify(i)},signal:AbortSignal.timeout(b)})}catch(d){throw new u(0,`the directory could not be reached: ${d instanceof Error?d.message:String(d)}`)}if(h.status===401&&a===0){t.tokens.drop(c);continue}if(!h.ok)throw new u(h.status,`directory ${n} ${r} answered ${h.status}`);try{return await h.json()}catch{throw new u(502,`directory ${n} ${r} answered a body that is not JSON`)}}}return o(w,"call"),{async list(){const n=t.person?.(),r=await w("GET",_("/v1/machines",n));if(!Array.isArray(r))throw new u(502,"the directory answered a machine list that is not an array");const i=r.map(k),l=t.now(),c=y(n);for(const a of i)c.set(a.machine_id,{machine:a,at:l}),g(a.machine_id,a.name);return f.set(n??"",i),i},lastList(){return f.get(t.person?.()??"")??null},async reach(n){const r=m(n),i=t.person?.(),l=y(i),c=l.get(r);if(c&&t.now()-c.at<U)return c.machine;try{const a=k(await w("GET",_(`/v1/machines/${encodeURIComponent(r)}/reach`,i)));return l.set(r,{machine:a,at:t.now()}),g(a.machine_id,a.name),a}catch(a){if(a instanceof u&&a.status===404)return l.delete(r),null;if(c&&a instanceof u&&a.status===0)return c.machine;throw a}},async status(n){const r=e(),i=await w("PUT",`/v1/machines/${encodeURIComponent(r)}/status`,n);if(!i||typeof i.machine_id!="string"||typeof i.url!="string")throw new u(502,"the directory answered a status record with a missing machine_id or url");return{machine_id:i.machine_id,url:i.url.replace(/\/$/,""),reach:T(i.reach)}},invalidate(n){if(n===void 0){s.clear(),f.clear();return}const r=m(n);for(const i of s.values())i.delete(r)}}}o(L,"createDirectoryClient");function v(){return m(M().runtime)}o(v,"ownMachineId");const p=L({issuer:$,tokens:S,fetch:o((t,e)=>fetch(t,e),"fetch"),now:Date.now,person:D},v),q=o(()=>p.list(),"listMachines"),B=o(t=>p.reach(t),"machineReach"),x="machine_url";async function K(){return(await(await E()).prepare("SELECT value FROM runtime_state WHERE key = ?").get(x))?.value??null}o(K,"machineUrl");async function N(t){await(await E()).prepare("INSERT INTO runtime_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(x,t)}o(N,"storeMachineUrl");async function W(t=p){if($()===null)return null;try{M()}catch{return null}const e=await t.status({plugins:R(),crtr_version:I()});if(e.machine_id!==v())throw new u(502,"the directory answered a status for another machine");return await N(e.url),e}o(W,"reportMachineStatus");export{b as DIRECTORY_CALL_TIMEOUT_MS,u as DirectoryError,U as REACH_TTL_MS,D as actingPerson,L as createDirectoryClient,p as directory,q as listMachines,B as machineReach,K as machineUrl,m as normalizeMachineId,v as ownMachineId,W as reportMachineStatus};
@@ -1,11 +1,11 @@
1
1
  import { type DirectoryToken } from '../grants/sync.js';
2
2
  export declare const REFRESH_BEFORE_EXPIRY_MS = 30000;
3
- export type Mint = (issuer: string, audience?: string) => Promise<DirectoryToken>;
3
+ export type Mint = (issuer: string, audience?: string, sub?: string) => Promise<DirectoryToken>;
4
4
  export interface TokenCache {
5
5
  /** A token for `audience` (a peer machine URL or the relay origin), or for the directory's own `/v1` when omitted. */
6
- get(issuer: string, audience?: string): Promise<string>;
6
+ get(issuer: string, audience?: string, sub?: string): Promise<string>;
7
7
  /** Forget a token the far side refused (revoked key, clock skew); the next `get` mints a new one. */
8
- drop(issuer: string, audience?: string): void;
8
+ drop(issuer: string, audience?: string, sub?: string): void;
9
9
  clear(): void;
10
10
  }
11
11
  export declare function createTokenCache(mint?: Mint, now?: () => number): TokenCache;
@@ -1,2 +1,3 @@
1
- var _=Object.defineProperty;var p=(a,s)=>_(a,"name",{value:s,configurable:!0});import{mintDirectoryToken as k}from"../grants/sync.js";const g=3e4;function y(a=k,s=Date.now){const r=new Map,o=new Map,i=p((e,t)=>`${e.replace(/\/$/,"")}
2
- ${t??""}`,"keyOf");return{async get(e,t){const n=i(e,t),l=r.get(n);if(l&&l.expires_at-g>s())return l.access_token;let c=o.get(n);return c||(c=a(e,t).then(f=>(r.set(n,f),f)).finally(()=>{o.delete(n)}),o.set(n,c)),(await c).access_token},drop(e,t){r.delete(i(e,t))},clear(){r.clear(),o.clear()}}}p(y,"createTokenCache");const h=y();export{g as REFRESH_BEFORE_EXPIRY_MS,y as createTokenCache,h as peerTokens};
1
+ var k=Object.defineProperty;var f=(o,p)=>k(o,"name",{value:p,configurable:!0});import{mintDirectoryToken as d}from"../grants/sync.js";const g=3e4;function y(o=d,p=Date.now){const c=new Map,a=new Map,i=f((e,t,n)=>`${e.replace(/\/$/,"")}
2
+ ${t??""}
3
+ ${n??""}`,"keyOf");return{async get(e,t,n){const r=i(e,t,n),s=c.get(r);if(s&&s.expires_at-g>p())return s.access_token;let l=a.get(r);return l||(l=(n===void 0?o(e,t):o(e,t,n)).then(_=>(c.set(r,_),_)).finally(()=>{a.delete(r)}),a.set(r,l)),(await l).access_token},drop(e,t,n){c.delete(i(e,t,n))},clear(){c.clear(),a.clear()}}}f(y,"createTokenCache");const w=y();export{g as REFRESH_BEFORE_EXPIRY_MS,y as createTokenCache,w as peerTokens};
@@ -1,3 +1,3 @@
1
- var M=Object.defineProperty;var m=(o,t)=>M(o,"name",{value:t,configurable:!0});import{killBashJobObject as C,recordBashJobObject as D}from"../../../core/spaces/stop.js";import{readerFor as L}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as x,appProcessSandboxed as z}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as G}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as q}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as B}from"../../../core/canvas/node-agent-paths.js";import{getNode as S}from"../../../core/canvas/canvas.js";import{isBrokerLive as Q}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as W}from"../../../core/runtime/reopen.js";import{reviveNode as Y}from"../../../core/runtime/revive.js";import{checkStart as Z}from"../../../core/runtime/start-check.js";import{bashJobPaths as J,isBashJobProcessGroupAlive as V,isSafeBashJobId as N,readBashNiceness as tt,signalBashJob as et,stopBackgroundBashJob as ot}from"../../../core/bash-jobs.js";import{applyJobReport as nt,jobRow as it,ownerRunsRemotely as O,runningJobs as I,setJobDeadline as T,markJobQuietOk as rt}from"../../../core/graph/jobs.js";import{withCanvasWrite as A,openDb as _}from"../../../core/canvas/db.js";import{getById as E}from"../../../core/graph/objects.js";import{blobStore as P}from"../../../core/blobs/index.js";import{ApiError as a}from"../../../api/index.js";import{BASH_JOB_OUTPUT_DEFAULT_BYTES as at,BASH_JOB_OUTPUT_MAX_BYTES as st}from"../../../api/index.js";import{notFound as dt}from"../../../core/errors.js";import{freshChildNodeExecPath as ut}from"../../../core/runtime/branded-host.js";async function g(o){const t=o.params.id;if(t===void 0||!K(t))throw new a(400,"invalid_node_id",`invalid node id: ${JSON.stringify(t)}`);if(await S(t)===null)throw dt(`unknown node: ${t}`,{received:t});const e=o.params.jobId;if(e!==void 0){if(!N(e))throw new a(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return{nodeId:t,jobId:e,dir:await B(t)}}return{nodeId:t,dir:await B(t)}}m(g,"requireTarget");async function pt(o){const{nodeId:t,dir:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may start a job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.start requires a JSON body");const s=e;await q(t,s.expected_execution_id);const n=s.job_id,r=s.cwd,d=s.env;if(typeof n!="string"||!N(n)||typeof r!="string"||!d||typeof d!="object"||Array.isArray(d)||Object.entries(d).some(([l,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l)||typeof p!="string"))throw new a(400,"invalid_request","invalid job id, cwd or environment");const b=await S(t);if(await Z({grantee:b.grantee??"app:terminal",sub:b.sub,grant_id:b.grant_id}),!z())throw new a(400,"invalid_request","job.start is only used with the root launcher");const u=J(i,n);if(!(k(u.root,u.jobRun)||k(u.root,u.jobBg))||![u.cmdSh,u.jobLog].every(l=>k(u.root,l)))throw new a(404,"job_not_found","job was not prepared by this node");const f=H(u.dir,"job.starting");try{$(u.root,f,"")}catch(l){throw l.code==="EEXIST"?new a(409,"job_already_started","job was already started"):l}let h;try{const l=d,p=X("bash",l,r),j=await S(t),v=await ut();return h=await x({nodeId:t,app:j.grantee??"app:terminal",isolated:j.isolated,cwd:r,env:l,capture:!1,command:[p,"-c",G,"--",u.cmdSh,u.jobLog,u.jobExit,u.jobRun,u.jobDone,p,String(tt(i)),v,u.jobActivity]}),$(u.root,u.jobPgid,String(h.pid),384),$(u.root,u.jobPgidIdentity,`launcher:${h.pid}`,384),{status:201,body:{pid:h.pid}}}catch(l){if(h!==void 0)try{await h.stop()}catch(p){throw new AggregateError([l,p],`job ${n} launched but could not be recorded or stopped`)}try{U(u.root,f)}catch(p){if(p.code!=="ENOENT")throw p}throw l}}m(pt,"handleStart");async function lt(o){const{nodeId:t}=await g(o),i=Date.now(),e=await O(await _(),t);return{status:200,body:(await I(await _(),t)).map(n=>({job_id:n.jobId,command:n.command,purpose:n.purpose,started_at:new Date(n.startedAtMs).toISOString(),elapsed_ms:Math.max(0,i-n.startedAtMs),output_key:n.outputKey,deadline_at:n.deadlineAtMs===null?null:new Date(n.deadlineAtMs).toISOString(),pgid:n.pgid,pgid_alive:!e&&n.pgid!==null&&n.pgidIdentity!==null&&V(n.pgid,n.pgidIdentity)}))}}m(lt,"handleList");function R(o,t,i){const e=o.query.get(t);if(e===null)return;const s=Number(e);if(!/^[0-9]+$/.test(e)||!Number.isSafeInteger(s)||s<1||s>i)throw new a(400,"invalid_request",`${t} must be an integer from 1 to ${i}`);return s}m(R,"boundedQueryInt");async function ct(o){const{nodeId:t,jobId:i}=await g(o),e=R(o,"tail_lines",Number.MAX_SAFE_INTEGER),s=R(o,"max_bytes",st)??at,n=await _(),r=await E(n,i??"");if(r===null||r.type!=="job"||r.owner!==t||r.deleted_at!==null)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);const d=await it(n,r);if(d===null)throw new Error(`job object ${r.id} has no jobs row`);const b=await P(),u=await b.list(`${d.output_key}/`),w=[];let f=0,h=0,l=u.length;for(;l>0&&f<=s&&(e===void 0||h<=e+1);){const c=u[--l],y=await b.get(c);if(y===null)throw new Error(`job ${r.id} output chunk ${c} is listed but cannot be read`);w.unshift(y),f+=y.length;for(const F of y)F===10&&h++}let p=Buffer.concat(w),j=l>0;if(p.length>s){p=p.subarray(p.length-s);let c=0;for(;c<p.length&&(p[c]&192)===128;)c++;p=p.subarray(c),j=!0}let v=p.toString("utf8");if(e!==void 0){const c=v.split(`
1
+ var M=Object.defineProperty;var m=(o,t)=>M(o,"name",{value:t,configurable:!0});import{killBashJobObject as C,recordBashJobObject as D}from"../../../core/spaces/stop.js";import{readerFor as L}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as x,appProcessSandboxed as z}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as G}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as q}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as J}from"../../../core/canvas/node-agent-paths.js";import{getNode as S}from"../../../core/canvas/canvas.js";import{isBrokerLive as Q}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as W}from"../../../core/runtime/reopen.js";import{reviveNode as Y}from"../../../core/runtime/revive.js";import{checkStart as Z}from"../../../core/runtime/start-check.js";import{bashJobPaths as N,isBashJobProcessGroupAlive as V,isSafeBashJobId as O,readBashNiceness as tt,signalBashJob as et,stopBackgroundBashJob as ot}from"../../../core/bash-jobs.js";import{applyJobReport as nt,jobRow as it,ownerRunsRemotely as A,runningJobs as I,setJobDeadline as T,markJobQuietOk as rt}from"../../../core/graph/jobs.js";import{withCanvasWrite as E,openDb as h}from"../../../core/canvas/db.js";import{getById as B}from"../../../core/graph/objects.js";import{blobStore as P}from"../../../core/blobs/index.js";import{ApiError as a}from"../../../api/index.js";import{BASH_JOB_OUTPUT_DEFAULT_BYTES as at,BASH_JOB_OUTPUT_MAX_BYTES as st}from"../../../api/index.js";import{notFound as dt}from"../../../core/errors.js";import{freshChildNodeExecPath as ut}from"../../../core/runtime/branded-host.js";async function g(o){const t=o.params.id;if(t===void 0||!K(t))throw new a(400,"invalid_node_id",`invalid node id: ${JSON.stringify(t)}`);if(await S(t)===null)throw dt(`unknown node: ${t}`,{received:t});const e=o.params.jobId;if(e!==void 0){if(!O(e))throw new a(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return{nodeId:t,jobId:e,dir:await J(t)}}return{nodeId:t,dir:await J(t)}}m(g,"requireTarget");async function pt(o){const{nodeId:t,dir:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may start a job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.start requires a JSON body");const s=e;await q(t,s.expected_execution_id);const n=s.job_id,r=s.cwd,d=s.env;if(typeof n!="string"||!O(n)||typeof r!="string"||!d||typeof d!="object"||Array.isArray(d)||Object.entries(d).some(([l,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l)||typeof p!="string"))throw new a(400,"invalid_request","invalid job id, cwd or environment");const b=await S(t);if(await Z({grantee:b.grantee??"app:terminal",sub:b.sub,grant_id:b.grant_id}),!z())throw new a(400,"invalid_request","job.start is only used with the root launcher");const u=N(i,n);if(!(k(u.root,u.jobRun)||k(u.root,u.jobBg))||![u.cmdSh,u.jobLog].every(l=>k(u.root,l)))throw new a(404,"job_not_found","job was not prepared by this node");const f=H(u.dir,"job.starting");try{$(u.root,f,"")}catch(l){throw l.code==="EEXIST"?new a(409,"job_already_started","job was already started"):l}let _;try{const l=d,p=X("bash",l,r),j=await S(t),v=await ut();return _=await x({nodeId:t,app:j.grantee??"app:terminal",isolated:j.isolated,cwd:r,env:l,capture:!1,command:[p,"-c",G,"--",u.cmdSh,u.jobLog,u.jobExit,u.jobRun,u.jobDone,p,String(tt(i)),v,u.jobActivity]}),$(u.root,u.jobPgid,String(_.pid),384),$(u.root,u.jobPgidIdentity,`launcher:${_.pid}`,384),{status:201,body:{pid:_.pid}}}catch(l){if(_!==void 0)try{await _.stop()}catch(p){throw new AggregateError([l,p],`job ${n} launched but could not be recorded or stopped`)}try{U(u.root,f)}catch(p){if(p.code!=="ENOENT")throw p}throw l}}m(pt,"handleStart");async function lt(o){const{nodeId:t}=await g(o),i=Date.now(),e=await A(await h(),t);return{status:200,body:(await I(await h(),t)).map(n=>({job_id:n.jobId,command:n.command,purpose:n.purpose,started_at:new Date(n.startedAtMs).toISOString(),elapsed_ms:Math.max(0,i-n.startedAtMs),output_key:n.outputKey,deadline_at:n.deadlineAtMs===null?null:new Date(n.deadlineAtMs).toISOString(),pgid:n.pgid,pgid_alive:!e&&n.pgid!==null&&n.pgidIdentity!==null&&V(n.pgid,n.pgidIdentity)}))}}m(lt,"handleList");function R(o,t,i){const e=o.query.get(t);if(e===null)return;const s=Number(e);if(!/^[0-9]+$/.test(e)||!Number.isSafeInteger(s)||s<1||s>i)throw new a(400,"invalid_request",`${t} must be an integer from 1 to ${i}`);return s}m(R,"boundedQueryInt");async function ct(o){const{nodeId:t,jobId:i}=await g(o),e=R(o,"tail_lines",Number.MAX_SAFE_INTEGER),s=R(o,"max_bytes",st)??at,n=await h(),r=await B(n,i??"");if(r===null||r.type!=="job"||r.owner!==t||r.deleted_at!==null)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);const d=await it(n,r);if(d===null)throw new Error(`job object ${r.id} has no jobs row`);const b=await P(),u=await b.list(`${d.output_key}/`),w=[];let f=0,_=0,l=u.length;for(;l>0&&f<=s&&(e===void 0||_<=e+1);){const c=u[--l],y=await b.get(c);if(y===null)throw new Error(`job ${r.id} output chunk ${c} is listed but cannot be read`);w.unshift(y),f+=y.length;for(const F of y)F===10&&_++}let p=Buffer.concat(w),j=l>0;if(p.length>s){p=p.subarray(p.length-s);let c=0;for(;c<p.length&&(p[c]&192)===128;)c++;p=p.subarray(c),j=!0}let v=p.toString("utf8");if(e!==void 0){const c=v.split(`
2
2
  `),y=c[c.length-1]===""?e+1:e;c.length>y&&(v=c.slice(c.length-y).join(`
3
- `),j=!0)}return{status:200,body:{job_id:r.id,output:v,truncated:j}}}m(ct,"handleOutput");async function bt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.query.get("foreground")==="1"){if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await q(t,o.body?.expected_execution_id);const w=await ot(e,i,!0,t);if(w.kind==="missing")throw new a(404,"job_not_found",`no job ${i} for ${t}`);if(w.kind==="retired")throw new a(404,"job_not_found",`job ${i} for ${t} is no longer running`);if(w.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${i} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:i,signaled:w.signaled}}}const n=(await I(await _(),t)).find(w=>w.jobId===i);if(n===void 0)throw new a(404,"job_not_found",`no running background job ${i} for ${t}`);const r=await O(await _(),t);if(!r&&(n.pgid===null||n.pgidIdentity===null))throw new a(409,"job_not_stoppable",`job ${i} reported no trusted process identity`);await W(t);const d=r?!0:await et(n.pgid,n.pgidIdentity,t);await C(i,async w=>{const f=await L(w,o);return f.class==="person"?f.person:f.class==="app"?f.app:f.node});const b=await S(t);if(b!==null&&!Q(b))try{await Y(t,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:t,job_id:i,signaled:d}}}m(bt,"handleStop");async function wt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may record its job");const s=o.body,n=J(e,i),r=s?.purpose,d=s?.deadline_at_ms;if(typeof s?.command!="string"||r!=null&&typeof r!="string"||d!=null&&!Number.isFinite(d))throw new a(400,"invalid_request","job.background requires command, and optionally purpose and deadline_at_ms");if(!k(n.root,n.jobBg))throw new a(404,"job_not_found",`job ${i} of ${t} is not backgrounded`);return{status:201,body:{id:(await D(t,i,{command:s.command,purpose:r??null,deadlineAtMs:d??null})).id}}}m(wt,"handleBackground");async function ft(o,t){if(t===void 0)throw new a(400,"invalid_request","a job id is required");const i=await E(await _(),t);if(i===null||i.type!=="job"||i.owner!==o)throw new a(404,"job_not_found",`no job ${t} for ${o}`);if(!(await I(await _(),o)).some(e=>e.jobId===t))throw new a(409,"job_not_running",`job ${t} for ${o} is no longer running`);return t}m(ft,"requireRunningJob");async function mt(o){const{nodeId:t,jobId:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may report its job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.report requires a JSON body");await q(t,e.expected_execution_id);const s=await E(await _(),i??"");if(s===null||s.type!=="job"||s.owner!==t)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);if(!(await I(await _(),t)).some(d=>d.jobId===i))throw new a(409,"job_not_running",`job ${String(i)} for ${t} is no longer running`);const n=e.output;if(n!==void 0){if(!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.data_base64!="string")throw new a(400,"invalid_request","output requires seq and data_base64");const d=await A(async b=>await b.prepare("SELECT output_key FROM jobs WHERE object = ?").get(i));await(await P()).put(`${d.output_key}/${String(n.seq).padStart(8,"0")}`,Buffer.from(n.data_base64,"base64"))}const r=e.activity;if(r!==void 0&&(!Number.isFinite(r.last_ms)||!Number.isFinite(r.sampled_ms)||!Array.isArray(r.files)))throw new a(400,"invalid_request","activity requires last_ms, sampled_ms and files");return await A(async d=>nt(d,i,{...typeof e.pgid=="number"?{pgid:e.pgid}:{},...typeof e.pgid_identity=="string"?{pgidIdentity:e.pgid_identity}:{},...typeof e.exit_code=="number"?{exitCode:e.exit_code}:{},...e.vanished===!0?{vanished:!0}:{},...r===void 0?{}:{activity:{lastActivityMs:r.last_ms,sampledAtMs:r.sampled_ms,files:r.files}}})),{status:204}}m(mt,"handleReport");async function ht(o){const{nodeId:t,jobId:i}=await g(o),e=await ft(t,i),s=o.body,n=s?.deadline_at_ms,r=s?.keep===!0;if(s?.quiet_ok!==!0&&!r&&!Number.isFinite(n))throw new a(400,"invalid_request","patch requires quiet_ok, keep or deadline_at_ms");if(r&&n!==void 0)throw new a(400,"invalid_request","keep and deadline_at_ms are exclusive");return await A(async d=>{s?.quiet_ok===!0&&await rt(d,e),r?await T(d,e,null):Number.isFinite(n)&&await T(d,e,n)}),{status:204}}m(ht,"handlePatch");const xt=[{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/background",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/report",handler:mt},{method:"PATCH",pattern:"/v1/nodes/:id/jobs/:jobId",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:pt},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:lt},{method:"GET",pattern:"/v1/nodes/:id/jobs/:jobId/output",handler:ct},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:bt}];export{xt as bashJobRoutes};
3
+ `),j=!0)}return{status:200,body:{job_id:r.id,output:v,truncated:j}}}m(ct,"handleOutput");async function bt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.query.get("foreground")==="1"){if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await q(t,o.body?.expected_execution_id);const w=await ot(e,i,!0,t);if(w.kind==="missing")throw new a(404,"job_not_found",`no job ${i} for ${t}`);if(w.kind==="retired")throw new a(404,"job_not_found",`job ${i} for ${t} is no longer running`);if(w.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${i} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:i,signaled:w.signaled}}}const n=(await I(await h(),t)).find(w=>w.jobId===i);if(n===void 0)throw new a(404,"job_not_found",`no running background job ${i} for ${t}`);const r=await A(await h(),t);if(!r&&(n.pgid===null||n.pgidIdentity===null))throw new a(409,"job_not_stoppable",`job ${i} reported no trusted process identity`);await W(t);const d=r?!0:await et(n.pgid,n.pgidIdentity,t);await C(i,async w=>{const f=await L(w,o);return f.class==="person"?f.person:f.class==="app"?f.app:f.node});const b=await S(t);if(b!==null&&!Q(b))try{await Y(t,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:t,job_id:i,signaled:d}}}m(bt,"handleStop");async function wt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may record its job");const s=o.body,n=N(e,i),r=s?.purpose,d=s?.deadline_at_ms;if(typeof s?.command!="string"||r!=null&&typeof r!="string"||d!=null&&!Number.isFinite(d))throw new a(400,"invalid_request","job.background requires command, and optionally purpose and deadline_at_ms");if(!await A(await h(),t)&&!k(n.root,n.jobBg))throw new a(404,"job_not_found",`job ${i} of ${t} is not backgrounded`);return{status:201,body:{id:(await D(t,i,{command:s.command,purpose:r??null,deadlineAtMs:d??null})).id}}}m(wt,"handleBackground");async function ft(o,t){if(t===void 0)throw new a(400,"invalid_request","a job id is required");const i=await B(await h(),t);if(i===null||i.type!=="job"||i.owner!==o)throw new a(404,"job_not_found",`no job ${t} for ${o}`);if(!(await I(await h(),o)).some(e=>e.jobId===t))throw new a(409,"job_not_running",`job ${t} for ${o} is no longer running`);return t}m(ft,"requireRunningJob");async function mt(o){const{nodeId:t,jobId:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may report its job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.report requires a JSON body");await q(t,e.expected_execution_id);const s=await B(await h(),i??"");if(s===null||s.type!=="job"||s.owner!==t)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);if(!(await I(await h(),t)).some(d=>d.jobId===i))throw new a(409,"job_not_running",`job ${String(i)} for ${t} is no longer running`);const n=e.output;if(n!==void 0){if(!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.data_base64!="string")throw new a(400,"invalid_request","output requires seq and data_base64");const d=await E(async b=>await b.prepare("SELECT output_key FROM jobs WHERE object = ?").get(i));await(await P()).put(`${d.output_key}/${String(n.seq).padStart(8,"0")}`,Buffer.from(n.data_base64,"base64"))}const r=e.activity;if(r!==void 0&&(!Number.isFinite(r.last_ms)||!Number.isFinite(r.sampled_ms)||!Array.isArray(r.files)))throw new a(400,"invalid_request","activity requires last_ms, sampled_ms and files");return await E(async d=>nt(d,i,{...typeof e.pgid=="number"?{pgid:e.pgid}:{},...typeof e.pgid_identity=="string"?{pgidIdentity:e.pgid_identity}:{},...typeof e.exit_code=="number"?{exitCode:e.exit_code}:{},...e.vanished===!0?{vanished:!0}:{},...r===void 0?{}:{activity:{lastActivityMs:r.last_ms,sampledAtMs:r.sampled_ms,files:r.files}}})),{status:204}}m(mt,"handleReport");async function ht(o){const{nodeId:t,jobId:i}=await g(o),e=await ft(t,i),s=o.body,n=s?.deadline_at_ms,r=s?.keep===!0;if(s?.quiet_ok!==!0&&!r&&!Number.isFinite(n))throw new a(400,"invalid_request","patch requires quiet_ok, keep or deadline_at_ms");if(r&&n!==void 0)throw new a(400,"invalid_request","keep and deadline_at_ms are exclusive");return await E(async d=>{s?.quiet_ok===!0&&await rt(d,e),r?await T(d,e,null):Number.isFinite(n)&&await T(d,e,n)}),{status:204}}m(ht,"handlePatch");const xt=[{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/background",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/report",handler:mt},{method:"PATCH",pattern:"/v1/nodes/:id/jobs/:jobId",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:pt},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:lt},{method:"GET",pattern:"/v1/nodes/:id/jobs/:jobId/output",handler:ct},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:bt}];export{xt as bashJobRoutes};
@@ -16,4 +16,4 @@ ${a}
16
16
  `),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Gt();const n=await Ot({waitForJoinLock:!0});_.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
17
17
  `),process.exit(1)}process.exit(0)}s(rr,"performHandover");function x(){if(E!==void 0)return E;const n=Ze();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function tr(){S={phase:"initializing",message:qn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:zn}))}s(tr,"drainApi");async function Se(n){try{n==="SIGTERM"&&e.role==="api"&&await tr(),await x(),await Vt({claimed:s(async()=>{try{return p&&await Ut()}finally{await pe()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
18
18
  ${w}
19
- `),process.exit(1)}}s(Se,"handleSignal");function ye(){Se("SIGINT")}s(ye,"onSigint");function _e(){Se("SIGTERM")}s(_e,"onSigterm");function be(){x().catch(()=>{})}s(be,"onExit");async function ce(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(ce,"enqueue");async function V(){!T||Z||(Ye.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Kt({log:c}),await jn(Date.now(),ve)}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(V,"enqueueTick");let B=null;async function nr(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const n=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw B=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(nr,"admitStartup");async function or(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await fn({dryRun:n.dryRun});if(n.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(or,"repairMigrations");async function ir(){X=e.intervalMs??nt;const n=g.token;C=new sn({epoch:n,enqueue:ce}),$t(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const a=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Gr(a);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=tt()}catch{return}t!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),yt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Or(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await rt(),await Xr(),await Zr(Date.now()),await et(Date.now())}),await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ft(ut);t.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await Me();for(const o of await Ce())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Le(o.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Tt();for(const t of ln){const o=await t.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(Yr()),I){const t=s(()=>{k(I().catch(()=>{})),k(lr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Vr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),G=setInterval(t,Ne*1e3),G.unref(),se=cr({joined:!0,register:k})}await ce(async()=>{await an(),await on()}),U=setInterval(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},X),ee=await Dt(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))}),re=await H.subscribe(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>m({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(ir,"completeStartup");function le(){return Qe??=ir().catch(n=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),dn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...r}}),f!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:f.person,joined_from:f.joinedFrom,retired:f.retired,columns:f.columns}}),N(e.role)?J=await vr():gr(wr());const n=g.token;Nt({epoch:n,requestHandover:er,registerDetached:k,startupBlock:Xe,admitStartup:nr,repairMigrations:or}),Je(),L=N(e.role)?Cr({tcp:e.tcp}):Un(e),await L.ready;const a=hr()??de("user").document_port;if(N(e.role)){const t=Ar(a,Nr());try{await t.ready,ne=t}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=de("user").runtime;if(w?.issuer&&(I=Kr(w.issuer,k),w.unsandboxed===!0&&(F=dr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Wr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),O=setInterval(t,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await Ur()),j(e.role)&&(ie=Jr()),ae=await qr({serves:N(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(M=await Mr(w,async()=>await Qr(w.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await mn()}catch(t){if($=null,t instanceof pn)return S={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(kr(),await br("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Jn,"runDaemon");var Ki=Jn;export{zn as API_DRAIN_GRACE_MS,Qi as brokerCommandDeclaresCanvasHome,he as brokerCommandEpoch,Ki as default,j as roleRunsLanes,N as roleServesRequests,Jn as runDaemon,jn as superviseTick,bn as teardownFleet};
19
+ `),process.exit(1)}}s(Se,"handleSignal");function ye(){Se("SIGINT")}s(ye,"onSigint");function _e(){Se("SIGTERM")}s(_e,"onSigterm");function be(){x().catch(()=>{})}s(be,"onExit");async function ce(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(ce,"enqueue");async function V(){!T||Z||(Ye.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Kt({log:c}),await jn(Date.now(),ve)}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(V,"enqueueTick");let B=null;async function nr(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const n=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw B=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(nr,"admitStartup");async function or(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await fn({dryRun:n.dryRun});if(n.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(or,"repairMigrations");async function ir(){X=e.intervalMs??nt;const n=g.token;C=new sn({epoch:n,enqueue:ce}),$t(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const a=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Gr(a);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=tt()}catch{return}t!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),yt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Or(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await rt(),await Xr(),await Zr(Date.now()),await et(Date.now())}),e.role===void 0&&await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ft(ut);t.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await Me();for(const o of await Ce())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Le(o.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Tt();for(const t of ln){const o=await t.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(Yr()),I){const t=s(()=>{k(I().catch(()=>{})),k(lr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Vr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),G=setInterval(t,Ne*1e3),G.unref(),se=cr({joined:!0,register:k})}await ce(async()=>{await an(),await on()}),U=setInterval(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},X),ee=await Dt(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))}),re=await H.subscribe(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>m({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(ir,"completeStartup");function le(){return Qe??=ir().catch(n=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),dn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...r}}),f!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:f.person,joined_from:f.joinedFrom,retired:f.retired,columns:f.columns}}),N(e.role)?J=await vr():gr(wr());const n=g.token;Nt({epoch:n,requestHandover:er,registerDetached:k,startupBlock:Xe,admitStartup:nr,repairMigrations:or}),Je(),L=N(e.role)?Cr({tcp:e.tcp}):Un(e),await L.ready;const a=hr()??de("user").document_port;if(N(e.role)){const t=Ar(a,Nr());try{await t.ready,ne=t}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=de("user").runtime;if(w?.issuer&&(I=Kr(w.issuer,k),w.unsandboxed===!0&&(F=dr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Wr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),O=setInterval(t,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await Ur()),j(e.role)&&(ie=Jr()),ae=await qr({serves:N(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(M=await Mr(w,async()=>await Qr(w.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await mn()}catch(t){if($=null,t instanceof pn)return S={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(kr(),await br("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Jn,"runDaemon");var Ki=Jn;export{zn as API_DRAIN_GRACE_MS,Qi as brokerCommandDeclaresCanvasHome,he as brokerCommandEpoch,Ki as default,j as roleRunsLanes,N as roleServesRequests,Jn as runDaemon,jn as superviseTick,bn as teardownFleet};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.650",
3
+ "version": "0.3.651",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.650",
148
+ "@north-light/identity": "0.3.651",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.650",
3
+ "version": "0.3.651",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",