@north-light/cli 0.3.464 → 0.3.466

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.
@@ -192,7 +192,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
192
192
  `);V0.mkdirSync(dC.dirname(W),{recursive:!0}),V0.writeFileSync(W,me),this.stop();let K=[`Rendered line ${P} exceeds terminal width (${Ie(U)} > ${e}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${W}`].join(`
193
193
  `);throw new Error(K)}_.append(U)}let k=O;if(this.previousLines.length>l.length){if(O<l.length-1){let U=l.length-1-O;_.append(`\x1B[${U}B`),k=l.length-1}let P=this.previousLines.length-l.length;for(let U=l.length;U<this.previousLines.length;U++)_.append(`\r
194
194
  \x1B[2K`);_.append(`\x1B[${P}A`)}if(_.append("\x1B[?2026l"),process.env.PI_TUI_DEBUG==="1"){let P="/tmp/tui";V0.mkdirSync(P,{recursive:!0});let U=dC.join(P,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),q=[`firstChanged: ${g}`,`viewportTop: ${a}`,`cursorRow: ${this.cursorRow}`,`height: ${n}`,`lineDiff: ${D}`,`hardwareCursorRow: ${c}`,`renderEnd: ${O}`,`finalCursorRow: ${k}`,`cursorPos: ${JSON.stringify(d)}`,`newLines.length: ${l.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(l,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${_.length} chars written in bounded chunks]`].join(`
195
- `);V0.writeFileSync(U,q)}_.flush(),this.cursorRow=Math.max(0,l.length-1),this.hardwareCursorRow=k,this.maxLinesRendered=Math.max(this.maxLinesRendered,l.length),this.previousViewportTop=Math.max(s,k-n+1),this.positionHardwareCursor(d,l.length),this.previousLines=l,this.previousKittyImageIds=this.collectKittyImageIds(l),this.previousWidth=e,this.previousHeight=n}positionHardwareCursor(e,n){if(!e||n<=0){this.terminal.hideCursor();return}let r=Math.max(0,Math.min(e.row,n-1)),i=Math.max(0,e.col),o=r-this.hardwareCursorRow,s="";o>0?s+=`\x1B[${o}B`:o<0&&(s+=`\x1B[${-o}A`),s+=`\x1B[${i+1}G`,s&&this.terminal.write(s),this.hardwareCursorRow=r,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}}});var et=h(()=>{E0e();Wit();Xit();Eot();Sot();swe();Fot();Uot();Q7();ewe();qot();Got();hwe();iwe();zot();Vot();Z0e();Kot();Yot();l7();q0();bb();dwe();V7();L0e();ywe();Awe();pst();W0e();Eb();Tf();kst();Nst();zs()});function pC(t){return s9+t.replace(/\./g,`${B2n}.${s9}`)+Sb}function Lst(t={}){let n=[`${$2n}${s9}crouter${Sb}${t.version?`${kQ} v${t.version}${Sb}`:""}`,`${kQ}the agentic runtime${Sb}`];t.profile&&n.push(`${kQ}profile: ${Sb}${s9}${t.profile}${Sb}`),t.cwd&&n.push(`${kQ}${t.cwd}${Sb}`);let r=[];for(let i=0;i<Pst.length;i++){let o=i>=1&&i-1<n.length?` ${n[i-1]}`:"";r.push(Pst[i]+o)}return t.hint&&r.push("",`${kQ}${t.hint}${Sb}`),r}var Sb,s9,B2n,$2n,kQ,Pst,Bst=h(()=>{"use strict";Sb="\x1B[0m",s9="\x1B[38;5;180m",B2n="\x1B[38;5;137m",$2n="\x1B[1m",kQ="\x1B[2m";Pst=[pC(" ________"),pC(" / /|"),pC(" / . . / |"),pC(" /_______/ |"),pC(" | . . | |"),pC(" | . . | /"),pC(" |_______|/")]});function F2n(t,e,n,r,i,o,s,a,c){return Object.freeze({id:t,group:e,name:n,description:r,defaults:Object.freeze([...i]),inputKind:o,contexts:Object.freeze([...s]),...a===void 0?{}:{safety:a},...c===void 0?{}:{pair:Object.freeze({...c})}})}function mi(t,e,n,r,i){let o=`crtr.tmux.menu.${t}`,s=`crtr.tmux.menu-global.${t}`;return[je(o,"Global tmux",e,n,r,"tmux-menu-selector",i,void 0,{field:"menu",pairedId:s}),je(s,"Global tmux",e,n,[],"tmux-global-action",["tmux.root"],void 0,{field:"global",pairedId:o})]}function gp(t,e,n,r,i,o){return[je(t,"Attach",n,r,i,"tmux-menu-selector",["tmux.menu.attach"],void 0,{field:"menu",pairedId:e}),je(e,"Attach",n,r,o,"host-global",Cb,void 0,{field:"direct",pairedId:t})]}function Q2n(){let t="browse";return[je("crtr.browse.quit","Browse and pickers","Quit browse","Leave canvas browse.",["q","escape","ctrl+c"],"terminal",[t],"leave-screen"),je("crtr.browse.down","Browse and pickers","Move down","Move to the next row.",["j","down"],"terminal",[t]),je("crtr.browse.up","Browse and pickers","Move up","Move to the previous row.",["k","up"],"terminal",[t]),je("crtr.browse.first","Browse and pickers","First row","Move to the first row.",["g"],"terminal",[t]),je("crtr.browse.last","Browse and pickers","Last row","Move to the last row.",["shift+g"],"terminal",[t]),je("crtr.browse.expand-or-child","Browse and pickers","Expand or child","Expand a row or move to its child.",["l","right"],"terminal",[t]),je("crtr.browse.collapse-or-parent","Browse and pickers","Collapse or parent","Collapse a row or move to its parent.",["h","left"],"terminal",[t]),je("crtr.browse.toggle-fold","Browse and pickers","Toggle fold","Toggle the selected fold.",["space"],"terminal",[t]),je("crtr.browse.tab-next","Browse and pickers","Next tab","Select the next browse tab.",["tab","]"],"terminal",[t]),je("crtr.browse.tab-previous","Browse and pickers","Previous tab","Select the previous browse tab.",["shift+tab","["],"terminal",[t]),...[1,2,3,4,5].map(e=>je(`crtr.browse.tab.${e}`,"Browse and pickers",`Tab ${e}`,`Select browse tab ${e}.`,[`${e}`],"terminal",[t])),je("crtr.browse.close-subtree","Browse and pickers","Close subtree","Ask to close the selected subtree.",["x"],"terminal",[t]),je("crtr.browse.confirm-close","Browse and pickers","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["browse.confirm"]),je("crtr.browse.sort","Browse and pickers","Change sort","Change the browse sort.",["s"],"terminal",[t]),je("crtr.browse.scope","Browse and pickers","Change scope","Toggle the browse cwd scope.",["c"],"terminal",[t]),je("crtr.browse.profile","Browse and pickers","Toggle profile","Toggle the browse profile scope.",["shift+p"],"terminal",[t]),je("crtr.browse.residents","Browse and pickers","Toggle residents","Toggle resident display.",["r"],"terminal",[t]),je("crtr.browse.preview","Browse and pickers","Toggle preview","Toggle the preview panel.",["v"],"terminal",[t]),je("crtr.browse.report","Browse and pickers","Toggle report","Swap the preview panel between the conversation and the node's newest report.",["shift+v"],"terminal",[t]),je("crtr.browse.pin","Browse and pickers","Pin node","Star or unstar the selected node.",["p"],"terminal",[t]),je("crtr.browse.search","Browse and pickers","Search","Open browse search.",["/"],"terminal",[t]),je("crtr.browse.revive-now","Browse and pickers","Revive now","Revive the selected node now.",["shift+k"],"terminal",[t]),je("crtr.browse.focus","Browse and pickers","Focus node","Focus the selected node.",["enter","o"],"terminal",[t]),je("crtr.browse.focus-background","Browse and pickers","Focus node (keep browsing)","Focus the selected node without leaving the navigator.",["shift+o"],"terminal",[t]),je("crtr.browse.yank-id","Browse and pickers","Yank node id","Copy the selected node id to the system clipboard.",["y"],"terminal",[t]),je("crtr.browse.search.cancel","Browse and pickers","Cancel search","Cancel browse search.",["escape"],"terminal",["browse.search"],"dismiss-modal"),je("crtr.browse.search.commit","Browse and pickers","Commit search","Apply browse search.",["enter"],"terminal",["browse.search"]),je("crtr.browse.search.delete","Browse and pickers","Delete search text","Delete the previous search character.",["backspace"],"terminal",["browse.search"]),je("crtr.browse.search.quit","Browse and pickers","Quit browse","Leave canvas browse from search.",["ctrl+c"],"terminal",["browse.search"],"leave-screen")]}function W2n(){let t="profile.menu",e="profile.search";return[je("crtr.profile.menu.up","Profiles","Move up","Move to the previous profile.",["k","up"],"terminal",[t]),je("crtr.profile.menu.down","Profiles","Move down","Move to the next profile.",["j","down"],"terminal",[t]),je("crtr.profile.menu.select","Profiles","Select profile","Select the highlighted profile.",["enter"],"terminal",[t]),je("crtr.profile.menu.accept-default","Profiles","Accept default","Accept the default profile.",["escape"],"terminal",[t],"leave-screen"),je("crtr.profile.menu.abort","Profiles","Abort","Leave profile selection.",["ctrl+c"],"terminal",[t],"leave-screen"),...[1,2,3,4,5,6,7,8,9].map(n=>je(`crtr.profile.menu.slot.${n}`,"Profiles",`Profile slot ${n}`,`Select profile slot ${n}.`,[`${n}`],"terminal",[t])),je("crtr.profile.menu.create","Profiles","Create profile","Create a profile.",["c"],"terminal",[t]),je("crtr.profile.menu.search-existing","Profiles","Search profiles","Search existing profiles.",["s"],"terminal",[t]),je("crtr.profile.menu.use-root","Profiles","Use root profile","Use the root profile.",["r"],"terminal",[t]),je("crtr.profile.menu.set-default","Profiles","Set default","Set the selected profile as default.",["d"],"terminal",[t]),je("crtr.profile.menu.add-directory","Profiles","Add directory","Add a directory to the profile.",["a"],"terminal",[t]),je("crtr.profile.menu.unpin","Profiles","Unpin directory","Unpin the selected directory.",["u"],"terminal",[t]),je("crtr.profile.menu.manage","Profiles","Manage profiles","Open the profiles settings page in a popup.",["v"],"terminal",[t]),je("crtr.profile.search.up","Profiles","Move up","Move to the previous search result.",["up","ctrl+p"],"terminal",[e]),je("crtr.profile.search.down","Profiles","Move down","Move to the next search result.",["down","ctrl+n"],"terminal",[e]),je("crtr.profile.search.pick","Profiles","Pick profile","Pick the highlighted profile.",["enter"],"terminal",[e]),je("crtr.profile.search.back","Profiles","Back","Return to profile selection.",["escape"],"terminal",[e],"leave-screen"),je("crtr.profile.search.delete","Profiles","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",[e]),je("crtr.profile.search.abort","Profiles","Abort","Leave profile search.",["ctrl+c"],"terminal",[e],"leave-screen")]}function H2n(){return[je("crtr.setup.cancel","Setup","Cancel setup","Leave the setup wizard.",["q","ctrl+c","ctrl+d"],"terminal",U2n,"leave-screen"),je("crtr.setup.tab-next","Setup","Next tab","Select the next setup tab.",["tab","right"],"terminal",$st),je("crtr.setup.tab-previous","Setup","Previous tab","Select the previous setup tab.",["shift+tab","left"],"terminal",$st),je("crtr.setup.open","Setup","Open","Open the selected setup item.",["enter"],"terminal",["setup.login"]),je("crtr.setup.list-down","Setup","Move down","Move to the next setup item.",["j","down"],"terminal",["setup.list","setup.models","setup.models.dimension-picker","setup.models.route-form"]),je("crtr.setup.list-up","Setup","Move up","Move to the previous setup item.",["k","up"],"terminal",["setup.list","setup.models","setup.models.dimension-picker","setup.models.route-form"]),je("crtr.setup.toggle","Setup","Toggle","Toggle the selected setup item.",["space"],"terminal",["setup.list","setup.keybindings"]),je("crtr.setup.details","Setup","Show details","Show details for the selected item.",["?"],"terminal",["setup.list"]),je("crtr.setup.advance","Setup","Advance","Advance the setup flow.",["enter"],"terminal",["setup.list"]),je("crtr.setup.confirm.accept","Setup","Confirm","Accept the setup confirmation.",["y","enter"],"terminal",["setup.confirm","setup.models.confirm"]),je("crtr.setup.confirm.back","Setup","Go back","Cancel the setup confirmation.",["n","escape","q"],"terminal",["setup.confirm","setup.models.confirm"],"dismiss-modal"),je("crtr.setup.keybindings.edit","Setup","Edit binding","Edit the selected binding.",["enter"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.commit-edit","Setup","Commit edit","Commit the active binding edit.",["enter"],"terminal",["setup.keybindings.edit"]),je("crtr.setup.keybindings.cancel-edit","Setup","Cancel edit","Cancel the active binding edit.",["escape"],"terminal",["setup.keybindings.edit"],"dismiss-modal"),je("crtr.setup.keybindings.unbind","Setup","Unbind","Disable the selected binding.",["delete"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.reset-row","Setup","Reset binding","Reset the selected binding.",["r"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.reset-all","Setup","Reset all bindings","Reset all bindings to defaults.",["shift+r"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.save","Setup","Save bindings","Save keybinding changes.",["s"],"terminal",["setup.keybindings"],"save-keybindings"),je("crtr.setup.keybindings.discard","Setup","Discard changes","Discard keybinding changes.",["escape"],"terminal",["setup.keybindings"],"leave-screen"),je("crtr.setup.keybindings.page-up","Setup","Page up","Move up one keybinding page.",["pageup"],"terminal",["setup.keybindings","setup.keybindings.edit"]),je("crtr.setup.keybindings.page-down","Setup","Page down","Move down one keybinding page.",["pagedown"],"terminal",["setup.keybindings","setup.keybindings.edit"]),je("crtr.setup.keybindings.filter","Setup","Filter bindings","Open the keybinding filter.",["/"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.filter-delete","Setup","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",["setup.keybindings.filter"]),je("crtr.setup.keybindings.filter-clear","Setup","Clear filter","Clear the keybinding filter.",["escape"],"terminal",["setup.keybindings.filter"],"dismiss-modal"),je("crtr.setup.cell-previous","Setup","Previous field","Select the previous field or setup table cell.",["h"],"terminal",["setup.models","setup.keybindings"]),je("crtr.setup.cell-next","Setup","Next field","Select the next field or setup table cell.",["l"],"terminal",["setup.models","setup.keybindings"]),je("crtr.setup.models.open","Setup","Edit model","Edit the selected model cell or route field.",["enter"],"terminal",["setup.models","setup.models.route-form"]),je("crtr.setup.models.scope-next","Setup","Next model config scope","Edit the next applicable user, profile, or project config.",["s"],"terminal",["setup.models"]),je("crtr.setup.models.commit","Setup","Commit pick","Commit the provider, strength, model, or thinking-level pick.",["enter"],"terminal",["setup.models.picker","setup.models.dimension-picker"]),je("crtr.setup.models.cancel","Setup","Cancel pick","Cancel the model picker or route form.",["escape"],"terminal",["setup.models.picker","setup.models.dimension-picker","setup.models.route-form"],"dismiss-modal")]}function RQ(t){return t.contexts.includes("attach")&&(t.inputKind==="terminal"||t.inputKind==="host-global")}var je,Cb,U2n,$st,yp,fC,Swe,a9=h(()=>{"use strict";je=F2n;Cb=["attach","graph","graph.confirm"],U2n=["setup.login","setup.list","setup.input","setup.keybindings","setup.keybindings.edit","setup.keybindings.filter","setup.models"],$st=["setup.login","setup.list","setup.keybindings","setup.models"],yp=Object.freeze([je("crtr.tmux.menu.open","Global tmux","Open crouter menu","Open the crouter action menu.",["alt+c"],"host-global",["tmux.root"]),je("crtr.tmux.menu.attach","Global tmux","Attach actions","Open the attach-viewer action submenu.",["a"],"tmux-menu-selector",["tmux.menu"]),...mi("promote","Promote to orchestrator","Promote the focused node to orchestrator \u2014 it holds a roadmap and delegates.",["o"],["tmux.menu"]),...mi("demote-mode","Demote to base node","Demote the focused orchestrator back to a base node \u2014 hands-on again in its own window, no roadmap to drive.",["shift+o"],["tmux.menu"]),...mi("resume","Find node","Open the canvas navigator and go to the chosen node.",["/"],["tmux.menu"]),...mi("fork","Fork node","Fork the focused node into an independent idle root.",["f"],["tmux.menu"]),...mi("demote","Demote to terminal","Demote the focused node to terminal \u2014 it keeps running, owes a final up the spine, and reaps when done.",["d"],["tmux.menu"]),...mi("make-resident","Make resident","Flip the focused node to resident \u2014 interactable, never forced to submit a final, and wakeable while attached or awaiting something live.",["shift+r"],["tmux.menu"]),...mi("detach","Demote and close viewer","Demote the focused node and close its viewer; its broker keeps running off-screen.",["shift+d"],["tmux.menu"]),...mi("close-subtree","Close subtree","Close the focused node and its subtree.",["x"],["tmux.menu"]),...mi("background-bash","Background running bash","Hand the focused node\u2019s running bash command to its background job system.",["b"],["tmux.menu"]),...mi("file-review","Review a file","Open a line-anchored review of a file named in the transcript.",["v"],["tmux.menu"]),...mi("pin","Pin conversation","Pin or unpin this conversation in the canvas navigator.",["p"],["tmux.menu"]),...mi("show","Inspect node","Open the focused node\u2019s inspection menu.",["i"],["tmux.menu"]),...mi("view-settings","Display settings","Open the viewer display-settings menu.",["z"],["tmux.menu"]),...mi("fold-tools","Fold finished tool calls","Fold every finished tool call in the transcript to its single call line.",["f"],["tmux.menu.view-settings"]),...mi("show-working","Show working","With consolidated replies on, show or hide the messages and tool calls behind each reply.",["w"],["tmux.menu.view-settings"]),...mi("metadata","Show metadata","Show the focused node\u2019s metadata dossier.",["m"],["tmux.menu.show"]),...mi("context","Browse context","Browse the focused node context.",["c"],["tmux.menu.show"]),...mi("providers","Open settings","Open the crouter settings panel.",[","],["tmux.menu"]),...mi("provider-options","Provider options","Open provider options \u2014 how an authenticated provider serves your turns, including Codex fast mode.",["."],["tmux.menu"]),...mi("plugins","Browse plugins","Open the crouter plugin browser.",["l"],["tmux.menu"]),...mi("analytics","Analytics","Open the Analytics page: how agents worked in the last 24 hours or 7 days.",["shift+a"],["tmux.menu"]),...mi("context-admin","Context surface","Open the context surface: which documents each event delivers, and the surfaces, gates, and caps that decide it.",["shift+c"],["tmux.menu"]),...mi("graph","Canvas graph","Open the canvas graph.",["g"],["tmux.menu"]),...mi("focus-manager","Go to manager","Focus this node\u2019s manager.",["h"],["tmux.menu"]),...mi("copy-id","Copy node id","Copy the focused node id to the system clipboard.",["y"],["tmux.menu"]),...mi("reload-viewer","Reload viewer","Respawn this pane\u2019s viewer onto the current runtime generation.",["r"],["tmux.menu"]),...mi("recap","Generate recap","Generate the focused node\u2019s Goal and State recap and refresh its generated title.",["s"],["tmux.menu"]),...mi("issues","Open create menu","Open the create submenu.",["c"],["tmux.menu"]),...mi("issue.idea","Create idea","Create an idea issue.",["i"],["tmux.menu.issue"]),...mi("issue.bug","Create bug","Create a bug issue.",["b"],["tmux.menu.issue"]),je("crtr.tmux.node.next","Global tmux","Next node","Focus the next canvas node.",["alt+]"],"host-global",["tmux.root"]),je("crtr.tmux.node.previous","Global tmux","Previous node","Focus the previous canvas node.",["alt+["],"host-global",["tmux.root"]),je("crtr.tmux.inbox.toggle","Global tmux","Toggle inbox","Open or close the human inbox in the focused viewer.",["alt+i"],"host-global",["tmux.root"]),...gp("crtr.tmux.menu.attach.detach","crtr.attach.detach","Detach","Detach from the node.",["d"],["ctrl+d"]),...gp("crtr.tmux.menu.attach.clear-or-detach","crtr.attach.clear-or-detach","Clear input (cancel agent on repeat)","Clear the input; press again within a second to cancel the running agent turn. Detach lives on its own binding.",["c"],["ctrl+c"]),...gp("crtr.tmux.menu.attach.graph.toggle","crtr.attach.graph.toggle","Toggle graph","Open or close the graph overlay.",["g"],["alt+g"]),...gp("crtr.tmux.menu.attach.help.toggle","crtr.attach.help.toggle","Help","Open the attach help overlay.",["?"],["alt+shift+k"]),...gp("crtr.tmux.menu.attach.inbox.toggle","crtr.attach.inbox.toggle","Toggle inbox","Open or close the human inbox surface in this viewer.",["i"],[]),...gp("crtr.tmux.menu.attach.inbox-strip","crtr.attach.inbox-strip","Pending requests","Jump to the pending human-request strip at the top of the pane.",["u"],["alt+u"]),...gp("crtr.tmux.menu.attach.model-ladder.next","crtr.attach.model-ladder.next","Next model","Move to the next model ladder rung.",["]"],["alt+m"]),...gp("crtr.tmux.menu.attach.model-ladder.previous","crtr.attach.model-ladder.previous","Previous model","Move to the previous model ladder rung.",["["],["alt+shift+m"]),...gp("crtr.tmux.menu.attach.command.inspect","crtr.attach.command.inspect","Inspect loaded command","Open the loaded slash command\u2019s expanded prompt.",["h"],["alt+shift+h"]),...gp("crtr.tmux.menu.attach.file-review","crtr.attach.file-review","Review a file","Open a line-anchored review of a file named in the transcript.",[],["alt+shift+r"]),...gp("crtr.tmux.menu.attach.profile-files","crtr.attach.profile-files","Search profile files","Fuzzy-match path segments across the node family\u2019s working directories, their context directories (files), profile projects and the profile\u2019s own directory; Ctrl+Y copies a selected path.",["f"],["ctrl+f"]),...gp("crtr.tmux.menu.attach.search","crtr.attach.search","Search transcript","Search the transcript as it is currently displayed \u2014 folded tool output is not searched until it is unfolded.",["/"],["alt+/"]),...gp("crtr.tmux.menu.attach.whip","crtr.attach.whip","Whip agent","Interrupt the agent and send a playful command.",["w"],[]),je("crtr.attach.scroll.up","Attach","Scroll up","Scroll the transcript one line up.",["shift+up"],"terminal",Cb),je("crtr.attach.scroll.down","Attach","Scroll down","Scroll the transcript one line down.",["shift+down"],"terminal",Cb),je("crtr.attach.scroll.page-up","Attach","Scroll page up","Scroll the transcript one page up.",["pageup"],"terminal",Cb),je("crtr.attach.scroll.page-down","Attach","Scroll page down","Scroll the transcript one page down.",["pagedown"],"terminal",Cb),je("crtr.attach.scroll.live","Attach","Return to live","Return the transcript to the live bottom.",["shift+end"],"terminal",Cb),je("crtr.attach.mouse.toggle","Attach","Toggle mouse wheel scrolling","Toggle mouse wheel scrolling on or off.",["alt+shift+o"],"terminal",Cb),je("crtr.attach.copy.message","Attach","Copy visible message","Copy the newest message visible in the transcript viewport.",["alt+shift+y"],"terminal",Cb),je("crtr.attach.search.next","Attach","Next match","Move to the next transcript search match.",["n"],"terminal",["attach.search"]),je("crtr.attach.search.previous","Attach","Previous match","Move to the previous transcript search match.",["shift+n"],"terminal",["attach.search"]),je("crtr.attach.search.edit","Attach","Edit query","Return to editing the transcript search query.",["/"],"terminal",["attach.search"]),je("crtr.attach.search.close","Attach","Close search","Leave transcript search and clear its highlights.",["escape"],"terminal",["attach.search"],"dismiss-modal"),je("crtr.graph.down","GRAPH","Move down","Move to the next graph row.",["j","down"],"terminal",["graph"]),je("crtr.graph.up","GRAPH","Move up","Move to the previous graph row.",["k","up"],"terminal",["graph"]),je("crtr.graph.first","GRAPH","First row","Move to the first graph row.",["g"],"terminal",["graph"]),je("crtr.graph.last","GRAPH","Last row","Move to the last graph row.",["shift+g"],"terminal",["graph"]),je("crtr.graph.collapse-or-manager","GRAPH","Collapse or manager","Collapse a node or move to its manager.",["h","left"],"terminal",["graph"]),je("crtr.graph.expand-or-child","GRAPH","Expand or child","Expand a node or move to its child.",["l","right"],"terminal",["graph"]),je("crtr.graph.focus","GRAPH","Focus node","Focus the selected node.",["enter"],"terminal",["graph"]),je("crtr.graph.revive","GRAPH","Revive node","Revive and open the selected dormant node.",["r"],"terminal",["graph"]),je("crtr.graph.focus-manager","GRAPH","Focus manager","Focus the selected node manager.",["m"],"terminal",["graph"]),je("crtr.graph.close-subtree","GRAPH","Close subtree","Ask to close the selected subtree.",["x"],"terminal",["graph"]),je("crtr.graph.dismiss","GRAPH","Dismiss graph","Close the graph overlay.",["escape"],"terminal",["graph"],"dismiss-modal"),je("crtr.graph.confirm.accept","GRAPH","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["graph.confirm"]),je("crtr.graph.confirm.cancel","GRAPH","Cancel close","Cancel closing the selected subtree.",["n","escape"],"terminal",["graph.confirm"],"dismiss-modal"),je("crtr.inspector.force-quit","Inspector","Force quit Inspector","Immediately leave the Inspector.",["ctrl+c"],"host-global",["inspector"],"leave-screen"),je("crtr.inspector.down","Inspector","Move down","Move the Inspector selection or scroll cursor down.",["j","down"],"terminal",["inspector"]),je("crtr.inspector.up","Inspector","Move up","Move the Inspector selection or scroll cursor up.",["k","up"],"terminal",["inspector"]),je("crtr.inspector.section-next","Inspector","Next section","Move to the next Inspector section.",["tab"],"terminal",["inspector"]),je("crtr.inspector.section-prev","Inspector","Previous section","Move to the previous Inspector section.",["shift+tab"],"terminal",["inspector"]),je("crtr.inspector.page-down","Inspector","Page down","Scroll the Inspector detail body down.",["ctrl+d","pagedown"],"terminal",["inspector"]),je("crtr.inspector.page-up","Inspector","Page up","Scroll the Inspector detail body up.",["ctrl+u","pageup"],"terminal",["inspector"]),je("crtr.inspector.toggle-detail","Inspector","Toggle item detail","Expand or collapse the selected cron or background job.",["enter"],"terminal",["inspector"]),je("crtr.inspector.cancel-item","Inspector","Cancel selected item","Arm cancellation for the selected cron, or stopping for the selected background job.",["x"],"terminal",["inspector"]),je("crtr.inspector.open-log","Inspector","Open job log","Follow the selected background job\u2019s log in a new tmux window.",["o"],"terminal",["inspector"]),je("crtr.inspector.confirm","Inspector","Confirm action","Confirm the armed Inspector action.",["y"],"terminal",["inspector"]),je("crtr.inspector.dismiss","Inspector","Dismiss action","Dismiss an Inspector confirmation or banner.",["escape"],"terminal",["inspector"],"dismiss-modal"),je("crtr.inspector.retarget","Inspector","Retarget","Inspect the selected cron anchor or creator node.",["t"],"terminal",["inspector"]),je("crtr.inspector.refresh","Inspector","Refresh","Refresh the Inspector now.",["g","r"],"terminal",["inspector"]),je("crtr.inspector.quit","Inspector","Quit","Leave the Inspector.",["q"],"terminal",["inspector"],"leave-screen"),...Q2n(),...W2n(),...H2n()]);fC=new Set(yp.map(t=>t.id));Swe=Object.freeze([{context:"graph",capability:"dismiss-modal"},{context:"graph.confirm",capability:"dismiss-modal"},{context:"inspector",capability:"leave-screen"},{context:"inspector",capability:"dismiss-modal"},{context:"attach.search",capability:"dismiss-modal"},{context:"browse",capability:"leave-screen"},{context:"browse.search",capability:"dismiss-modal"},{context:"profile.menu",capability:"leave-screen"},{context:"profile.search",capability:"leave-screen"},{context:"setup.login",capability:"leave-screen"},{context:"setup.list",capability:"leave-screen"},{context:"setup.input",capability:"leave-screen"},{context:"setup.confirm",capability:"dismiss-modal"},{context:"setup.keybindings",capability:"leave-screen"},{context:"setup.keybindings",capability:"save-keybindings"},{context:"setup.keybindings.edit",capability:"dismiss-modal"},{context:"setup.keybindings.filter",capability:"dismiss-modal"},{context:"setup.models",capability:"leave-screen"},{context:"setup.models.picker",capability:"dismiss-modal"},{context:"setup.models.dimension-picker",capability:"dismiss-modal"},{context:"setup.models.route-form",capability:"dismiss-modal"},{context:"setup.models.confirm",capability:"dismiss-modal"}])});function Ust(t){if(!Array.isArray(t))return[Cwe];let e=t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return e.length>0?e:[Cwe]}var Cwe,Fst,c9,u9=h(()=>{"use strict";Cwe="working",Fst=["thinking","planning","checking",Cwe],c9="Working..."});function p9(){return{schema_version:Qst,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:j2n,auto_open_child_viewers:!0,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...Fst],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...d9],whip_message_mode:q2n,mouse_mode_default:"tmux",live_cycles:Iwe,condensed_history:Twe,bash_tool_purpose:!0,fold_finished_tools:!0,summarize_tool_calls:!0,detailed_tool_recaps:!0,consolidate_replies:!1,keybindings:{},tmux_passthrough:[],modelLadders:Dwe(),providerOptions:{},kinds:Rwe(),remoteCanvas:kwe(),api:{tcp:""},spawnEnv:{allow:[]},bin:{},humanActions:{}}}function kwe(){return{targets:{}}}function Rwe(){return{general:{whenToUse:"Anything else \u2014 the catch-all worker for a task that does not fit a specialist kind.",model:"anthropic/strong"},explore:{whenToUse:"Gather current-state evidence about unfamiliar code or existing architecture \u2014 read-only code-path research with concrete file:line support. Diagnosis or recommendations belong to advisor, target architecture to design, required behavior or acceptance criteria to spec, and implementation decomposition to plan.",model:"openai/light",orchestratorModel:"anthropic/strong"},developer:{whenToUse:"Implement a change \u2014 make the feature or fix genuinely work against its acceptance criteria, not merely compile.",model:"openai/medium",orchestratorModel:"anthropic/strong"},design:{whenToUse:"Architect a solution \u2014 produce one design document an implementer can build from without re-deciding anything left open.",model:"anthropic/strong"},plan:{whenToUse:"Break work into steps \u2014 turn a spec or design into a concrete, phased, parallelizable plan with every decision resolved.",model:"anthropic/strong",orchestratorModel:"anthropic/strong"},spec:{whenToUse:"Collaborate with the user to discover what to build, then write the spec \u2014 behavior, non-goals, interfaces, edge cases, testable acceptance criteria.",model:"anthropic/strong"},review:{whenToUse:"Validate or critique code, a plan, or a spec \u2014 deliver a complete, severity-rated verdict without adjudicating.",model:"openai/medium",orchestratorModel:"openai/strong"},advisor:{whenToUse:"Debug failures, investigate why something is broken or misbehaving, diagnose live/runtime issues, or give engineering advice and second opinions \u2014 reason from evidence and recommend the next move. Use advisor (not explore) whenever the task is to find out what is going wrong.",model:"anthropic/strong"},"review/companion":{whenToUse:"Born by the daemon for one human review; never spawned by an agent.",availableTo:[]}}}function Dwe(){return{anthropic:{ultra:"anthropic/claude-fable-5:xhigh",strong:"anthropic/claude-opus-5-5:medium",medium:"anthropic/claude-sonnet-5-5:medium",light:"anthropic/claude-haiku-5-5:high"},openai:{ultra:"openai-codex/gpt-6-astra:max",strong:"openai-codex/gpt-6.1-sol:high",medium:"openai-codex/gpt-6.1-sol:medium",light:"openai-codex/gpt-6-luna:low"}}}function Mwe(){return{marketplaces:{},plugins:{}}}var Li,Qst,Wst,Hst,mC,dy,py,l9,j2n,d9,hC,q2n,Iwe,gC,yC,Twe,Ha=h(()=>{"use strict";u9();Li={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},Qst=4,Wst=".crouter-plugin",Hst="plugin.json",mC=".crouter",dy="config.json",py="state.json",l9="profiles",j2n=3,d9=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],hC=["random","go-faster"],q2n="random",Iwe=2,gC=["tmux","on","off"],yC=["none","user","agent","both"],Twe="none"});function Df(t,e){return new Ii("not_found",t,Li.NOT_FOUND,e)}function Ap(t,e){return new Ii("usage",t,Li.USAGE,e)}function qst(t,e){return new Ii("ambiguous",t,Li.AMBIGUOUS,e)}function Owe(t,e){let n="owner_only",r=`${t}; only the person's terminal can.`;return new Ii(n,r,Li.USAGE,{error:n,message:r,next:e})}var Ii,qo=h(()=>{"use strict";Ha();_o();Ii=class extends Error{code;exitCode;details;constructor(e,n,r=Li.GENERAL,i){super(n),this.name="CrtrError",this.code=e,this.exitCode=r,this.details=i}}});import{appendFileSync as Gst,existsSync as zst,mkdirSync as G2n,renameSync as Vst,rmSync as z2n,statSync as V2n}from"node:fs";import{dirname as K2n}from"node:path";function Jst(t,e){let n="";try{G2n(K2n(t),{recursive:!0});let r=zst(t)?V2n(t).size:0;for(let i of e){let o=`${i}
195
+ `);V0.writeFileSync(U,q)}_.flush(),this.cursorRow=Math.max(0,l.length-1),this.hardwareCursorRow=k,this.maxLinesRendered=Math.max(this.maxLinesRendered,l.length),this.previousViewportTop=Math.max(s,k-n+1),this.positionHardwareCursor(d,l.length),this.previousLines=l,this.previousKittyImageIds=this.collectKittyImageIds(l),this.previousWidth=e,this.previousHeight=n}positionHardwareCursor(e,n){if(!e||n<=0){this.terminal.hideCursor();return}let r=Math.max(0,Math.min(e.row,n-1)),i=Math.max(0,e.col),o=r-this.hardwareCursorRow,s="";o>0?s+=`\x1B[${o}B`:o<0&&(s+=`\x1B[${-o}A`),s+=`\x1B[${i+1}G`,s&&this.terminal.write(s),this.hardwareCursorRow=r,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}}});var et=h(()=>{E0e();Wit();Xit();Eot();Sot();swe();Fot();Uot();Q7();ewe();qot();Got();hwe();iwe();zot();Vot();Z0e();Kot();Yot();l7();q0();bb();dwe();V7();L0e();ywe();Awe();pst();W0e();Eb();Tf();kst();Nst();zs()});function pC(t){return s9+t.replace(/\./g,`${B2n}.${s9}`)+Sb}function Lst(t={}){let n=[`${$2n}${s9}crouter${Sb}${t.version?`${kQ} v${t.version}${Sb}`:""}`,`${kQ}the agentic runtime${Sb}`];t.profile&&n.push(`${kQ}profile: ${Sb}${s9}${t.profile}${Sb}`),t.cwd&&n.push(`${kQ}${t.cwd}${Sb}`);let r=[];for(let i=0;i<Pst.length;i++){let o=i>=1&&i-1<n.length?` ${n[i-1]}`:"";r.push(Pst[i]+o)}return t.hint&&r.push("",`${kQ}${t.hint}${Sb}`),r}var Sb,s9,B2n,$2n,kQ,Pst,Bst=h(()=>{"use strict";Sb="\x1B[0m",s9="\x1B[38;5;180m",B2n="\x1B[38;5;137m",$2n="\x1B[1m",kQ="\x1B[2m";Pst=[pC(" ________"),pC(" / /|"),pC(" / . . / |"),pC(" /_______/ |"),pC(" | . . | |"),pC(" | . . | /"),pC(" |_______|/")]});function F2n(t,e,n,r,i,o,s,a,c){return Object.freeze({id:t,group:e,name:n,description:r,defaults:Object.freeze([...i]),inputKind:o,contexts:Object.freeze([...s]),...a===void 0?{}:{safety:a},...c===void 0?{}:{pair:Object.freeze({...c})}})}function mi(t,e,n,r,i){let o=`crtr.tmux.menu.${t}`,s=`crtr.tmux.menu-global.${t}`;return[je(o,"Global tmux",e,n,r,"tmux-menu-selector",i,void 0,{field:"menu",pairedId:s}),je(s,"Global tmux",e,n,[],"tmux-global-action",["tmux.root"],void 0,{field:"global",pairedId:o})]}function gp(t,e,n,r,i,o){return[je(t,"Attach",n,r,i,"tmux-menu-selector",["tmux.menu.attach"],void 0,{field:"menu",pairedId:e}),je(e,"Attach",n,r,o,"host-global",Cb,void 0,{field:"direct",pairedId:t})]}function Q2n(){let t="browse";return[je("crtr.browse.quit","Browse and pickers","Quit browse","Leave canvas browse.",["q","escape","ctrl+c"],"terminal",[t],"leave-screen"),je("crtr.browse.down","Browse and pickers","Move down","Move to the next row.",["j","down"],"terminal",[t]),je("crtr.browse.up","Browse and pickers","Move up","Move to the previous row.",["k","up"],"terminal",[t]),je("crtr.browse.first","Browse and pickers","First row","Move to the first row.",["g"],"terminal",[t]),je("crtr.browse.last","Browse and pickers","Last row","Move to the last row.",["shift+g"],"terminal",[t]),je("crtr.browse.expand-or-child","Browse and pickers","Expand or child","Expand a row or move to its child.",["l","right"],"terminal",[t]),je("crtr.browse.collapse-or-parent","Browse and pickers","Collapse or parent","Collapse a row or move to its parent.",["h","left"],"terminal",[t]),je("crtr.browse.toggle-fold","Browse and pickers","Toggle fold","Toggle the selected fold.",["space"],"terminal",[t]),je("crtr.browse.tab-next","Browse and pickers","Next tab","Select the next browse tab.",["tab","]"],"terminal",[t]),je("crtr.browse.tab-previous","Browse and pickers","Previous tab","Select the previous browse tab.",["shift+tab","["],"terminal",[t]),...[1,2,3,4,5].map(e=>je(`crtr.browse.tab.${e}`,"Browse and pickers",`Tab ${e}`,`Select browse tab ${e}.`,[`${e}`],"terminal",[t])),je("crtr.browse.close-subtree","Browse and pickers","Close subtree","Ask to close the selected subtree.",["x"],"terminal",[t]),je("crtr.browse.confirm-close","Browse and pickers","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["browse.confirm"]),je("crtr.browse.sort","Browse and pickers","Change sort","Change the browse sort.",["s"],"terminal",[t]),je("crtr.browse.scope","Browse and pickers","Change scope","Toggle the browse cwd scope.",["c"],"terminal",[t]),je("crtr.browse.profile","Browse and pickers","Toggle profile","Toggle the browse profile scope.",["shift+p"],"terminal",[t]),je("crtr.browse.residents","Browse and pickers","Toggle residents","Toggle resident display.",["r"],"terminal",[t]),je("crtr.browse.preview","Browse and pickers","Toggle preview","Toggle the preview panel.",["v"],"terminal",[t]),je("crtr.browse.report","Browse and pickers","Toggle report","Swap the preview panel between the conversation and the node's newest report.",["shift+v"],"terminal",[t]),je("crtr.browse.pin","Browse and pickers","Pin node","Star or unstar the selected node.",["p"],"terminal",[t]),je("crtr.browse.search","Browse and pickers","Search","Open browse search.",["/"],"terminal",[t]),je("crtr.browse.revive-now","Browse and pickers","Revive now","Revive the selected node now.",["shift+k"],"terminal",[t]),je("crtr.browse.focus","Browse and pickers","Focus node","Focus the selected node.",["enter","o"],"terminal",[t]),je("crtr.browse.focus-background","Browse and pickers","Focus node (keep browsing)","Focus the selected node without leaving the navigator.",["shift+o"],"terminal",[t]),je("crtr.browse.yank-id","Browse and pickers","Yank node id","Copy the selected node id to the system clipboard.",["y"],"terminal",[t]),je("crtr.browse.search.cancel","Browse and pickers","Cancel search","Cancel browse search.",["escape"],"terminal",["browse.search"],"dismiss-modal"),je("crtr.browse.search.commit","Browse and pickers","Commit search","Apply browse search.",["enter"],"terminal",["browse.search"]),je("crtr.browse.search.delete","Browse and pickers","Delete search text","Delete the previous search character.",["backspace"],"terminal",["browse.search"]),je("crtr.browse.search.quit","Browse and pickers","Quit browse","Leave canvas browse from search.",["ctrl+c"],"terminal",["browse.search"],"leave-screen")]}function W2n(){let t="profile.menu",e="profile.search";return[je("crtr.profile.menu.up","Profiles","Move up","Move to the previous profile.",["k","up"],"terminal",[t]),je("crtr.profile.menu.down","Profiles","Move down","Move to the next profile.",["j","down"],"terminal",[t]),je("crtr.profile.menu.select","Profiles","Select profile","Select the highlighted profile.",["enter"],"terminal",[t]),je("crtr.profile.menu.accept-default","Profiles","Accept default","Accept the default profile.",["escape"],"terminal",[t],"leave-screen"),je("crtr.profile.menu.abort","Profiles","Abort","Leave profile selection.",["ctrl+c"],"terminal",[t],"leave-screen"),...[1,2,3,4,5,6,7,8,9].map(n=>je(`crtr.profile.menu.slot.${n}`,"Profiles",`Profile slot ${n}`,`Select profile slot ${n}.`,[`${n}`],"terminal",[t])),je("crtr.profile.menu.create","Profiles","Create profile","Create a profile.",["c"],"terminal",[t]),je("crtr.profile.menu.search-existing","Profiles","Search profiles","Search existing profiles.",["s"],"terminal",[t]),je("crtr.profile.menu.use-root","Profiles","Use root profile","Use the root profile.",["r"],"terminal",[t]),je("crtr.profile.menu.set-default","Profiles","Set default","Set the selected profile as default.",["d"],"terminal",[t]),je("crtr.profile.menu.add-directory","Profiles","Add directory","Add a directory to the profile.",["a"],"terminal",[t]),je("crtr.profile.menu.unpin","Profiles","Unpin directory","Unpin the selected directory.",["u"],"terminal",[t]),je("crtr.profile.menu.manage","Profiles","Manage profiles","Open the profiles settings page in a popup.",["v"],"terminal",[t]),je("crtr.profile.search.up","Profiles","Move up","Move to the previous search result.",["up","ctrl+p"],"terminal",[e]),je("crtr.profile.search.down","Profiles","Move down","Move to the next search result.",["down","ctrl+n"],"terminal",[e]),je("crtr.profile.search.pick","Profiles","Pick profile","Pick the highlighted profile.",["enter"],"terminal",[e]),je("crtr.profile.search.back","Profiles","Back","Return to profile selection.",["escape"],"terminal",[e],"leave-screen"),je("crtr.profile.search.delete","Profiles","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",[e]),je("crtr.profile.search.abort","Profiles","Abort","Leave profile search.",["ctrl+c"],"terminal",[e],"leave-screen")]}function H2n(){return[je("crtr.setup.cancel","Setup","Cancel setup","Leave the setup wizard.",["q","ctrl+c","ctrl+d"],"terminal",U2n,"leave-screen"),je("crtr.setup.tab-next","Setup","Next tab","Select the next setup tab.",["tab","right"],"terminal",$st),je("crtr.setup.tab-previous","Setup","Previous tab","Select the previous setup tab.",["shift+tab","left"],"terminal",$st),je("crtr.setup.open","Setup","Open","Open the selected setup item.",["enter"],"terminal",["setup.login"]),je("crtr.setup.list-down","Setup","Move down","Move to the next setup item.",["j","down"],"terminal",["setup.list","setup.models","setup.models.dimension-picker","setup.models.route-form"]),je("crtr.setup.list-up","Setup","Move up","Move to the previous setup item.",["k","up"],"terminal",["setup.list","setup.models","setup.models.dimension-picker","setup.models.route-form"]),je("crtr.setup.toggle","Setup","Toggle","Toggle the selected setup item.",["space"],"terminal",["setup.list","setup.keybindings"]),je("crtr.setup.details","Setup","Show details","Show details for the selected item.",["?"],"terminal",["setup.list"]),je("crtr.setup.advance","Setup","Advance","Advance the setup flow.",["enter"],"terminal",["setup.list"]),je("crtr.setup.confirm.accept","Setup","Confirm","Accept the setup confirmation.",["y","enter"],"terminal",["setup.confirm","setup.models.confirm"]),je("crtr.setup.confirm.back","Setup","Go back","Cancel the setup confirmation.",["n","escape","q"],"terminal",["setup.confirm","setup.models.confirm"],"dismiss-modal"),je("crtr.setup.keybindings.edit","Setup","Edit binding","Edit the selected binding.",["enter"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.commit-edit","Setup","Commit edit","Commit the active binding edit.",["enter"],"terminal",["setup.keybindings.edit"]),je("crtr.setup.keybindings.cancel-edit","Setup","Cancel edit","Cancel the active binding edit.",["escape"],"terminal",["setup.keybindings.edit"],"dismiss-modal"),je("crtr.setup.keybindings.unbind","Setup","Unbind","Disable the selected binding.",["delete"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.reset-row","Setup","Reset binding","Reset the selected binding.",["r"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.reset-all","Setup","Reset all bindings","Reset all bindings to defaults.",["shift+r"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.save","Setup","Save bindings","Save keybinding changes.",["s"],"terminal",["setup.keybindings"],"save-keybindings"),je("crtr.setup.keybindings.discard","Setup","Discard changes","Discard keybinding changes.",["escape"],"terminal",["setup.keybindings"],"leave-screen"),je("crtr.setup.keybindings.page-up","Setup","Page up","Move up one keybinding page.",["pageup"],"terminal",["setup.keybindings","setup.keybindings.edit"]),je("crtr.setup.keybindings.page-down","Setup","Page down","Move down one keybinding page.",["pagedown"],"terminal",["setup.keybindings","setup.keybindings.edit"]),je("crtr.setup.keybindings.filter","Setup","Filter bindings","Open the keybinding filter.",["/"],"terminal",["setup.keybindings"]),je("crtr.setup.keybindings.filter-delete","Setup","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",["setup.keybindings.filter"]),je("crtr.setup.keybindings.filter-clear","Setup","Clear filter","Clear the keybinding filter.",["escape"],"terminal",["setup.keybindings.filter"],"dismiss-modal"),je("crtr.setup.cell-previous","Setup","Previous field","Select the previous field or setup table cell.",["h"],"terminal",["setup.models","setup.keybindings"]),je("crtr.setup.cell-next","Setup","Next field","Select the next field or setup table cell.",["l"],"terminal",["setup.models","setup.keybindings"]),je("crtr.setup.models.open","Setup","Edit model","Edit the selected model cell or route field.",["enter"],"terminal",["setup.models","setup.models.route-form"]),je("crtr.setup.models.scope-next","Setup","Next model config scope","Edit the next applicable user, profile, or project config.",["s"],"terminal",["setup.models"]),je("crtr.setup.models.commit","Setup","Commit pick","Commit the provider, strength, model, or thinking-level pick.",["enter"],"terminal",["setup.models.picker","setup.models.dimension-picker"]),je("crtr.setup.models.cancel","Setup","Cancel pick","Cancel the model picker or route form.",["escape"],"terminal",["setup.models.picker","setup.models.dimension-picker","setup.models.route-form"],"dismiss-modal")]}function RQ(t){return t.contexts.includes("attach")&&(t.inputKind==="terminal"||t.inputKind==="host-global")}var je,Cb,U2n,$st,yp,fC,Swe,a9=h(()=>{"use strict";je=F2n;Cb=["attach","graph","graph.confirm"],U2n=["setup.login","setup.list","setup.input","setup.keybindings","setup.keybindings.edit","setup.keybindings.filter","setup.models"],$st=["setup.login","setup.list","setup.keybindings","setup.models"],yp=Object.freeze([je("crtr.tmux.menu.open","Global tmux","Open crouter menu","Open the crouter action menu.",["alt+c"],"host-global",["tmux.root"]),je("crtr.tmux.menu.attach","Global tmux","Attach actions","Open the attach-viewer action submenu.",["a"],"tmux-menu-selector",["tmux.menu"]),...mi("promote","Promote to orchestrator","Promote the focused node to orchestrator \u2014 it holds a roadmap and delegates.",["o"],["tmux.menu"]),...mi("demote-mode","Demote to base node","Demote the focused orchestrator back to a base node \u2014 hands-on again in its own window, no roadmap to drive.",["shift+o"],["tmux.menu"]),...mi("resume","Find node","Open the canvas navigator and go to the chosen node.",["/"],["tmux.menu"]),...mi("fork","Fork node","Fork the focused node into an independent idle root.",["f"],["tmux.menu"]),...mi("demote","Demote to terminal","Demote the focused node to terminal \u2014 it keeps running, owes a final up the spine, and reaps when done.",["d"],["tmux.menu"]),...mi("make-resident","Make resident","Flip the focused node to resident \u2014 interactable, never forced to submit a final, and wakeable while attached or awaiting something live.",["shift+r"],["tmux.menu"]),...mi("detach","Demote and close viewer","Demote the focused node and close its viewer; its broker keeps running off-screen.",["shift+d"],["tmux.menu"]),...mi("close-subtree","Close subtree","Close the focused node and its subtree.",["x"],["tmux.menu"]),...mi("background-bash","Background running bash","Hand the focused node\u2019s running bash command to its background job system.",["b"],["tmux.menu"]),...mi("file-review","Review a file","Open a line-anchored review of a file named in the transcript.",["v"],["tmux.menu"]),...mi("pin","Pin conversation","Pin or unpin this conversation in the canvas navigator.",["p"],["tmux.menu"]),...mi("show","Inspect node","Open the focused node\u2019s inspection menu.",["i"],["tmux.menu"]),...mi("view-settings","Display settings","Open the viewer display-settings menu.",["z"],["tmux.menu"]),...mi("fold-tools","Fold finished tool calls","Fold every finished tool call in the transcript to its single call line.",["f"],["tmux.menu.view-settings"]),...mi("show-working","Show working","With consolidated replies on, show or hide the messages and tool calls behind each reply.",["w"],["tmux.menu.view-settings"]),...mi("metadata","Show metadata","Show the focused node\u2019s metadata dossier.",["m"],["tmux.menu.show"]),...mi("context","Browse context","Browse the focused node context.",["c"],["tmux.menu.show"]),...mi("providers","Open settings","Open the crouter settings panel.",[","],["tmux.menu"]),...mi("provider-options","Provider options","Open provider options \u2014 how an authenticated provider serves your turns, including Codex fast mode.",["."],["tmux.menu"]),...mi("plugins","Browse plugins","Open the crouter plugin browser.",["l"],["tmux.menu"]),...mi("analytics","Analytics","Open the Analytics page: how agents worked in the last 24 hours or 7 days.",["shift+a"],["tmux.menu"]),...mi("context-admin","Context surface","Open the context surface: which documents each event delivers, and the surfaces, gates, and caps that decide it.",["shift+c"],["tmux.menu"]),...mi("graph","Canvas graph","Open the canvas graph.",["g"],["tmux.menu"]),...mi("focus-manager","Go to manager","Focus this node\u2019s manager.",["h"],["tmux.menu"]),...mi("copy-id","Copy node id","Copy the focused node id to the system clipboard.",["y"],["tmux.menu"]),...mi("reload-viewer","Reload viewer","Respawn this pane\u2019s viewer onto the current runtime generation.",["r"],["tmux.menu"]),...mi("recap","Generate recap","Generate the focused node\u2019s Goal and State recap and refresh its generated title.",["s"],["tmux.menu"]),...mi("issues","Open create menu","Open the create submenu.",["c"],["tmux.menu"]),...mi("issue.idea","Create idea","Create an idea issue.",["i"],["tmux.menu.issue"]),...mi("issue.bug","Create bug","Create a bug issue.",["b"],["tmux.menu.issue"]),je("crtr.tmux.node.next","Global tmux","Next node","Focus the next canvas node.",["alt+]"],"host-global",["tmux.root"]),je("crtr.tmux.node.previous","Global tmux","Previous node","Focus the previous canvas node.",["alt+["],"host-global",["tmux.root"]),je("crtr.tmux.inbox.toggle","Global tmux","Toggle inbox","Open or close the human inbox in the focused viewer.",["alt+i"],"host-global",["tmux.root"]),...gp("crtr.tmux.menu.attach.detach","crtr.attach.detach","Detach","Detach from the node.",["d"],["ctrl+d"]),...gp("crtr.tmux.menu.attach.clear-or-detach","crtr.attach.clear-or-detach","Clear input (cancel agent on repeat)","Clear the input; press again within a second to cancel the running agent turn. Detach lives on its own binding.",["c"],["ctrl+c"]),...gp("crtr.tmux.menu.attach.graph.toggle","crtr.attach.graph.toggle","Toggle graph","Open or close the graph overlay.",["g"],["alt+g"]),...gp("crtr.tmux.menu.attach.help.toggle","crtr.attach.help.toggle","Help","Open the attach help overlay.",["?"],["alt+shift+k"]),...gp("crtr.tmux.menu.attach.inbox.toggle","crtr.attach.inbox.toggle","Toggle inbox","Open or close the human inbox surface in this viewer.",["i"],[]),...gp("crtr.tmux.menu.attach.inbox-strip","crtr.attach.inbox-strip","Pending requests","Jump to the pending human-request strip at the top of the pane.",["u"],["alt+u"]),...gp("crtr.tmux.menu.attach.model-ladder.next","crtr.attach.model-ladder.next","Next model","Move to the next model ladder rung.",["]"],["alt+m"]),...gp("crtr.tmux.menu.attach.model-ladder.previous","crtr.attach.model-ladder.previous","Previous model","Move to the previous model ladder rung.",["["],["alt+shift+m"]),...gp("crtr.tmux.menu.attach.command.inspect","crtr.attach.command.inspect","Inspect loaded command","Open the loaded slash command\u2019s expanded prompt.",["h"],["alt+shift+h"]),...gp("crtr.tmux.menu.attach.file-review","crtr.attach.file-review","Review a file","Open a line-anchored review of a file named in the transcript.",[],["alt+shift+r"]),...gp("crtr.tmux.menu.attach.profile-files","crtr.attach.profile-files","Search profile files","Fuzzy-match path segments across the node family\u2019s working directories, their context directories (files), profile projects and the profile\u2019s own directory; Ctrl+Y copies a selected path.",["f"],["ctrl+f"]),...gp("crtr.tmux.menu.attach.search","crtr.attach.search","Search transcript","Search the transcript as it is currently displayed \u2014 folded tool output is not searched until it is unfolded.",["/"],["alt+/"]),...gp("crtr.tmux.menu.attach.whip","crtr.attach.whip","Whip agent","Interrupt the agent and send a playful command.",["w"],[]),je("crtr.attach.scroll.up","Attach","Scroll up","Scroll the transcript one line up.",["shift+up"],"terminal",Cb),je("crtr.attach.scroll.down","Attach","Scroll down","Scroll the transcript one line down.",["shift+down"],"terminal",Cb),je("crtr.attach.scroll.page-up","Attach","Scroll page up","Scroll the transcript one page up.",["pageup"],"terminal",Cb),je("crtr.attach.scroll.page-down","Attach","Scroll page down","Scroll the transcript one page down.",["pagedown"],"terminal",Cb),je("crtr.attach.scroll.live","Attach","Return to live","Return the transcript to the live bottom.",["shift+end"],"terminal",Cb),je("crtr.attach.mouse.toggle","Attach","Toggle mouse wheel scrolling","Toggle mouse wheel scrolling on or off.",["alt+shift+o"],"terminal",Cb),je("crtr.attach.copy.message","Attach","Copy visible message","Copy the newest message visible in the transcript viewport.",["alt+shift+y"],"terminal",Cb),je("crtr.attach.search.next","Attach","Next match","Move to the next transcript search match.",["n"],"terminal",["attach.search"]),je("crtr.attach.search.previous","Attach","Previous match","Move to the previous transcript search match.",["shift+n"],"terminal",["attach.search"]),je("crtr.attach.search.edit","Attach","Edit query","Return to editing the transcript search query.",["/"],"terminal",["attach.search"]),je("crtr.attach.search.close","Attach","Close search","Leave transcript search and clear its highlights.",["escape"],"terminal",["attach.search"],"dismiss-modal"),je("crtr.graph.down","GRAPH","Move down","Move to the next graph row.",["j","down"],"terminal",["graph"]),je("crtr.graph.up","GRAPH","Move up","Move to the previous graph row.",["k","up"],"terminal",["graph"]),je("crtr.graph.first","GRAPH","First row","Move to the first graph row.",["g"],"terminal",["graph"]),je("crtr.graph.last","GRAPH","Last row","Move to the last graph row.",["shift+g"],"terminal",["graph"]),je("crtr.graph.collapse-or-manager","GRAPH","Collapse or manager","Collapse a node or move to its manager.",["h","left"],"terminal",["graph"]),je("crtr.graph.expand-or-child","GRAPH","Expand or child","Expand a node or move to its child.",["l","right"],"terminal",["graph"]),je("crtr.graph.focus","GRAPH","Focus node","Focus the selected node.",["enter"],"terminal",["graph"]),je("crtr.graph.revive","GRAPH","Revive node","Revive and open the selected dormant node.",["r"],"terminal",["graph"]),je("crtr.graph.focus-manager","GRAPH","Focus manager","Focus the selected node manager.",["m"],"terminal",["graph"]),je("crtr.graph.close-subtree","GRAPH","Close subtree","Ask to close the selected subtree.",["x"],"terminal",["graph"]),je("crtr.graph.dismiss","GRAPH","Dismiss graph","Close the graph overlay.",["escape"],"terminal",["graph"],"dismiss-modal"),je("crtr.graph.confirm.accept","GRAPH","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["graph.confirm"]),je("crtr.graph.confirm.cancel","GRAPH","Cancel close","Cancel closing the selected subtree.",["n","escape"],"terminal",["graph.confirm"],"dismiss-modal"),je("crtr.inspector.force-quit","Inspector","Force quit Inspector","Immediately leave the Inspector.",["ctrl+c"],"host-global",["inspector"],"leave-screen"),je("crtr.inspector.down","Inspector","Move down","Move the Inspector selection or scroll cursor down.",["j","down"],"terminal",["inspector"]),je("crtr.inspector.up","Inspector","Move up","Move the Inspector selection or scroll cursor up.",["k","up"],"terminal",["inspector"]),je("crtr.inspector.section-next","Inspector","Next section","Move to the next Inspector section.",["tab"],"terminal",["inspector"]),je("crtr.inspector.section-prev","Inspector","Previous section","Move to the previous Inspector section.",["shift+tab"],"terminal",["inspector"]),je("crtr.inspector.page-down","Inspector","Page down","Scroll the Inspector detail body down.",["ctrl+d","pagedown"],"terminal",["inspector"]),je("crtr.inspector.page-up","Inspector","Page up","Scroll the Inspector detail body up.",["ctrl+u","pageup"],"terminal",["inspector"]),je("crtr.inspector.toggle-detail","Inspector","Toggle item detail","Expand or collapse the selected cron or background job.",["enter"],"terminal",["inspector"]),je("crtr.inspector.cancel-item","Inspector","Cancel selected item","Arm cancellation for the selected cron, or stopping for the selected background job.",["x"],"terminal",["inspector"]),je("crtr.inspector.open-log","Inspector","Open job log","Follow the selected background job\u2019s log in a new tmux window.",["o"],"terminal",["inspector"]),je("crtr.inspector.confirm","Inspector","Confirm action","Confirm the armed Inspector action.",["y"],"terminal",["inspector"]),je("crtr.inspector.dismiss","Inspector","Dismiss action","Dismiss an Inspector confirmation or banner.",["escape"],"terminal",["inspector"],"dismiss-modal"),je("crtr.inspector.retarget","Inspector","Retarget","Inspect the selected cron anchor or creator node.",["t"],"terminal",["inspector"]),je("crtr.inspector.refresh","Inspector","Refresh","Refresh the Inspector now.",["g","r"],"terminal",["inspector"]),je("crtr.inspector.quit","Inspector","Quit","Leave the Inspector.",["q"],"terminal",["inspector"],"leave-screen"),...Q2n(),...W2n(),...H2n()]);fC=new Set(yp.map(t=>t.id));Swe=Object.freeze([{context:"graph",capability:"dismiss-modal"},{context:"graph.confirm",capability:"dismiss-modal"},{context:"inspector",capability:"leave-screen"},{context:"inspector",capability:"dismiss-modal"},{context:"attach.search",capability:"dismiss-modal"},{context:"browse",capability:"leave-screen"},{context:"browse.search",capability:"dismiss-modal"},{context:"profile.menu",capability:"leave-screen"},{context:"profile.search",capability:"leave-screen"},{context:"setup.login",capability:"leave-screen"},{context:"setup.list",capability:"leave-screen"},{context:"setup.input",capability:"leave-screen"},{context:"setup.confirm",capability:"dismiss-modal"},{context:"setup.keybindings",capability:"leave-screen"},{context:"setup.keybindings",capability:"save-keybindings"},{context:"setup.keybindings.edit",capability:"dismiss-modal"},{context:"setup.keybindings.filter",capability:"dismiss-modal"},{context:"setup.models",capability:"leave-screen"},{context:"setup.models.picker",capability:"dismiss-modal"},{context:"setup.models.dimension-picker",capability:"dismiss-modal"},{context:"setup.models.route-form",capability:"dismiss-modal"},{context:"setup.models.confirm",capability:"dismiss-modal"}])});function Ust(t){if(!Array.isArray(t))return[Cwe];let e=t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return e.length>0?e:[Cwe]}var Cwe,Fst,c9,u9=h(()=>{"use strict";Cwe="working",Fst=["thinking","planning","checking",Cwe],c9="Working..."});function p9(){return{schema_version:Qst,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:j2n,auto_open_child_viewers:!1,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...Fst],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...d9],whip_message_mode:q2n,mouse_mode_default:"tmux",live_cycles:Iwe,condensed_history:Twe,bash_tool_purpose:!0,fold_finished_tools:!0,summarize_tool_calls:!0,detailed_tool_recaps:!0,consolidate_replies:!1,keybindings:{},tmux_passthrough:[],modelLadders:Dwe(),providerOptions:{},kinds:Rwe(),remoteCanvas:kwe(),api:{tcp:""},spawnEnv:{allow:[]},bin:{},humanActions:{}}}function kwe(){return{targets:{}}}function Rwe(){return{general:{whenToUse:"Anything else \u2014 the catch-all worker for a task that does not fit a specialist kind.",model:"anthropic/strong"},explore:{whenToUse:"Gather current-state evidence about unfamiliar code or existing architecture \u2014 read-only code-path research with concrete file:line support. Diagnosis or recommendations belong to advisor, target architecture to design, required behavior or acceptance criteria to spec, and implementation decomposition to plan.",model:"openai/light",orchestratorModel:"anthropic/strong"},developer:{whenToUse:"Implement a change \u2014 make the feature or fix genuinely work against its acceptance criteria, not merely compile.",model:"openai/medium",orchestratorModel:"anthropic/strong"},design:{whenToUse:"Architect a solution \u2014 produce one design document an implementer can build from without re-deciding anything left open.",model:"anthropic/strong"},plan:{whenToUse:"Break work into steps \u2014 turn a spec or design into a concrete, phased, parallelizable plan with every decision resolved.",model:"anthropic/strong",orchestratorModel:"anthropic/strong"},spec:{whenToUse:"Collaborate with the user to discover what to build, then write the spec \u2014 behavior, non-goals, interfaces, edge cases, testable acceptance criteria.",model:"anthropic/strong"},review:{whenToUse:"Validate or critique code, a plan, or a spec \u2014 deliver a complete, severity-rated verdict without adjudicating.",model:"openai/medium",orchestratorModel:"openai/strong"},advisor:{whenToUse:"Debug failures, investigate why something is broken or misbehaving, diagnose live/runtime issues, or give engineering advice and second opinions \u2014 reason from evidence and recommend the next move. Use advisor (not explore) whenever the task is to find out what is going wrong.",model:"anthropic/strong"},"review/companion":{whenToUse:"Born by the daemon for one human review; never spawned by an agent.",availableTo:[]}}}function Dwe(){return{anthropic:{ultra:"anthropic/claude-fable-5:xhigh",strong:"anthropic/claude-opus-5-5:medium",medium:"anthropic/claude-sonnet-5-5:medium",light:"anthropic/claude-haiku-5-5:high"},openai:{ultra:"openai-codex/gpt-6-astra:max",strong:"openai-codex/gpt-6.1-sol:high",medium:"openai-codex/gpt-6.1-sol:medium",light:"openai-codex/gpt-6-luna:low"}}}function Mwe(){return{marketplaces:{},plugins:{}}}var Li,Qst,Wst,Hst,mC,dy,py,l9,j2n,d9,hC,q2n,Iwe,gC,yC,Twe,Ha=h(()=>{"use strict";u9();Li={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},Qst=4,Wst=".crouter-plugin",Hst="plugin.json",mC=".crouter",dy="config.json",py="state.json",l9="profiles",j2n=3,d9=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],hC=["random","go-faster"],q2n="random",Iwe=2,gC=["tmux","on","off"],yC=["none","user","agent","both"],Twe="none"});function Df(t,e){return new Ii("not_found",t,Li.NOT_FOUND,e)}function Ap(t,e){return new Ii("usage",t,Li.USAGE,e)}function qst(t,e){return new Ii("ambiguous",t,Li.AMBIGUOUS,e)}function Owe(t,e){let n="owner_only",r=`${t}; only the person's terminal can.`;return new Ii(n,r,Li.USAGE,{error:n,message:r,next:e})}var Ii,qo=h(()=>{"use strict";Ha();_o();Ii=class extends Error{code;exitCode;details;constructor(e,n,r=Li.GENERAL,i){super(n),this.name="CrtrError",this.code=e,this.exitCode=r,this.details=i}}});import{appendFileSync as Gst,existsSync as zst,mkdirSync as G2n,renameSync as Vst,rmSync as z2n,statSync as V2n}from"node:fs";import{dirname as K2n}from"node:path";function Jst(t,e){let n="";try{G2n(K2n(t),{recursive:!0});let r=zst(t)?V2n(t).size:0;for(let i of e){let o=`${i}
196
196
  `,s=Buffer.byteLength(o,"utf8");r+s>Y2n&&r>0&&(n!==""&&(Gst(t,n,"utf8"),n=""),z2n(`${t}.2`,{force:!0}),zst(`${t}.1`)&&Vst(`${t}.1`,`${t}.2`),Vst(t,`${t}.1`),r=0),n+=o,r+=s}return n!==""&&Gst(t,n,"utf8"),!0}catch{return!1}}function m9(t,e){return e.includes(`
197
197
  `)||e.includes("\r")||Buffer.byteLength(e,"utf8")+1>Yst?!1:Jst(t,[e])}function Xst(t,e){if(e.includes(`
198
198
  `)||e.includes("\r"))return!1;let n=Buffer.byteLength(e,"utf8")+1;return n>Yst?!1:(wp!==void 0&&wp.path!==t&&f9(),wp===void 0&&(wp={path:t,records:[],bytes:0},Kst||(process.on("exit",f9),Kst=!0)),wp.path=t,wp.records.push(e),wp.bytes+=n,wp.bytes>=J2n?f9():wp.timer===void 0&&(wp.timer=setTimeout(f9,X2n),wp.timer.unref()),!0)}function f9(){let t=wp;if(!(t===void 0||t.records.length===0)&&(t.timer!==void 0&&clearTimeout(t.timer),wp=void 0,!Jst(t.path,t.records)))for(let e of t.records)process.stderr.write(`[crtrd] event log append failed: ${e}
@@ -1 +1 @@
1
- var re=Object.defineProperty;var f=(e,t)=>re(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as L}from"../../api/command-manifest/result.js";import{callerAllows as G,requireGroup as te}from"../../daemon/api/handlers/providers.js";import{grantFor as oe,terminalGrant as ne}from"../grants/mirror.js";import{assertUnderCap as z,UNCAPPED_GRANTEE as ie}from"../usage/ledger.js";import{listInstalledPlugins as se}from"../resolver.js";import{ProviderError as u}from"./errors.js";import{resolveProviderRef as ae}from"./roots.js";import{ensureProviderBundle as de,refreshProviderBundle as ue,resolveProviderBundle as O,unavailableProviderError as pe}from"./bundles.js";import{prepareFileCall as le,resignForRetry as Q,resolveFileResult as V}from"./files.js";import{consumeApproval as ce,requireProviderApproval as fe}from"./approval.js";import{outboundToken as me}from"./mint.js";import{discardFile as ve}from"./token-cache.js";import{registerProviderCall as ge}from"./inflight.js";import{buildRequestPlan as he}from"../command-plugins/transport/http-plan.js";import{sendProviderRequest as we,ProviderTransportError as be}from"./request.js";import{acceptProviderReceipt as ye}from"./receipts.js";import{writeProviderAudit as _e}from"./audit.js";import{selectDevice as Ae,sendDeviceCall as je,deviceFailure as ke,deviceUnreachable as qe,DEFAULT_DEVICE_REQUEST_MS as Pe}from"./device.js";import{envelopeForProviderCaller as $e}from"../peer/envelope.js";function K(e){const t=[],s=e.roots.length===1?e.roots[0].name:void 0,p=f((r,n)=>{const d=[...n,r.name];if(r.kind==="branch"){for(const g of r.children)p(g,d);return}const o=d[0]===s?d.slice(1).join(" "):d.join(" ");t.push({tool:o,leaf:r})},"walk");for(const r of e.roots)p(r,[]);return t}f(K,"providerLeaves");function W(e,t,s){if(e.kind!=="branch")return null;const p=[];for(const v of e.children)if(v.kind==="branch"){const m=W(v,t,s);m&&p.push(m)}else if("group"in v&&v.group&&G(s,`${t}:${v.group}`)){const{kind:m,name:_,description:j,whenToUse:P,tier:i,summary:$,params:y,output:k,effects:A,group:E}=v;p.push({kind:m,name:_,description:j,whenToUse:P,...i===void 0?{}:{tier:i},summary:$,params:y,output:k,effects:A,group:E})}if(p.length===0)return null;const{kind:r,name:n,description:d,whenToUse:o,tier:g,summary:c,model:w,rootEntry:b}=e;return{kind:r,name:n,description:d,whenToUse:o,...g===void 0?{}:{tier:g},summary:c,...w===void 0?{}:{model:w},...b===void 0?{}:{rootEntry:b},children:p}}f(W,"providerHelpBranch");async function er(e,t){const s=await O(t),p=K(s.commands),r=se("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:s.major,display_name:r,transport:s.transport.kind,groups:s.provider.groups.filter(n=>G(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:p.filter(({leaf:d})=>d.group===n.group).map(({tool:d,leaf:o})=>({tool:d,description:o.description,summary:o.summary,params:o.params,output:o.output}))})),commands:s.commands.roots.flatMap(n=>{const d=W(n,t,e);return d?[d]:[]})}}f(er,"providerTools");function Ee(e){return ye(e.headers["crtr-receipt"],e)}f(Ee,"onProviderResponse");function X(e){if(!(e.class==="person"||!e.sub||!e.grantee))return{grantee:e.grantee,spend_cap:oe(e.grantee,e.sub)?.spend_cap??null}}f(X,"capTarget");function Re(e){if(e.class==="person"){const t=ne()?.sub;if(!t)throw new u("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys join` again from /account/machines.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new u("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}f(Re,"identity");function Te(e,t){return[`${e.id}:${t.group}`]}f(Te,"callScope");function Fe(e,t){const s=K(e.commands).find(p=>p.tool===t);if(!s)throw new u("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!s.leaf.group)throw new u("not_found",`tool "${t}" has no group`,{param:"tool"});return s.leaf}f(Fe,"leafFor");function I(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}f(I,"errorBody");function Ne(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const s=Number(t);if(Number.isFinite(s)&&s>=0)return s;const p=Date.parse(t);return Number.isFinite(p)?Math.max(0,Math.ceil((p-Date.now())/1e3)):void 0}f(Ne,"retryAfter");function B(e,t,s,p=!1){const r=I(t),n=typeof r.code=="string"?r.code:void 0,d=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,o=typeof r.field=="string"?r.field:void 0,c={origin:"provider",details:{code:n??null,message:d,...o?{field:o}:{},...typeof r.next=="string"?{next:r.next}:{},...r.received!==void 0?{received:r.received}:{},status:e},...o?{param:o}:{}};return e===429?new u("provider_rate_limited",d,{...c,retry_after_s:Ne(s["retry-after"])}):e===401||e>=500?new u("provider_unavailable",d,c):e===403&&n==="provider_refused"?new u("provider_refused",d,c):e===403&&n==="approval_required"?new u("provider_error",p?"provider asked for approval again":"provider approval question is invalid",{...c,status:e}):new u("provider_error",d,{...c,status:e})}f(B,"mapProviderResponse");function Y(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}f(Y,"approvalShape");async function rr(e,t,s){const p=ae(t.provider);if(p===null)throw new u("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:p},n=new AbortController,d=f(()=>n.abort(s.signal.reason),"abort");s.signal.aborted?d():s.signal.addEventListener("abort",d,{once:!0});let o=s.requestId;const g=ge({request_id:o,run_id:e.run_id,node_id:e.node_id,controller:n});let c,w,b,v,m,_,j,P="allowed";try{try{await de(r.provider)}catch{throw pe(r.provider)}let i=await O(r.provider,r.version),$=!1,y,k,A,E=!1,J=!1,M,x=0;for(;;){const h=Fe(i,r.tool);if(b=`${i.id}:${h.group}`,te(e,i.id,h.group),z(X(e)),i.transport.kind!=="machine"&&r.machine!==void 0)throw new u("invalid_argument",`provider "${i.id}" is not served by a device, so it takes no machine`,{param:"machine"});i.transport.kind==="machine"&&M===void 0&&(M=await Ae(r.machine),x=Date.now()+(i.commands.timeouts?.requestMs??Pe));let S=null;if(r.approval&&!E){const a=ce(e,r,Y(i,h));A=a.option,S=a.prepared,j=r.approval,o=a.requestId,E=!0}const R={params:h.params.filter(a=>"type"in a&&a.type==="file").map(a=>a.name),output:h.output.find(a=>a.type==="file")?.name??null},H=JSON.stringify(R);if(k!==void 0&&k!==H)throw new u("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});k=H,S&&(y=await Q(e,R,r.arguments,S,{signal:n.signal})),y??=await le(e,R,r.arguments,{signal:n.signal});const{sub:U,grantee:T}=Re(e);if(z(X(e)),i.transport.kind==="machine"){const a=await Ce(e,i,r,h,y,{sub:U,requestId:o,deadlineAt:x,signal:n.signal,machine:M});return _=a.responder,c=a.cleanup,{status:200,body:a.result}}const F=await me({audience:i.transport.endpoint,sub:U,grantee:T,initiating_app:T,scope:Te(i,h)},{signal:n.signal});v=F.jti;const Z={registration:{name:i.id,endpoint:i.transport.endpoint},...i.commands.baseUrl?{baseUrl:i.commands.baseUrl}:{},...i.commands.timeouts?{timeouts:i.commands.timeouts}:{},params:h.params,rest:h.rest,output:h.output,commandPath:[i.id,...r.tool.split(" ")]},ee=he(Z,y.arguments,void 0,{authorization:`Bearer ${F.access_token}`,requestId:o,fileMode:"pass-through",extraHeaders:{...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...A?{"Crtr-Approval":A}:{},...y.headers}});w??=Date.now()+(i.commands.timeouts?.requestMs??3e4);let l;try{if(l=await we(ee,{connectMs:i.commands.timeouts?.connectMs,requestMs:i.commands.timeouts?.requestMs,deadlineAt:w,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(a){throw n.signal.aborted?n.signal.reason??a:a instanceof be?new u("provider_unavailable",a.message,{origin:"provider",details:{status:null,code:a.kind}}):a}if(m??=Ee({provider:i.id,tool:r.tool,request_id:o,run_id:e.run_id,sub:U,grantee:T,ledger_grantee:e.class==="person"?ie:T,jti:F.jti,status:l.status,headers:l.headers}),_=l.headers["crtr-responder"],l.status===401&&ve(F.key),l.status>=200&&l.status<300){const a=l.body;if(!a||typeof a!="object"||Array.isArray(a))throw new u("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:l.status,message:"provider result is not a JSON object"}});let C;try{C=await V(e,y,a,{signal:n.signal})}catch(q){throw q instanceof u&&q.code==="provider_error"?new u("provider_bad_response",q.message,{origin:"provider",details:{status:l.status,message:q.message}}):q}c=C.cleanup;const D=L(h.output,C.result);if(D)throw new u("provider_bad_response",`provider result has an invalid output field "${D.field}"`,{origin:"provider",param:D.field,details:{status:l.status,...D}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:C.result}}const N=I(l.body);if(l.status===403&&N.code==="approval_required"&&!A&&!J){J=!0;const a=await fe(e,r,o,N.question,n.signal,Y(i,h),y);if(j=a.questionId,A=a.option,y=await Q(e,R,r.arguments,y,{signal:n.signal}),w=void 0,n.signal.aborted)throw new u("user_denied","the approval wait was canceled");continue}if(l.status===403&&N.code==="approval_required"&&A)throw B(l.status,l.body,l.headers,!0);if(l.status!==401&&N.manifest_stale===!0&&!$){$=!0,await ue(i.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),i=await O(i.id,r.version);continue}throw B(l.status,l.body,l.headers,!!A)}}catch(i){throw i instanceof u&&i.question_id&&(j=i.question_id),_===void 0&&i instanceof u&&typeof i.responder=="string"&&(_=i.responder),P=`refused:${i instanceof u?i.code:"server_error"}`,c?.(),i}finally{try{_e({request_id:o,caller:e,provider:r.provider,tool:r.tool,scope_checked:b,outcome:P,jti:v,receipt_id:m,responder:_,question_id:j})}finally{g()}s.signal.removeEventListener("abort",d)}}f(rr,"callProvider");async function Ce(e,t,s,p,r,n){const{machine:d}=n,o=await je(d,{tool:s.tool,arguments:r.arguments,version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},$e(e,n.sub),n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in o)throw qe(d,o.unreachable.reason,o.unreachable.message);const g=o.headers["crtr-responder"],c=I(o.body);if(o.status<200||o.status>=300){const m=ke(d,o.status,typeof c.code=="string"?c.code:void 0,typeof c.message=="string"?c.message:void 0,o.body),_=m===null&&o.status>=500&&typeof c.code=="string"?new u("provider_error",typeof c.message=="string"?c.message:`the device answered HTTP ${o.status}`,{origin:"runtime",status:o.status,details:{code:c.code,status:o.status}}):null;throw Object.assign(m??_??B(o.status,o.body,o.headers),{responder:g})}const w=o.body&&typeof o.body=="object"&&!Array.isArray(o.body)?o.body.result:void 0;if(!w||typeof w!="object"||Array.isArray(w))throw Object.assign(new u("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:o.status,message:"the device result is not a JSON object"}}),{responder:g});let b;try{b=await V(e,r,w,{signal:n.signal})}catch(m){throw m instanceof u&&m.code==="provider_error"?Object.assign(new u("provider_bad_response",m.message,{origin:"provider",details:{status:o.status,message:m.message}}),{responder:g}):m}const v=L(p.output,b.result);if(v)throw b.cleanup?.(),Object.assign(new u("provider_bad_response",`the device result has an invalid output field "${v.field}"`,{origin:"provider",param:v.field,details:{status:o.status,...v}}),{responder:g});return{result:b.result,responder:g,cleanup:b.cleanup}}f(Ce,"callDevice");export{rr as callProvider,B as mapProviderResponse,Ee as onProviderResponse,K as providerLeaves,er as providerTools};
1
+ var oe=Object.defineProperty;var m=(e,t)=>oe(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as I}from"../../api/command-manifest/result.js";import{callerAllows as x,requireGroup as ne}from"../../daemon/api/handlers/providers.js";import{grantFor as ie,terminalGrant as se}from"../grants/mirror.js";import{assertUnderCap as z,UNCAPPED_GRANTEE as ae}from"../usage/ledger.js";import{listInstalledPlugins as de}from"../resolver.js";import{ProviderError as l}from"./errors.js";import{resolveProviderRef as ue}from"./roots.js";import{ensureProviderBundle as le,refreshProviderBundle as pe,resolveProviderBundle as B,unavailableProviderError as ce}from"./bundles.js";import{prepareFileCall as fe,resignForRetry as Q,resolveFileResult as V}from"./files.js";import{consumeApproval as me,requireProviderApproval as ve}from"./approval.js";import{outboundToken as ge}from"./mint.js";import{discardFile as he}from"./token-cache.js";import{registerProviderCall as we}from"./inflight.js";import{buildRequestPlan as be}from"../command-plugins/transport/http-plan.js";import{sendProviderRequest as ye,ProviderTransportError as _e}from"./request.js";import{acceptProviderReceipt as je}from"./receipts.js";import{writeProviderAudit as Ae}from"./audit.js";import{selectDevice as ke,sendDeviceCall as qe,deviceFailure as Pe,deviceUnreachable as K,DEFAULT_DEVICE_REQUEST_MS as $e}from"./device.js";import{isLibsSearch as W,wantsBundling as Ee,callLibsSearch as Re,bundleExec as Se,mapLibOutcome as Fe,reportLibCalls as Te}from"./device-libs.js";import{envelopeForProviderCaller as Ce}from"../peer/envelope.js";function X(e){const t=[],a=e.roots.length===1?e.roots[0].name:void 0,c=m((r,n)=>{const d=[...n,r.name];if(r.kind==="branch"){for(const _ of r.children)c(_,d);return}const p=d[0]===a?d.slice(1).join(" "):d.join(" ");t.push({tool:p,leaf:r})},"walk");for(const r of e.roots)c(r,[]);return t}m(X,"providerLeaves");function Y(e,t,a){if(e.kind!=="branch")return null;const c=[];for(const i of e.children)if(i.kind==="branch"){const h=Y(i,t,a);h&&c.push(h)}else if("group"in i&&i.group&&x(a,`${t}:${i.group}`)){const{kind:h,name:v,description:y,whenToUse:P,tier:o,summary:A,params:s,output:w,effects:k,group:E}=i;c.push({kind:h,name:v,description:y,whenToUse:P,...o===void 0?{}:{tier:o},summary:A,params:s,output:w,effects:k,group:E})}if(c.length===0)return null;const{kind:r,name:n,description:d,whenToUse:p,tier:_,summary:g,model:j,rootEntry:q}=e;return{kind:r,name:n,description:d,whenToUse:p,..._===void 0?{}:{tier:_},summary:g,...j===void 0?{}:{model:j},...q===void 0?{}:{rootEntry:q},children:c}}m(Y,"providerHelpBranch");async function ar(e,t){const a=await B(t),c=X(a.commands),r=de("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:a.major,display_name:r,transport:a.transport.kind,groups:a.provider.groups.filter(n=>x(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:c.filter(({leaf:d})=>d.group===n.group).map(({tool:d,leaf:p})=>({tool:d,description:p.description,summary:p.summary,params:p.params,output:p.output}))})),commands:a.commands.roots.flatMap(n=>{const d=Y(n,t,e);return d?[d]:[]})}}m(ar,"providerTools");function De(e){return je(e.headers["crtr-receipt"],e)}m(De,"onProviderResponse");function Z(e){if(!(e.class==="person"||!e.sub||!e.grantee))return{grantee:e.grantee,spend_cap:ie(e.grantee,e.sub)?.spend_cap??null}}m(Z,"capTarget");function Ne(e){if(e.class==="person"){const t=se()?.sub;if(!t)throw new l("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys join` again from /account/machines.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new l("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(Ne,"identity");function Oe(e,t){return[`${e.id}:${t.group}`]}m(Oe,"callScope");function Me(e,t){const a=X(e.commands).find(c=>c.tool===t);if(!a)throw new l("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!a.leaf.group)throw new l("not_found",`tool "${t}" has no group`,{param:"tool"});return a.leaf}m(Me,"leafFor");function L(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(L,"errorBody");function Ue(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const a=Number(t);if(Number.isFinite(a)&&a>=0)return a;const c=Date.parse(t);return Number.isFinite(c)?Math.max(0,Math.ceil((c-Date.now())/1e3)):void 0}m(Ue,"retryAfter");function N(e,t,a,c=!1){const r=L(t),n=typeof r.code=="string"?r.code:void 0,d=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,p=typeof r.field=="string"?r.field:void 0,g={origin:"provider",details:{code:n??null,message:d,...p?{field:p}:{},...typeof r.next=="string"?{next:r.next}:{},...r.received!==void 0?{received:r.received}:{},status:e},...p?{param:p}:{}};return e===429?new l("provider_rate_limited",d,{...g,retry_after_s:Ue(a["retry-after"])}):e===401||e>=500?new l("provider_unavailable",d,g):e===403&&n==="provider_refused"?new l("provider_refused",d,g):e===403&&n==="approval_required"?new l("provider_error",c?"provider asked for approval again":"provider approval question is invalid",{...g,status:e}):new l("provider_error",d,{...g,status:e})}m(N,"mapProviderResponse");function ee(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(ee,"approvalShape");async function dr(e,t,a){const c=ue(t.provider);if(c===null)throw new l("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:c},n=new AbortController,d=m(()=>n.abort(a.signal.reason),"abort");a.signal.aborted?d():a.signal.addEventListener("abort",d,{once:!0});let p=a.requestId;const _=we({request_id:p,run_id:e.run_id,node_id:e.node_id,controller:n});let g,j,q,i,h,v,y,P="allowed";try{try{await le(r.provider)}catch{throw ce(r.provider)}let o=await B(r.provider,r.version),A=!1,s,w,k,E=!1,J=!1,O,H=0;for(;;){const b=Me(o,r.tool);if(q=`${o.id}:${b.group}`,ne(e,o.id,b.group),z(Z(e)),o.transport.kind!=="machine"&&r.machine!==void 0)throw new l("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&O===void 0&&(O=await ke(r.machine,void 0,{newest:W(o.major,r.tool)}),H=Date.now()+(o.commands.timeouts?.requestMs??$e));let M=null;if(r.approval&&!E){const u=me(e,r,ee(o,b));k=u.option,M=u.prepared,y=r.approval,p=u.requestId,E=!0}const R={params:b.params.filter(u=>"type"in u&&u.type==="file").map(u=>u.name),output:b.output.find(u=>u.type==="file")?.name??null},G=JSON.stringify(R);if(w!==void 0&&w!==G)throw new l("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});w=G,M&&(s=await Q(e,R,r.arguments,M,{signal:n.signal})),s??=await fe(e,R,r.arguments,{signal:n.signal});const{sub:U,grantee:S}=Ne(e);if(z(Z(e)),o.transport.kind==="machine"){const u=await Ie(e,o,r,b,s,{sub:U,requestId:p,deadlineAt:H,signal:n.signal,machine:O});return v=u.responder,g=u.cleanup,{status:200,body:u.result}}const F=await ge({audience:o.transport.endpoint,sub:U,grantee:S,initiating_app:S,scope:Oe(o,b)},{signal:n.signal});i=F.jti;const re={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:b.params,rest:b.rest,output:b.output,commandPath:[o.id,...r.tool.split(" ")]},te=be(re,s.arguments,void 0,{authorization:`Bearer ${F.access_token}`,requestId:p,fileMode:"pass-through",extraHeaders:{...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...k?{"Crtr-Approval":k}:{},...s.headers}});j??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await ye(te,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:j,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(u){throw n.signal.aborted?n.signal.reason??u:u instanceof _e?new l("provider_unavailable",u.message,{origin:"provider",details:{status:null,code:u.kind}}):u}if(h??=De({provider:o.id,tool:r.tool,request_id:p,run_id:e.run_id,sub:U,grantee:S,ledger_grantee:e.class==="person"?ae:S,jti:F.jti,status:f.status,headers:f.headers}),v=f.headers["crtr-responder"],f.status===401&&he(F.key),f.status>=200&&f.status<300){const u=f.body;if(!u||typeof u!="object"||Array.isArray(u))throw new l("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let C;try{C=await V(e,s,u,{signal:n.signal})}catch($){throw $ instanceof l&&$.code==="provider_error"?new l("provider_bad_response",$.message,{origin:"provider",details:{status:f.status,message:$.message}}):$}g=C.cleanup;const D=I(b.output,C.result);if(D)throw new l("provider_bad_response",`provider result has an invalid output field "${D.field}"`,{origin:"provider",param:D.field,details:{status:f.status,...D}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:C.result}}const T=L(f.body);if(f.status===403&&T.code==="approval_required"&&!k&&!J){J=!0;const u=await ve(e,r,p,T.question,n.signal,ee(o,b),s);if(y=u.questionId,k=u.option,s=await Q(e,R,r.arguments,s,{signal:n.signal}),j=void 0,n.signal.aborted)throw new l("user_denied","the approval wait was canceled");continue}if(f.status===403&&T.code==="approval_required"&&k)throw N(f.status,f.body,f.headers,!0);if(f.status!==401&&T.manifest_stale===!0&&!A){A=!0,await pe(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await B(o.id,r.version);continue}throw N(f.status,f.body,f.headers,!!k)}}catch(o){throw o instanceof l&&o.question_id&&(y=o.question_id),v===void 0&&o instanceof l&&typeof o.responder=="string"&&(v=o.responder),P=`refused:${o instanceof l?o.code:"server_error"}`,g?.(),o}finally{try{Ae({request_id:p,caller:e,provider:r.provider,tool:r.tool,scope_checked:q,outcome:P,jti:i,receipt_id:h,responder:v,question_id:y})}finally{_()}a.signal.removeEventListener("abort",d)}}m(dr,"callProvider");async function Ie(e,t,a,c,r,n){const{machine:d}=n,p=Ce(e,n.sub),_={machine:d,envelope:p,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:N};if(W(t.major,a.tool)){const s=await Re(_,r.arguments,t.major),w=I(c.output,s);if(w)throw new l("provider_bad_response",`the libraries result has an invalid output field "${w.field}"`,{origin:"provider",param:w.field,details:{status:200,...w}});return{result:s,responder:void 0,cleanup:void 0}}let g=r.arguments,j=null,q="";if(Ee(t.major,a.tool,r.arguments)){const s=await Se(_,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw K(d,"timeout","");s!==null&&(g=s.arguments,j=s.services,q=s.release)}const i=await qe(d,{tool:a.tool,arguments:g,version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},p,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in i)throw K(d,i.unreachable.reason,i.unreachable.message);const h=i.headers["crtr-responder"],v=L(i.body);if(i.status<200||i.status>=300){const s=Pe(d,i.status,typeof v.code=="string"?v.code:void 0,typeof v.message=="string"?v.message:void 0,i.body),w=s===null&&i.status>=500&&typeof v.code=="string"?new l("provider_error",typeof v.message=="string"?v.message:`the device answered HTTP ${i.status}`,{origin:"runtime",status:i.status,details:{code:v.code,status:i.status}}):null;throw Object.assign(s??w??N(i.status,i.body,i.headers),{responder:h})}const y=i.body&&typeof i.body=="object"&&!Array.isArray(i.body)?i.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new l("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:i.status,message:"the device result is not a JSON object"}}),{responder:h});let P=y;if(j!==null){const s=Fe(P,j);if(Te(d,p,q,s.calls),"error"in s)throw Object.assign(s.error,{responder:h});P=s.result}let o;try{o=await V(e,r,P,{signal:n.signal})}catch(s){throw s instanceof l&&s.code==="provider_error"?Object.assign(new l("provider_bad_response",s.message,{origin:"provider",details:{status:i.status,message:s.message}}),{responder:h}):s}const A=I(c.output,o.result);if(A)throw o.cleanup?.(),Object.assign(new l("provider_bad_response",`the device result has an invalid output field "${A.field}"`,{origin:"provider",param:A.field,details:{status:i.status,...A}}),{responder:h});return{result:o.result,responder:h,cleanup:o.cleanup}}m(Ie,"callDevice");export{dr as callProvider,N as mapProviderResponse,De as onProviderResponse,X as providerLeaves,ar as providerTools};
@@ -0,0 +1,71 @@
1
+ import type { Machine } from '../peer/directory.js';
2
+ import type { Envelope } from '../peer/envelope.js';
3
+ import { ProviderError } from './errors.js';
4
+ /** Wire contract §9.1. */
5
+ export declare const LIBS_SEARCH_PATH = "/v1/libs/search";
6
+ export declare const LIBS_BUNDLE_PATH = "/v1/libs/bundle";
7
+ export declare const LIBS_REPORT_PATH = "/v1/libs/report";
8
+ /** The device wire version libs routes and bundled execs are served at. */
9
+ export declare const LIBS_MAJOR = 2;
10
+ export declare const isLibsSearch: (major: number, tool: string) => boolean;
11
+ /** An exec whose code may import a library. The relay does the exact leading-import parse; a false positive costs one round trip. */
12
+ export declare function wantsBundling(major: number, tool: string, args: Record<string, unknown>): boolean;
13
+ export interface LibsContext {
14
+ machine: Machine;
15
+ envelope: Envelope;
16
+ /** The provider call's own signal (the caller went away). */
17
+ signal: AbortSignal;
18
+ /** Unix epoch ms: the call's one shared device deadline. */
19
+ deadlineAt: number;
20
+ /** The generic provider-response mapping for a relay answer that is not a device failure (`mapProviderResponse`). */
21
+ mapFailure: (status: number, body: unknown, headers: Record<string, string | string[] | undefined>) => ProviderError;
22
+ }
23
+ /** `browser libs`: the relay's catalog search. The caller validates the result against the leaf's output. */
24
+ export declare function callLibsSearch(ctx: LibsContext, args: Record<string, unknown>, version: number): Promise<Record<string, unknown>>;
25
+ /** An imported library, as the bundle answer lists it. `domains` is its domains and domain suffixes; `writes` its write functions. */
26
+ export interface LibService {
27
+ id: string;
28
+ name: string;
29
+ domains: string[];
30
+ writes: string[];
31
+ }
32
+ export interface LibsBundle {
33
+ /** The exec's arguments with `code` replaced by `bundle` and `domains`. */
34
+ arguments: Record<string, unknown>;
35
+ release: string;
36
+ services: LibService[];
37
+ }
38
+ /** Bundle an exec's code. `null` when the relay found no library import (`bundled: false`): the arguments go to Desktop unchanged. */
39
+ export declare function bundleExec(ctx: LibsContext, args: Record<string, unknown>, version: number): Promise<LibsBundle | null>;
40
+ /** One lib call, as the runtime records it: metadata only. */
41
+ export interface CallRecord {
42
+ service: string;
43
+ fn: string;
44
+ ok: boolean;
45
+ durationMs: number;
46
+ errorClass?: string;
47
+ status?: number;
48
+ upstreamCode?: string;
49
+ wasDispatched?: boolean;
50
+ }
51
+ export interface LibResult {
52
+ result: unknown;
53
+ url: string;
54
+ calls: CallRecord[];
55
+ warning?: string;
56
+ }
57
+ /** The envelope comes from a web page's JavaScript, so it is rebuilt field by field: only the documented metadata survives, bounded,
58
+ * and nothing a lib call received or returned can ride along in a record. */
59
+ export declare function sanitizeCalls(value: unknown): CallRecord[];
60
+ export type LibOutcome = {
61
+ calls: CallRecord[];
62
+ result: LibResult;
63
+ } | {
64
+ calls: CallRecord[];
65
+ error: ProviderError;
66
+ };
67
+ /** Turns Desktop's `{envelope, url, warning?}` into the leaf's answer or the design's error. Rules run top to bottom; the first match wins.
68
+ * `calls` is always returned, so a failed record can be reported whichever way the exec ended. */
69
+ export declare function mapLibOutcome(desktop: Record<string, unknown>, services: LibService[]): LibOutcome;
70
+ /** Fire-and-forget: tell the relay which lib calls failed so it can report them (metadata only). Nothing here can fail the call. */
71
+ export declare function reportLibCalls(machine: Machine, envelope: Envelope, release: string, calls: CallRecord[]): void;
@@ -0,0 +1 @@
1
+ var T=Object.defineProperty;var a=(e,r)=>T(e,"name",{value:r,configurable:!0});import{ProviderError as p}from"./errors.js";import{deviceDeps as w,deviceFailure as C,deviceUnreachable as _}from"./device.js";const $="/v1/libs/search",L="/v1/libs/bundle",R="/v1/libs/report",A=2,x=1e4,E=/@(northlight|vallum)\//,j=1e3,M=2e3,D=300,X=a((e,r)=>e===A&&r==="browser libs","isLibsSearch");function W(e,r,n){return e===A&&r==="browser executor exec"&&typeof n.code=="string"&&E.test(n.code)}a(W,"wantsBundling");function O(e){const r=e["retry-after"],n=Array.isArray(r)?r[0]:r,t=n===void 0?NaN:Number(n);return Number.isFinite(t)&&t>=0?t:void 0}a(O,"retryAfterSeconds");function U(e,r){const n=r.body?.error,t=n&&typeof n=="object"&&typeof n.code=="string"?n.code:void 0,o=n&&typeof n=="object"&&typeof n.message=="string"?n.message:void 0,i=C(e.machine,r.status,t,o,r.body);if(i!==null)return i;const s=e.mapFailure(r.status,r.body,r.headers),d=r.status===503?O(r.headers):void 0;return d===void 0||s.retry_after_s!==void 0?s:new p("provider_unavailable",s.message,{origin:s.origin,details:s.details,...s.param?{param:s.param}:{},retry_after_s:d})}a(U,"libsFailure");const N=a(e=>_(e.machine,"timeout",""),"budgetSpent");async function v(e,r,n,t){const o=e.deadlineAt-Date.now();if(o<=0)throw N(e);const i=await w.current.call(e.machine.machine_id,{method:"POST",path:r,body:{...n,version:t,deadline_at:e.deadlineAt}},{envelope:e.envelope,device:!0,signal:AbortSignal.any([e.signal,AbortSignal.timeout(o)])});if(e.signal.aborted)throw e.signal.reason??new Error("provider call aborted");if("unreachable"in i)throw _(e.machine,i.unreachable.reason,i.unreachable.message);if(i.status<200||i.status>=300)throw U(e,i);const s=i.body&&typeof i.body=="object"&&!Array.isArray(i.body)?i.body.result:void 0;if(!s||typeof s!="object"||Array.isArray(s))throw new p("provider_bad_response","the libraries result is not a JSON object",{origin:"provider",details:{status:i.status,message:"the libraries result is not a JSON object"}});return s}a(v,"libsRequest");function q(e,r,n){return v(e,$,{arguments:r},n)}a(q,"callLibsSearch");const b=a(e=>Array.isArray(e)&&e.every(r=>typeof r=="string")?e:null,"strings");function P(e){if(!Array.isArray(e))return null;const r=[];for(const n of e){const t=n,o=b(t?.domains),i=b(t?.writes);if(!t||typeof t.id!="string"||typeof t.name!="string"||o===null||i===null)return null;r.push({id:t.id,name:t.name,domains:o,writes:i})}return r}a(P,"parseServices");async function z(e,r,n){const t=await v(e,L,{code:r.code},n);if(t.bundled===!1)return null;const o=b(t.domains),i=P(t.services);if(t.bundled!==!0||typeof t.bundle!="string"||o===null||i===null||typeof t.release!="string")throw new p("provider_bad_response","the libraries bundle answer is malformed",{origin:"provider",details:{status:200,message:"the libraries bundle answer is malformed"}});const{code:s,...d}=r;return{arguments:{...d,bundle:t.bundle,domains:o},release:t.release,services:i}}a(z,"bundleExec");const S=a(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,"object"),l=a(e=>typeof e=="string"?e.slice(0,M):void 0,"text"),y=a(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"finite");function k(e){if(!Array.isArray(e))return[];const r=[];for(const n of e.slice(0,j)){const t=S(n),o=l(t?.service),i=l(t?.fn);if(!t||o===void 0||i===void 0)continue;const s=l(t.errorClass),d=y(t.status),u=l(t.upstreamCode);r.push({service:o,fn:i,ok:t.ok===!0,durationMs:Math.max(0,Math.round(y(t.durationMs)??0)),...s!==void 0&&{errorClass:s},...d!==void 0&&{status:d},...u!==void 0&&{upstreamCode:u},...typeof t.wasDispatched=="boolean"&&{wasDispatched:t.wasDispatched}})}return r}a(k,"sanitizeCalls");function F(e,r){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return!1}return r.some(t=>{const o=t.toLowerCase().replace(/^\*\./,"").replace(/^\./,"");return n===o||n.endsWith(`.${o}`)})}a(F,"hostMatches");function B(e,r,n){for(const t of e){if(t.ok||t.errorClass!=="Unauthenticated")continue;const o=r.find(s=>s.id===t.service);if(!o||o.domains.length===0||F(n,o.domains))continue;let i=n;try{i=new URL(n).hostname||n}catch{}return`${o.name} is not on ${i} (it runs on ${o.domains.join(", ")})`}}a(B,"offSiteCall");function f(e,r,n,t,o){return new p(e,n,{status:r,origin:"provider",details:{code:e,message:n,next:t,status:r},...o===void 0?{}:{retry_after_s:o}})}a(f,"outcomeError");function Y(e,r){const n=S(e.envelope);if(!n||typeof e.url!="string")return{calls:[],error:f("js_exception",409,"The page returned a result that could not be read","Run the code again; if it keeps happening, report it")};const t=e.url,o=k(n.calls),i=l(e.warning);if(!("error"in n))return{calls:o,result:{result:n.result===void 0?null:n.result,url:t,calls:o,...i!==void 0&&{warning:i}}};const s=l(n.error)??"The script threw",d=i===void 0?"":` ${i}`,u=l(n.errorClass),h=a(c=>({calls:o,error:c}),"fail"),g=o.filter(c=>c.wasDispatched===!0&&r.find(m=>m.id===c.service)?.writes.includes(c.fn)===!0);if(g.length>0)return h(f("outcome_unknown",409,`The script threw after ${g.map(c=>`${c.service}.${c.fn}`).join(", ")} was sent, so it may have taken effect: ${s}`,`Check the site before repeating this action; do not retry blindly.${d}`));if(u==="Unauthenticated"){const c=B(o,r,t);return h((c??i)!==void 0?f("wrong_site",409,`The executor is on the wrong site, not signed out: ${c??i} (${s})`,"Create the executor on the service's own site (browser executor create --url https://\u2026) or navigate it there, then run the code again"):f("site_signed_out",409,`The site is signed out in this Chrome profile: ${s}`,"Sign in to the service in Chrome through the Northlight Desktop menu's Open Chrome profile, then run the code again"))}if(u==="RateLimited"){const c=y(n.retryAfterS),m=c!==void 0&&c>=1?Math.ceil(c):D;return h(f("rate_limited",429,s,`Wait for Retry-After seconds, then run the code again.${d}`,m))}return h(u==="ContractDrift"?f("lib_broken",502,`The library no longer matches the site: ${s}`,`Do not retry; the library needs a fix. Use a different approach for now.${d}`):f("js_exception",409,u&&u!=="Unknown"?`${u}: ${s}`:s,`Fix the code or its arguments and run it again.${d}`))}a(Y,"mapLibOutcome");function G(e,r,n,t){if(t.some(o=>!o.ok))try{w.current.call(e.machine_id,{method:"POST",path:R,body:{release:n,calls:t}},{envelope:r,device:!0,signal:AbortSignal.timeout(x)}).catch(()=>{})}catch{}}a(G,"reportLibCalls");export{L as LIBS_BUNDLE_PATH,A as LIBS_MAJOR,R as LIBS_REPORT_PATH,$ as LIBS_SEARCH_PATH,z as bundleExec,q as callLibsSearch,X as isLibsSearch,Y as mapLibOutcome,G as reportLibCalls,k as sanitizeCalls,W as wantsBundling};
@@ -16,8 +16,11 @@ export declare const deviceDeps: {
16
16
  export declare const DEVICE_CALL_PATH = "/v1/device/call";
17
17
  /** The bundle's `timeouts.requestMs` when it declares none (device spec "Per-call deadline"). */
18
18
  export declare const DEFAULT_DEVICE_REQUEST_MS = 60000;
19
- /** The §2.1 selection table. `named` is the caller's `machine`, prefix optional. */
20
- export declare function selectDevice(named: string | undefined, deps?: DeviceDeps): Promise<Machine>;
19
+ /** The §2.1 selection table. `named` is the caller's `machine`, prefix optional. `newest`: an unnamed choice among several devices takes
20
+ * the one seen last instead of refusing (browser libs: the answer is the same on every machine, so the agent need not choose). */
21
+ export declare function selectDevice(named: string | undefined, deps?: DeviceDeps, options?: {
22
+ newest?: boolean;
23
+ }): Promise<Machine>;
21
24
  export interface DeviceRequest {
22
25
  tool: string;
23
26
  arguments: Record<string, unknown>;
@@ -1 +1 @@
1
- var _=Object.defineProperty;var a=(e,n)=>_(e,"name",{value:n,configurable:!0});import{directory as c,normalizeMachineId as h}from"../peer/directory.js";import{peerCall as m}from"../peer/client.js";import{ProviderError as t}from"./errors.js";const l={current:{list:a(()=>c.list(),"list"),lastList:a(()=>c.lastList(),"lastList"),call:a((e,n,i)=>m(e,n,i),"call")}},p="/v1/device/call",D=6e4,f=a(e=>({machine_id:e.machine_id,name:e.name,last_seen:e.last_seen}),"candidateView");function s(e,n){const i=e.map(r=>`${r.name} (${r.machine_id})`).join(", ");return new t("machine_required",n===void 0?`This account has ${e.length} devices: ${i}. Pick one with --machine <machine_id>.`:`${n} is not one of this account's devices. Devices: ${i}. Pick one with --machine <machine_id>.`,{param:"machine",details:{candidates:e.map(f)}})}a(s,"machineRequired");async function x(e,n=l.current){let i;try{i=await n.list()}catch(o){const d=n.lastList();if(d===null)throw new t("provider_unavailable",`The directory could not be reached to find your devices: ${o instanceof Error?o.message:String(o)}`,{origin:"directory"});i=d}const r=i.filter(o=>o.kind==="device");if(r.length===0)throw new t("provider_not_connected","No device is connected to this account. Install Northlight Desktop on your Mac and sign in.",{origin:"directory"});if(e!==void 0){const o=h(e),d=r.find(u=>u.machine_id===o);if(!d)throw s(r,e);return d}if(r.length>1)throw s(r,void 0);return r[0]}a(x,"selectDevice");function v(e){return{tool:e.tool,arguments:e.arguments,version:e.version,request_id:e.requestId,...e.runId===null?{}:{run_id:e.runId},deadline_at:e.deadlineAt,...e.upload===null?{}:{upload:e.upload}}}a(v,"deviceBody");async function A(e,n,i,r,o=l.current){const d=Math.max(1,n.deadlineAt-Date.now());return o.call(e.machine_id,{method:"POST",path:p,body:v(n)},{envelope:i,device:!0,signal:AbortSignal.any([r,AbortSignal.timeout(d)])})}a(A,"sendDeviceCall");function E(e,n,i){switch(n){case"timeout":return new t("device_timeout",`${e.name} did not answer in time.`,{origin:"runtime",details:{machine_id:e.machine_id}});case"directory_unreachable":case"no_directory":return new t("provider_unavailable",i,{origin:"directory"});case"unknown_machine":return new t("provider_not_connected",`${e.name} is no longer on this account.`,{origin:"directory"});case"not_a_crtr_peer":return new t("server_error",i);default:return new t("device_offline",i.trim()===""?`${e.name} is offline.`:i,{origin:"runtime",details:{machine_id:e.machine_id}})}}a(E,"deviceUnreachable");function b(e,n,i,r,o){if(n===401)return new t("device_offline",`${e.name}: Desktop is signed out. Sign in to Northlight Desktop again.`,{origin:"runtime",details:{machine_id:e.machine_id}});if(n===426){const d=o?.error?.details?.supported;return new t("peer_version_too_old",r??`${e.name} does not serve this device major. Update Northlight Desktop.`,{origin:"runtime",details:{machine_id:e.machine_id,...Array.isArray(d)?{supported:d}:{}}})}return n===502&&i==="machine_disconnected"?new t("device_disconnected",`${e.name} disconnected during the call; the action may have run.`,{origin:"runtime",details:{machine_id:e.machine_id}}):i==="payload_too_large"||i==="response_too_large"?new t("provider_error",r??"The call or its answer was too large for the relay (16 MiB).",{origin:"runtime",status:413,details:{code:i,message:r??null,status:n}}):null}a(b,"deviceFailure");export{D as DEFAULT_DEVICE_REQUEST_MS,p as DEVICE_CALL_PATH,v as deviceBody,l as deviceDeps,b as deviceFailure,E as deviceUnreachable,x as selectDevice,A as sendDeviceCall};
1
+ var m=Object.defineProperty;var a=(e,n)=>m(e,"name",{value:n,configurable:!0});import{directory as l,normalizeMachineId as p}from"../peer/directory.js";import{peerCall as f}from"../peer/client.js";import{ProviderError as d}from"./errors.js";const s={current:{list:a(()=>l.list(),"list"),lastList:a(()=>l.lastList(),"lastList"),call:a((e,n,i)=>f(e,n,i),"call")}},v="/v1/device/call",x=6e4,g=a(e=>({machine_id:e.machine_id,name:e.name,last_seen:e.last_seen}),"candidateView");function u(e,n){const i=e.map(t=>`${t.name} (${t.machine_id})`).join(", ");return new d("machine_required",n===void 0?`This account has ${e.length} devices: ${i}. Pick one with --machine <machine_id>.`:`${n} is not one of this account's devices. Devices: ${i}. Pick one with --machine <machine_id>.`,{param:"machine",details:{candidates:e.map(g)}})}a(u,"machineRequired");const _=a(e=>{const n=e.last_seen===null?NaN:Date.parse(e.last_seen);return Number.isFinite(n)?n:-1/0},"seenAt");async function E(e,n=s.current,i={}){let t;try{t=await n.list()}catch(r){const c=n.lastList();if(c===null)throw new d("provider_unavailable",`The directory could not be reached to find your devices: ${r instanceof Error?r.message:String(r)}`,{origin:"directory"});t=c}const o=t.filter(r=>r.kind==="device");if(o.length===0)throw new d("provider_not_connected","No device is connected to this account. Install Northlight Desktop on your Mac and sign in.",{origin:"directory"});if(e!==void 0){const r=p(e),c=o.find(h=>h.machine_id===r);if(!c)throw u(o,e);return c}if(o.length>1&&i.newest===!0)return o.reduce((r,c)=>_(c)>_(r)?c:r);if(o.length>1)throw u(o,void 0);return o[0]}a(E,"selectDevice");function w(e){return{tool:e.tool,arguments:e.arguments,version:e.version,request_id:e.requestId,...e.runId===null?{}:{run_id:e.runId},deadline_at:e.deadlineAt,...e.upload===null?{}:{upload:e.upload}}}a(w,"deviceBody");async function b(e,n,i,t,o=s.current){const r=Math.max(1,n.deadlineAt-Date.now());return o.call(e.machine_id,{method:"POST",path:v,body:w(n)},{envelope:i,device:!0,signal:AbortSignal.any([t,AbortSignal.timeout(r)])})}a(b,"sendDeviceCall");function k(e,n,i){switch(n){case"timeout":return new d("device_timeout",`${e.name} did not answer in time.`,{origin:"runtime",details:{machine_id:e.machine_id}});case"directory_unreachable":case"no_directory":return new d("provider_unavailable",i,{origin:"directory"});case"unknown_machine":return new d("provider_not_connected",`${e.name} is no longer on this account.`,{origin:"directory"});case"not_a_crtr_peer":return new d("server_error",i);default:return new d("device_offline",i.trim()===""?`${e.name} is offline.`:i,{origin:"runtime",details:{machine_id:e.machine_id}})}}a(k,"deviceUnreachable");function I(e,n,i,t,o){if(n===401)return new d("device_offline",`${e.name}: Desktop is signed out. Sign in to Northlight Desktop again.`,{origin:"runtime",details:{machine_id:e.machine_id}});if(n===426){const r=o?.error?.details?.supported;return new d("peer_version_too_old",t??`${e.name} does not serve this device major. Update Northlight Desktop.`,{origin:"runtime",details:{machine_id:e.machine_id,...Array.isArray(r)?{supported:r}:{}}})}return n===502&&i==="machine_disconnected"?new d("device_disconnected",`${e.name} disconnected during the call; the action may have run.`,{origin:"runtime",details:{machine_id:e.machine_id}}):i==="payload_too_large"||i==="response_too_large"?new d("provider_error",t??"The call or its answer was too large for the relay (16 MiB).",{origin:"runtime",status:413,details:{code:i,message:t??null,status:n}}):null}a(I,"deviceFailure");export{x as DEFAULT_DEVICE_REQUEST_MS,v as DEVICE_CALL_PATH,w as deviceBody,s as deviceDeps,I as deviceFailure,k as deviceUnreachable,E as selectDevice,b as sendDeviceCall};
@@ -1 +1 @@
1
- var y=Object.defineProperty;var d=(i,t)=>y(i,"name",{value:t,configurable:!0});import{RunError as _}from"../runs/operations.js";import{errorCodes as r}from"../../api/error-codes.js";const g={provider_error:{type:"invalid_request_error",status:400,retryable:!1},provider_rate_limited:r.provider_rate_limited,provider_unavailable:r.provider_unavailable,provider_refused:r.provider_refused,provider_not_connected:r.provider_not_connected,provider_version_retired:r.provider_version_retired,storage_unavailable:r.storage_unavailable,approval_pending:{...r.approval_pending,user_action:"answer_question"},user_denied:r.user_denied},b={unauthorized:r.unauthorized,grant_revoked:r.grant_revoked,machine_revoked:r.machine_revoked,scope_missing:r.scope_missing,permission_error:r.permission_error,invalid_request:r.invalid_request,not_found:r.not_found,not_implemented:r.not_implemented,runtime_starting:r.runtime_starting,server_error:r.server_error,provider_bad_response:r.provider_bad_response,invalid_argument:r.invalid_argument,machine_required:r.machine_required,device_offline:r.device_offline,device_timeout:r.device_timeout,device_disconnected:r.device_disconnected,peer_version_too_old:r.peer_version_too_old};function a(i,t){return g[i]??b[i]??(Object.prototype.hasOwnProperty.call(r,i)?r[i]:void 0)??{type:t===401?"authentication_error":t===403?"permission_error":t===429?"rate_limit_error":t>=500?"server_error":"invalid_request_error",status:t,retryable:t>=500}}d(a,"codeRow");class u extends _{static{d(this,"ProviderError")}origin;type;retry_after_s;question_id;user_action;run_id;constructor(t,s,n={}){const e=a(t,n.status??500);super(n.status??e.status,t,s,n.param,n.details,n.scope,e.retryable),this.type=e.type,this.origin=n.origin??"runtime",n.retry_after_s!==void 0&&(this.retry_after_s=n.retry_after_s),n.question_id!==void 0&&(this.question_id=n.question_id),n.run_id!==void 0&&(this.run_id=n.run_id),e.user_action!==void 0&&(this.user_action=e.user_action)}}function O(i){return new u("scope_missing",`missing scope ${i}`,{scope:i})}d(O,"scopeMissing");function q(i){if(!(i instanceof Error))return null;const{status:t,code:s,details:n,retryable:e}=i;return typeof t!="number"||typeof s!="string"||t<400||t>599?null:new _(t,s,i.message,void 0,n,void 0,typeof e=="boolean"?e:a(s,t).retryable)}d(q,"shaped");function h(i){if(i.code==="unauthorized"||i.code==="grant_revoked")return"reconnect";if(i.code==="scope_missing"&&i.scope)return`grant_scope:${i.scope}`}d(h,"directoryAction");function k(i,t,s,n){const e=i instanceof _?i:q(i)??new u("server_error","provider request failed"),o=e instanceof u?e:null,v=a(e.code,e.status),c=o?.run_id??n,p=o?.user_action??(e.code==="cap_exhausted"?"raise_cap":s?h(e):void 0),f=e.code==="cap_exhausted"?e.details?.reset_at:void 0,m={code:e.code,message:e.message,...e.details===void 0?{}:{details:e.details},type:o?.type??v.type,...e.param?{param:e.param}:{},origin:o?.origin??"runtime",retryable:e.retryable,...o?.retry_after_s===void 0?{}:{retry_after_s:o.retry_after_s},...typeof f=="string"?{reset_at:f}:{},request_id:t,...c?{run_id:c}:{},...o?.question_id?{question_id:o.question_id}:{},...p?{user_action:p}:{},...e.scope?{scope:e.scope}:{}},l={"Request-Id":t};return o?.retry_after_s!==void 0&&(l["Retry-After"]=String(o.retry_after_s)),{status:e.status,body:{error:m},headers:l}}d(k,"providerErrorBody");export{g as PROVIDER_CODES,u as ProviderError,a as codeRow,k as providerErrorBody,O as scopeMissing};
1
+ var m=Object.defineProperty;var _=(t,i)=>m(t,"name",{value:i,configurable:!0});import{RunError as d}from"../runs/operations.js";import{errorCodes as r}from"../../api/error-codes.js";const g={provider_error:{type:"invalid_request_error",status:400,retryable:!1},provider_rate_limited:r.provider_rate_limited,provider_unavailable:r.provider_unavailable,provider_refused:r.provider_refused,provider_not_connected:r.provider_not_connected,provider_version_retired:r.provider_version_retired,storage_unavailable:r.storage_unavailable,approval_pending:{...r.approval_pending,user_action:"answer_question"},user_denied:r.user_denied},b={unauthorized:r.unauthorized,grant_revoked:r.grant_revoked,machine_revoked:r.machine_revoked,scope_missing:r.scope_missing,permission_error:r.permission_error,invalid_request:r.invalid_request,not_found:r.not_found,not_implemented:r.not_implemented,runtime_starting:r.runtime_starting,server_error:r.server_error,provider_bad_response:r.provider_bad_response,invalid_argument:r.invalid_argument,machine_required:r.machine_required,device_offline:r.device_offline,device_timeout:r.device_timeout,device_disconnected:r.device_disconnected,peer_version_too_old:r.peer_version_too_old,outcome_unknown:{type:"invalid_request_error",status:409,retryable:!1},wrong_site:{type:"invalid_request_error",status:409,retryable:!1},site_signed_out:{type:"invalid_request_error",status:409,retryable:!1},js_exception:{type:"invalid_request_error",status:409,retryable:!1},lib_broken:{type:"server_error",status:502,retryable:!1}};function a(t,i){return g[t]??b[t]??(Object.prototype.hasOwnProperty.call(r,t)?r[t]:void 0)??{type:i===401?"authentication_error":i===403?"permission_error":i===429?"rate_limit_error":i>=500?"server_error":"invalid_request_error",status:i,retryable:i>=500}}_(a,"codeRow");class u extends d{static{_(this,"ProviderError")}origin;type;retry_after_s;question_id;user_action;run_id;constructor(i,o,n={}){const e=a(i,n.status??500);super(n.status??e.status,i,o,n.param,n.details,n.scope,e.retryable),this.type=e.type,this.origin=n.origin??"runtime",n.retry_after_s!==void 0&&(this.retry_after_s=n.retry_after_s),n.question_id!==void 0&&(this.question_id=n.question_id),n.run_id!==void 0&&(this.run_id=n.run_id),e.user_action!==void 0&&(this.user_action=e.user_action)}}function R(t){return new u("scope_missing",`missing scope ${t}`,{scope:t})}_(R,"scopeMissing");function q(t){if(!(t instanceof Error))return null;const{status:i,code:o,details:n,retryable:e}=t;return typeof i!="number"||typeof o!="string"||i<400||i>599?null:new d(i,o,t.message,void 0,n,void 0,typeof e=="boolean"?e:a(o,i).retryable)}_(q,"shaped");function h(t){if(t.code==="unauthorized"||t.code==="grant_revoked")return"reconnect";if(t.code==="scope_missing"&&t.scope)return`grant_scope:${t.scope}`}_(h,"directoryAction");function w(t,i,o,n){const e=t instanceof d?t:q(t)??new u("server_error","provider request failed"),s=e instanceof u?e:null,v=a(e.code,e.status),c=s?.run_id??n,p=s?.user_action??(e.code==="cap_exhausted"?"raise_cap":o?h(e):void 0),l=e.code==="cap_exhausted"?e.details?.reset_at:void 0,y={code:e.code,message:e.message,...e.details===void 0?{}:{details:e.details},type:s?.type??v.type,...e.param?{param:e.param}:{},origin:s?.origin??"runtime",retryable:e.retryable,...s?.retry_after_s===void 0?{}:{retry_after_s:s.retry_after_s},...typeof l=="string"?{reset_at:l}:{},request_id:i,...c?{run_id:c}:{},...s?.question_id?{question_id:s.question_id}:{},...p?{user_action:p}:{},...e.scope?{scope:e.scope}:{}},f={"Request-Id":i};return s?.retry_after_s!==void 0&&(f["Retry-After"]=String(s.retry_after_s)),{status:e.status,body:{error:y},headers:f}}_(w,"providerErrorBody");export{g as PROVIDER_CODES,u as ProviderError,a as codeRow,w as providerErrorBody,R as scopeMissing};
@@ -1,14 +1,14 @@
1
- var _e=Object.defineProperty;var s=(t,n)=>_e(t,"name",{value:n,configurable:!0});import{startPeerOutbox as ke}from"./peer/outbox.js";import{reportMachineStatus as Ee}from"../core/peer/directory.js";import{createPeerRelay as Re}from"./peer/relay-service.js";import{writeFileSync as xe,readFileSync as Pe,rmSync as Ie,mkdirSync as Z,existsSync as k,chmodSync as Te}from"node:fs";import{createServer as ee}from"node:http";import{dirname as De}from"node:path";import{envCrtrdTcp as Ce}from"../shared/env.js";import{serveCanvasConversationStore as Le}from"../core/canvas/sessions.js";import{pollRunObservers as $e}from"./runs/observer.js";import{randomBytes as Ae}from"node:crypto";import{apiSocketPath as Ne,crtrHome as Me}from"../core/canvas/paths.js";import{activeAppUsers as Oe}from"../core/spaces/users.js";import{ensureAppSpace as Ge,ensureUserFiles as Fe}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as x}from"../launcher/spec.js";import{launcherRequest as I}from"../launcher/client.js";import{installLauncherEventSink as He}from"./launcher-events.js";import{initializeEmptyLayout as Be,layoutNeedsMigration as je,socketDir as re}from"../core/layout.js";import{migrateLooseKeys as qe}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as ze}from"../core/profiles/relocate.js";import{getNode as We,listNodesForSupervision as Ue,setFrozen as Ke}from"../core/canvas/index.js";import{createApiServer as Je}from"./api/server.js";import{createAppListener as Ve}from"./api/app-listener.js";import{installLocalTerminalGrant as Qe}from"../core/grants/local.js";import{onRunEventAppended as Ye}from"../core/runs/events.js";import{runNotices as Xe}from"./run-notices.js";import{createGrantSync as Ze,GRANT_SYNC_INTERVAL_S as er}from"../core/grants/sync.js";import{runRemovalCascades as rr}from"../core/grants/remove.js";import{sweepSandboxes as tr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as nr}from"./cron/run-socket.js";import{hasSyncedGrants as or}from"../core/grants/mirror.js";import{readConfig as ir}from"../core/config.js";import{reconcileUndeliveredTickets as sr}from"./human/sweep.js";import{resetHandedOffDeliveries as ar}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as cr}from"../core/canvas/daemon-actions.js";import{sweepReviews as dr}from"./review/sweep.js";import{pidfilePath as F}from"./pidfile.js";import{rendererWarning as lr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as pr}from"./supervise-cadence.js";import{createResumeDetector as mr}from"./resume-detector.js";import{BrokerSupervisionReconciler as fr}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as ur}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as hr}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as vr}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as wr}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as gr}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as yr}from"./reconcilers/action-lane.js";import{endLiveExecution as Sr,migrateLegacyExecutionIdentities as br}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _r}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as kr}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as Er}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rr}from"./reconcilers/storage-due-work.js";import{BashDeadlineReconciler as xr}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Pr}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Ir}from"./reconcilers/structured-request-lane.js";import{reconcileStructuredRequestSidecars as Tr}from"./structured-requests/boot.js";import{captureLivenessSnapshot as te,capturePidCommand as Dr,captureTeardownSnapshot as ne,isPidAlive as Cr,isAnyPidAlive as oe,killProcessTreePids as ie}from"../core/canvas/pid.js";import{bindFleet as Lr,boundFleet as $r}from"../core/runtime/fleet.js";import{bindDaemonControl as Ar,clearDaemonControl as Nr}from"./control.js";import{execDaemon as Mr,spawnDaemon as Or}from"./manage.js";import{reconcileAndMigrateBoot as Gr}from"../core/canvas/boot.js";import{resolveInstallId as Fr}from"../core/canvas/install-id.js";import{setInstallId as Hr}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Br,releaseDaemonOwnership as se}from"../core/canvas/daemon-owner.js";import{migrate as jr,openDb as ae,withCanvasWrite as qr,bindDaemonCanvasOpenHook as zr,clearDaemonCanvasOpenHook as ce}from"../core/canvas/db.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Wr}from"./api/handlers/broker-signals.js";import{reconcilePackageDocuments as Ur}from"../core/graph/package-docs.js";import{startRepoSync as Kr}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as Jr,reapStaleSpares as Vr}from"../core/runtime/warm-pool.js";import{DaemonFleet as Qr}from"./fleet.js";import{BOOT_MIGRATIONS as Yr}from"./boot-migrations.js";import{applyJoinedOwner as Xr}from"./joined-owner.js";import{emitEvent as u}from"../core/events/emit.js";import{operationIdContext as b}from"../core/events/operation-id.js";import{bindDaemonEventSource as Zr}from"../core/events/source.js";import{activateCanvasImport as et,MigrationBlockedError as rt,runForcedCanvasImport as tt}from"../migrations/activation.js";import{convertLegacyProviderStore as nt,convertLegacyScopedStore as ot}from"../core/scoped-state/migrate.js";import{userScopeRoot as it}from"../core/scope.js";import{secretsDir as st}from"../core/layout.js";function B(t,n){return t.includes(` --canvas-home ${n} `)}s(B,"brokerCommandDeclaresCanvasHome");function j(t){return/ --epoch (\S+) /.exec(t)?.[1]??null}s(j,"brokerCommandEpoch");const at=5e3,de=150;async function ct(t){const n=te();if(n===null)throw u({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const a=Me(),m=[];for(const[i,p]of n.processes){const y=p.command;if(p.zombie||!y.includes("broker-cli.js")||!B(y,a)||j(y)===t)continue;const S=y.trim().split(/\s+/).at(-1)??"";S===""||S.endsWith("broker-cli.js")||m.push({pid:i,nodeId:S})}let f=0;const o=[];for(const i of m){const p=Dr(i.pid);if(p===null||!p.includes("broker-cli.js")||!B(p,a)||j(p)===t||p.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const y=ne(i.pid,null);if(!y.reused){try{process.platform==="linux"&&k(x)?await I({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}f++,o.push({pid:i.pid,snap:y})}}const g=Date.now()+at;for(;Date.now()<g&&o.some(i=>oe(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,de));let v=0;for(const i of o){const p=i.snap.tree.length>0?i.snap.tree:[i.pid];oe(p)&&(process.platform==="linux"&&k(x)?await I({operation:"stop",pid:i.pid}):ie(p,"SIGKILL",i.snap.identities),v++)}v>0&&await new Promise(i=>setTimeout(i,de));const d=te();if(d===null)throw u({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const l=[];for(const[i,p]of d.processes){const y=p.command;p.zombie||!y.includes("broker-cli.js")||B(y,a)&&j(y)!==t&&l.push(i)}if(l.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${l.join(", ")}`);u({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:f,sigkilled:v}})}s(ct,"reapPriorEpochBrokers");const dt=5e3;async function lt(t){const n=Array.from(t.entries());if(n.length===0)return;for(const[o]of n){const g=We(o)?.status;(g==="active"||g==="idle")&&Ke(o,new Date().toISOString())}const a=n.map(([,o])=>({pid:o.pid,snap:ne(o.pid,null),exited:o.handle.exited}));for(const o of a)if(!o.snap.reused)try{process.platform==="linux"&&k(x)?await I({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,dt).unref()});await Promise.allSettled(a.map(o=>Promise.race([o.exited.then(()=>{}),m])));const f=[];for(const o of a)Cr(o.pid)&&(process.platform==="linux"&&k(x)?await I({operation:"stop",pid:o.pid}):ie(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),f.push(o));await Promise.all(f.map(o=>o.exited));for(const[o]of n)Sr(o,{reason:"daemon-teardown"});u({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:a.length,sigkilled:f.length}})}s(lt,"teardownFleet");function le(){Z(De(F()),{recursive:!0}),xe(F(),String(process.pid),"utf8")}s(le,"writePidfile");function pe(t){return typeof t=="object"&&t!==null&&t.code==="ENOENT"}s(pe,"isMissingPathError");function me(t){const n=F();let a;try{a=Pe(n,"utf8")}catch(m){if(pe(m))return;throw m}if(a.trim()!==String(t))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${t})`);try{Ie(n)}catch(m){if(pe(m))return;throw m}}s(me,"removeOwnedPidfileMirror");const pt={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(t=>{t.catch(()=>{})},"registerDetached")},q=new fr,mt=new ur,ft=new hr,ut=new vr,ht=new wr,vt=new gr,wt=new yr,gt=new kr,yt=new Er,St=new Rr,bt=new xr,_t=new Pr,kt=new Ir;async function Et(t=Date.now(),n=pt){const a=$r(),m=await q.runFleetPreamble(a);let f,o;try{const v=Ue();f=v.filter(d=>d.status==="active"||d.status==="idle"),o=v.filter(d=>d.status==="done"||d.status==="canceled"||d.status==="dead")}catch(v){u({level:"error",event:"canvas.node_list.failed",error:v});return}await q.run(t,{rows:f,fleet:a,lifecycle:n}),mt.run(t,{rows:f});const g=await ft.run(t,{rows:[...f,...o],fleet:a});ut.run(t),kt.run(t),ht.run(t,{lifecycle:n}),vt.run(t,{lifecycle:n}),wt.run(t,{lifecycle:n}),gt.run(t,{lifecycle:n}),yt.run(t,{lifecycle:n,fleet:a}),St.run(t,{lifecycle:n}),$e(),_t.run(t,{fleet:a,lifecycle:n}),await bt.run(t,{rows:f}),q.warnIfSaturated({fleet:a,lifecycle:n,thresholds:m,frozen:g})}s(Et,"superviseTick");async function Rt(t){Z(re(),{recursive:!0,mode:493}),process.platform==="linux"&&Te(re(),493);const n=Ne();if(k(n))throw new Error(`layout refusal cannot bind occupied socket: ${n}`);const a=ee((d,l)=>{if(d.method==="GET"&&d.url==="/healthz"){l.writeHead(200,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}l.writeHead(503,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,l)=>{a.once("error",l),a.listen(n,()=>{a.off("error",l),d()})});let m;const f=t.tcp??Ce();if(f){const d=/^(.*):(\d+)$/.exec(f);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${f}`);const l=ee(a.listeners("request")[0]);await new Promise((i,p)=>{l.once("error",p),l.listen(Number(d[2]),d[1],()=>{l.off("error",p),i()})}),m=l}le();let o;const g=s(()=>(o??=(async()=>{a.closeAllConnections(),m?.closeAllConnections(),await Promise.all([a,m].filter(d=>d!==void 0).map(d=>new Promise((l,i)=>d.close(p=>p?i(p):l())))),me(process.pid),process.off("SIGINT",v),process.off("SIGTERM",v)})(),o),"cleanup"),v=s(()=>{g().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
2
- `),process.exit(1)})},"onSignal");return process.on("SIGINT",v),process.on("SIGTERM",v),g}s(Rt,"serveLayoutRefusal");async function xt(t={}){if(je())return Rt(t);Be();const n=Br(Ae(16).toString("hex"));if(!n.claimed){if(n.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${n.incumbentPid??"?"})
3
- `);else{const r=[n.incumbentPid!==void 0?`pid ${n.incumbentPid}`:void 0,n.verdict!==void 0?`verdict ${n.verdict}`:void 0].filter(c=>c!==void 0),e=r.length>0?` (${r.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${n.reason}${e}
4
- `),n.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(n.reason==="own_identity_indeterminate"||n.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const a=n.claim;let m=null;try{await ct(a.token),ot({kind:"user",root:it()});for(const e of ze())process.stderr.write(`[crtrd] ${e}
5
- `);if(process.platform==="darwin"){const{readConfig:e,updateConfig:c}=await import("../core/config.js");if(e("user").paths?.user_files===void 0){const{homedir:w}=await import("node:os");c("user",X=>{X.paths??={},X.paths.user_files??=w()})}}await nt(st());for(const e of qe())process.stderr.write(`[crtrd] ${e}
6
- `);jr(ae()),zr(e=>H.install(e));const r=qr(e=>Ur(e));for(const e of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${e.message}
1
+ var Ee=Object.defineProperty;var a=(t,n)=>Ee(t,"name",{value:n,configurable:!0});import{startPeerOutbox as Re}from"./peer/outbox.js";import{reportMachineStatus as xe}from"../core/peer/directory.js";import{createPeerRelay as Pe}from"./peer/relay-service.js";import{writeFileSync as Ie,readFileSync as De,rmSync as Te,mkdirSync as Z,existsSync as k,chmodSync as Ce}from"node:fs";import{createServer as ee}from"node:http";import{dirname as Le}from"node:path";import{envCrtrdTcp as $e}from"../shared/env.js";import{serveCanvasConversationStore as Ae}from"../core/canvas/sessions.js";import{pollRunObservers as Ne}from"./runs/observer.js";import{randomBytes as Me}from"node:crypto";import{apiSocketPath as Oe,crtrHome as Ge}from"../core/canvas/paths.js";import{activeAppUsers as Fe}from"../core/spaces/users.js";import{ensureAppSpace as He,ensureUserFiles as Be}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as x}from"../launcher/spec.js";import{launcherRequest as I}from"../launcher/client.js";import{installLauncherEventSink as je}from"./launcher-events.js";import{initializeEmptyLayout as qe,layoutNeedsMigration as ze,socketDir as re}from"../core/layout.js";import{migrateLooseKeys as We}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Ue}from"../core/profiles/relocate.js";import{getNode as Ke,listNodesForSupervision as te,setFrozen as ne}from"../core/canvas/index.js";import{createApiServer as Je}from"./api/server.js";import{createAppListener as Ve}from"./api/app-listener.js";import{installLocalTerminalGrant as Qe}from"../core/grants/local.js";import{onRunEventAppended as Ye}from"../core/runs/events.js";import{runNotices as Xe}from"./run-notices.js";import{createGrantSync as Ze,GRANT_SYNC_INTERVAL_S as er}from"../core/grants/sync.js";import{runRemovalCascades as rr}from"../core/grants/remove.js";import{sweepSandboxes as tr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as nr}from"./cron/run-socket.js";import{hasSyncedGrants as or}from"../core/grants/mirror.js";import{readConfig as ir}from"../core/config.js";import{reconcileUndeliveredTickets as sr}from"./human/sweep.js";import{resetHandedOffDeliveries as ar}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as cr}from"../core/canvas/daemon-actions.js";import{sweepReviews as dr}from"./review/sweep.js";import{pidfilePath as F}from"./pidfile.js";import{rendererWarning as lr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as pr}from"./supervise-cadence.js";import{createResumeDetector as mr}from"./resume-detector.js";import{BrokerSupervisionReconciler as fr}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as ur}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as hr}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as vr}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as wr}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as gr}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as yr}from"./reconcilers/action-lane.js";import{endLiveExecution as Sr,migrateLegacyExecutionIdentities as _r}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as br}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as kr}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as Er}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rr}from"./reconcilers/storage-due-work.js";import{BashDeadlineReconciler as xr}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Pr}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Ir}from"./reconcilers/structured-request-lane.js";import{reconcileStructuredRequestSidecars as Dr}from"./structured-requests/boot.js";import{captureLivenessSnapshot as oe,capturePidCommand as Tr,captureTeardownSnapshot as ie,isPidAlive as Cr,isAnyPidAlive as se,killProcessTreePids as ae}from"../core/canvas/pid.js";import{bindFleet as Lr,boundFleet as $r}from"../core/runtime/fleet.js";import{bindDaemonControl as Ar,clearDaemonControl as Nr}from"./control.js";import{execDaemon as Mr,spawnDaemon as Or}from"./manage.js";import{reconcileAndMigrateBoot as Gr}from"../core/canvas/boot.js";import{resolveInstallId as Fr}from"../core/canvas/install-id.js";import{setInstallId as Hr}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Br,releaseDaemonOwnership as ce}from"../core/canvas/daemon-owner.js";import{migrate as jr,openDb as de,withCanvasWrite as qr,bindDaemonCanvasOpenHook as zr,clearDaemonCanvasOpenHook as le}from"../core/canvas/db.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Wr}from"./api/handlers/broker-signals.js";import{reconcilePackageDocuments as Ur}from"../core/graph/package-docs.js";import{startRepoSync as Kr}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as Jr,reapStaleSpares as Vr}from"../core/runtime/warm-pool.js";import{DaemonFleet as Qr}from"./fleet.js";import{BOOT_MIGRATIONS as Yr}from"./boot-migrations.js";import{applyJoinedOwner as Xr}from"./joined-owner.js";import{emitEvent as u}from"../core/events/emit.js";import{operationIdContext as S}from"../core/events/operation-id.js";import{bindDaemonEventSource as Zr}from"../core/events/source.js";import{activateCanvasImport as et,MigrationBlockedError as rt,runForcedCanvasImport as tt}from"../migrations/activation.js";import{convertLegacyProviderStore as nt,convertLegacyScopedStore as ot}from"../core/scoped-state/migrate.js";import{userScopeRoot as it}from"../core/scope.js";import{secretsDir as st}from"../core/layout.js";function B(t,n){return t.includes(` --canvas-home ${n} `)}a(B,"brokerCommandDeclaresCanvasHome");function j(t){return/ --epoch (\S+) /.exec(t)?.[1]??null}a(j,"brokerCommandEpoch");const at=5e3,pe=150;async function ct(t){const n=oe();if(n===null)throw u({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const c=Ge(),m=[];for(const[s,p]of n.processes){const y=p.command;if(p.zombie||!y.includes("broker-cli.js")||!B(y,c)||j(y)===t)continue;const _=y.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||m.push({pid:s,nodeId:_})}let f=0;const o=[];for(const s of m){const p=Tr(s.pid);if(p===null||!p.includes("broker-cli.js")||!B(p,c)||j(p)===t||p.trim().split(/\s+/).at(-1)!==s.nodeId)continue;const y=ie(s.pid,null);if(!y.reused){try{process.platform==="linux"&&k(x)?await I({operation:"stop",pid:s.pid}):process.kill(s.pid,"SIGTERM")}catch{continue}f++,o.push({pid:s.pid,snap:y})}}const g=Date.now()+at;for(;Date.now()<g&&o.some(s=>se(s.snap.tree.length>0?s.snap.tree:[s.pid]));)await new Promise(s=>setTimeout(s,pe));let v=0;for(const s of o){const p=s.snap.tree.length>0?s.snap.tree:[s.pid];se(p)&&(process.platform==="linux"&&k(x)?await I({operation:"stop",pid:s.pid}):ae(p,"SIGKILL",s.snap.identities),v++)}v>0&&await new Promise(s=>setTimeout(s,pe));const d=oe();if(d===null)throw u({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const l=[];for(const[s,p]of d.processes){const y=p.command;p.zombie||!y.includes("broker-cli.js")||B(y,c)&&j(y)!==t&&l.push(s)}if(l.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${l.join(", ")}`);u({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:f,sigkilled:v}})}a(ct,"reapPriorEpochBrokers");const dt=5e3;async function lt(t){const n=Array.from(t.entries());if(n.length===0)return;for(const[o]of n){const g=Ke(o)?.status;(g==="active"||g==="idle")&&ne(o,new Date().toISOString())}const c=n.map(([,o])=>({pid:o.pid,snap:ie(o.pid,null),exited:o.handle.exited}));for(const o of c)if(!o.snap.reused)try{process.platform==="linux"&&k(x)?await I({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,dt).unref()});await Promise.allSettled(c.map(o=>Promise.race([o.exited.then(()=>{}),m])));const f=[];for(const o of c)Cr(o.pid)&&(process.platform==="linux"&&k(x)?await I({operation:"stop",pid:o.pid}):ae(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),f.push(o));await Promise.all(f.map(o=>o.exited));for(const[o]of n)Sr(o,{reason:"daemon-teardown"});u({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:c.length,sigkilled:f.length}})}a(lt,"teardownFleet");function me(){Z(Le(F()),{recursive:!0}),Ie(F(),String(process.pid),"utf8")}a(me,"writePidfile");function fe(t){return typeof t=="object"&&t!==null&&t.code==="ENOENT"}a(fe,"isMissingPathError");function ue(t){const n=F();let c;try{c=De(n,"utf8")}catch(m){if(fe(m))return;throw m}if(c.trim()!==String(t))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${t})`);try{Te(n)}catch(m){if(fe(m))return;throw m}}a(ue,"removeOwnedPidfileMirror");const pt={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(t=>{t.catch(()=>{})},"registerDetached")},q=new fr,mt=new ur,ft=new hr,ut=new vr,ht=new wr,vt=new gr,wt=new yr,gt=new kr,yt=new Er,St=new Rr,_t=new xr,bt=new Pr,kt=new Ir;async function Et(t=Date.now(),n=pt){const c=$r(),m=await q.runFleetPreamble(c);let f,o;try{const v=te();f=v.filter(d=>d.status==="active"||d.status==="idle"),o=v.filter(d=>d.status==="done"||d.status==="canceled"||d.status==="dead")}catch(v){u({level:"error",event:"canvas.node_list.failed",error:v});return}await q.run(t,{rows:f,fleet:c,lifecycle:n}),mt.run(t,{rows:f});const g=await ft.run(t,{rows:[...f,...o],fleet:c});ut.run(t),kt.run(t),ht.run(t,{lifecycle:n}),vt.run(t,{lifecycle:n}),wt.run(t,{lifecycle:n}),gt.run(t,{lifecycle:n}),yt.run(t,{lifecycle:n,fleet:c}),St.run(t,{lifecycle:n}),Ne(),bt.run(t,{fleet:c,lifecycle:n}),await _t.run(t,{rows:f}),q.warnIfSaturated({fleet:c,lifecycle:n,thresholds:m,frozen:g})}a(Et,"superviseTick");async function Rt(t){Z(re(),{recursive:!0,mode:493}),process.platform==="linux"&&Ce(re(),493);const n=Oe();if(k(n))throw new Error(`layout refusal cannot bind occupied socket: ${n}`);const c=ee((d,l)=>{if(d.method==="GET"&&d.url==="/healthz"){l.writeHead(200,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}l.writeHead(503,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,l)=>{c.once("error",l),c.listen(n,()=>{c.off("error",l),d()})});let m;const f=t.tcp??$e();if(f){const d=/^(.*):(\d+)$/.exec(f);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${f}`);const l=ee(c.listeners("request")[0]);await new Promise((s,p)=>{l.once("error",p),l.listen(Number(d[2]),d[1],()=>{l.off("error",p),s()})}),m=l}me();let o;const g=a(()=>(o??=(async()=>{c.closeAllConnections(),m?.closeAllConnections(),await Promise.all([c,m].filter(d=>d!==void 0).map(d=>new Promise((l,s)=>d.close(p=>p?s(p):l())))),ue(process.pid),process.off("SIGINT",v),process.off("SIGTERM",v)})(),o),"cleanup"),v=a(()=>{g().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
2
+ `),process.exit(1)})},"onSignal");return process.on("SIGINT",v),process.on("SIGTERM",v),g}a(Rt,"serveLayoutRefusal");async function xt(t={}){if(ze())return Rt(t);qe();const n=Br(Me(16).toString("hex"));if(!n.claimed){if(n.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${n.incumbentPid??"?"})
3
+ `);else{const r=[n.incumbentPid!==void 0?`pid ${n.incumbentPid}`:void 0,n.verdict!==void 0?`verdict ${n.verdict}`:void 0].filter(i=>i!==void 0),e=r.length>0?` (${r.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${n.reason}${e}
4
+ `),n.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(n.reason==="own_identity_indeterminate"||n.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const c=n.claim;let m=null;try{await ct(c.token),ot({kind:"user",root:it()});for(const e of Ue())process.stderr.write(`[crtrd] ${e}
5
+ `);if(process.platform==="darwin"){const{readConfig:e,updateConfig:i}=await import("../core/config.js");if(e("user").paths?.user_files===void 0){const{homedir:w}=await import("node:os");i("user",X=>{X.paths??={},X.paths.user_files??=w()})}}await nt(st());for(const e of We())process.stderr.write(`[crtrd] ${e}
6
+ `);jr(de()),zr(e=>H.install(e));const r=qr(e=>Ur(e));for(const e of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${e.message}
7
7
  `);for(const e of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${e.path}: ${e.error}
8
8
  `);for(const e of r.quarantined)process.stderr.write(`[crtrd] plugin "${e.name}" has a damaged ${e.file} (${e.reason}); ${e.movedTo!==void 0?`moved to ${e.movedTo}`:"left in place and skipped"}
9
- `);m=Xr(),process.platform==="linux"&&k(x)&&(He(),await I({operation:"users.sync",users:Oe()})),_r(a.token)}catch(r){ce(),H.close();try{const{released:e}=se(a);if(!e)throw new Error("daemon ownership claim was not released")}catch(e){throw new AggregateError([r,e],"daemon startup failed and cleanup also failed")}throw r}let f=!0,o,g=Promise.resolve(),v=!1,d,l;const i=new Set;let p=!1,y=!1,S,$,z=!1,A,T,D,C,M;const fe=mr();let E,h={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},P="initial startup activation",ue=null;function he(){return h.phase==="ready"?null:{phase:h.phase,message:h.message,blockerPaths:h.blockerPaths}}s(he,"startupBlock");function _(r){i.add(r),r.finally(()=>{i.delete(r)}).catch(()=>{})}s(_,"registerDetached");const W={acceptsDetachedWork:s(()=>f,"acceptsDetachedWork"),registerDetached:_};Kr(W,ae);async function ve(){try{f=!1,Wr.close(),ce(),H.close(),d!==void 0&&(clearInterval(d),d=void 0),D!==void 0&&(clearInterval(D),D=void 0),M?.(),M=void 0;let r;do r=g,await r;while(r!==g);for(;i.size>0;)await Promise.allSettled([...i]);if(l!==void 0&&(await lt(l),l.dispose()),$!==void 0&&!z&&(z=!0,await $.close()),C!==void 0){const e=C;C=void 0,await e.stop()}if(T!==void 0){const e=T;T=void 0,await e.close()}if(A!==void 0){const e=A;A=void 0,await e.close()}if(p||(me(process.pid),p=!0),p&&!y){const{released:e}=se(a);if(!e)throw new Error("daemon ownership claim was not released");y=!0}}finally{Nr(),process.off("SIGINT",J),process.off("SIGTERM",V),process.off("exit",Q)}}s(ve,"cleanupAttempt");const N=1e3;let U=!1;function we(){return U?{graceMs:N}:(U=!0,b.fresh(()=>{u({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:N}})}),setTimeout(()=>{ge()},N),{graceMs:N})}s(we,"requestHandover");async function ge(){try{await R()}catch(r){const e=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
9
+ `);m=Xr(),process.platform==="linux"&&k(x)&&(je(),await I({operation:"users.sync",users:Fe()})),br(c.token)}catch(r){le(),H.close();try{const{released:e}=ce(c);if(!e)throw new Error("daemon ownership claim was not released")}catch(e){throw new AggregateError([r,e],"daemon startup failed and cleanup also failed")}throw r}let f=!0,o,g=Promise.resolve(),v=!1,d,l;const s=new Set;let p=!1,y=!1,_,$,z=!1,A,D,T,C,M;const he=mr();let E,h={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},P="initial startup activation",ve=null;function we(){return h.phase==="ready"?null:{phase:h.phase,message:h.message,blockerPaths:h.blockerPaths}}a(we,"startupBlock");function b(r){s.add(r),r.finally(()=>{s.delete(r)}).catch(()=>{})}a(b,"registerDetached");const W={acceptsDetachedWork:a(()=>f,"acceptsDetachedWork"),registerDetached:b};Kr(W,de);async function ge(){try{f=!1,Wr.close(),le(),H.close(),d!==void 0&&(clearInterval(d),d=void 0),T!==void 0&&(clearInterval(T),T=void 0),M?.(),M=void 0;let r;do r=g,await r;while(r!==g);for(;s.size>0;)await Promise.allSettled([...s]);if(l!==void 0&&(await lt(l),l.dispose()),$!==void 0&&!z&&(z=!0,await $.close()),C!==void 0){const e=C;C=void 0,await e.stop()}if(D!==void 0){const e=D;D=void 0,await e.close()}if(A!==void 0){const e=A;A=void 0,await e.close()}if(p||(ue(process.pid),p=!0),p&&!y){const{released:e}=ce(c);if(!e)throw new Error("daemon ownership claim was not released");y=!0}}finally{Nr(),process.off("SIGINT",J),process.off("SIGTERM",V),process.off("exit",Q)}}a(ge,"cleanupAttempt");const N=1e3;let U=!1;function ye(){return U?{graceMs:N}:(U=!0,S.fresh(()=>{u({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:N}})}),setTimeout(()=>{Se()},N),{graceMs:N})}a(ye,"requestHandover");async function Se(){try{await R()}catch(r){const e=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
10
10
  ${e}
11
- `),process.exit(1)}try{process.platform==="linux"&&k(x)&&(await I({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Mr();const r=await Or({waitForJoinLock:!0});b.fresh(()=>{u({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:r.pid??r.existing_pid??null,spawned:r.started}})})}catch(r){b.fresh(()=>{u({level:"error",event:"daemon.handover.successor_failed",error:r})});const e=r instanceof Error?r.message:String(r);process.stderr.write(`[crtrd] handover successor failed to start: ${e}
12
- `),process.exit(1)}process.exit(0)}s(ge,"performHandover");function R(){if(S!==void 0)return S;const r=ve();return S=r,r.then(()=>{S===r&&(S=void 0)},()=>{S===r&&(S=void 0)}),r}s(R,"requestCleanup");async function K(r){try{await R(),process.exit(0)}catch(e){process.exitCode=1;const c=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);process.stderr.write(`[crtrd] ${r} cleanup failed:
13
- ${c}
14
- `),process.exit(1)}}s(K,"handleSignal");function J(){K("SIGINT")}s(J,"onSigint");function V(){K("SIGTERM")}s(V,"onSigterm");function Q(){R().catch(()=>{})}s(Q,"onExit");function O(r){f&&(g=g.then(r).then(()=>{},e=>{b.fresh(()=>{u({level:"error",event:"daemon.lane_job.failed",error:e})})}))}s(O,"enqueue");function Y(){!f||v||(fe.check()&&E&&(u({level:"info",event:"daemon.resume.detected"}),_(E().catch(()=>{}))),v=!0,O(async()=>{if(v=!1,!!f)try{await Et(Date.now(),W)}catch(r){b.fresh(()=>{u({level:"error",event:"daemon.tick.failed",error:r})})}}))}s(Y,"enqueueTick");let L=null;async function ye(){if(L!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${L instanceof Error?L.message:String(L)}`};if(h.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(h.phase!=="prepared"&&h.phase!=="recovering")throw{status:409,code:"not_prepared",message:h.message};const r=h.phase==="prepared";try{return await G(),h={phase:"ready",message:"",blockerPaths:[]},r?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(e){throw L=e,{status:500,code:"admission_failed",message:`daemon admission failed: ${e instanceof Error?e.message:String(e)}`}}}s(ye,"admitStartup");async function Se(r){if(P!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${P})`};P="repair";try{const e=await tt({dryRun:r.dryRun});if(r.dryRun||e.pending||h.phase!=="blocked")return{result:e,resumed:!1};if(t.prepare)return h={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:e,resumed:!1};try{return await G(),h={phase:"ready",message:"",blockerPaths:[]},{result:e,resumed:!0}}catch(c){const w=c instanceof Error?c.message:String(c);return setTimeout(()=>{R().catch(()=>{})},1e3),{result:e,resumed:!1,resumeError:w}}}finally{P=null}}s(Se,"repairMigrations");async function be(){o=t.intervalMs??pr;const r=a.token;l=new Qr({epoch:r,enqueue:O}),Lr(l),h={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},b.fresh(()=>{u({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:o}})});const e=Fr();if(Hr(e),b.fresh(()=>{u({level:"info",event:"daemon.install_id.resolved",fields:{install_id:e}})}),b.fresh(()=>{let c;try{c=lr()}catch{return}c!==null&&u({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:c.slice(0,2048)}})}),await b.fresh(async()=>{await dr(),await sr(),ar(Date.now()),cr(Date.now())}),b.fresh(()=>{const{reconcile:c,migrated:w}=Gr(br);c.changed&&u({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:c.cleared.length,same_boot_proven:c.sameBootProven}}),w.length>0&&u({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:w.length}})}),b.fresh(()=>{Tr();for(const c of Yr){const w=c.apply();w.changed&&u({level:"info",event:"daemon.boot_migration.applied",fields:{migration:c.id,...w.summary}})}}),_(nr()),E){const c=s(()=>{_(E().catch(()=>{})),_(Ee().then(w=>C?.observe(w)).then(()=>{},w=>{u({level:"warn",event:"daemon.peer.status_failed",error:w})}))},"refresh");_(rr().catch(()=>{})),_(tr().then(({completion:w})=>w).catch(w=>{u({level:"error",event:"daemon.grants.sweep_failed",error:w})})),c(),D=setInterval(c,er*1e3),D.unref(),M=ke({joined:!0,register:_})}O(()=>{Vr(),Jr()}),d=setInterval(Y,o),Y()}s(be,"completeStartup");function G(){return ue??=be().catch(r=>{throw h={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},r})}s(G,"resumeStartup");try{process.on("SIGINT",J),process.on("SIGTERM",V),process.on("exit",Q),Zr(),m!==null&&u({level:"info",event:"daemon.joined_owner.applied",fields:{owner:m.owner,rows:m.rows}}),A=await Le();const r=a.token;Ar({epoch:r,requestHandover:we,registerDetached:_,startupBlock:he,admitStartup:ye,repairMigrations:Se}),le(),$=Je({tcp:t.tcp}),await $.ready;const e=ir("user").runtime;e?.issuer?(E=Ze(e.issuer,_),e.unsandboxed===!0&&(C=Re({syncGrants:E})),Ye(c=>Xe().appended(c))):Qe(),e?.unsandboxed===!0&&e.listener!==void 0&&u({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),e!==void 0&&e.listener!==void 0&&e.unsandboxed!==!0&&(T=Ve(e,()=>or(e.issuer.replace(/\/$/,"")),E),await T.ready);try{await et()}catch(c){if(P=null,c instanceof rt)return h={phase:"blocked",message:c.message,blockerPaths:c.blockerPaths},R;throw c}process.platform==="linux"&&k(x)&&(Fe(),await Ge("app:terminal"));try{t.prepare?h={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await G(),h={phase:"ready",message:"",blockerPaths:[]})}finally{P=null}return R}catch(r){try{await R()}catch(e){throw new AggregateError([r,e],"daemon startup failed and cleanup also failed")}throw r}}s(xt,"runDaemon");var eo=xt;export{B as brokerCommandDeclaresCanvasHome,j as brokerCommandEpoch,eo as default,xt as runDaemon,Et as superviseTick,lt as teardownFleet};
11
+ `),process.exit(1)}try{process.platform==="linux"&&k(x)&&(await I({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Mr();const r=await Or({waitForJoinLock:!0});S.fresh(()=>{u({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:r.pid??r.existing_pid??null,spawned:r.started}})})}catch(r){S.fresh(()=>{u({level:"error",event:"daemon.handover.successor_failed",error:r})});const e=r instanceof Error?r.message:String(r);process.stderr.write(`[crtrd] handover successor failed to start: ${e}
12
+ `),process.exit(1)}process.exit(0)}a(Se,"performHandover");function R(){if(_!==void 0)return _;const r=ge();return _=r,r.then(()=>{_===r&&(_=void 0)},()=>{_===r&&(_=void 0)}),r}a(R,"requestCleanup");async function K(r){try{await R(),process.exit(0)}catch(e){process.exitCode=1;const i=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);process.stderr.write(`[crtrd] ${r} cleanup failed:
13
+ ${i}
14
+ `),process.exit(1)}}a(K,"handleSignal");function J(){K("SIGINT")}a(J,"onSigint");function V(){K("SIGTERM")}a(V,"onSigterm");function Q(){R().catch(()=>{})}a(Q,"onExit");function O(r){f&&(g=g.then(r).then(()=>{},e=>{S.fresh(()=>{u({level:"error",event:"daemon.lane_job.failed",error:e})})}))}a(O,"enqueue");function Y(){!f||v||(he.check()&&E&&(u({level:"info",event:"daemon.resume.detected"}),b(E().catch(()=>{}))),v=!0,O(async()=>{if(v=!1,!!f)try{await Et(Date.now(),W)}catch(r){S.fresh(()=>{u({level:"error",event:"daemon.tick.failed",error:r})})}}))}a(Y,"enqueueTick");let L=null;async function _e(){if(L!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${L instanceof Error?L.message:String(L)}`};if(h.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(h.phase!=="prepared"&&h.phase!=="recovering")throw{status:409,code:"not_prepared",message:h.message};const r=h.phase==="prepared";try{return await G(),h={phase:"ready",message:"",blockerPaths:[]},r?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(e){throw L=e,{status:500,code:"admission_failed",message:`daemon admission failed: ${e instanceof Error?e.message:String(e)}`}}}a(_e,"admitStartup");async function be(r){if(P!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${P})`};P="repair";try{const e=await tt({dryRun:r.dryRun});if(r.dryRun||e.pending||h.phase!=="blocked")return{result:e,resumed:!1};if(t.prepare)return h={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:e,resumed:!1};try{return await G(),h={phase:"ready",message:"",blockerPaths:[]},{result:e,resumed:!0}}catch(i){const w=i instanceof Error?i.message:String(i);return setTimeout(()=>{R().catch(()=>{})},1e3),{result:e,resumed:!1,resumeError:w}}}finally{P=null}}a(be,"repairMigrations");async function ke(){o=t.intervalMs??pr;const r=c.token;l=new Qr({epoch:r,enqueue:O}),Lr(l),h={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},S.fresh(()=>{u({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:o}})});const e=Fr();if(Hr(e),S.fresh(()=>{u({level:"info",event:"daemon.install_id.resolved",fields:{install_id:e}})}),S.fresh(()=>{let i;try{i=lr()}catch{return}i!==null&&u({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:i.slice(0,2048)}})}),await S.fresh(async()=>{await dr(),await sr(),ar(Date.now()),cr(Date.now())}),S.fresh(()=>{const{reconcile:i,migrated:w}=Gr(_r);i.changed&&u({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:i.cleared.length,same_boot_proven:i.sameBootProven}}),w.length>0&&u({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:w.length}})}),S.fresh(()=>{for(const i of te())i.status!=="active"||i.pi_pid!=null||i.frozen_at!=null||i.respawn_not_before!=null||(ne(i.node_id,new Date().toISOString()),u({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:i.node_id}))}),S.fresh(()=>{Dr();for(const i of Yr){const w=i.apply();w.changed&&u({level:"info",event:"daemon.boot_migration.applied",fields:{migration:i.id,...w.summary}})}}),b(nr()),E){const i=a(()=>{b(E().catch(()=>{})),b(xe().then(w=>C?.observe(w)).then(()=>{},w=>{u({level:"warn",event:"daemon.peer.status_failed",error:w})}))},"refresh");b(rr().catch(()=>{})),b(tr().then(({completion:w})=>w).catch(w=>{u({level:"error",event:"daemon.grants.sweep_failed",error:w})})),i(),T=setInterval(i,er*1e3),T.unref(),M=Re({joined:!0,register:b})}O(()=>{Vr(),Jr()}),d=setInterval(Y,o),Y()}a(ke,"completeStartup");function G(){return ve??=ke().catch(r=>{throw h={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},r})}a(G,"resumeStartup");try{process.on("SIGINT",J),process.on("SIGTERM",V),process.on("exit",Q),Zr(),m!==null&&u({level:"info",event:"daemon.joined_owner.applied",fields:{owner:m.owner,rows:m.rows}}),A=await Ae();const r=c.token;Ar({epoch:r,requestHandover:ye,registerDetached:b,startupBlock:we,admitStartup:_e,repairMigrations:be}),me(),$=Je({tcp:t.tcp}),await $.ready;const e=ir("user").runtime;e?.issuer?(E=Ze(e.issuer,b),e.unsandboxed===!0&&(C=Pe({syncGrants:E})),Ye(i=>Xe().appended(i))):Qe(),e?.unsandboxed===!0&&e.listener!==void 0&&u({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),e!==void 0&&e.listener!==void 0&&e.unsandboxed!==!0&&(D=Ve(e,()=>or(e.issuer.replace(/\/$/,"")),E),await D.ready);try{await et()}catch(i){if(P=null,i instanceof rt)return h={phase:"blocked",message:i.message,blockerPaths:i.blockerPaths},R;throw i}process.platform==="linux"&&k(x)&&(Be(),await He("app:terminal"));try{t.prepare?h={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await G(),h={phase:"ready",message:"",blockerPaths:[]})}finally{P=null}return R}catch(r){try{await R()}catch(e){throw new AggregateError([r,e],"daemon startup failed and cleanup also failed")}throw r}}a(xt,"runDaemon");var eo=xt;export{B as brokerCommandDeclaresCanvasHome,j as brokerCommandEpoch,eo as default,xt as runDaemon,Et as superviseTick,lt as teardownFleet};
@@ -4,8 +4,8 @@ var T=Object.defineProperty;var r=(n,e)=>T(n,"name",{value:e,configurable:!0});i
4
4
  WHERE deadline_at IS NOT NULL AND outcome_at IS NULL AND status IN ('active', 'idle') AND kind != 'human'`).filter(e=>!p(e.profile_id)).map(e=>s(e.deadline_at))),"nextDue")}),o("structuredRequests",{nextDue:r(e=>a("SELECT 1 FROM structured_requests WHERE state != 'pending' AND effects_done_at IS NULL LIMIT 1")!==void 0?e:a("SELECT MIN(deadline_at) AS at FROM structured_requests WHERE state = 'pending' AND deadline_at IS NOT NULL")?.at??null,"nextDue")}),o("cronLane",{nextDue:r(()=>{const e=_(`SELECT fire_at, profile FROM crons
5
5
  WHERE state = 'active' AND run_state = 'idle'
6
6
  AND NOT (held = 1 AND recur IS NULL AND expires_at IS NULL)`).filter(i=>!p(i.profile)).map(i=>s(i.fire_at)),t=_("SELECT expires_at FROM crons WHERE expires_at IS NOT NULL AND run_state = 'idle'").map(i=>s(i.expires_at));return c([...e,...t])},"nextDue")});const n=r(e=>()=>a(`SELECT MIN(next_attempt_at) AS at FROM ${e} WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at IS NOT NULL`)?.at??null,"attempts");o("deliveryLane",{nextDue:n("deliveries")}),o("actionLane",{nextDue:n("daemon_actions")}),o("pendingReviewSubmit",{nextDue:r(e=>O().length>0?e:null,"nextDue")}),o("storageDueWork",{nextDue:r(e=>{if(A()===null)return null;if(a("SELECT 1 FROM uploads WHERE delete_pending_since IS NOT NULL LIMIT 1")!==void 0||a("SELECT 1 FROM shares WHERE status = 'off' AND object_deleted_at IS NULL LIMIT 1")!==void 0)return e;const t=a("SELECT MIN(expires_at) AS at FROM shares WHERE status = 'on' AND expires_at IS NOT NULL")?.at,i=a(`SELECT MIN(created_at) AS at FROM uploads u WHERE delete_pending_since IS NULL
7
- AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`)?.at,u=s(i);return c([s(t),u===null?null:u+h])},"nextDue")}),o("faultRetryBackstop",{nextDue:r(()=>c(I().map(e=>b(e))),"nextDue")})}r(D,"installDueSources");const R=12e4;function C(n){const e=_(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
7
+ AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`)?.at,u=s(i);return c([s(t),u===null?null:u+h])},"nextDue")}),o("faultRetryBackstop",{nextDue:r(()=>c(I().map(e=>b(e))),"nextDue")})}r(D,"installDueSources");const R=12e4;function v(n){const e=_(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
8
8
  n.turn_open_at, n.turn_closed_at,
9
9
  (SELECT x.started_at FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited') AS exec_started_at
10
10
  FROM node_rows n
11
- WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${m}`);for(const t of e){if(p(t.profile_id)||!N({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&x(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=s(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<R||L(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null)return!0;const u=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>s(d)??0));if(u>0&&n-u<R||t.status==="idle"&&L(t.node_id))return!0}return!1}r(C,"nodesOweWork");function X(n=Date.now()){D();const{dueNow:e,nextDueMs:t}=w(n,(u,d)=>{M({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:u}})});return{busy:e||C(n)||a("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||a("SELECT 1 FROM jobs j JOIN objects o ON o.rowid = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}r(X,"dueReport");function K(){return D(),[...U(),...g()]}r(K,"coveredLanes");export{R as START_GRACE_MS,K as coveredLanes,X as dueReport,D as installDueSources};
11
+ WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${m}`);for(const t of e){if(p(t.profile_id)||!N({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&x(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=s(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<R||L(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const u=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>s(d)??0));if(u>0&&n-u<R||t.status==="idle"&&L(t.node_id))return!0}return!1}r(v,"nodesOweWork");function X(n=Date.now()){D();const{dueNow:e,nextDueMs:t}=w(n,(u,d)=>{M({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:u}})});return{busy:e||v(n)||a("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||a("SELECT 1 FROM jobs j JOIN objects o ON o.rowid = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}r(X,"dueReport");function K(){return D(),[...U(),...g()]}r(K,"coveredLanes");export{R as START_GRACE_MS,K as coveredLanes,X as dueReport,D as installDueSources};
@@ -1 +1 @@
1
- var w=Object.defineProperty;var s=(i,t)=>w(i,"name",{value:t,configurable:!0});import{clearFrozen as v,getNode as E,getRow as y}from"../../../core/canvas/index.js";import{fullName as g}from"../../../core/canvas/labels.js";import{isSafeNodeId as d}from"../../../core/canvas/paths.js";import{emitEvent as l}from"../../../core/events/emit.js";import{operationIdContext as A}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as k}from"../../../core/canvas/deliveries.js";import{publishNotice as z}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{reviveNode as m}from"../../../core/runtime/revive.js";import{hasPendingWake as _}from"../live-obligation.js";import{readInterruptedTurn as S}from"../../../core/canvas/recovery.js";const u=6,R=10*6e4,L=2e4;function M(i,t){if(t)return 2;const r=i.launched_at;if(r==null)return 1;const e=i.last_settled_at;return e==null?2:Date.parse(e)>Date.parse(r)?1:2}s(M,"thawTier");function C(i,t){if(i.tier!==t.tier)return i.tier-t.tier;const r=i.row.frozen_at,e=t.row.frozen_at;return r==null?e==null?0:1:e==null?-1:Date.parse(r)-Date.parse(e)}s(C,"compareThaw");class B{static{s(this,"FreezeLaneReconciler")}relaunchState=new Map;endEpisode(t){this.relaunchState.delete(t)}async run(t,r){const e=r.candidates.map(a=>({...a,tier:M(a.row,_(a.row.node_id))}));e.sort(C);const n={stalled:0,waitingOnMail:0};for(const a of e)await A.fresh(()=>this.enact(t,a,r.fleet))==="frozen"&&(a.tier===1?n.stalled+=1:n.waitingOnMail+=1);return n}async enact(t,r,e){const n=r.row.node_id;try{return r.enact==="thaw"?await this.enactThaw(r.row):r.enact==="idle-release"?await this.enactIdleRelease(t,r.row):(await e.applyDeadRowPolicy(n),e.has(n)?"launched":y(n)?.frozen_at!=null?"frozen":"skipped")}catch(a){return l({level:"error",event:"node.lifecycle.enact_failed",...d(n)?{node_id:n}:{},error:a,fields:{...d(n)?{}:{affected_node_id:n},enact:r.enact}}),"skipped"}}async enactThaw(t){if(t.lifecycle==="resident"&&E(t.node_id)?.pi_session_id!=null&&!_(t.node_id))return p(t.node_id,"release"),v(t.node_id),"skipped";const r=S(t.node_id)?.interrupted===!0;return(await m(t.node_id,{resume:!0,capacity:"freeze",recovery:!0,...r?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}async enactIdleRelease(t,r){const e=r.node_id,n=k(e),a=this.relaunchState.get(e),c=a===void 0||a.acknowledgedCount!==n,o=c?0:a.attempts;if(o>=u)return this.relaunchState.delete(e),l({level:"warn",event:"broker.idle_release.exhausted",...d(e)?{node_id:e}:{},fields:{...d(e)?{}:{affected_node_id:e},attempts:o,max_attempts:u}}),p(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:o}}}),z(e,"notice.crash",`Child crashed \u2014 ${g(r)} (${e}) failed to relaunch after ${o} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e}),"skipped";const f=c?void 0:a?.lastAttempt,h=Math.min(L*2**o,R);return f!==void 0&&t-f<h?"skipped":(await m(e,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":(this.relaunchState.set(e,{acknowledgedCount:n,attempts:o+1,lastAttempt:t}),l({level:"info",event:"broker.revive.idle_release",...d(e)?{node_id:e}:{},attempt:o+1,fields:{...d(e)?{}:{affected_node_id:e},attempts:o+1,max_attempts:u}}),"launched")}}export{B as FreezeLaneReconciler,C as compareThaw,M as thawTier};
1
+ var E=Object.defineProperty;var d=(i,t)=>E(i,"name",{value:t,configurable:!0});import{clearFrozen as m,getNode as _,getRow as g}from"../../../core/canvas/index.js";import{fullName as y}from"../../../core/canvas/labels.js";import{isSafeNodeId as s}from"../../../core/canvas/paths.js";import{emitEvent as l}from"../../../core/events/emit.js";import{operationIdContext as A}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as S}from"../../../core/canvas/deliveries.js";import{publishNotice as k}from"../../../core/runtime/close.js";import{transition as u}from"../../../core/runtime/lifecycle.js";import{reviveNode as h}from"../../../core/runtime/revive.js";import{hasPendingWake as v}from"../live-obligation.js";import{readInterruptedTurn as z}from"../../../core/canvas/recovery.js";const f=6,R=10*6e4,L=2e4;function M(i,t){if(t)return 2;const r=i.launched_at;if(r==null)return 1;const e=i.last_settled_at;return e==null?2:Date.parse(e)>Date.parse(r)?1:2}d(M,"thawTier");function C(i,t){if(i.tier!==t.tier)return i.tier-t.tier;const r=i.row.frozen_at,e=t.row.frozen_at;return r==null?e==null?0:1:e==null?-1:Date.parse(r)-Date.parse(e)}d(C,"compareThaw");class B{static{d(this,"FreezeLaneReconciler")}relaunchState=new Map;endEpisode(t){this.relaunchState.delete(t)}async run(t,r){const e=r.candidates.map(a=>({...a,tier:M(a.row,v(a.row.node_id))}));e.sort(C);const n={stalled:0,waitingOnMail:0};for(const a of e)await A.fresh(()=>this.enact(t,a,r.fleet))==="frozen"&&(a.tier===1?n.stalled+=1:n.waitingOnMail+=1);return n}async enact(t,r,e){const n=r.row.node_id;try{return r.enact==="thaw"?await this.enactThaw(r.row):r.enact==="idle-release"?await this.enactIdleRelease(t,r.row):(await e.applyDeadRowPolicy(n),e.has(n)?"launched":g(n)?.frozen_at!=null?"frozen":"skipped")}catch(a){return l({level:"error",event:"node.lifecycle.enact_failed",...s(n)?{node_id:n}:{},error:a,fields:{...s(n)?{}:{affected_node_id:n},enact:r.enact}}),"skipped"}}async enactThaw(t){if(t.lifecycle==="resident"&&_(t.node_id)?.pi_session_id!=null&&!v(t.node_id))return u(t.node_id,"release"),m(t.node_id),"skipped";const r=z(t.node_id)?.interrupted===!0;try{return(await h(t.node_id,{resume:!0,capacity:"freeze",recovery:!0,...r?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(e){const n=_(t.node_id);throw n!==null&&(n.status==="active"||n.status==="idle")&&(u(t.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}),m(t.node_id)),e}}async enactIdleRelease(t,r){const e=r.node_id,n=S(e),a=this.relaunchState.get(e),c=a===void 0||a.acknowledgedCount!==n,o=c?0:a.attempts;if(o>=f)return this.relaunchState.delete(e),l({level:"warn",event:"broker.idle_release.exhausted",...s(e)?{node_id:e}:{},fields:{...s(e)?{}:{affected_node_id:e},attempts:o,max_attempts:f}}),u(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:o}}}),k(e,"notice.crash",`Child crashed \u2014 ${y(r)} (${e}) failed to relaunch after ${o} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e}),"skipped";const p=c?void 0:a?.lastAttempt,w=Math.min(L*2**o,R);return p!==void 0&&t-p<w?"skipped":(await h(e,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":(this.relaunchState.set(e,{acknowledgedCount:n,attempts:o+1,lastAttempt:t}),l({level:"info",event:"broker.revive.idle_release",...s(e)?{node_id:e}:{},attempt:o+1,fields:{...s(e)?{}:{affected_node_id:e},attempts:o+1,max_attempts:f}}),"launched")}}export{B as FreezeLaneReconciler,C as compareThaw,M as thawTier};
@@ -7,6 +7,9 @@ export interface NodeLifecycleContext {
7
7
  rows: readonly NodeRow[];
8
8
  fleet: FleetRegistry;
9
9
  }
10
+ /** How long an active row with no engine may be a birth in flight rather than stranded. */
11
+ export declare const LAUNCH_GRACE_MS = 120000;
12
+ export declare function isLaunchInFlight(row: Pick<NodeRow, 'created' | 'launched_at'>, now: number): boolean;
10
13
  export declare class NodeLifecycleReconciler {
11
14
  private readonly freezeLane;
12
15
  run(now: number, ctx: NodeLifecycleContext): Promise<FrozenCounts>;
@@ -1 +1 @@
1
- var u=Object.defineProperty;var d=(a,i)=>u(a,"name",{value:i,configurable:!0});import{clearFrozen as c,endLiveExecution as l,getNode as m}from"../../../core/canvas/index.js";import{isSafeNodeId as h}from"../../../core/canvas/paths.js";import{recordedPidLiveness as o}from"../../../core/canvas/pid.js";import{emitEvent as _}from"../../../core/events/emit.js";import{operationIdContext as y}from"../../../core/events/operation-id.js";import{readInterruptedTurn as P}from"../../../core/canvas/recovery.js";import{isProfilePaused as p}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as k}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as v}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as z}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as I}from"../../fleet.js";import{applyParkEvent as L,hasPendingWake as R,parkEvent as E}from"../live-obligation.js";import{FreezeLaneReconciler as M}from"./freeze-lane.js";import{isInBackoff as N}from"./respawn-policy.js";import{handleTerminatingRow as b}from"./terminating.js";import{wantsExecution as g}from"./wants-execution.js";function D(a){return a.status==="done"||a.status==="canceled"||a.status==="dead"}d(D,"isTerminal");class X{static{d(this,"NodeLifecycleReconciler")}freezeLane=new M;async run(i,e){const r=[];for(const n of e.rows)await y.fresh(async()=>{try{await this.classifyRow(i,n,e,r)}catch(t){const s=n.node_id;_({level:"error",event:"node.lifecycle.classify_failed",...h(s)?{node_id:s}:{fields:{affected_node_id:s}},error:t})}});return this.freezeLane.run(i,{fleet:e.fleet,candidates:r})}async classifyRow(i,e,r,n){const t=e.node_id;if(D(e)){if(b(e,r.fleet.has(t)))return;e.pi_pid!=null&&o(e.pi_pid,e.pi_pid_identity)==="dead"&&l(t,{reason:"observed-dead"}),e.frozen_at!=null&&n.push({row:e,enact:"thaw"});return}if(r.fleet.has(t)){p(e.profile_id)?r.fleet.interruptForProfilePause(t):this.thawMark(e);return}if(p(e.profile_id)){this.freezeLane.endEpisode(t);return}if(k(t))return;const s=e.pi_pid!=null&&o(e.pi_pid,e.pi_pid_identity)==="dead";if(s&&!r.fleet.hasProfilePauseInterruption(t)&&l(t,{reason:"observed-dead"}),!g(e)){this.thawMark(e),this.settleParked(e);return}if(N(e,i))return;if(e.status==="idle"&&z(e)&&v(t)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}e.frozen_at!=null&&n.push({row:e,enact:"thaw"});return}if(!s)return;const f=I(m(t),P(t)?.interrupted===!0,R(t));if(f==="respawn-fresh"||f==="respawn-cycle"||f==="respawn-resume"){n.push({row:e,enact:"policy"});return}await r.fleet.applyDeadRowPolicy(t),this.thawMark(e)}thawMark(i){i.frozen_at!=null&&c(i.node_id)}settleParked(i){if(i.status!=="idle")return;this.freezeLane.endEpisode(i.node_id);const e=E(i.node_id,i.lifecycle);e!=="release"&&L(i.node_id,e)}}export{X as NodeLifecycleReconciler};
1
+ var c=Object.defineProperty;var d=(r,i)=>c(r,"name",{value:i,configurable:!0});import{clearFrozen as m,endLiveExecution as l,getNode as h}from"../../../core/canvas/index.js";import{isSafeNodeId as _}from"../../../core/canvas/paths.js";import{recordedPidLiveness as o}from"../../../core/canvas/pid.js";import{emitEvent as p}from"../../../core/events/emit.js";import{operationIdContext as y}from"../../../core/events/operation-id.js";import{readInterruptedTurn as P}from"../../../core/canvas/recovery.js";import{isProfilePaused as u}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as v}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as k}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as L}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as z}from"../../fleet.js";import{applyParkEvent as I,hasPendingWake as R,parkEvent as E}from"../live-obligation.js";import{FreezeLaneReconciler as M}from"./freeze-lane.js";import{isInBackoff as g}from"./respawn-policy.js";import{handleTerminatingRow as N}from"./terminating.js";import{wantsExecution as b}from"./wants-execution.js";function C(r){return r.status==="done"||r.status==="canceled"||r.status==="dead"}d(C,"isTerminal");const D=12e4;function F(r,i){const e=Math.max(...[r.created,r.launched_at].map(n=>n==null?0:Date.parse(n)||0));return e>0&&i-e<D}d(F,"isLaunchInFlight");class Y{static{d(this,"NodeLifecycleReconciler")}freezeLane=new M;async run(i,e){const n=[];for(const a of e.rows)await y.fresh(async()=>{try{await this.classifyRow(i,a,e,n)}catch(t){const s=a.node_id;p({level:"error",event:"node.lifecycle.classify_failed",..._(s)?{node_id:s}:{fields:{affected_node_id:s}},error:t})}});return this.freezeLane.run(i,{fleet:e.fleet,candidates:n})}async classifyRow(i,e,n,a){const t=e.node_id;if(C(e)){if(N(e,n.fleet.has(t)))return;e.pi_pid!=null&&o(e.pi_pid,e.pi_pid_identity)==="dead"&&l(t,{reason:"observed-dead"}),e.frozen_at!=null&&a.push({row:e,enact:"thaw"});return}if(n.fleet.has(t)){u(e.profile_id)?n.fleet.interruptForProfilePause(t):this.thawMark(e);return}if(u(e.profile_id)){this.freezeLane.endEpisode(t);return}if(v(t))return;const s=e.pi_pid!=null&&o(e.pi_pid,e.pi_pid_identity)==="dead";if(s&&!n.fleet.hasProfilePauseInterruption(t)&&l(t,{reason:"observed-dead"}),!b(e)){this.thawMark(e),this.settleParked(e);return}if(g(e,i))return;if(e.status==="idle"&&L(e)&&k(t)){a.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null){if(e.respawn_not_before!=null){a.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){a.push({row:e,enact:"thaw"});return}if(n.fleet.isClaimed(t)||F(e,i))return;p({level:"warn",event:"node.lifecycle.stranded_launch",node_id:t}),a.push({row:e,enact:"thaw"});return}if(!s)return;const f=z(h(t),P(t)?.interrupted===!0,R(t));if(f==="respawn-fresh"||f==="respawn-cycle"||f==="respawn-resume"){a.push({row:e,enact:"policy"});return}await n.fleet.applyDeadRowPolicy(t),this.thawMark(e)}thawMark(i){i.frozen_at!=null&&m(i.node_id)}settleParked(i){if(i.status!=="idle")return;this.freezeLane.endEpisode(i.node_id);const e=E(i.node_id,i.lifecycle);e!=="release"&&I(i.node_id,e)}}export{D as LAUNCH_GRACE_MS,Y as NodeLifecycleReconciler,F as isLaunchInFlight};
package/dist/types.js CHANGED
@@ -1 +1 @@
1
- var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const _={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,f=".crouter-plugin",E="plugin.json",v=".crouter-marketplace",w="marketplace.json",k=".crouter",x="config.json",b="state.json",S="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],T=["random","go-faster"],c="random",l=2,I=["tmux","on","off"],A=["none","user","agent","both"],p="none";function D(){return{schema_version:r,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:i,auto_open_child_viewers:!0,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...a],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...s],whip_message_mode:c,mouse_mode_default:"tmux",live_cycles:l,condensed_history:p,bash_tool_purpose:!0,fold_finished_tools:!0,summarize_tool_calls:!0,detailed_tool_recaps:!0,consolidate_replies:!1,keybindings:{},tmux_passthrough:[],modelLadders:u(),providerOptions:{},kinds:h(),remoteCanvas:d(),api:{tcp:""},spawnEnv:{allow:[]},bin:{},humanActions:{}}}e(D,"defaultScopeConfig");function d(){return{targets:{}}}e(d,"defaultRemoteCanvasConfig");function h(){return{general:{whenToUse:"Anything else \u2014 the catch-all worker for a task that does not fit a specialist kind.",model:"anthropic/strong"},explore:{whenToUse:"Gather current-state evidence about unfamiliar code or existing architecture \u2014 read-only code-path research with concrete file:line support. Diagnosis or recommendations belong to advisor, target architecture to design, required behavior or acceptance criteria to spec, and implementation decomposition to plan.",model:"openai/light",orchestratorModel:"anthropic/strong"},developer:{whenToUse:"Implement a change \u2014 make the feature or fix genuinely work against its acceptance criteria, not merely compile.",model:"openai/medium",orchestratorModel:"anthropic/strong"},design:{whenToUse:"Architect a solution \u2014 produce one design document an implementer can build from without re-deciding anything left open.",model:"anthropic/strong"},plan:{whenToUse:"Break work into steps \u2014 turn a spec or design into a concrete, phased, parallelizable plan with every decision resolved.",model:"anthropic/strong",orchestratorModel:"anthropic/strong"},spec:{whenToUse:"Collaborate with the user to discover what to build, then write the spec \u2014 behavior, non-goals, interfaces, edge cases, testable acceptance criteria.",model:"anthropic/strong"},review:{whenToUse:"Validate or critique code, a plan, or a spec \u2014 deliver a complete, severity-rated verdict without adjudicating.",model:"openai/medium",orchestratorModel:"openai/strong"},advisor:{whenToUse:"Debug failures, investigate why something is broken or misbehaving, diagnose live/runtime issues, or give engineering advice and second opinions \u2014 reason from evidence and recommend the next move. Use advisor (not explore) whenever the task is to find out what is going wrong.",model:"anthropic/strong"},"review/companion":{whenToUse:"Born by the daemon for one human review; never spawned by an agent.",availableTo:[]}}}e(h,"defaultKindsConfig");function u(){return{anthropic:{ultra:"anthropic/claude-fable-5:xhigh",strong:"anthropic/claude-opus-5-5:medium",medium:"anthropic/claude-sonnet-5-5:medium",light:"anthropic/claude-haiku-5-5:high"},openai:{ultra:"openai-codex/gpt-6-astra:max",strong:"openai-codex/gpt-6.1-sol:high",medium:"openai-codex/gpt-6.1-sol:medium",light:"openai-codex/gpt-6-luna:low"}}}e(u,"defaultModelLaddersConfig");function M(){return{marketplaces:{},plugins:{}}}e(M,"defaultScopeState");export{S as AGENTS_DIR,A as CONDENSED_HISTORY_MODES,x as CONFIG_FILE,k as CRTR_DIR_NAME,p as DEFAULT_CONDENSED_HISTORY,l as DEFAULT_LIVE_CYCLES,i as DEFAULT_MAX_PANES_PER_WINDOW,s as DEFAULT_WHIP_MESSAGES,c as DEFAULT_WHIP_MESSAGE_MODE,_ as ExitCode,v as MARKETPLACE_MANIFEST_DIR,w as MARKETPLACE_MANIFEST_FILE,I as MOUSE_MODE_DEFAULTS,f as PLUGIN_MANIFEST_DIR,E as PLUGIN_MANIFEST_FILE,y as PROFILE_DIR,r as SCHEMA_VERSION,b as STATE_FILE,T as WHIP_MESSAGE_MODES,h as defaultKindsConfig,u as defaultModelLaddersConfig,d as defaultRemoteCanvasConfig,D as defaultScopeConfig,M as defaultScopeState};
1
+ var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const f={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,_=".crouter-plugin",E="plugin.json",v=".crouter-marketplace",w="marketplace.json",k=".crouter",x="config.json",b="state.json",S="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],T=["random","go-faster"],c="random",l=2,I=["tmux","on","off"],A=["none","user","agent","both"],p="none";function D(){return{schema_version:r,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:i,auto_open_child_viewers:!1,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...a],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...s],whip_message_mode:c,mouse_mode_default:"tmux",live_cycles:l,condensed_history:p,bash_tool_purpose:!0,fold_finished_tools:!0,summarize_tool_calls:!0,detailed_tool_recaps:!0,consolidate_replies:!1,keybindings:{},tmux_passthrough:[],modelLadders:u(),providerOptions:{},kinds:h(),remoteCanvas:d(),api:{tcp:""},spawnEnv:{allow:[]},bin:{},humanActions:{}}}e(D,"defaultScopeConfig");function d(){return{targets:{}}}e(d,"defaultRemoteCanvasConfig");function h(){return{general:{whenToUse:"Anything else \u2014 the catch-all worker for a task that does not fit a specialist kind.",model:"anthropic/strong"},explore:{whenToUse:"Gather current-state evidence about unfamiliar code or existing architecture \u2014 read-only code-path research with concrete file:line support. Diagnosis or recommendations belong to advisor, target architecture to design, required behavior or acceptance criteria to spec, and implementation decomposition to plan.",model:"openai/light",orchestratorModel:"anthropic/strong"},developer:{whenToUse:"Implement a change \u2014 make the feature or fix genuinely work against its acceptance criteria, not merely compile.",model:"openai/medium",orchestratorModel:"anthropic/strong"},design:{whenToUse:"Architect a solution \u2014 produce one design document an implementer can build from without re-deciding anything left open.",model:"anthropic/strong"},plan:{whenToUse:"Break work into steps \u2014 turn a spec or design into a concrete, phased, parallelizable plan with every decision resolved.",model:"anthropic/strong",orchestratorModel:"anthropic/strong"},spec:{whenToUse:"Collaborate with the user to discover what to build, then write the spec \u2014 behavior, non-goals, interfaces, edge cases, testable acceptance criteria.",model:"anthropic/strong"},review:{whenToUse:"Validate or critique code, a plan, or a spec \u2014 deliver a complete, severity-rated verdict without adjudicating.",model:"openai/medium",orchestratorModel:"openai/strong"},advisor:{whenToUse:"Debug failures, investigate why something is broken or misbehaving, diagnose live/runtime issues, or give engineering advice and second opinions \u2014 reason from evidence and recommend the next move. Use advisor (not explore) whenever the task is to find out what is going wrong.",model:"anthropic/strong"},"review/companion":{whenToUse:"Born by the daemon for one human review; never spawned by an agent.",availableTo:[]}}}e(h,"defaultKindsConfig");function u(){return{anthropic:{ultra:"anthropic/claude-fable-5:xhigh",strong:"anthropic/claude-opus-5-5:medium",medium:"anthropic/claude-sonnet-5-5:medium",light:"anthropic/claude-haiku-5-5:high"},openai:{ultra:"openai-codex/gpt-6-astra:max",strong:"openai-codex/gpt-6.1-sol:high",medium:"openai-codex/gpt-6.1-sol:medium",light:"openai-codex/gpt-6-luna:low"}}}e(u,"defaultModelLaddersConfig");function M(){return{marketplaces:{},plugins:{}}}e(M,"defaultScopeState");export{S as AGENTS_DIR,A as CONDENSED_HISTORY_MODES,x as CONFIG_FILE,k as CRTR_DIR_NAME,p as DEFAULT_CONDENSED_HISTORY,l as DEFAULT_LIVE_CYCLES,i as DEFAULT_MAX_PANES_PER_WINDOW,s as DEFAULT_WHIP_MESSAGES,c as DEFAULT_WHIP_MESSAGE_MODE,f as ExitCode,v as MARKETPLACE_MANIFEST_DIR,w as MARKETPLACE_MANIFEST_FILE,I as MOUSE_MODE_DEFAULTS,_ as PLUGIN_MANIFEST_DIR,E as PLUGIN_MANIFEST_FILE,y as PROFILE_DIR,r as SCHEMA_VERSION,b as STATE_FILE,T as WHIP_MESSAGE_MODES,h as defaultKindsConfig,u as defaultModelLaddersConfig,d as defaultRemoteCanvasConfig,D as defaultScopeConfig,M as defaultScopeState};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.464",
3
+ "version": "0.3.466",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -137,7 +137,7 @@
137
137
  },
138
138
  "license": "UNLICENSED",
139
139
  "dependencies": {
140
- "@north-light/identity": "0.3.464",
140
+ "@north-light/identity": "0.3.466",
141
141
  "@earendil-works/pi-agent-core": "1.1.0",
142
142
  "@earendil-works/pi-ai": "1.1.0",
143
143
  "@earendil-works/pi-coding-agent": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.464",
3
+ "version": "0.3.466",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.464",
3
+ "version": "0.3.466",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.464",
9
+ "version": "0.3.466",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -18,7 +18,7 @@
18
18
  "@earendil-works/pi-ai": "1.1.0",
19
19
  "@earendil-works/pi-coding-agent": "1.1.0",
20
20
  "@earendil-works/pi-tui": "1.1.0",
21
- "@north-light/identity": "0.3.464",
21
+ "@north-light/identity": "0.3.466",
22
22
  "cron-parser": "^5.6.0",
23
23
  "esbuild": "^0.27.7",
24
24
  "jose": "^6.2.12",
@@ -12095,17 +12095,17 @@
12095
12095
  },
12096
12096
  "packages/crouter-api": {
12097
12097
  "name": "@north-light/api",
12098
- "version": "0.3.464",
12098
+ "version": "0.3.466",
12099
12099
  "license": "UNLICENSED"
12100
12100
  },
12101
12101
  "packages/crouter-env-docker": {
12102
12102
  "name": "@north-light/env-docker",
12103
- "version": "0.3.464",
12103
+ "version": "0.3.466",
12104
12104
  "license": "UNLICENSED"
12105
12105
  },
12106
12106
  "packages/crouter-identity": {
12107
12107
  "name": "@north-light/identity",
12108
- "version": "0.3.464",
12108
+ "version": "0.3.466",
12109
12109
  "license": "UNLICENSED",
12110
12110
  "dependencies": {
12111
12111
  "jose": "^6.2.1"
@@ -12113,20 +12113,20 @@
12113
12113
  },
12114
12114
  "packages/crouter-plugin": {
12115
12115
  "name": "@north-light/plugin",
12116
- "version": "0.3.464",
12116
+ "version": "0.3.466",
12117
12117
  "license": "UNLICENSED",
12118
12118
  "dependencies": {
12119
- "@north-light/api": "0.3.464",
12120
- "@north-light/identity": "0.3.464"
12119
+ "@north-light/api": "0.3.466",
12120
+ "@north-light/identity": "0.3.466"
12121
12121
  }
12122
12122
  },
12123
12123
  "packages/crouter-sdk": {
12124
12124
  "name": "@north-light/sdk",
12125
- "version": "0.3.464",
12125
+ "version": "0.3.466",
12126
12126
  "license": "UNLICENSED",
12127
12127
  "dependencies": {
12128
- "@north-light/api": "0.3.464",
12129
- "@north-light/identity": "0.3.464",
12128
+ "@north-light/api": "0.3.466",
12129
+ "@north-light/identity": "0.3.466",
12130
12130
  "jose": "^6.2.1"
12131
12131
  },
12132
12132
  "bin": {