@north-light/crouter 0.3.275 → 0.3.277

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/builtin-memory/02-turn-lifecycle/01-terminal.md +1 -1
  2. package/dist/clients/attach/viewer.js +1 -1
  3. package/dist/commands/cron.js +3 -3
  4. package/dist/commands/node/create.js +3 -1
  5. package/dist/commands/node-worktree.js +7 -7
  6. package/dist/commands/pkg/plugin-manage.js +19 -8
  7. package/dist/commands/push.js +1 -1
  8. package/dist/core/__tests__/helpers/harness.d.ts +1 -0
  9. package/dist/core/__tests__/helpers/harness.js +12 -10
  10. package/dist/core/__tests__/integration/command-plugins.test.js +6 -6
  11. package/dist/core/__tests__/integration/worktree-land.test.js +7 -2
  12. package/dist/core/__tests__/seam/broker-provider-retry.test.js +3 -16
  13. package/dist/core/canvas/types.d.ts +18 -0
  14. package/dist/core/command-manifests/manifest.d.ts +4 -2
  15. package/dist/core/command-plugins/bundle.d.ts +7 -0
  16. package/dist/core/command-plugins/bundle.js +18 -4
  17. package/dist/core/command-plugins/help-addenda.d.ts +12 -3
  18. package/dist/core/command-plugins/help-addenda.js +17 -4
  19. package/dist/core/command.js +2 -2
  20. package/dist/core/git.d.ts +5 -1
  21. package/dist/core/git.js +18 -4
  22. package/dist/core/runtime/spawn.d.ts +2 -0
  23. package/dist/core/runtime/spawn.js +1 -1
  24. package/dist/core/worktree-sweep.js +28 -5
  25. package/dist/core/worktree.d.ts +1 -12
  26. package/dist/core/worktree.js +222 -10
  27. package/dist/daemon/api/handlers/crons.js +5 -4
  28. package/dist/daemon/api/handlers/messages.js +5 -0
  29. package/dist/daemon/api/handlers/nodes.js +2 -0
  30. package/dist/daemon/api/handlers/reports.js +11 -7
  31. package/dist/daemon/reconcilers/live-obligation.d.ts +3 -2
  32. package/dist/daemon/reconcilers/live-obligation.js +4 -0
  33. package/dist/types.d.ts +3 -3
  34. package/dist/types.js +2 -2
  35. package/package.json +3 -1
  36. package/runtime.lock.json +2 -2
@@ -10,7 +10,7 @@ surfaces:
10
10
  ## Finishing
11
11
  You are **terminal**: you owe a final result and you reap when done, so finish explicitly with `crtr push final` (`crtr push -h`) — a tight summary plus pointers to your artifacts.
12
12
 
13
- **Stopping without `push final` is not finishing**: stop with open work and nothing to wait for and you will be re-prompted to finish or escalate. Something you are waiting on counts, though — that is waiting, not finishing, so end your turn dormant and never finish just to stop waiting. A one-off message from a parent, controller, or sibling without a live subscription needs `crtr node wait controller -h` to declare the wait before you stop.
13
+ **Stopping without `push final` is not finishing**: stop with open work and nothing to wait for and you will be re-prompted to finish or escalate. Something you are waiting on counts, though — that is waiting, not finishing, so end your turn dormant and never finish just to stop waiting. A node whose final is already latched should push an update with the new information, then stop. A one-off message from a parent, controller, or sibling without a live subscription needs `crtr node wait controller -h` to declare the wait before you stop.
14
14
 
15
15
  ## Reaching the user
16
16
  You run headlessly — your turn-by-turn output reaches nobody, so anything you need from a person goes through `crtr human`.
@@ -1774,7 +1774,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
1774
1774
  `);L8.mkdirSync(SK.dirname(et),{recursive:!0}),L8.writeFileSync(et,Dt),this.stop();let xt=[`Rendered line ${be} exceeds terminal width (${Ia(Ue)} > ${t}).`,"","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: ${et}`].join(`
1775
1775
  `);throw new Error(xt)}z+=Ue}let ne=ie;if(this.previousLines.length>m.length){if(ie<m.length-1){let Ue=m.length-1-ie;z+=`\x1B[${Ue}B`,ne=m.length-1}let be=this.previousLines.length-m.length;for(let Ue=m.length;Ue<this.previousLines.length;Ue++)z+=`\r
1776
1776
  \x1B[2K`;z+=`\x1B[${be}A`}if(z+="\x1B[?2026l",process.env.PI_TUI_DEBUG==="1"){let be="/tmp/tui";L8.mkdirSync(be,{recursive:!0});let Ue=SK.join(be,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),Ve=[`firstChanged: ${C}`,`viewportTop: ${p}`,`cursorRow: ${this.cursorRow}`,`height: ${r}`,`lineDiff: ${J}`,`hardwareCursorRow: ${f}`,`renderEnd: ${ie}`,`finalCursorRow: ${ne}`,`cursorPos: ${JSON.stringify(g)}`,`newLines.length: ${m.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(m,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(z)].join(`
1777
- `);L8.writeFileSync(Ue,Ve)}this.terminal.write(z),this.cursorRow=Math.max(0,m.length-1),this.hardwareCursorRow=ne,this.maxLinesRendered=Math.max(this.maxLinesRendered,m.length),this.previousViewportTop=Math.max(u,ne-r+1),this.positionHardwareCursor(g,m.length),this.previousLines=m,this.previousKittyImageIds=this.collectKittyImageIds(m),this.previousWidth=t,this.previousHeight=r}positionHardwareCursor(t,r){if(!t||r<=0){this.terminal.hideCursor();return}let i=Math.max(0,Math.min(t.row,r-1)),o=Math.max(0,t.col),a=i-this.hardwareCursorRow,u="";a>0?u+=`\x1B[${a}B`:a<0&&(u+=`\x1B[${-a}A`),u+=`\x1B[${o+1}G`,u&&this.terminal.write(u),this.hardwareCursorRow=i,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};var vK="\x1B[0m",M6e="\x1B[38;5;180m",ZBi="\x1B[38;5;137m",eUi="\x1B[1m",D6e="\x1B[2m";function TK(e){return M6e+e.replace(/\./g,`${ZBi}.${M6e}`)+vK}var TIr=[TK(" ________"),TK(" / /|"),TK(" / . . / |"),TK(" /_______/ |"),TK(" | . . | |"),TK(" | . . | /"),TK(" |_______|/")];function vIr(e={}){let r=[`${eUi}${M6e}crouter${vK}${e.version?`${D6e} v${e.version}${vK}`:""}`,`${D6e}the agentic runtime${vK}`];e.profile&&r.push(`${D6e}profile: ${vK}${M6e}${e.profile}${vK}`),e.cwd&&r.push(`${D6e}${e.cwd}${vK}`);let i=[];for(let o=0;o<TIr.length;o++){let a=o>=1&&o-1<r.length?` ${r[o-1]}`:"";i.push(TIr[o]+a)}return i}import{execFile as s3i,spawnSync as Bwr}from"node:child_process";function tUi(e,t,r,i,o,a,u,p,f){return Object.freeze({id:e,group:t,name:r,description:i,defaults:Object.freeze([...o]),inputKind:a,contexts:Object.freeze([...u]),...p===void 0?{}:{safety:p},...f===void 0?{}:{pair:Object.freeze({...f})}})}var qa=tUi;function vb(e,t,r,i,o){let a=`crtr.tmux.menu.${e}`,u=`crtr.tmux.menu-global.${e}`;return[qa(a,"Global tmux",t,r,i,"tmux-menu-selector",o,void 0,{field:"menu",pairedId:u}),qa(u,"Global tmux",t,r,[],"tmux-global-action",["tmux.root"],void 0,{field:"global",pairedId:a})]}function IP(e,t,r,i,o,a){return[qa(e,"Attach",r,i,o,"tmux-menu-selector",["tmux.menu.attach"],void 0,{field:"menu",pairedId:t}),qa(t,"Attach",r,i,a,"host-global",F7,void 0,{field:"direct",pairedId:e})]}var F7=["attach","graph","graph.confirm"],rUi=["setup.login","setup.list","setup.input","setup.keybindings","setup.keybindings.edit","setup.keybindings.filter","setup.models"],CIr=["setup.login","setup.list","setup.keybindings","setup.models"],wP=Object.freeze([qa("crtr.tmux.menu.open","Global tmux","Open crouter menu","Open the crouter action menu.",["alt+c"],"host-global",["tmux.root"]),qa("crtr.tmux.menu.attach","Global tmux","Attach actions","Open the attach-viewer action submenu.",["a"],"tmux-menu-selector",["tmux.menu"]),...vb("promote","Promote to orchestrator","Promote the focused node to orchestrator \u2014 it holds a roadmap and delegates.",["o"],["tmux.menu"]),...vb("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"]),...vb("resume","Find node","Open the canvas navigator and go to the chosen node.",["/"],["tmux.menu"]),...vb("fork","Fork node","Fork the focused node into an independent idle root.",["f"],["tmux.menu"]),...vb("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"]),...vb("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"]),...vb("detach","Demote and close viewer","Demote the focused node and close its viewer; its broker keeps running off-screen.",["shift+d"],["tmux.menu"]),...vb("close-subtree","Close subtree","Close the focused node and its subtree.",["x"],["tmux.menu"]),...vb("background-bash","Background running bash","Hand the focused node\u2019s running bash command to its background job system.",["b"],["tmux.menu"]),...vb("file-review","Review a file","Open a line-anchored review of a file named in the transcript.",["v"],["tmux.menu"]),...vb("pin","Pin conversation","Pin or unpin this conversation in the canvas navigator.",["p"],["tmux.menu"]),...vb("show","Inspect node","Open the focused node\u2019s inspection menu.",["i"],["tmux.menu"]),...vb("view-settings","Display settings","Open the viewer display-settings menu.",["z"],["tmux.menu"]),...vb("fold-tools","Fold finished tool calls","Fold every finished tool call in the transcript to its single call line.",["f"],["tmux.menu.view-settings"]),...vb("metadata","Show metadata","Show the focused node\u2019s metadata dossier.",["m"],["tmux.menu.show"]),...vb("context","Browse context","Browse the focused node context.",["c"],["tmux.menu.show"]),...vb("providers","Open settings","Open the crouter settings panel.",[","],["tmux.menu"]),...vb("plugins","Browse plugins","Open the crouter plugin browser.",["l"],["tmux.menu"]),...vb("context-admin","Context surface","Open the context surface: what memory each event delivers, and the surfaces, gates, and caps that decide it.",["shift+c"],["tmux.menu"]),...vb("graph","Canvas graph","Open the canvas graph.",["g"],["tmux.menu"]),...vb("focus-manager","Go to manager","Focus this node\u2019s manager.",["h"],["tmux.menu"]),...vb("copy-id","Copy node id","Copy the focused node id to the system clipboard.",["y"],["tmux.menu"]),...vb("reload-viewer","Reload viewer","Respawn this pane\u2019s viewer onto the current runtime generation.",["r"],["tmux.menu"]),...vb("recap","Generate recap","Generate the focused node\u2019s Goal and State recap and refresh its generated title.",["s"],["tmux.menu"]),...vb("issues","Open create menu","Open the create submenu.",["c"],["tmux.menu"]),...vb("issue.idea","Create idea","Create an idea issue.",["i"],["tmux.menu.issue"]),...vb("issue.bug","Create bug","Create a bug issue.",["b"],["tmux.menu.issue"]),qa("crtr.tmux.node.next","Global tmux","Next node","Focus the next canvas node.",["alt+]"],"host-global",["tmux.root"]),qa("crtr.tmux.node.previous","Global tmux","Previous node","Focus the previous canvas node.",["alt+["],"host-global",["tmux.root"]),qa("crtr.tmux.inbox.toggle","Global tmux","Toggle inbox","Open or close the human inbox in the focused viewer.",["alt+i"],"host-global",["tmux.root"]),...IP("crtr.tmux.menu.attach.detach","crtr.attach.detach","Detach","Detach from the node.",["d"],["ctrl+d"]),...IP("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"]),...IP("crtr.tmux.menu.attach.graph.toggle","crtr.attach.graph.toggle","Toggle graph","Open or close the graph overlay.",["g"],["alt+g"]),...IP("crtr.tmux.menu.attach.help.toggle","crtr.attach.help.toggle","Help","Open the attach help overlay.",["?"],["alt+shift+k"]),...IP("crtr.tmux.menu.attach.inbox.toggle","crtr.attach.inbox.toggle","Toggle inbox","Open or close the human inbox surface in this viewer.",["i"],[]),...IP("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"]),...IP("crtr.tmux.menu.attach.model-ladder.next","crtr.attach.model-ladder.next","Next model","Move to the next model ladder rung.",["]"],["alt+m"]),...IP("crtr.tmux.menu.attach.model-ladder.previous","crtr.attach.model-ladder.previous","Previous model","Move to the previous model ladder rung.",["["],["alt+shift+m"]),...IP("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"]),...IP("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"]),...IP("crtr.tmux.menu.attach.profile-files","crtr.attach.profile-files","Search profile files","Fuzzy-match path segments across the node family\u2019s working directories, profile projects and memory, and ancestor crouter memory stores; Ctrl+Y copies a selected path.",["f"],["ctrl+f"]),...IP("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+/"]),...IP("crtr.tmux.menu.attach.whip","crtr.attach.whip","Whip agent","Interrupt the agent and send a playful command.",["w"],[]),qa("crtr.attach.scroll.up","Attach","Scroll up","Scroll the transcript one line up.",["shift+up"],"terminal",F7),qa("crtr.attach.scroll.down","Attach","Scroll down","Scroll the transcript one line down.",["shift+down"],"terminal",F7),qa("crtr.attach.scroll.page-up","Attach","Scroll page up","Scroll the transcript one page up.",["pageup"],"terminal",F7),qa("crtr.attach.scroll.page-down","Attach","Scroll page down","Scroll the transcript one page down.",["pagedown"],"terminal",F7),qa("crtr.attach.scroll.live","Attach","Return to live","Return the transcript to the live bottom.",["shift+end"],"terminal",F7),qa("crtr.attach.mouse.toggle","Attach","Toggle mouse wheel scrolling","Toggle mouse wheel scrolling on or off.",["alt+shift+o"],"terminal",F7),qa("crtr.attach.copy.message","Attach","Copy visible message","Copy the newest message visible in the transcript viewport.",["alt+shift+y"],"terminal",F7),qa("crtr.attach.search.next","Attach","Next match","Move to the next transcript search match.",["n"],"terminal",["attach.search"]),qa("crtr.attach.search.previous","Attach","Previous match","Move to the previous transcript search match.",["shift+n"],"terminal",["attach.search"]),qa("crtr.attach.search.edit","Attach","Edit query","Return to editing the transcript search query.",["/"],"terminal",["attach.search"]),qa("crtr.attach.search.close","Attach","Close search","Leave transcript search and clear its highlights.",["escape"],"terminal",["attach.search"],"dismiss-modal"),qa("crtr.graph.down","GRAPH","Move down","Move to the next graph row.",["j"],"terminal",["graph"]),qa("crtr.graph.up","GRAPH","Move up","Move to the previous graph row.",["k"],"terminal",["graph"]),qa("crtr.graph.first","GRAPH","First row","Move to the first graph row.",["g"],"terminal",["graph"]),qa("crtr.graph.last","GRAPH","Last row","Move to the last graph row.",["shift+g"],"terminal",["graph"]),qa("crtr.graph.collapse-or-manager","GRAPH","Collapse or manager","Collapse a node or move to its manager.",["h"],"terminal",["graph"]),qa("crtr.graph.expand-or-child","GRAPH","Expand or child","Expand a node or move to its child.",["l"],"terminal",["graph"]),qa("crtr.graph.focus","GRAPH","Focus node","Focus the selected node.",["enter"],"terminal",["graph"]),qa("crtr.graph.revive","GRAPH","Revive node","Revive and open the selected dormant node.",["r"],"terminal",["graph"]),qa("crtr.graph.focus-manager","GRAPH","Focus manager","Focus the selected node manager.",["m"],"terminal",["graph"]),qa("crtr.graph.close-subtree","GRAPH","Close subtree","Ask to close the selected subtree.",["x"],"terminal",["graph"]),qa("crtr.graph.dismiss","GRAPH","Dismiss graph","Close the graph overlay.",["escape"],"terminal",["graph"],"dismiss-modal"),qa("crtr.graph.confirm.accept","GRAPH","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["graph.confirm"]),qa("crtr.graph.confirm.cancel","GRAPH","Cancel close","Cancel closing the selected subtree.",["n","escape"],"terminal",["graph.confirm"],"dismiss-modal"),qa("crtr.inspector.force-quit","Inspector","Force quit Inspector","Immediately leave the Inspector.",["ctrl+c"],"host-global",["inspector"],"leave-screen"),qa("crtr.inspector.down","Inspector","Move down","Move the Inspector selection or scroll cursor down.",["j","down"],"terminal",["inspector"]),qa("crtr.inspector.up","Inspector","Move up","Move the Inspector selection or scroll cursor up.",["k","up"],"terminal",["inspector"]),qa("crtr.inspector.section-next","Inspector","Next section","Move to the next Inspector section.",["tab"],"terminal",["inspector"]),qa("crtr.inspector.section-prev","Inspector","Previous section","Move to the previous Inspector section.",["shift+tab"],"terminal",["inspector"]),qa("crtr.inspector.page-down","Inspector","Page down","Scroll the Inspector detail body down.",["ctrl+d","pagedown"],"terminal",["inspector"]),qa("crtr.inspector.page-up","Inspector","Page up","Scroll the Inspector detail body up.",["ctrl+u","pageup"],"terminal",["inspector"]),qa("crtr.inspector.toggle-detail","Inspector","Toggle item detail","Expand or collapse the selected cron or background job.",["enter"],"terminal",["inspector"]),qa("crtr.inspector.cancel-item","Inspector","Cancel selected item","Arm cancellation for the selected cron, or stopping for the selected background job.",["x"],"terminal",["inspector"]),qa("crtr.inspector.open-log","Inspector","Open job log","Follow the selected background job\u2019s log in a new tmux window.",["o"],"terminal",["inspector"]),qa("crtr.inspector.confirm","Inspector","Confirm action","Confirm the armed Inspector action.",["y"],"terminal",["inspector"]),qa("crtr.inspector.dismiss","Inspector","Dismiss action","Dismiss an Inspector confirmation or banner.",["escape"],"terminal",["inspector"],"dismiss-modal"),qa("crtr.inspector.retarget","Inspector","Retarget","Inspect the selected cron anchor or creator node.",["t"],"terminal",["inspector"]),qa("crtr.inspector.refresh","Inspector","Refresh","Refresh the Inspector now.",["g","r"],"terminal",["inspector"]),qa("crtr.inspector.quit","Inspector","Quit","Leave the Inspector.",["q"],"terminal",["inspector"],"leave-screen"),...nUi(),...iUi(),...oUi()]);function nUi(){let e="browse";return[qa("crtr.browse.quit","Browse and pickers","Quit browse","Leave canvas browse.",["q","escape","ctrl+c"],"terminal",[e],"leave-screen"),qa("crtr.browse.down","Browse and pickers","Move down","Move to the next row.",["j","down"],"terminal",[e]),qa("crtr.browse.up","Browse and pickers","Move up","Move to the previous row.",["k","up"],"terminal",[e]),qa("crtr.browse.first","Browse and pickers","First row","Move to the first row.",["g"],"terminal",[e]),qa("crtr.browse.last","Browse and pickers","Last row","Move to the last row.",["shift+g"],"terminal",[e]),qa("crtr.browse.expand-or-child","Browse and pickers","Expand or child","Expand a row or move to its child.",["l","right"],"terminal",[e]),qa("crtr.browse.collapse-or-parent","Browse and pickers","Collapse or parent","Collapse a row or move to its parent.",["h","left"],"terminal",[e]),qa("crtr.browse.toggle-fold","Browse and pickers","Toggle fold","Toggle the selected fold.",["space"],"terminal",[e]),qa("crtr.browse.tab-next","Browse and pickers","Next tab","Select the next browse tab.",["tab","]"],"terminal",[e]),qa("crtr.browse.tab-previous","Browse and pickers","Previous tab","Select the previous browse tab.",["shift+tab","["],"terminal",[e]),...[1,2,3,4,5].map(t=>qa(`crtr.browse.tab.${t}`,"Browse and pickers",`Tab ${t}`,`Select browse tab ${t}.`,[`${t}`],"terminal",[e])),qa("crtr.browse.close-subtree","Browse and pickers","Close subtree","Ask to close the selected subtree.",["x"],"terminal",[e]),qa("crtr.browse.confirm-close","Browse and pickers","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["browse.confirm"]),qa("crtr.browse.sort","Browse and pickers","Change sort","Change the browse sort.",["s"],"terminal",[e]),qa("crtr.browse.scope","Browse and pickers","Change scope","Toggle the browse cwd scope.",["c"],"terminal",[e]),qa("crtr.browse.profile","Browse and pickers","Toggle profile","Toggle the browse profile scope.",["shift+p"],"terminal",[e]),qa("crtr.browse.residents","Browse and pickers","Toggle residents","Toggle resident display.",["r"],"terminal",[e]),qa("crtr.browse.preview","Browse and pickers","Toggle preview","Toggle the preview panel.",["v"],"terminal",[e]),qa("crtr.browse.pin","Browse and pickers","Pin node","Star or unstar the selected node.",["p"],"terminal",[e]),qa("crtr.browse.search","Browse and pickers","Search","Open browse search.",["/"],"terminal",[e]),qa("crtr.browse.revive-now","Browse and pickers","Revive now","Revive the selected node now.",["shift+k"],"terminal",[e]),qa("crtr.browse.focus","Browse and pickers","Focus node","Focus the selected node.",["enter","o"],"terminal",[e]),qa("crtr.browse.focus-background","Browse and pickers","Focus node (keep browsing)","Focus the selected node without leaving the navigator.",["shift+o"],"terminal",[e]),qa("crtr.browse.yank-id","Browse and pickers","Yank node id","Copy the selected node id to the system clipboard.",["y"],"terminal",[e]),qa("crtr.browse.search.cancel","Browse and pickers","Cancel search","Cancel browse search.",["escape"],"terminal",["browse.search"],"dismiss-modal"),qa("crtr.browse.search.commit","Browse and pickers","Commit search","Apply browse search.",["enter"],"terminal",["browse.search"]),qa("crtr.browse.search.delete","Browse and pickers","Delete search text","Delete the previous search character.",["backspace"],"terminal",["browse.search"]),qa("crtr.browse.search.quit","Browse and pickers","Quit browse","Leave canvas browse from search.",["ctrl+c"],"terminal",["browse.search"],"leave-screen")]}function iUi(){let e="profile.menu",t="profile.search";return[qa("crtr.profile.menu.up","Profiles","Move up","Move to the previous profile.",["k","up"],"terminal",[e]),qa("crtr.profile.menu.down","Profiles","Move down","Move to the next profile.",["j","down"],"terminal",[e]),qa("crtr.profile.menu.select","Profiles","Select profile","Select the highlighted profile.",["enter"],"terminal",[e]),qa("crtr.profile.menu.accept-default","Profiles","Accept default","Accept the default profile.",["escape"],"terminal",[e],"leave-screen"),qa("crtr.profile.menu.abort","Profiles","Abort","Leave profile selection.",["ctrl+c"],"terminal",[e],"leave-screen"),...[1,2,3,4,5,6,7,8,9].map(r=>qa(`crtr.profile.menu.slot.${r}`,"Profiles",`Profile slot ${r}`,`Select profile slot ${r}.`,[`${r}`],"terminal",[e])),qa("crtr.profile.menu.create","Profiles","Create profile","Create a profile.",["c"],"terminal",[e]),qa("crtr.profile.menu.search-existing","Profiles","Search profiles","Search existing profiles.",["s"],"terminal",[e]),qa("crtr.profile.menu.use-root","Profiles","Use root profile","Use the root profile.",["r"],"terminal",[e]),qa("crtr.profile.menu.set-default","Profiles","Set default","Set the selected profile as default.",["d"],"terminal",[e]),qa("crtr.profile.menu.add-directory","Profiles","Add directory","Add a directory to the profile.",["a"],"terminal",[e]),qa("crtr.profile.menu.unpin","Profiles","Unpin directory","Unpin the selected directory.",["u"],"terminal",[e]),qa("crtr.profile.menu.manage","Profiles","Manage profiles","Open the profiles settings page in a popup.",["v"],"terminal",[e]),qa("crtr.profile.search.up","Profiles","Move up","Move to the previous search result.",["up","ctrl+p"],"terminal",[t]),qa("crtr.profile.search.down","Profiles","Move down","Move to the next search result.",["down","ctrl+n"],"terminal",[t]),qa("crtr.profile.search.pick","Profiles","Pick profile","Pick the highlighted profile.",["enter"],"terminal",[t]),qa("crtr.profile.search.back","Profiles","Back","Return to profile selection.",["escape"],"terminal",[t],"leave-screen"),qa("crtr.profile.search.delete","Profiles","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",[t]),qa("crtr.profile.search.abort","Profiles","Abort","Leave profile search.",["ctrl+c"],"terminal",[t],"leave-screen")]}function oUi(){return[qa("crtr.setup.cancel","Setup","Cancel setup","Leave the setup wizard.",["q","ctrl+c","ctrl+d"],"terminal",rUi,"leave-screen"),qa("crtr.setup.tab-next","Setup","Next tab","Select the next setup tab.",["tab","right"],"terminal",CIr),qa("crtr.setup.tab-previous","Setup","Previous tab","Select the previous setup tab.",["shift+tab","left"],"terminal",CIr),qa("crtr.setup.open","Setup","Open","Open the selected setup item.",["enter"],"terminal",["setup.login"]),qa("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"]),qa("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"]),qa("crtr.setup.toggle","Setup","Toggle","Toggle the selected setup item.",["space"],"terminal",["setup.list","setup.keybindings"]),qa("crtr.setup.details","Setup","Show details","Show details for the selected item.",["?"],"terminal",["setup.list"]),qa("crtr.setup.advance","Setup","Advance","Advance the setup flow.",["enter"],"terminal",["setup.list"]),qa("crtr.setup.confirm.accept","Setup","Confirm","Accept the setup confirmation.",["y","enter"],"terminal",["setup.confirm","setup.models.confirm"]),qa("crtr.setup.confirm.back","Setup","Go back","Cancel the setup confirmation.",["n","escape","q"],"terminal",["setup.confirm","setup.models.confirm"],"dismiss-modal"),qa("crtr.setup.keybindings.edit","Setup","Edit binding","Edit the selected binding.",["enter"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.commit-edit","Setup","Commit edit","Commit the active binding edit.",["enter"],"terminal",["setup.keybindings.edit"]),qa("crtr.setup.keybindings.cancel-edit","Setup","Cancel edit","Cancel the active binding edit.",["escape"],"terminal",["setup.keybindings.edit"],"dismiss-modal"),qa("crtr.setup.keybindings.unbind","Setup","Unbind","Disable the selected binding.",["delete"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.reset-row","Setup","Reset binding","Reset the selected binding.",["r"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.reset-all","Setup","Reset all bindings","Reset all bindings to defaults.",["shift+r"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.save","Setup","Save bindings","Save keybinding changes.",["s"],"terminal",["setup.keybindings"],"save-keybindings"),qa("crtr.setup.keybindings.discard","Setup","Discard changes","Discard keybinding changes.",["escape"],"terminal",["setup.keybindings"],"leave-screen"),qa("crtr.setup.keybindings.page-up","Setup","Page up","Move up one keybinding page.",["pageup"],"terminal",["setup.keybindings","setup.keybindings.edit"]),qa("crtr.setup.keybindings.page-down","Setup","Page down","Move down one keybinding page.",["pagedown"],"terminal",["setup.keybindings","setup.keybindings.edit"]),qa("crtr.setup.keybindings.filter","Setup","Filter bindings","Open the keybinding filter.",["/"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.filter-delete","Setup","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",["setup.keybindings.filter"]),qa("crtr.setup.keybindings.filter-clear","Setup","Clear filter","Clear the keybinding filter.",["escape"],"terminal",["setup.keybindings.filter"],"dismiss-modal"),qa("crtr.setup.cell-previous","Setup","Previous field","Select the previous field or setup table cell.",["h"],"terminal",["setup.models","setup.keybindings"]),qa("crtr.setup.cell-next","Setup","Next field","Select the next field or setup table cell.",["l"],"terminal",["setup.models","setup.keybindings"]),qa("crtr.setup.models.open","Setup","Edit model","Edit the selected model cell or route field.",["enter"],"terminal",["setup.models","setup.models.route-form"]),qa("crtr.setup.models.scope-next","Setup","Next model config scope","Edit the next applicable user, profile, or project config.",["s"],"terminal",["setup.models"]),qa("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"]),qa("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")]}var CK=new Set(wP.map(e=>e.id));function aTe(e){return e.contexts.includes("attach")&&(e.inputKind==="terminal"||e.inputKind==="host-global")}var evt=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"}]);import{dirname as f$i,join as Cwr}from"node:path";var tvt="working",xIr=["thinking","planning","checking",tvt],L6e="Working...";function IIr(e){if(!Array.isArray(e))return[tvt];let t=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return t.length>0?t:[tvt]}var RP={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},rvt=4,wIr=".crouter-plugin",RIr="plugin.json";var dM=".crouter",F6e="config.json",kIr="state.json";var NIr="profiles",sUi=3,B6e=["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"],xK=["random","go-faster"],aUi="random",nvt=2,IK=["tmux","on","off"],wK=["none","user","agent","both"],ivt="none";function U6e(){return{schema_version:rvt,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:sUi,auto_open_child_viewers:!0,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...xIr],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...B6e],whip_message_mode:aUi,mouse_mode_default:"tmux",live_cycles:nvt,condensed_history:ivt,bash_tool_purpose:!0,fold_finished_tools:!1,summarize_tool_calls:!1,detailed_tool_recaps:!0,keybindings:{},tmux_passthrough:[],modelLadders:avt(),kinds:svt(),remoteCanvas:ovt(),spawnEnv:{allow:[]},bin:{},humanActions:{}}}function ovt(){return{targets:{}}}function svt(){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 avt(){return{anthropic:{ultra:"anthropic/claude-fable-5:xhigh",strong:"anthropic/claude-opus-5:medium",medium:"anthropic/claude-sonnet-5:xhigh",light:"anthropic/claude-haiku-4-5:high"},openai:{ultra:"openai-codex/gpt-5.6-sol:max",strong:"openai-codex/gpt-5.6-sol:high",medium:"openai-codex/gpt-5.6-terra:medium",light:"openai-codex/gpt-5.6-luna:low"}}}function cvt(){return{marketplaces:{},plugins:{}}}var r$=class extends Error{code;exitCode;details;constructor(t,r,i=RP.GENERAL,o){super(r),this.name="CrtrError",this.code=t,this.exitCode=i,this.details=o}};function lvt(e,t){return new r$("not_found",e,RP.NOT_FOUND,t)}function mR(e,t){return new r$("usage",e,RP.USAGE,t)}function PIr(e,t){return new r$("ambiguous",e,RP.AMBIGUOUS,t)}import{appendFileSync as cUi,existsSync as OIr,mkdirSync as lUi,renameSync as DIr,rmSync as uUi,statSync as pUi}from"node:fs";import{dirname as dUi}from"node:path";var fUi=65536,mUi=5*1024*1024;function $6e(e,t){if(t.includes(`
1777
+ `);L8.writeFileSync(Ue,Ve)}this.terminal.write(z),this.cursorRow=Math.max(0,m.length-1),this.hardwareCursorRow=ne,this.maxLinesRendered=Math.max(this.maxLinesRendered,m.length),this.previousViewportTop=Math.max(u,ne-r+1),this.positionHardwareCursor(g,m.length),this.previousLines=m,this.previousKittyImageIds=this.collectKittyImageIds(m),this.previousWidth=t,this.previousHeight=r}positionHardwareCursor(t,r){if(!t||r<=0){this.terminal.hideCursor();return}let i=Math.max(0,Math.min(t.row,r-1)),o=Math.max(0,t.col),a=i-this.hardwareCursorRow,u="";a>0?u+=`\x1B[${a}B`:a<0&&(u+=`\x1B[${-a}A`),u+=`\x1B[${o+1}G`,u&&this.terminal.write(u),this.hardwareCursorRow=i,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};var vK="\x1B[0m",M6e="\x1B[38;5;180m",ZBi="\x1B[38;5;137m",eUi="\x1B[1m",D6e="\x1B[2m";function TK(e){return M6e+e.replace(/\./g,`${ZBi}.${M6e}`)+vK}var TIr=[TK(" ________"),TK(" / /|"),TK(" / . . / |"),TK(" /_______/ |"),TK(" | . . | |"),TK(" | . . | /"),TK(" |_______|/")];function vIr(e={}){let r=[`${eUi}${M6e}crouter${vK}${e.version?`${D6e} v${e.version}${vK}`:""}`,`${D6e}the agentic runtime${vK}`];e.profile&&r.push(`${D6e}profile: ${vK}${M6e}${e.profile}${vK}`),e.cwd&&r.push(`${D6e}${e.cwd}${vK}`);let i=[];for(let o=0;o<TIr.length;o++){let a=o>=1&&o-1<r.length?` ${r[o-1]}`:"";i.push(TIr[o]+a)}return i}import{execFile as s3i,spawnSync as Bwr}from"node:child_process";function tUi(e,t,r,i,o,a,u,p,f){return Object.freeze({id:e,group:t,name:r,description:i,defaults:Object.freeze([...o]),inputKind:a,contexts:Object.freeze([...u]),...p===void 0?{}:{safety:p},...f===void 0?{}:{pair:Object.freeze({...f})}})}var qa=tUi;function vb(e,t,r,i,o){let a=`crtr.tmux.menu.${e}`,u=`crtr.tmux.menu-global.${e}`;return[qa(a,"Global tmux",t,r,i,"tmux-menu-selector",o,void 0,{field:"menu",pairedId:u}),qa(u,"Global tmux",t,r,[],"tmux-global-action",["tmux.root"],void 0,{field:"global",pairedId:a})]}function IP(e,t,r,i,o,a){return[qa(e,"Attach",r,i,o,"tmux-menu-selector",["tmux.menu.attach"],void 0,{field:"menu",pairedId:t}),qa(t,"Attach",r,i,a,"host-global",F7,void 0,{field:"direct",pairedId:e})]}var F7=["attach","graph","graph.confirm"],rUi=["setup.login","setup.list","setup.input","setup.keybindings","setup.keybindings.edit","setup.keybindings.filter","setup.models"],CIr=["setup.login","setup.list","setup.keybindings","setup.models"],wP=Object.freeze([qa("crtr.tmux.menu.open","Global tmux","Open crouter menu","Open the crouter action menu.",["alt+c"],"host-global",["tmux.root"]),qa("crtr.tmux.menu.attach","Global tmux","Attach actions","Open the attach-viewer action submenu.",["a"],"tmux-menu-selector",["tmux.menu"]),...vb("promote","Promote to orchestrator","Promote the focused node to orchestrator \u2014 it holds a roadmap and delegates.",["o"],["tmux.menu"]),...vb("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"]),...vb("resume","Find node","Open the canvas navigator and go to the chosen node.",["/"],["tmux.menu"]),...vb("fork","Fork node","Fork the focused node into an independent idle root.",["f"],["tmux.menu"]),...vb("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"]),...vb("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"]),...vb("detach","Demote and close viewer","Demote the focused node and close its viewer; its broker keeps running off-screen.",["shift+d"],["tmux.menu"]),...vb("close-subtree","Close subtree","Close the focused node and its subtree.",["x"],["tmux.menu"]),...vb("background-bash","Background running bash","Hand the focused node\u2019s running bash command to its background job system.",["b"],["tmux.menu"]),...vb("file-review","Review a file","Open a line-anchored review of a file named in the transcript.",["v"],["tmux.menu"]),...vb("pin","Pin conversation","Pin or unpin this conversation in the canvas navigator.",["p"],["tmux.menu"]),...vb("show","Inspect node","Open the focused node\u2019s inspection menu.",["i"],["tmux.menu"]),...vb("view-settings","Display settings","Open the viewer display-settings menu.",["z"],["tmux.menu"]),...vb("fold-tools","Fold finished tool calls","Fold every finished tool call in the transcript to its single call line.",["f"],["tmux.menu.view-settings"]),...vb("metadata","Show metadata","Show the focused node\u2019s metadata dossier.",["m"],["tmux.menu.show"]),...vb("context","Browse context","Browse the focused node context.",["c"],["tmux.menu.show"]),...vb("providers","Open settings","Open the crouter settings panel.",[","],["tmux.menu"]),...vb("plugins","Browse plugins","Open the crouter plugin browser.",["l"],["tmux.menu"]),...vb("context-admin","Context surface","Open the context surface: what memory each event delivers, and the surfaces, gates, and caps that decide it.",["shift+c"],["tmux.menu"]),...vb("graph","Canvas graph","Open the canvas graph.",["g"],["tmux.menu"]),...vb("focus-manager","Go to manager","Focus this node\u2019s manager.",["h"],["tmux.menu"]),...vb("copy-id","Copy node id","Copy the focused node id to the system clipboard.",["y"],["tmux.menu"]),...vb("reload-viewer","Reload viewer","Respawn this pane\u2019s viewer onto the current runtime generation.",["r"],["tmux.menu"]),...vb("recap","Generate recap","Generate the focused node\u2019s Goal and State recap and refresh its generated title.",["s"],["tmux.menu"]),...vb("issues","Open create menu","Open the create submenu.",["c"],["tmux.menu"]),...vb("issue.idea","Create idea","Create an idea issue.",["i"],["tmux.menu.issue"]),...vb("issue.bug","Create bug","Create a bug issue.",["b"],["tmux.menu.issue"]),qa("crtr.tmux.node.next","Global tmux","Next node","Focus the next canvas node.",["alt+]"],"host-global",["tmux.root"]),qa("crtr.tmux.node.previous","Global tmux","Previous node","Focus the previous canvas node.",["alt+["],"host-global",["tmux.root"]),qa("crtr.tmux.inbox.toggle","Global tmux","Toggle inbox","Open or close the human inbox in the focused viewer.",["alt+i"],"host-global",["tmux.root"]),...IP("crtr.tmux.menu.attach.detach","crtr.attach.detach","Detach","Detach from the node.",["d"],["ctrl+d"]),...IP("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"]),...IP("crtr.tmux.menu.attach.graph.toggle","crtr.attach.graph.toggle","Toggle graph","Open or close the graph overlay.",["g"],["alt+g"]),...IP("crtr.tmux.menu.attach.help.toggle","crtr.attach.help.toggle","Help","Open the attach help overlay.",["?"],["alt+shift+k"]),...IP("crtr.tmux.menu.attach.inbox.toggle","crtr.attach.inbox.toggle","Toggle inbox","Open or close the human inbox surface in this viewer.",["i"],[]),...IP("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"]),...IP("crtr.tmux.menu.attach.model-ladder.next","crtr.attach.model-ladder.next","Next model","Move to the next model ladder rung.",["]"],["alt+m"]),...IP("crtr.tmux.menu.attach.model-ladder.previous","crtr.attach.model-ladder.previous","Previous model","Move to the previous model ladder rung.",["["],["alt+shift+m"]),...IP("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"]),...IP("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"]),...IP("crtr.tmux.menu.attach.profile-files","crtr.attach.profile-files","Search profile files","Fuzzy-match path segments across the node family\u2019s working directories, profile projects and memory, and ancestor crouter memory stores; Ctrl+Y copies a selected path.",["f"],["ctrl+f"]),...IP("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+/"]),...IP("crtr.tmux.menu.attach.whip","crtr.attach.whip","Whip agent","Interrupt the agent and send a playful command.",["w"],[]),qa("crtr.attach.scroll.up","Attach","Scroll up","Scroll the transcript one line up.",["shift+up"],"terminal",F7),qa("crtr.attach.scroll.down","Attach","Scroll down","Scroll the transcript one line down.",["shift+down"],"terminal",F7),qa("crtr.attach.scroll.page-up","Attach","Scroll page up","Scroll the transcript one page up.",["pageup"],"terminal",F7),qa("crtr.attach.scroll.page-down","Attach","Scroll page down","Scroll the transcript one page down.",["pagedown"],"terminal",F7),qa("crtr.attach.scroll.live","Attach","Return to live","Return the transcript to the live bottom.",["shift+end"],"terminal",F7),qa("crtr.attach.mouse.toggle","Attach","Toggle mouse wheel scrolling","Toggle mouse wheel scrolling on or off.",["alt+shift+o"],"terminal",F7),qa("crtr.attach.copy.message","Attach","Copy visible message","Copy the newest message visible in the transcript viewport.",["alt+shift+y"],"terminal",F7),qa("crtr.attach.search.next","Attach","Next match","Move to the next transcript search match.",["n"],"terminal",["attach.search"]),qa("crtr.attach.search.previous","Attach","Previous match","Move to the previous transcript search match.",["shift+n"],"terminal",["attach.search"]),qa("crtr.attach.search.edit","Attach","Edit query","Return to editing the transcript search query.",["/"],"terminal",["attach.search"]),qa("crtr.attach.search.close","Attach","Close search","Leave transcript search and clear its highlights.",["escape"],"terminal",["attach.search"],"dismiss-modal"),qa("crtr.graph.down","GRAPH","Move down","Move to the next graph row.",["j"],"terminal",["graph"]),qa("crtr.graph.up","GRAPH","Move up","Move to the previous graph row.",["k"],"terminal",["graph"]),qa("crtr.graph.first","GRAPH","First row","Move to the first graph row.",["g"],"terminal",["graph"]),qa("crtr.graph.last","GRAPH","Last row","Move to the last graph row.",["shift+g"],"terminal",["graph"]),qa("crtr.graph.collapse-or-manager","GRAPH","Collapse or manager","Collapse a node or move to its manager.",["h"],"terminal",["graph"]),qa("crtr.graph.expand-or-child","GRAPH","Expand or child","Expand a node or move to its child.",["l"],"terminal",["graph"]),qa("crtr.graph.focus","GRAPH","Focus node","Focus the selected node.",["enter"],"terminal",["graph"]),qa("crtr.graph.revive","GRAPH","Revive node","Revive and open the selected dormant node.",["r"],"terminal",["graph"]),qa("crtr.graph.focus-manager","GRAPH","Focus manager","Focus the selected node manager.",["m"],"terminal",["graph"]),qa("crtr.graph.close-subtree","GRAPH","Close subtree","Ask to close the selected subtree.",["x"],"terminal",["graph"]),qa("crtr.graph.dismiss","GRAPH","Dismiss graph","Close the graph overlay.",["escape"],"terminal",["graph"],"dismiss-modal"),qa("crtr.graph.confirm.accept","GRAPH","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["graph.confirm"]),qa("crtr.graph.confirm.cancel","GRAPH","Cancel close","Cancel closing the selected subtree.",["n","escape"],"terminal",["graph.confirm"],"dismiss-modal"),qa("crtr.inspector.force-quit","Inspector","Force quit Inspector","Immediately leave the Inspector.",["ctrl+c"],"host-global",["inspector"],"leave-screen"),qa("crtr.inspector.down","Inspector","Move down","Move the Inspector selection or scroll cursor down.",["j","down"],"terminal",["inspector"]),qa("crtr.inspector.up","Inspector","Move up","Move the Inspector selection or scroll cursor up.",["k","up"],"terminal",["inspector"]),qa("crtr.inspector.section-next","Inspector","Next section","Move to the next Inspector section.",["tab"],"terminal",["inspector"]),qa("crtr.inspector.section-prev","Inspector","Previous section","Move to the previous Inspector section.",["shift+tab"],"terminal",["inspector"]),qa("crtr.inspector.page-down","Inspector","Page down","Scroll the Inspector detail body down.",["ctrl+d","pagedown"],"terminal",["inspector"]),qa("crtr.inspector.page-up","Inspector","Page up","Scroll the Inspector detail body up.",["ctrl+u","pageup"],"terminal",["inspector"]),qa("crtr.inspector.toggle-detail","Inspector","Toggle item detail","Expand or collapse the selected cron or background job.",["enter"],"terminal",["inspector"]),qa("crtr.inspector.cancel-item","Inspector","Cancel selected item","Arm cancellation for the selected cron, or stopping for the selected background job.",["x"],"terminal",["inspector"]),qa("crtr.inspector.open-log","Inspector","Open job log","Follow the selected background job\u2019s log in a new tmux window.",["o"],"terminal",["inspector"]),qa("crtr.inspector.confirm","Inspector","Confirm action","Confirm the armed Inspector action.",["y"],"terminal",["inspector"]),qa("crtr.inspector.dismiss","Inspector","Dismiss action","Dismiss an Inspector confirmation or banner.",["escape"],"terminal",["inspector"],"dismiss-modal"),qa("crtr.inspector.retarget","Inspector","Retarget","Inspect the selected cron anchor or creator node.",["t"],"terminal",["inspector"]),qa("crtr.inspector.refresh","Inspector","Refresh","Refresh the Inspector now.",["g","r"],"terminal",["inspector"]),qa("crtr.inspector.quit","Inspector","Quit","Leave the Inspector.",["q"],"terminal",["inspector"],"leave-screen"),...nUi(),...iUi(),...oUi()]);function nUi(){let e="browse";return[qa("crtr.browse.quit","Browse and pickers","Quit browse","Leave canvas browse.",["q","escape","ctrl+c"],"terminal",[e],"leave-screen"),qa("crtr.browse.down","Browse and pickers","Move down","Move to the next row.",["j","down"],"terminal",[e]),qa("crtr.browse.up","Browse and pickers","Move up","Move to the previous row.",["k","up"],"terminal",[e]),qa("crtr.browse.first","Browse and pickers","First row","Move to the first row.",["g"],"terminal",[e]),qa("crtr.browse.last","Browse and pickers","Last row","Move to the last row.",["shift+g"],"terminal",[e]),qa("crtr.browse.expand-or-child","Browse and pickers","Expand or child","Expand a row or move to its child.",["l","right"],"terminal",[e]),qa("crtr.browse.collapse-or-parent","Browse and pickers","Collapse or parent","Collapse a row or move to its parent.",["h","left"],"terminal",[e]),qa("crtr.browse.toggle-fold","Browse and pickers","Toggle fold","Toggle the selected fold.",["space"],"terminal",[e]),qa("crtr.browse.tab-next","Browse and pickers","Next tab","Select the next browse tab.",["tab","]"],"terminal",[e]),qa("crtr.browse.tab-previous","Browse and pickers","Previous tab","Select the previous browse tab.",["shift+tab","["],"terminal",[e]),...[1,2,3,4,5].map(t=>qa(`crtr.browse.tab.${t}`,"Browse and pickers",`Tab ${t}`,`Select browse tab ${t}.`,[`${t}`],"terminal",[e])),qa("crtr.browse.close-subtree","Browse and pickers","Close subtree","Ask to close the selected subtree.",["x"],"terminal",[e]),qa("crtr.browse.confirm-close","Browse and pickers","Confirm close","Confirm closing the selected subtree.",["y"],"terminal",["browse.confirm"]),qa("crtr.browse.sort","Browse and pickers","Change sort","Change the browse sort.",["s"],"terminal",[e]),qa("crtr.browse.scope","Browse and pickers","Change scope","Toggle the browse cwd scope.",["c"],"terminal",[e]),qa("crtr.browse.profile","Browse and pickers","Toggle profile","Toggle the browse profile scope.",["shift+p"],"terminal",[e]),qa("crtr.browse.residents","Browse and pickers","Toggle residents","Toggle resident display.",["r"],"terminal",[e]),qa("crtr.browse.preview","Browse and pickers","Toggle preview","Toggle the preview panel.",["v"],"terminal",[e]),qa("crtr.browse.pin","Browse and pickers","Pin node","Star or unstar the selected node.",["p"],"terminal",[e]),qa("crtr.browse.search","Browse and pickers","Search","Open browse search.",["/"],"terminal",[e]),qa("crtr.browse.revive-now","Browse and pickers","Revive now","Revive the selected node now.",["shift+k"],"terminal",[e]),qa("crtr.browse.focus","Browse and pickers","Focus node","Focus the selected node.",["enter","o"],"terminal",[e]),qa("crtr.browse.focus-background","Browse and pickers","Focus node (keep browsing)","Focus the selected node without leaving the navigator.",["shift+o"],"terminal",[e]),qa("crtr.browse.yank-id","Browse and pickers","Yank node id","Copy the selected node id to the system clipboard.",["y"],"terminal",[e]),qa("crtr.browse.search.cancel","Browse and pickers","Cancel search","Cancel browse search.",["escape"],"terminal",["browse.search"],"dismiss-modal"),qa("crtr.browse.search.commit","Browse and pickers","Commit search","Apply browse search.",["enter"],"terminal",["browse.search"]),qa("crtr.browse.search.delete","Browse and pickers","Delete search text","Delete the previous search character.",["backspace"],"terminal",["browse.search"]),qa("crtr.browse.search.quit","Browse and pickers","Quit browse","Leave canvas browse from search.",["ctrl+c"],"terminal",["browse.search"],"leave-screen")]}function iUi(){let e="profile.menu",t="profile.search";return[qa("crtr.profile.menu.up","Profiles","Move up","Move to the previous profile.",["k","up"],"terminal",[e]),qa("crtr.profile.menu.down","Profiles","Move down","Move to the next profile.",["j","down"],"terminal",[e]),qa("crtr.profile.menu.select","Profiles","Select profile","Select the highlighted profile.",["enter"],"terminal",[e]),qa("crtr.profile.menu.accept-default","Profiles","Accept default","Accept the default profile.",["escape"],"terminal",[e],"leave-screen"),qa("crtr.profile.menu.abort","Profiles","Abort","Leave profile selection.",["ctrl+c"],"terminal",[e],"leave-screen"),...[1,2,3,4,5,6,7,8,9].map(r=>qa(`crtr.profile.menu.slot.${r}`,"Profiles",`Profile slot ${r}`,`Select profile slot ${r}.`,[`${r}`],"terminal",[e])),qa("crtr.profile.menu.create","Profiles","Create profile","Create a profile.",["c"],"terminal",[e]),qa("crtr.profile.menu.search-existing","Profiles","Search profiles","Search existing profiles.",["s"],"terminal",[e]),qa("crtr.profile.menu.use-root","Profiles","Use root profile","Use the root profile.",["r"],"terminal",[e]),qa("crtr.profile.menu.set-default","Profiles","Set default","Set the selected profile as default.",["d"],"terminal",[e]),qa("crtr.profile.menu.add-directory","Profiles","Add directory","Add a directory to the profile.",["a"],"terminal",[e]),qa("crtr.profile.menu.unpin","Profiles","Unpin directory","Unpin the selected directory.",["u"],"terminal",[e]),qa("crtr.profile.menu.manage","Profiles","Manage profiles","Open the profiles settings page in a popup.",["v"],"terminal",[e]),qa("crtr.profile.search.up","Profiles","Move up","Move to the previous search result.",["up","ctrl+p"],"terminal",[t]),qa("crtr.profile.search.down","Profiles","Move down","Move to the next search result.",["down","ctrl+n"],"terminal",[t]),qa("crtr.profile.search.pick","Profiles","Pick profile","Pick the highlighted profile.",["enter"],"terminal",[t]),qa("crtr.profile.search.back","Profiles","Back","Return to profile selection.",["escape"],"terminal",[t],"leave-screen"),qa("crtr.profile.search.delete","Profiles","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",[t]),qa("crtr.profile.search.abort","Profiles","Abort","Leave profile search.",["ctrl+c"],"terminal",[t],"leave-screen")]}function oUi(){return[qa("crtr.setup.cancel","Setup","Cancel setup","Leave the setup wizard.",["q","ctrl+c","ctrl+d"],"terminal",rUi,"leave-screen"),qa("crtr.setup.tab-next","Setup","Next tab","Select the next setup tab.",["tab","right"],"terminal",CIr),qa("crtr.setup.tab-previous","Setup","Previous tab","Select the previous setup tab.",["shift+tab","left"],"terminal",CIr),qa("crtr.setup.open","Setup","Open","Open the selected setup item.",["enter"],"terminal",["setup.login"]),qa("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"]),qa("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"]),qa("crtr.setup.toggle","Setup","Toggle","Toggle the selected setup item.",["space"],"terminal",["setup.list","setup.keybindings"]),qa("crtr.setup.details","Setup","Show details","Show details for the selected item.",["?"],"terminal",["setup.list"]),qa("crtr.setup.advance","Setup","Advance","Advance the setup flow.",["enter"],"terminal",["setup.list"]),qa("crtr.setup.confirm.accept","Setup","Confirm","Accept the setup confirmation.",["y","enter"],"terminal",["setup.confirm","setup.models.confirm"]),qa("crtr.setup.confirm.back","Setup","Go back","Cancel the setup confirmation.",["n","escape","q"],"terminal",["setup.confirm","setup.models.confirm"],"dismiss-modal"),qa("crtr.setup.keybindings.edit","Setup","Edit binding","Edit the selected binding.",["enter"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.commit-edit","Setup","Commit edit","Commit the active binding edit.",["enter"],"terminal",["setup.keybindings.edit"]),qa("crtr.setup.keybindings.cancel-edit","Setup","Cancel edit","Cancel the active binding edit.",["escape"],"terminal",["setup.keybindings.edit"],"dismiss-modal"),qa("crtr.setup.keybindings.unbind","Setup","Unbind","Disable the selected binding.",["delete"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.reset-row","Setup","Reset binding","Reset the selected binding.",["r"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.reset-all","Setup","Reset all bindings","Reset all bindings to defaults.",["shift+r"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.save","Setup","Save bindings","Save keybinding changes.",["s"],"terminal",["setup.keybindings"],"save-keybindings"),qa("crtr.setup.keybindings.discard","Setup","Discard changes","Discard keybinding changes.",["escape"],"terminal",["setup.keybindings"],"leave-screen"),qa("crtr.setup.keybindings.page-up","Setup","Page up","Move up one keybinding page.",["pageup"],"terminal",["setup.keybindings","setup.keybindings.edit"]),qa("crtr.setup.keybindings.page-down","Setup","Page down","Move down one keybinding page.",["pagedown"],"terminal",["setup.keybindings","setup.keybindings.edit"]),qa("crtr.setup.keybindings.filter","Setup","Filter bindings","Open the keybinding filter.",["/"],"terminal",["setup.keybindings"]),qa("crtr.setup.keybindings.filter-delete","Setup","Delete filter text","Delete the previous filter character.",["backspace"],"terminal",["setup.keybindings.filter"]),qa("crtr.setup.keybindings.filter-clear","Setup","Clear filter","Clear the keybinding filter.",["escape"],"terminal",["setup.keybindings.filter"],"dismiss-modal"),qa("crtr.setup.cell-previous","Setup","Previous field","Select the previous field or setup table cell.",["h"],"terminal",["setup.models","setup.keybindings"]),qa("crtr.setup.cell-next","Setup","Next field","Select the next field or setup table cell.",["l"],"terminal",["setup.models","setup.keybindings"]),qa("crtr.setup.models.open","Setup","Edit model","Edit the selected model cell or route field.",["enter"],"terminal",["setup.models","setup.models.route-form"]),qa("crtr.setup.models.scope-next","Setup","Next model config scope","Edit the next applicable user, profile, or project config.",["s"],"terminal",["setup.models"]),qa("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"]),qa("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")]}var CK=new Set(wP.map(e=>e.id));function aTe(e){return e.contexts.includes("attach")&&(e.inputKind==="terminal"||e.inputKind==="host-global")}var evt=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"}]);import{dirname as f$i,join as Cwr}from"node:path";var tvt="working",xIr=["thinking","planning","checking",tvt],L6e="Working...";function IIr(e){if(!Array.isArray(e))return[tvt];let t=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return t.length>0?t:[tvt]}var RP={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},rvt=4,wIr=".crouter-plugin",RIr="plugin.json";var dM=".crouter",F6e="config.json",kIr="state.json";var NIr="profiles",sUi=3,B6e=["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"],xK=["random","go-faster"],aUi="random",nvt=2,IK=["tmux","on","off"],wK=["none","user","agent","both"],ivt="none";function U6e(){return{schema_version:rvt,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:sUi,auto_open_child_viewers:!0,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...xIr],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...B6e],whip_message_mode:aUi,mouse_mode_default:"tmux",live_cycles:nvt,condensed_history:ivt,bash_tool_purpose:!0,fold_finished_tools:!0,summarize_tool_calls:!0,detailed_tool_recaps:!0,keybindings:{},tmux_passthrough:[],modelLadders:avt(),kinds:svt(),remoteCanvas:ovt(),spawnEnv:{allow:[]},bin:{},humanActions:{}}}function ovt(){return{targets:{}}}function svt(){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 avt(){return{anthropic:{ultra:"anthropic/claude-fable-5:xhigh",strong:"anthropic/claude-opus-5:medium",medium:"anthropic/claude-sonnet-5:xhigh",light:"anthropic/claude-haiku-4-5:high"},openai:{ultra:"openai-codex/gpt-5.6-sol:max",strong:"openai-codex/gpt-5.6-sol:high",medium:"openai-codex/gpt-5.6-terra:medium",light:"openai-codex/gpt-5.6-luna:low"}}}function cvt(){return{marketplaces:{},plugins:{}}}var r$=class extends Error{code;exitCode;details;constructor(t,r,i=RP.GENERAL,o){super(r),this.name="CrtrError",this.code=t,this.exitCode=i,this.details=o}};function lvt(e,t){return new r$("not_found",e,RP.NOT_FOUND,t)}function mR(e,t){return new r$("usage",e,RP.USAGE,t)}function PIr(e,t){return new r$("ambiguous",e,RP.AMBIGUOUS,t)}import{appendFileSync as cUi,existsSync as OIr,mkdirSync as lUi,renameSync as DIr,rmSync as uUi,statSync as pUi}from"node:fs";import{dirname as dUi}from"node:path";var fUi=65536,mUi=5*1024*1024;function $6e(e,t){if(t.includes(`
1778
1778
  `)||t.includes("\r"))return!1;let r=Buffer.byteLength(t,"utf8")+1;if(r>fUi)return!1;try{lUi(dUi(e),{recursive:!0});let i=OIr(e)?pUi(e).size:0;return i+r>mUi&&i>0&&(uUi(`${e}.2`,{force:!0}),OIr(`${e}.1`)&&DIr(`${e}.1`,`${e}.2`),DIr(e,`${e}.1`)),cUi(e,`${t}
1779
1779
  `,"utf8"),!0}catch{return!1}}var uvt=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"];function hUi(e){return typeof e=="object"&&e!==null?e:void 0}function MIr(e){return typeof e=="string"?e:""}function LIr(e){if(e instanceof Error){let r={type:e.name||"Error",message:e.message};return typeof e.stack=="string"&&(r.stack=e.stack),e.cause!==void 0&&(r.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),r}if(typeof e=="string")return{type:"Error",message:e};let t=hUi(e);return{type:MIr(t?.name)||"Error",message:MIr(t?.message)||String(e)}}import{AsyncLocalStorage as _Ui}from"node:async_hooks";import{randomBytes as gUi}from"node:crypto";var yUi=/^(?!0{32}$)[0-9a-f]{32}$/,pvt=new _Ui;function RK(e){if(typeof e!="string"||!yUi.test(e))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return e}function dvt(){let e;do e=gUi(16).toString("hex");while(e==="00000000000000000000000000000000");return RK(e)}var cTe={current:()=>pvt.getStore(),run:(e,t)=>pvt.run(RK(e),t),fresh:e=>{let t=dvt();return pvt.run(t,()=>e(t))}};var bUi=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,EUi=new Set(["error","warn","info","debug"]),AUi=new Set(["daemon","broker","control-plane","front","sentinel"]),SUi=new Set(["succeeded","failed","skipped"]),TUi=new Set(["auto","manual","fatal"]),vUi=new Set(uvt);function CUi(e){return Buffer.byteLength(e,"utf8")}function z6e(e,t,r=128){if(typeof e!="string"||e===""||CUi(e)>r)throw new TypeError(`${t} must be a non-empty string of at most ${r} UTF-8 bytes`);return e}function xUi(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e))throw new TypeError("ts must be an ISO 8601 timestamp");let t=new Date(e);if(Number.isNaN(t.getTime()))throw new TypeError("ts must be an ISO 8601 timestamp");return t.toISOString()}function IUi(e){if(!vUi.has(e.class))throw new TypeError("error_class.class is invalid");let t={class:e.class};if(e.status!==void 0){if(!Number.isInteger(e.status))throw new TypeError("error_class.status must be an integer");t.status=e.status}if(e.provider!==void 0&&(t.provider=z6e(e.provider,"error_class.provider")),e.retry_disposition!==void 0){if(!TUi.has(e.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");t.retry_disposition=e.retry_disposition}return t}function FIr(e){if(!EUi.has(e.level))throw new TypeError("level is invalid");if(!AUi.has(e.component))throw new TypeError("component is invalid");let t=z6e(e.event,"event");if(!bUi.test(t))throw new TypeError("event must be a lowercase dotted identifier");let r=e.operation_id===void 0?cTe.current()??dvt():RK(e.operation_id),i={v:1,ts:e.ts===void 0?new Date().toISOString():xUi(e.ts),level:e.level,event:t,component:e.component,operation_id:r};if(e.node_id!==void 0&&(i.node_id=z6e(e.node_id,"node_id")),e.stream_id!==void 0&&(i.stream_id=z6e(e.stream_id,"stream_id")),e.duration_ms!==void 0){if(!Number.isFinite(e.duration_ms)||e.duration_ms<0)throw new TypeError("duration_ms must be finite and non-negative");i.duration_ms=e.duration_ms}if(e.outcome!==void 0){if(!SUi.has(e.outcome))throw new TypeError("outcome is invalid");i.outcome=e.outcome}if(e.attempt!==void 0){if(!Number.isInteger(e.attempt)||e.attempt<=0)throw new TypeError("attempt must be a positive integer");i.attempt=e.attempt}return e.error_class!==void 0&&(i.error_class=IUi(e.error_class)),e.error!==void 0&&(i.error=LIr(e.error)),e.fields!==void 0&&(i.fields=e.fields),i}function NK(e){return Buffer.byteLength(e,"utf8")}function kK(e,t){if(NK(e)<=t)return{value:e,altered:!1};let r="\u2026",i=t-NK(r),o=0,a="";for(let u of e){let p=NK(u);if(o+p>i)break;a+=u,o+=p}return{value:a+r,altered:!0}}function wUi(e){return e===void 0?"[Unsupported undefined]":typeof e=="function"?`[Unsupported function${e.name?` ${e.name}`:""}]`:typeof e=="symbol"?`[Unsupported ${String(e)}]`:`[Unsupported ${e?.constructor?.name??typeof e}]`}function fvt(e,t,r,i){if(i.remaining<=0)return{value:"[Omitted]",altered:!0,dropped:0};if(i.remaining-=1,e===null||typeof e=="boolean")return{value:e,altered:!1,dropped:0};if(typeof e=="string"){let o=kK(e,4096);return{value:o.value,altered:o.altered,dropped:0}}if(typeof e=="number")return Number.isFinite(e)?{value:e,altered:!1,dropped:0}:{value:String(e),altered:!0,dropped:0};if(typeof e=="bigint")return{value:e.toString(),altered:!0,dropped:0};if(e instanceof Date)return{value:Number.isNaN(e.getTime())?"Invalid Date":e.toISOString(),altered:!0,dropped:0};if(typeof e!="object"||e===void 0)return{value:wUi(e),altered:!0,dropped:0};if(r.has(e))return{value:"[Circular]",altered:!0,dropped:0};if(t>=4)return{value:"[Max depth]",altered:!0,dropped:0};r.add(e);try{if(Array.isArray(e)){let h=Math.min(e.length,64),m=[],g=e.length>h,E=e.length-h;for(let v=0;v<h;v+=1){if(i.remaining<=0){g=!0,E+=h-v;break}let T=fvt(e[v],t+1,r,i);m.push(T.value),g||=T.altered,E+=T.dropped}return{value:m,altered:g,dropped:E}}let o;try{o=Object.keys(e).sort()}catch{return{value:"[Unsupported object]",altered:!0,dropped:0}}let a=o.slice(0,64),u={},p=o.length>a.length,f=o.length-a.length;for(let h=0;h<a.length;h+=1){let m=a[h];if(i.remaining<=0){p=!0,f+=a.length-h;break}let g=kK(m,128),E;try{E=fvt(e[m],t+1,r,i)}catch{E={value:"[Unsupported property]",altered:!0,dropped:0}}if(Object.prototype.hasOwnProperty.call(u,g.value)){p=!0,f+=1;continue}u[g.value]=E.value,p||=g.altered||E.altered,f+=E.dropped}return{value:u,altered:p,dropped:f}}finally{r.delete(e)}}function RUi(e){let t=kK(String(e.type),128),r=kK(String(e.message),4096),i={type:t.value,message:r.value},o=t.altered||r.altered;if(e.stack!==void 0){let a=kK(String(e.stack),16384);i.stack=a.value,o||=a.altered}if(e.cause!==void 0){let a=kK(String(e.cause),4096);i.cause=a.value,o||=a.altered}return{value:i,altered:o}}function j6e(e){return JSON.stringify(e)}function lTe(e){return NK(j6e(e))+1}function BIr(e){let t=e.fields===void 0?void 0:fvt(e.fields,0,new WeakSet,{remaining:5e3}),r=e.error===void 0?void 0:RUi(e.error),i={v:1,ts:e.ts,level:e.level,event:e.event,component:e.component,operation_id:e.operation_id,...e.node_id===void 0?{}:{node_id:e.node_id},...e.stream_id===void 0?{}:{stream_id:e.stream_id},...e.duration_ms===void 0?{}:{duration_ms:e.duration_ms},...e.outcome===void 0?{}:{outcome:e.outcome},...e.attempt===void 0?{}:{attempt:e.attempt},...e.error_class===void 0?{}:{error_class:e.error_class},...r===void 0?{}:{error:r.value},...t===void 0?{}:{fields:t.value}},o=lTe(i),a=t?.altered===!0||r?.altered===!0||o>65536,u=t?.dropped??0;for(a&&Object.assign(i,{record_truncated:!0,original_bytes:o,dropped_fields_count:u});lTe(i)>65536&&i.fields!==void 0;){let h=i.fields,m=Object.keys(h);if(m.length===0){delete i.fields;break}m.sort((g,E)=>{let v=NK(j6e(h[E]))-NK(j6e(h[g]));return v!==0?v:E<g?-1:E>g?1:0}),delete h[m[0]],u+=1,i.record_truncated=!0,i.original_bytes=o,i.dropped_fields_count=u}let p=i.error;lTe(i)>65536&&p?.stack!==void 0&&delete p.stack,lTe(i)>65536&&p?.cause!==void 0&&delete p.cause,lTe(i)>65536&&p!==void 0&&(p.message=kK(p.message,64).value);let f=j6e(i);if(NK(f)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return f}import{join as PUi}from"node:path";import{homedir as kUi}from"node:os";import{join as PK}from"node:path";function wC(){let e=process.env.CRTR_HOME;return e!==void 0&&e!==""?e:PK(kUi(),dM,"canvas")}function mvt(){return PK(wC(),"on-disk-migration.lock")}function uTe(e){return $Ir(e),PK(G6e(e),"view.sock")}function q6e(){return PK(wC(),"nodes")}var NUi=128;function UIr(e){return typeof e=="string"&&e!==""&&e!=="."&&e!==".."&&!/[\\/\0]/u.test(e)&&Buffer.byteLength(e,"utf8")<=NUi}function $Ir(e){if(!UIr(e))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function G6e(e){return $Ir(e),PK(q6e(),e)}function B7(e){return PK(G6e(e),"context")}function fM(e){return PK(G6e(e),"job")}var V6e;function OUi(e,t){return e.component===t.component&&e.path===t.path&&e.node_id===t.node_id&&e.stream_id===t.stream_id}function DUi(e){if(V6e===void 0){V6e=e;return}if(!OUi(V6e,e))throw new Error("event source is already bound for this process")}function zIr(){DUi({component:"daemon",path:PUi(wC(),"crtrd.log")})}function W6e(){return V6e}function mM(e){let t=W6e();if(t===void 0)return!1;if(t.component==="broker"&&t.node_id!==void 0&&e.node_id!==void 0&&e.node_id!==t.node_id)throw new TypeError(`broker event target node_id must match bound node_id; received ${e.node_id}`);if(e.level==="debug"&&process.env.CRTR_LOG!=="debug")return!1;let r=FIr({...e,component:t.component,...t.node_id===void 0?{}:{node_id:t.node_id},...t.stream_id===void 0?{}:{stream_id:t.stream_id}});return $6e(t.path,BIr(r))}import{existsSync as pTe,lstatSync as DPs,mkdirSync as MUi,readdirSync as LUi,readFileSync as jIr,rmSync as FUi,statSync as BUi,symlinkSync as MPs,writeFileSync as UUi,cpSync as LPs,readlinkSync as FPs,renameSync as $Ui,chmodSync as zUi,realpathSync as jUi}from"node:fs";import{dirname as qUi,join as GUi,relative as UPs,sep as $Ps}from"node:path";import{homedir as VUi,platform as WUi}from"node:os";function ak(e){try{return jUi(e)}catch{return e}}function hvt(e,t=VUi()){return e==="~"?t:e.startsWith("~/")||WUi()==="win32"&&e.startsWith("~\\")?GUi(t,e.slice(2)):e}function dTe(e){MUi(e,{recursive:!0})}function AF(e,t,r){fTe(e,JSON.stringify(t,null,2)+`
1780
1780
  `,r)}function fTe(e,t,r){dTe(qUi(e));let i=`${e}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,o=r?.mode??(pTe(e)?BUi(e).mode&511:384);try{UUi(i,t,{mode:o}),zUi(i,o),$Ui(i,e)}finally{pTe(i)&&FUi(i,{force:!0})}}function QUi(e){return JSON.parse(jIr(e,"utf8"))}function n$(e){return pTe(e)?QUi(e):null}function hM(e){try{return JSON.parse(jIr(e,"utf8"))}catch{return null}}function OK(e){return pTe(e)}function Q6e(e){return pTe(e)?LUi(e,{withFileTypes:!0}).filter(t=>t.isDirectory()||t.isSymbolicLink()).map(t=>t.name):[]}import{homedir as ZIr}from"node:os";import{existsSync as I4i,statSync as w4i}from"node:fs";import{join as ewr,resolve as twr,dirname as R4i}from"node:path";import{existsSync as H6e,readdirSync as d4i,readFileSync as f4i,realpathSync as HIr,renameSync as XPs,rmSync as ZPs,statSync as eOs,writeFileSync as tOs}from"node:fs";import{dirname as nOs,join as hTe,relative as m4i,resolve as yvt,sep as h4i}from"node:path";var mTe=["none","name","preview","content"];import{existsSync as HUi,mkdirSync as JUi,readdirSync as GIr,rmSync as VIr,rmdirSync as YUi,statSync as KUi,unlinkSync as XUi,writeFileSync as ZUi}from"node:fs";import{randomUUID as e4i}from"node:crypto";var _vt="owner.",t4i=10,r4i=250,n4i=3e4,i4i=5e3;function o4i(e){return Math.min(e*2,r4i)}function s4i(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function gvt(e,t){return`${e}/${_vt}${t}`}function WIr(e){try{return GIr(e).find(t=>t.startsWith(_vt))?.slice(_vt.length)??null}catch{return null}}function a4i(e){let t=Number(e.split(".",1)[0]);if(!Number.isSafeInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}function c4i(e){try{return GIr(e).length===0}catch{return!1}}function l4i(e){try{return Date.now()-KUi(e).mtimeMs}catch{return 0}}function u4i(e,t){let r=WIr(e);if(r!==null){if(a4i(r))return;try{XUi(gvt(e,r))}catch(i){if(i.code==="ENOENT")return;throw i}}else{if(l4i(e)<=t)return;if(!c4i(e)){VIr(e,{recursive:!0,force:!0});return}}try{YUi(e)}catch(i){let o=i.code;if(o!=="ENOENT"&&o!=="ENOTEMPTY"&&o!=="EEXIST")throw i}}function QIr(e){let t=WIr(e);if(t===null)return null;let r=Number(t.split(".",1)[0]);return Number.isSafeInteger(r)&&r>0?r:null}function qIr(e,t){let r=`${process.pid}.${e4i()}`;try{return JUi(e,{mode:448}),ZUi(gvt(e,r),"",{flag:"wx",mode:384}),{path:e,token:r}}catch(i){if(i.code!=="EEXIST")throw i;return u4i(e,t),null}}function ck(e,t,r={}){let i=r.staleMs??n4i,o=Date.now()+(r.timeoutMs??i4i),a=t4i,u=qIr(e,i);for(;u===null;){if(Date.now()>=o)throw r.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${e}`);s4i(Math.min(a,Math.max(0,o-Date.now()))),a=o4i(a),u=qIr(e,i)}try{return t()}finally{HUi(gvt(u.path,u.token))&&VIr(u.path,{recursive:!0,force:!0})}}var bvt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,_4i="root-00000000";function _Te(){return hTe(i$(),NIr)}function g4i(e){if(!bvt.test(e))throw mR(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function y4i(e){let t=_Te(),r=yvt(t),i=H6e(t)?HIr(t):r,o=H6e(e)?HIr(e):yvt(i,m4i(r,yvt(e)));if(o!==i&&!o.startsWith(i+h4i))throw mR(`profile path escapes the profiles root: ${e}`)}function JIr(e){g4i(e);let t=hTe(_Te(),e);return y4i(t),t}function J6e(e){return hTe(JIr(e),"memory")}function b4i(e,t){let r=typeof t.home=="string"&&t.home!==""?t.home:null,i=e===_4i?r:r??t.projects[0]?.path??null,o=typeof t.paused_at=="string"&&t.paused_at!==""?t.paused_at:null;return{...t,home:i,paused_at:o}}function E4i(e){let t=mTe.join(", ");if(!Array.isArray(e))throw mR("projects must be an array of {path, memory} objects",{received:typeof e,field:"projects",next:`Pass entries like {"path": "/abs/dir", "memory": "content"} \u2014 memory is one of: ${t}.`});for(let r of e){if(typeof r!="object"||r===null||Array.isArray(r))throw mR(`invalid project entry: ${JSON.stringify(r)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir", "memory": "content"}.'});let{path:i,memory:o}=r;if(typeof i!="string"||i.trim()==="")throw mR(`project entry has no path: ${JSON.stringify(r)}`,{field:"projects",next:"Give every project entry a non-empty directory path."});if(typeof o!="string"||!mTe.includes(o))throw mR(`invalid project memory value: ${JSON.stringify(o)}`,{received:String(o),field:"projects",next:`Set memory on ${i} to one of: ${t}.`})}}function A4i(e){try{return E4i(e),!0}catch{return!1}}function S4i(e,t){if(!H6e(e))return null;try{let r=JSON.parse(f4i(e,"utf8"));return A4i(r.projects)?b4i(t,r):null}catch{return null}}function YIr(){let e=_Te();if(!H6e(e))return{entries:[],unreadableIds:[]};let t=[],r=[];for(let i of d4i(e,{withFileTypes:!0})){if(!i.isDirectory())continue;let o=i.name;if(!bvt.test(o))continue;let a=S4i(hTe(e,o,"profile.json"),o);a===null?r.push(o):t.push({profileId:o,manifest:a})}return{entries:t,unreadableIds:r}}function T4i(){return YIr().entries}function v4i(e){let{entries:t,unreadableIds:r}=YIr(),i=C4i(t,e);return i!==null?{kind:"resolved",entry:i}:r.includes(e)?{kind:"unreadable",profileId:e,manifestPath:hTe(_Te(),e,"profile.json")}:{kind:"absent"}}function C4i(e,t){if(bvt.test(t)){let i=e.find(o=>o.profileId===t);if(i!==void 0)return i}let r=e.filter(i=>i.manifest.name===t);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>o.profileId);throw PIr(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function x4i(e,t){let r=e.map(i=>`${i.profileId} (${i.manifest.name})`);return lvt(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function U7(e){let t=v4i(e);if(t.kind==="resolved")return t.entry;throw x4i(T4i(),e)}var Evt="content",XIr=new Map;function k4i(e,t){return`${e}\0${t??""}`}function i$(){return ewr(ZIr(),dM)}function N4i(e,t){if(!I4i(e)||ak(e)===ak(t))return!1;try{return w4i(e).isDirectory()}catch{return!1}}function P4i(e=process.cwd()){return rwr(e)[0]??null}function O4i(e,t){let r=[],i=ak(ZIr()),o=twr(e);for(;;){let a=ewr(o,dM);if(N4i(a,t)&&r.push(a),ak(o)===i)return r;let u=R4i(o);if(u===o)return r;o=u}}function rwr(e=process.cwd(),t=Iae()||null){return D4i(e,t).roots}function D4i(e,t){let r=twr(e),i=k4i(r,t),o=XIr.get(i);if(o!==void 0)return o;let a=i$(),u=[{dir:r,memory:null}];if(t!==null&&t!=="")try{let{manifest:E}=U7(t);for(let v of E.projects)u.push({dir:v.path,memory:v.memory})}catch{}let p=new Set,f=[],h=new Map;for(let E of u)for(let v of O4i(E.dir,a))p.has(v)||(p.add(v),f.push(v)),E.memory!==null&&!h.has(v)&&h.set(v,E.memory);let m=f.map(E=>({root:E,memory:h.get(E)??Evt})),g={roots:f,annotated:m};return XIr.set(i,g),g}function nwr(e){return P4i(e)}function o$(e){return e==="builtin"?null:e==="user"?i$():nwr()}function Avt(e){let t=o$(e);if(!t)throw mR(`no ${e} scope available \u2014 run \`crtr init\` here or use --scope user`);return t}import{join as Ivt}from"node:path";import{join as r$i}from"node:path";import{request as M4i}from"node:http";import{request as L4i}from"node:https";import{homedir as F4i}from"node:os";import{join as swr}from"node:path";var p_=class extends Error{status;code;details;constructor(t,r,i,o){super(i),this.name="ApiError",this.status=t,this.code=r,o!==void 0&&(this.details=o)}};function Tvt(e){if(typeof e!="object"||e===null)return!1;let t=e.error;if(typeof t!="object"||t===null)return!1;let{code:r,message:i}=t;return typeof r=="string"&&typeof i=="string"}var cc={healthz:()=>"/healthz",status:()=>"/v1/status",daemonRestart:()=>"/v1/daemon/restart",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:e=>`/v1/nodes/${e}`,nodeSnapshot:e=>`/v1/nodes/${e}/snapshot`,nodeSubject:e=>`/v1/nodes/${e}/subject`,nodeSession:e=>`/v1/nodes/${e}/session`,nodeChatInventory:e=>`/v1/nodes/${e}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:e=>`/v1/nodes/${e}/transcript`,nodeContext:e=>`/v1/nodes/${e}/context`,nodeArtifacts:e=>`/v1/nodes/${e}/artifacts`,nodeReports:e=>`/v1/nodes/${e}/reports`,nodeJobs:e=>`/v1/nodes/${e}/jobs`,nodeJob:(e,t)=>`/v1/nodes/${e}/jobs/${t}`,nodeMessages:e=>`/v1/nodes/${e}/messages`,nodeInterrupt:e=>`/v1/nodes/${e}/interrupt`,nodeFork:e=>`/v1/nodes/${e}/fork`,nodeRevive:e=>`/v1/nodes/${e}/revive`,nodeRelaunchRoot:e=>`/v1/nodes/${e}/relaunch-root`,nodeBrokerSessionBound:e=>`/v1/nodes/${e}/broker/session-bound`,nodeBrokerSettle:e=>`/v1/nodes/${e}/broker/settle`,nodeBrokerInboxCursor:e=>`/v1/nodes/${e}/broker/inbox-cursor`,nodeBrokerModel:e=>`/v1/nodes/${e}/broker/model`,nodeBrokerExtensionState:e=>`/v1/nodes/${e}/broker/extension-state`,nodeBrokerGeneratedName:e=>`/v1/nodes/${e}/broker/generated-name`,nodeBrokerPersonaAck:e=>`/v1/nodes/${e}/broker/persona-ack`,nodeClose:e=>`/v1/nodes/${e}/close`,nodeRecycle:e=>`/v1/nodes/${e}/recycle`,nodeDemote:e=>`/v1/nodes/${e}/demote`,nodePromote:e=>`/v1/nodes/${e}/promote`,nodeYield:e=>`/v1/nodes/${e}/yield`,nodeWait:e=>`/v1/nodes/${e}/wait`,nodeConfig:e=>`/v1/nodes/${e}/config`,nodeWorktreeClose:e=>`/v1/nodes/${e}/worktree/close`,nodeWorktreeAbandon:e=>`/v1/nodes/${e}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",nodeAttach:e=>`/v1/nodes/${e}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:e=>`/v1/focuses/${e}`,nodeSubscriptions:e=>`/v1/nodes/${e}/subscriptions`,nodeSubscription:(e,t)=>`/v1/nodes/${e}/subscriptions/${t}`,crons:()=>"/v1/crons",cron:e=>`/v1/crons/${e}`,cronPause:e=>`/v1/crons/${e}/pause`,cronResume:e=>`/v1/crons/${e}/resume`,cronRun:e=>`/v1/crons/${e}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasRoster:()=>"/v1/canvas/roster",canvasPrune:()=>"/v1/canvas/prune",canvasRebuildIndex:()=>"/v1/canvas/rebuild-index",humanBridge:()=>"/v1/human/bridge",humanTicketResolve:e=>`/v1/human/tickets/${e}/resolve`,humanTicketCancel:e=>`/v1/human/tickets/${e}/cancel`,humanReviews:()=>"/v1/human/reviews",humanReview:e=>`/v1/human/reviews/${e}`,humanReviewByBridge:e=>`/v1/human/reviews/by-bridge/${e}`,humanReviewSubmit:e=>`/v1/human/reviews/${e}/submit`,humanReviewCancel:e=>`/v1/human/reviews/${e}/cancel`,humanReviewDocument:e=>`/v1/human/reviews/${e}/document`,humanReviewComments:e=>`/v1/human/reviews/${e}/comments`,humanReviewCommentEvents:e=>`/v1/human/reviews/${e}/comment-events`,humanReviewCommentRanges:e=>`/v1/human/reviews/${e}/comment-ranges`,humanComment:e=>`/v1/human/comments/${e}`,humanCommentEdit:e=>`/v1/human/comments/${e}/edit`,humanCommentResolve:e=>`/v1/human/comments/${e}/resolve`,humanCommentReopen:e=>`/v1/human/comments/${e}/reopen`,humanCommentDelete:e=>`/v1/human/comments/${e}/delete`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:e=>`/v1/human/inbox/${e}`,humanInboxRespond:e=>`/v1/human/inbox/${e}/respond`,humanInboxProgress:e=>`/v1/human/inbox/${e}/progress`,humanInboxResponse:e=>`/v1/human/inbox/${e}/response`,humanInboxCancel:e=>`/v1/human/inbox/${e}/cancel`,humanInboxFeedbackResolve:(e,t)=>`/v1/human/inbox/${e}/feedback-comments/${t}/resolve`,humanRequests:()=>"/v1/human/requests",humanRequest:e=>`/v1/human/requests/${e}`,humanRequestReplace:e=>`/v1/human/requests/${e}/replace`,humanRequestRespond:e=>`/v1/human/requests/${e}/respond`,humanRequestDismiss:e=>`/v1/human/requests/${e}/dismiss`,humanRequestCancel:e=>`/v1/human/requests/${e}/cancel`,profiles:()=>"/v1/profiles",profile:e=>`/v1/profiles/${e}`,profileMetadata:e=>`/v1/profiles/${e}/metadata`,modelAuths:()=>"/v1/model-auth",modelAuth:e=>`/v1/model-auth/${e}`,filePeek:()=>"/v1/files/peek",memoryResolve:()=>"/v1/memory/resolve"};function X6e(e){return typeof e=="string"&&e!==""&&e!=="."&&e!==".."&&!/[\\/\0]/u.test(e)&&Buffer.byteLength(e,"utf8")<=128}function iwr(e){return typeof e=="string"&&e!==""&&e!=="."&&e!==".."&&/^[A-Za-z0-9._~-]+$/u.test(e)&&Buffer.byteLength(e,"utf8")<=128}function owr(e){return typeof e=="string"&&e!==""&&e!=="."&&e!==".."&&!/[\\/\0\s?#%]/u.test(e)&&Buffer.byteLength(e,"utf8")<=128}var B4i=".crouter",U4i="crtrd.sock";function $4i(){let e=w7(),t=e!==void 0&&e!==""?e:swr(F4i(),B4i,"canvas");return swr(t,U4i)}var z4i=3e4,j4i=1e4,awr=200,$7=class e{socketPath;baseUrl;headers;autostart;timeoutMs;onColdSocket;coldStartDiagnostic;coldStartPollWindowMs;coldStartAbort;coldStartAttempted=!1;constructor(t){let r=t.socketPath!==void 0&&t.socketPath!=="",i=t.baseUrl!==void 0&&t.baseUrl!=="";if(r===i)throw new TypeError("CrtrClient requires exactly one of socketPath | baseUrl");r&&(this.socketPath=t.socketPath),i&&(this.baseUrl=new URL(t.baseUrl)),this.headers={...t.headers},this.autostart=t.autostart??r,this.timeoutMs=t.timeoutMs??z4i,t.onColdSocket!==void 0&&(this.onColdSocket=t.onColdSocket),t.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=t.coldStartDiagnostic),t.coldStartAbort!==void 0&&(this.coldStartAbort=t.coldStartAbort),this.coldStartPollWindowMs=t.coldStartPollWindowMs??j4i}static forLocalSocket(t){return new e({socketPath:$4i(),autostart:!0,...t})}healthz(){return this.request("GET",cc.healthz())}status(){return this.request("GET",cc.status())}restartDaemon(){return this.request("POST",cc.daemonRestart())}createNode(t){return this.request("POST",cc.nodes(),t)}listNodes(t){return this.request("GET",C0(cc.nodes(),t))}getNode(t){return this.request("GET",cc.node(this.nodePath(t)))}listBashJobs(t){return this.request("GET",cc.nodeJobs(this.nodePath(t)))}stopBashJob(t,r){return this.request("DELETE",cc.nodeJob(this.nodePath(t),this.jobPath(r)))}sendMessage(t,r){return this.request("POST",cc.nodeMessages(this.nodePath(t)),r)}interruptNode(t){return this.request("POST",cc.nodeInterrupt(this.nodePath(t)),{})}pushReport(t,r){return this.request("POST",cc.nodeReports(this.nodePath(t)),r)}forkNode(t){return this.request("POST",cc.nodeFork(this.nodePath(t)),{})}reviveNode(t,r){return this.request("POST",cc.nodeRevive(this.nodePath(t)),r??{})}relaunchRoot(t){return this.request("POST",cc.nodeRelaunchRoot(this.nodePath(t)),{})}bindBrokerSession(t,r){return this.request("POST",cc.nodeBrokerSessionBound(this.nodePath(t)),r)}settleBroker(t,r){return this.request("POST",cc.nodeBrokerSettle(this.nodePath(t)),r)}advanceBrokerInboxCursor(t,r){return this.request("POST",cc.nodeBrokerInboxCursor(this.nodePath(t)),r)}commitBrokerModel(t,r){return this.request("POST",cc.nodeBrokerModel(this.nodePath(t)),r)}brokerExtensionState(t){return this.request("GET",cc.nodeBrokerExtensionState(this.nodePath(t)))}commitBrokerGeneratedName(t,r){return this.request("POST",cc.nodeBrokerGeneratedName(this.nodePath(t)),r)}commitBrokerPersonaAck(t,r){return this.request("POST",cc.nodeBrokerPersonaAck(this.nodePath(t)),r)}closeNode(t,r){return this.request("POST",cc.nodeClose(this.nodePath(t)),r??{})}recycleNode(t){return this.request("POST",cc.nodeRecycle(this.nodePath(t)),{})}demoteNode(t){return this.request("POST",cc.nodeDemote(this.nodePath(t)),{})}promoteNode(t,r){return this.request("POST",cc.nodePromote(this.nodePath(t)),r)}yieldNode(t,r){return this.request("POST",cc.nodeYield(this.nodePath(t)),r)}waitNode(t,r){return this.request("POST",cc.nodeWait(this.nodePath(t)),r)}patchConfig(t,r){return this.request("PATCH",cc.nodeConfig(this.nodePath(t)),r)}closeWorktree(t){return this.request("POST",cc.nodeWorktreeClose(this.nodePath(t)),{})}abandonWorktree(t,r){return this.request("POST",cc.nodeWorktreeAbandon(this.nodePath(t)),r)}listQuarantinedWorktrees(){return this.request("GET",cc.quarantinedWorktrees())}subscribe(t,r){return this.request("POST",cc.nodeSubscriptions(this.nodePath(t)),r)}listFocuses(){return this.request("GET",cc.focuses())}focusOf(t){return this.request("GET",C0(cc.focusByNode(),{node_id:t}))}focusByPane(t){return this.request("GET",C0(cc.focusByPane(),{pane:t}))}registerFocus(t){return this.request("POST",cc.focuses(),t)}async setFocusPane(t,r){await this.request("PATCH",cc.focus(t),r)}async closeFocus(t){await this.request("DELETE",cc.focus(t))}async unsubscribe(t,r){await this.request("DELETE",cc.nodeSubscription(this.nodePath(t),this.nodePath(r)))}armCron(t){return this.request("POST",cc.crons(),t)}listCrons(t){return this.request("GET",C0(cc.crons(),t))}showCron(t,r){return this.request("GET",C0(cc.cron(this.cronPath(t)),r))}pauseCron(t,r){return this.request("POST",C0(cc.cronPause(this.cronPath(t)),r),{})}resumeCron(t,r){return this.request("POST",C0(cc.cronResume(this.cronPath(t)),r),{})}runCron(t,r){return this.request("POST",C0(cc.cronRun(this.cronPath(t)),r),{})}async cancelCron(t,r){await this.request("DELETE",C0(cc.cron(this.cronPath(t)),r))}pokeCrons(){return this.request("POST",cc.cronsPoke(),{})}ensureAttach(t,r){return this.request("POST",cc.nodeAttach(this.nodePath(t)),r??{})}getReports(t,r){return this.request("GET",C0(cc.nodeReports(this.nodePath(t)),r))}getTranscript(t,r){return this.request("GET",C0(cc.nodeTranscript(this.nodePath(t)),r))}getSnapshot(t){return this.request("GET",cc.nodeSnapshot(this.nodePath(t)))}nodeSubject(t){return this.request("GET",cc.nodeSubject(this.nodePath(t)))}getNodeMessages(t,r){return this.request("GET",C0(cc.nodeMessages(this.nodePath(t)),r))}getSession(t){return this.request("GET",cc.nodeSession(this.nodePath(t)))}getChatInventory(t){return this.request("GET",cc.nodeChatInventory(this.nodePath(t)))}getProspectiveChatInventory(t){return this.request("GET",C0(cc.prospectiveChatInventory(),t))}getArtifacts(t,r){return this.request("GET",C0(cc.nodeArtifacts(this.nodePath(t)),r))}getContext(t){return this.request("GET",cc.nodeContext(this.nodePath(t)))}peekFile(t){return this.request("GET",C0(cc.filePeek(),{path:t}))}resolveMemoryDoc(t,r){return this.request("GET",C0(cc.memoryResolve(),{name:t,node:r}))}ensureProfile(t,r){return this.request("PUT",cc.profile(t),r??{})}listProfiles(){return this.request("GET",cc.profiles())}getProfile(t){return this.request("GET",cc.profile(t))}updateProfileMetadata(t,r){return this.request("PATCH",cc.profileMetadata(t),r)}deleteProfile(t,r){return this.request("DELETE",cc.profile(t),r)}listModelAuth(){return this.request("GET",cc.modelAuths())}installCredential(t,r){return this.request("PUT",cc.modelAuth(t),r)}removeCredential(t){return this.request("DELETE",cc.modelAuth(t))}createHumanBridge(t){return this.request("POST",cc.humanBridge(),t)}resolveHumanTicket(t,r){return this.request("POST",cc.humanTicketResolve(this.interactionPath(t)),r)}cancelHumanTicket(t,r){return this.request("POST",cc.humanTicketCancel(this.interactionPath(t)),r)}createReview(t){return this.request("POST",cc.humanReviews(),t)}listReviews(t){return this.request("GET",C0(cc.humanReviews(),t))}getReview(t){return this.request("GET",cc.humanReview(this.reviewPath(t)))}getReviewByBridge(t){return this.request("GET",cc.humanReviewByBridge(this.nodePath(t)))}submitReview(t){return this.request("POST",cc.humanReviewSubmit(this.reviewPath(t)),{})}cancelReview(t,r={}){return this.request("POST",cc.humanReviewCancel(this.reviewPath(t)),r)}getReviewDocumentBase(t){return this.request("GET",cc.humanReviewDocument(this.reviewPath(t)))}createReviewComment(t,r){let i=t===void 0?"self":this.reviewPath(t);return this.request("POST",cc.humanReviewComments(i),r)}listReviewComments(t,r){let i=t===void 0?"self":this.reviewPath(t);return this.request("GET",C0(cc.humanReviewComments(i),r))}readReviewCommentEvents(t,r){return this.request("GET",C0(cc.humanReviewCommentEvents(this.reviewPath(t)),r))}updateReviewCommentRanges(t,r){return this.request("POST",cc.humanReviewCommentRanges(this.reviewPath(t)),r)}getReviewComment(t){return this.request("GET",cc.humanComment(this.commentPath(t)))}editReviewComment(t,r){return this.request("POST",cc.humanCommentEdit(this.commentPath(t)),r)}resolveReviewComment(t,r={}){return this.request("POST",cc.humanCommentResolve(this.commentPath(t)),r)}reopenReviewComment(t,r={}){return this.request("POST",cc.humanCommentReopen(this.commentPath(t)),r)}deleteReviewComment(t,r={}){return this.request("POST",cc.humanCommentDelete(this.commentPath(t)),r)}listHumanInbox(){return this.request("GET",cc.humanInbox())}getHumanInboxPage(t){return this.request("GET",cc.humanInboxTicket(this.ticketId(t)))}getInboxHistory(t){if(t===void 0)return this.request("GET",cc.humanInbox()+"/history");if(typeof t!="string"||t==="")throw new TypeError(`invalid node id: ${JSON.stringify(t)}`);return this.request("GET",C0(cc.humanInbox()+"/history",{node_id:t}))}respondHumanInboxPage(t,r){return this.request("POST",cc.humanInboxRespond(this.ticketId(t)),r)}postInboxProgress(t,r){return this.request("POST",cc.humanInboxProgress(this.ticketId(t)),{responses:r})}getInboxResponse(t){return this.request("GET",cc.humanInboxResponse(this.ticketId(t)))}cancelHumanInboxTicket(t,r){return this.request("POST",cc.humanInboxCancel(this.ticketId(t)),r??{})}createHumanRequest(t){return this.request("POST",cc.humanRequests(),t)}getHumanRequest(t){return this.request("GET",cc.humanRequest(this.ticketId(t)))}replaceHumanRequest(t,r){return this.request("POST",cc.humanRequestReplace(this.ticketId(t)),r)}respondHumanRequest(t,r){return this.request("POST",cc.humanRequestRespond(this.ticketId(t)),r)}dismissHumanRequest(t,r={}){return this.request("POST",cc.humanRequestDismiss(this.ticketId(t)),r)}cancelHumanRequest(t,r={}){return this.request("POST",cc.humanRequestCancel(this.ticketId(t)),r)}resolvePageFeedbackComment(t,r,i){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(r))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(r)}`);return this.request("POST",cc.humanInboxFeedbackResolve(this.ticketId(t),r),{node_id:i})}async dashboard(t){let r=t?.under!==void 0?{under:t.under}:void 0,[i,o]=await Promise.all([this.listNodes(r),this.status()]);return{nodes:i,counts:o.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",cc.canvasAttention())}attentionCounts(t){let r={node_ids:t};return this.request("POST",cc.canvasAttentionCounts(),r)}historySearch(t){return this.request("POST",cc.canvasHistorySearch(),t)}historyGrep(t){return this.request("POST",cc.canvasHistoryGrep(),t)}historyRead(t){return this.request("GET",C0(cc.canvasHistoryRead(),t))}historyStats(t){return this.request("POST",cc.canvasHistoryStats(),t)}canvasSnapshot(){return this.request("GET",cc.canvasSnapshot())}canvasRoster(){return this.request("GET",cc.canvasRoster())}prune(t){return this.request("POST",cc.canvasPrune(),t)}rebuildIndex(){return this.request("POST",cc.canvasRebuildIndex(),{})}async request(t,r,i){return q4i(await this.send(t,r,i))}async send(t,r,i,o){try{return await this.transport(t,r,i,o)}catch(a){if(this.isColdSocketError(a))return await this.handleColdSocket(),await this.transport(t,r,i,o);if(this.isHandoverHangup(a))return await this.rideOutHandover(t,r,i,o);throw Z6e(a)}}nodePath(t){if(!X6e(t))throw new p_(400,"invalid_node_id",`invalid node id: ${JSON.stringify(t)}`);return t}interactionPath(t){if(!X6e(t))throw new p_(400,"invalid_ticket_id",`invalid interaction ticket id: ${JSON.stringify(t)}`);return t}jobPath(t){if(!iwr(t))throw new p_(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(t)}`);return t}cronPath(t){if(!owr(t))throw new p_(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(t)}`);return t}ticketId(t){if(!/^[a-f0-9]{64}$/.test(t))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(t)}`);return t}reviewPath(t){if(!X6e(t))throw new p_(400,"invalid_review_id",`invalid review id: ${JSON.stringify(t)}`);return t}commentPath(t){if(!/^[a-f0-9]{32}$/.test(t))throw new p_(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(t)}`);return t}transport(t,r,i,o){let u=this.baseUrl?.protocol==="https:"?L4i:M4i,p=i===void 0?void 0:JSON.stringify(i),f={accept:"application/json",...this.headers,...o};p!==void 0&&(f["content-type"]="application/json",f["content-length"]=String(Buffer.byteLength(p)));let h={method:t,path:r,headers:f,timeout:this.timeoutMs};return this.socketPath!==void 0?h.socketPath=this.socketPath:this.baseUrl!==void 0&&(h.protocol=this.baseUrl.protocol,h.hostname=this.baseUrl.hostname,this.baseUrl.port!==""&&(h.port=this.baseUrl.port)),new Promise((m,g)=>{let E=u(h,v=>{let T=[];v.on("data",C=>T.push(C)),v.on("end",()=>{let C={};for(let[I,N]of Object.entries(v.headers))N!==void 0&&(C[I]=Array.isArray(N)?N.join(", "):N);m({status:v.statusCode??0,text:Buffer.concat(T).toString("utf8"),headers:C})}),v.on("error",g)});E.on("error",g),E.on("timeout",()=>{E.destroy(Object.assign(new Error("request timed out"),{code:"ETIMEDOUT"}))}),p!==void 0&&E.write(p),E.end()})}isColdSocketError(t){if(this.socketPath===void 0)return!1;let r=t?.code;return r==="ECONNREFUSED"||r==="ENOENT"||r==="ENOTSOCK"}isHandoverHangup(t){if(this.socketPath===void 0)return!1;let r=t?.code;return r==="ECONNRESET"||r==="EPIPE"}async rideOutHandover(t,r,i,o){if(!await this.awaitHandover())throw new p_(503,"daemon_unavailable",`crtrd went away mid-request and did not come back within ${this.coldStartPollWindowMs}ms.`);if(t!=="GET"&&t!=="HEAD")throw new p_(503,"daemon_restarting",`crtrd handed over to a new runtime generation mid-request; this ${t} may or may not have been applied.`);try{return await this.transport(t,r,i,o)}catch(a){throw Z6e(a)}}async awaitHandover(){let t=Date.now()+this.coldStartPollWindowMs;for(;;){try{let r=await this.transport("GET",cc.healthz());if(r.status>=200&&r.status<300)return!0}catch(r){if(!this.isColdSocketError(r)&&!this.isHandoverHangup(r))throw Z6e(r)}if(Date.now()>=t)return!1;await cwr(awr)}}async handleColdSocket(){if(!this.autostart||this.onColdSocket===void 0)throw new p_(503,"daemon_unavailable","crtrd is not running and autostart is disabled; run `crtr sys daemon start`.");if(this.coldStartAttempted)throw new p_(503,"daemon_unavailable","crtrd did not become reachable after autostart.");this.coldStartAttempted=!0,await this.onColdSocket();let t=Date.now()+this.coldStartPollWindowMs;for(;;){try{let i=await this.transport("GET",cc.healthz());if(i.status>=200&&i.status<300)return}catch(i){if(!this.isColdSocketError(i))throw Z6e(i)}let r=null;try{r=this.coldStartAbort?.()??null}catch{r=null}if(r!==null)throw new p_(503,"daemon_unavailable",`crtrd cannot start: ${r}`);if(Date.now()>=t){let i=V4i(this.coldStartDiagnostic);throw new p_(503,"daemon_unavailable",G4i(i))}await cwr(awr)}}};function C0(e,t){if(t===void 0)return e;let r=new URLSearchParams;for(let[o,a]of Object.entries(t))a!=null&&r.set(o,String(a));let i=r.toString();return i===""?e:`${e}?${i}`}function q4i(e){let t=e.status>=200&&e.status<300,r=e.text.trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(t)return;throw new p_(e.status,"invalid_response",e.text.slice(0,500))}if(t)return i;throw Tvt(i)?new p_(e.status,i.error.code,i.error.message,i.error.details):new p_(e.status,"internal",`request failed with status ${e.status}`)}function Z6e(e){if(e instanceof p_)return e;let t=e?.code,r=e instanceof Error?e.message:String(e);return t==="ECONNREFUSED"||t==="ENOENT"?new p_(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):t==="ETIMEDOUT"?new p_(504,"request_timeout",`crtrd request timed out: ${r}`):new p_(503,"transport_error",r)}function cwr(e){return new Promise(t=>setTimeout(t,e))}function G4i(e){let t="crtrd did not start; run `crtr sys daemon start` and check crtrd.log.";return e!==void 0&&e!==""?`${t}
@@ -134,7 +134,7 @@ const addLeaf = defineLeaf({
134
134
  { kind: 'flag', name: 'at', type: 'string', required: false, constraint: 'One-shot: run the stored bash once at <when> — a duration ("90s","1h30m"), a zoned ISO ("2026-06-07T09:00:00Z"), or a bare ISO ("2026-06-07T09:00", interpreted in --tz else host zone). Exactly one of --at / --every is required. The row is deleted after its run unless the run\'s disposition pauses it.' },
135
135
  { kind: 'flag', name: 'every', type: 'string', required: false, constraint: 'Recurring: run the stored bash at each cadence — a fixed interval ("6h" — first fire one interval from now), a 5-field cron ("0 9 * * *"), or an @alias ("@daily"). Each fire is another bash run. Minimum cadence 60s. Exactly one of --at / --every is required. For a gated cron (a command that exits 75 while ineligible), pick a LONG cadence: each natural slot is only the backstop re-check, and the daemon poke supplies the latency — "6h" plus poke beats "15m" polling on both latency and cost.' },
136
136
  { kind: 'flag', name: 'tz', type: 'string', required: false, constraint: 'IANA zone (e.g. "America/New_York") for a bare-ISO --at or a calendar --every. Defaults to the host zone.' },
137
- { kind: 'flag', name: 'on-output', type: 'enum', choices: ['silent', 'on-failure', 'always', 'on-change'], required: false, default: 'on-failure', constraint: 'What each run does with its output. silent: record in the run log, tell nobody — never escalate. on-failure (default): no success delivery; a failing run pauses the cron and spawns a node to deal with it. always: deliver stdout every run to --sink at --tier. on-change: deliver stdout only when it differs from the previous run\'s — the shape polling wants.' },
137
+ { kind: 'flag', name: 'on-output', type: 'enum', choices: ['silent', 'on-failure', 'always', 'on-change'], required: false, constraint: 'What each run does with its output. Defaults to on-change for a node:<id> sink; otherwise on-failure. silent: record in the run log, tell nobody — never escalate. on-failure: no success delivery; a failing run pauses the cron and spawns a node to deal with it. always: deliver stdout every run to --sink at --tier. on-change: deliver stdout only when it differs from the previous run\'s — the shape polling wants.' },
138
138
  { kind: 'flag', name: 'sink', type: 'string', required: false, constraint: 'Where always/on-change stdout deliveries go: "node:<id>" (an existing node\'s inbox — must exist now; gone/finalized at fire time is a failure), "spawn:<kind>" (each delivered output creates a self-finishing node with stdout as kickoff — a managed child while its creator exists, otherwise a terminal parentless root), or "human" (the humanloop inbox). Required by always/on-change, rejected otherwise.' },
139
139
  { kind: 'flag', name: 'tier', type: 'enum', choices: ['normal', 'urgent', 'critical'], required: false, default: 'urgent', constraint: 'Inbox priority of a node-sink delivery. urgent (default): steers the target mid-turn, or wakes it when dormant — a fire is news the node asked for on a schedule, so it should land now. normal: waits for the running turn to settle. critical: aborts the running turn outright.' },
140
140
  { kind: 'flag', name: 'expires', type: 'string', required: false, constraint: 'Clock bound (same grammar as --at): the row is deleted once this instant passes. The self-limiting half of a poll-until pattern. For a held one-shot (last run exited 75), expiry bounds the wait for eligibility — the row is deleted UNFIRED, never fired blind at expiry.' },
@@ -254,7 +254,7 @@ const addLeaf = defineLeaf({
254
254
  env_json: envJson,
255
255
  profile: profile ?? null,
256
256
  scope,
257
- on_output: input['onOutput'] ?? 'on-failure',
257
+ on_output: input['onOutput'],
258
258
  sink: typeof input['sink'] === 'string' && input['sink'] !== '' ? input['sink'] : null,
259
259
  tier: input['tier'] ?? 'urgent',
260
260
  expires_at: expiresAt,
@@ -525,7 +525,7 @@ export function registerCron() {
525
525
  help: {
526
526
  name: 'cron',
527
527
  summary: 'scheduled bash commands, daemon-run',
528
- model: 'A cron stores and daemon-runs arbitrary bash at its clock. Use ordinary bash for ordinary work; choose node:<id> for stdout as inbox information to an existing node, an existing node\'s lifecycle fresh-revive action in the bash for a clean re-check without inbox output, or spawn:<kind> to route each output-producing fire to a fresh self-finishing node (a managed child while its creator exists, otherwise a terminal parentless root). Per-fire fresh agent work belongs on the existing spawn:<kind> sink, not an independent resident-root birth. A gate is bash, at the top of the command. Exit 0 after deciding not to act and the occurrence is simply spent — right when the recurrence is your polling cadence. Exit 75 and the occurrence is OWED: the row is held, fires again the moment the daemon receives an eligibility poke from the host platform, and otherwise re-checks at its next natural slot (a held one-shot instead waits for a poke until --expires deletes it unfired). Any other nonzero exit is a real failure and escalates per --on-output. Use 75 for "not yet — retry when conditions change" (a device coming online); keep gate ERRORS nonzero so a broken probe is loud instead of silently parked. Beyond the exit-code contract, cron has no native predicate-trigger semantics. --at runs once and deletes the row unless the run\'s disposition pauses it; --every runs each cadence. Output disposition (--on-output) records silently, escalates failures, or routes stdout to its --sink. Anchor a cron to delete it with a node; --cancel-on-wake instead deletes it when the anchor wakes. An unanchored recurring cron ends through --expires, explicit cancellation, or self-cancellation from its bash. Every run lands in a bounded per-cron run log (`cron show`); cwd, env, and profile are snapshotted at arm time, and --scope controls who lists and cancels it.',
528
+ model: 'A cron stores and daemon-runs arbitrary bash at its clock. Use ordinary bash for ordinary work; choose node:<id> for stdout as inbox information to an existing node (its disposition defaults to on-change), an existing node\'s lifecycle fresh-revive action in the bash for a clean re-check without inbox output, or spawn:<kind> to route each output-producing fire to a fresh self-finishing node (a managed child while its creator exists, otherwise a terminal parentless root). Per-fire fresh agent work belongs on the existing spawn:<kind> sink, not an independent resident-root birth. A gate is bash, at the top of the command. Exit 0 after deciding not to act and the occurrence is simply spent — right when the recurrence is your polling cadence. Exit 75 and the occurrence is OWED: the row is held, fires again the moment the daemon receives an eligibility poke from the host platform, and otherwise re-checks at its next natural slot (a held one-shot instead waits for a poke until --expires deletes it unfired). Any other nonzero exit is a real failure and escalates per --on-output. Use 75 for "not yet — retry when conditions change" (a device coming online); keep gate ERRORS nonzero so a broken probe is loud instead of silently parked. Beyond the exit-code contract, cron has no native predicate-trigger semantics. --at runs once and deletes the row unless the run\'s disposition pauses it; --every runs each cadence. Output disposition (--on-output) records silently, escalates failures, or routes stdout to its --sink. Anchor a cron to delete it with a node; --cancel-on-wake instead deletes it when the anchor wakes. An unanchored recurring cron ends through --expires, explicit cancellation, or self-cancellation from its bash. Every run lands in a bounded per-cron run log (`cron show`); cwd, env, and profile are snapshotted at arm time, and --scope controls who lists and cancels it.',
529
529
  },
530
530
  children: [addLeaf, listLeaf, showLeaf, runLeaf, pauseLeaf, resumeLeaf, cancelLeaf],
531
531
  });
@@ -12,6 +12,7 @@ import { stateBlock } from '../../core/help.js';
12
12
  import { cliClient, getNodeOrNull, rethrowAsCliError } from '../api-client.js';
13
13
  import { inTmux } from '../../core/runtime/placement-tmux.js';
14
14
  import { openSpawnViewer } from '../surface/node/placement.js';
15
+ import { resolve } from 'node:path';
15
16
  const YIELD_NUDGE_THRESHOLD = 100_000;
16
17
  const NODE_NEW_OUTPUT_SCHEMA_EFFECT = '--output-schema writes the accepted result to the node’s context/result.json and pushes it as the node’s final report.';
17
18
  const STD_CHILD_FOLLOW_UP = "Do not wait, poll, or duplicate this child's assignment in your own context — there is no result to await, stopping will not strand you, and duplicated work wastes the delegated context. You're auto-subscribed, so its finish wakes you on its own. Two moves only: do other independent work right now, or stop and end your turn — the wake brings you back.";
@@ -177,7 +178,8 @@ async function runNodeCreation(input) {
177
178
  }
178
179
  const kind = input['kind'];
179
180
  const mode = (input['mode'] ?? 'base');
180
- const pinCwd = input['cwd']?.trim();
181
+ const pinCwdRaw = input['cwd']?.trim();
182
+ const pinCwd = pinCwdRaw !== undefined && pinCwdRaw !== '' ? resolve(pinCwdRaw) : undefined;
181
183
  const name = input['name'];
182
184
  const parent = input['parent'];
183
185
  const root = input['root'] === true;
@@ -71,16 +71,16 @@ const worktreeAbandon = defineLeaf({
71
71
  });
72
72
  const worktreeClose = defineLeaf({
73
73
  name: 'close',
74
- description: 'land and close the current node-managed worktree',
75
- whenToUse: 'you are inside the node that owns an open managed worktree and are ready to rebase it onto its recorded local base branch and fast-forward that base before finishing; its active checkout is retained for deferred cleanup',
74
+ description: 'land or safely close the current node-managed worktree',
75
+ whenToUse: 'you are inside the node that owns an open managed worktree and are ready to land its recorded branch into the local base, or to close a moved real branch whose already-delivered content can be safely preserved while its checkout is disposed later',
76
76
  help: {
77
77
  name: 'node worktree close',
78
- summary: 'land and close the current node-managed worktree',
78
+ summary: 'land or safely close the current node-managed worktree',
79
79
  params: [],
80
80
  output: [
81
81
  { name: 'node_id', type: 'string', required: true, constraint: 'The caller node id whose managed worktree was closed.' },
82
- { name: 'branch', type: 'string', required: true, constraint: 'The worktree branch that was fast-forwarded into its recorded local base branch.' },
83
- { name: 'landed_sha', type: 'string', required: true, constraint: 'The commit SHA that the recorded local base branch was fast-forwarded onto.' },
82
+ { name: 'branch', type: 'string', required: true, constraint: 'The branch whose delivered content is retained: fast-forwarded into the recorded local base in an ordinary close, or preserved unchanged when a moved real branch is authorized for disposal.' },
83
+ { name: 'landed_sha', type: 'string', required: true, constraint: 'The retained branch tip: fast-forwarded into the local base in an ordinary close, or proven already contained in the local base or its upstream before a moved real branch is authorized for disposal.' },
84
84
  { name: 'worktree_path', type: 'string', required: true, constraint: 'The managed worktree path whose cleanup is deferred until its caller exits.' },
85
85
  { name: 'worktree_removed', type: 'boolean', required: true, constraint: 'Always false for an active caller: its checkout remains intact rather than being removed beneath the node.' },
86
86
  { name: 'worktree_remove_error', type: 'string', required: true, constraint: 'The named deferred-cleanup state and safe manual follow-up after the caller exits.' },
@@ -89,7 +89,7 @@ const worktreeClose = defineLeaf({
89
89
  ],
90
90
  outputKind: 'object',
91
91
  effects: [
92
- 'Rebases the worktree onto its recorded local base branch, fast-forwards that base onto it (never pushes to origin), marks the node-managed worktree closed with cleanup pending, and leaves the active caller checkout and branch intact.',
92
+ 'Rebases the worktree onto its recorded local base branch and fast-forwards that base onto it (never pushes to origin), marking the node-managed worktree closed with cleanup pending and leaving the active caller checkout and branch intact. When the recorded branch is gone because ordinary work moved this checkout onto a real branch, and that branch\'s content is already contained in the recorded base, closes by authorizing the checkout\'s later removal instead of landing — preserving that branch rather than deleting it.',
93
93
  ],
94
94
  },
95
95
  run: async () => {
@@ -105,7 +105,7 @@ const worktreeClose = defineLeaf({
105
105
  const branch = String(r['branch'] ?? '');
106
106
  const sha = String(r['landed_sha'] ?? '');
107
107
  const path = String(r['worktree_path'] ?? '');
108
- let base = `Managed worktree landed — its local base branch fast-forwarded to ${branch} at ${sha}.`;
108
+ let base = `Managed worktree closed — ${branch} at ${sha} is retained.`;
109
109
  const notes = [];
110
110
  if (r['worktree_removed'] === false) {
111
111
  notes.push(String(r['worktree_remove_error'] ?? `worktree checkout at ${path} could not be removed automatically.`));
@@ -1,6 +1,6 @@
1
1
  import { envProfileId } from '../../shared/env.js';
2
2
  import { dirname, join, resolve, isAbsolute, relative, sep } from 'node:path';
3
- import { renameSync, writeFileSync } from 'node:fs';
3
+ import { chmodSync, renameSync, writeFileSync } from 'node:fs';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { defineLeaf } from '../../core/command.js';
6
6
  import { notFound, usage, general, network } from '../../core/errors.js';
@@ -282,6 +282,15 @@ function writeStagedBundle(stagingRoot, manifest, bundle) {
282
282
  ensureDir(resolve(target, '..'));
283
283
  writeFileSync(target, document.bytes);
284
284
  }
285
+ if (bundle.hooks !== undefined) {
286
+ writeFileSync(stagedPath(stagingRoot, 'hooks.json'), bundle.hooks.manifest);
287
+ for (const file of bundle.hooks.files) {
288
+ const target = stagedPath(stagingRoot, file.path);
289
+ ensureDir(resolve(target, '..'));
290
+ writeFileSync(target, file.bytes);
291
+ }
292
+ chmodSync(stagedPath(stagingRoot, 'hooks/dispatch'), 0o755);
293
+ }
285
294
  }
286
295
  async function validateStagedBundle(name, scope, root, scopeRootPath, manifest) {
287
296
  const memory = await assertPluginCandidateValid(manifest, root, scope, scopeRootPath, `${root}/.crouter-plugin/plugin.json`);
@@ -345,6 +354,7 @@ async function replaceBundlePlugin(name, bundleSource, scope, options) {
345
354
  // later archive that no longer declares them is what retires them.
346
355
  ...(validated.bundle.page_components !== undefined ? { page_components: validated.bundle.page_components } : {}),
347
356
  ...(validated.bundle.memory_extensions !== undefined ? { memory_extensions: validated.bundle.memory_extensions } : {}),
357
+ ...(validated.bundle.hooks !== undefined ? { hooks: 'hooks.json', hookExecutable: 'hooks/dispatch' } : {}),
348
358
  };
349
359
  const tmpRoot = join(scopeRootPath, 'tmp');
350
360
  const staging = join(tmpRoot, `${name}.${process.pid}`);
@@ -390,7 +400,8 @@ async function replaceBundlePlugin(name, bundleSource, scope, options) {
390
400
  const commands = await commandReport(name, scope);
391
401
  if (commands === undefined)
392
402
  throw general(`bundle plugin "${name}" has no staged command report`);
393
- return { name, scope, path: root, transport: 'http', version, docs: validated.bundle.memory.length, kinds: Object.keys(validated.bundle.kinds ?? {}).length, pageComponents: (validated.bundle.page_components ?? []).length, commands, ...(memory !== undefined ? { memory } : {}) };
403
+ const hooks = await hookLifecycleReport(name, scope);
404
+ return { name, scope, path: root, transport: 'http', version, docs: validated.bundle.memory.length, kinds: Object.keys(validated.bundle.kinds ?? {}).length, pageComponents: (validated.bundle.page_components ?? []).length, commands, ...(hooks !== undefined ? { hooks } : {}), ...(memory !== undefined ? { memory } : {}) };
394
405
  }
395
406
  async function installHttpPlugin(name, endpoint, authEnv, scope) {
396
407
  const source = validateHttpInstall(name, endpoint, authEnv);
@@ -674,7 +685,7 @@ async function updateOnePlugin(plugin, marketplaceCache, opts) {
674
685
  const sourceInstalled = isSourceInstalled(plugin);
675
686
  if (!sourceInstalled && plugin.manifest.bundle !== undefined) {
676
687
  const replaced = await replaceBundlePlugin(plugin.name, plugin.manifest.bundle, plugin.scope, { enable: plugin.enabled });
677
- return { name: plugin.name, transport: 'http', updated: true, version: replaced.version, docs: replaced.docs, kinds: replaced.kinds, pageComponents: replaced.pageComponents, commands: replaced.commands, ...(replaced.memory !== undefined ? { memory: replaced.memory } : {}) };
688
+ return { name: plugin.name, transport: 'http', updated: true, version: replaced.version, docs: replaced.docs, kinds: replaced.kinds, pageComponents: replaced.pageComponents, commands: replaced.commands, ...(replaced.hooks !== undefined ? { hooks: replaced.hooks } : {}), ...(replaced.memory !== undefined ? { memory: replaced.memory } : {}) };
678
689
  }
679
690
  if (plugin.manifest.transport?.kind === 'http' && !sourceInstalled)
680
691
  rejectLegacyHttpPlugin(plugin.name);
@@ -729,16 +740,16 @@ export const pluginInstall = defineLeaf({
729
740
  { name: 'kinds', type: 'integer', required: false, constraint: 'Kind-registry entry count declared by an --endpoint archive\u2019s bundle.json.' },
730
741
  { name: 'pageComponents', type: 'integer', required: false, constraint: 'Page-component registration count declared by an --endpoint archive\u2019s bundle.json.' },
731
742
  { name: 'commands', type: 'object', required: false, constraint: 'Present only when the plugin declares a command manifest. {mounts: string[] (accepted top-level command names now live for the next invocation), issues: object[] (typed validation issues that rejected a contribution — {code, path?, message, received, expected, next})}. Validated statically; commands are never executed.' },
732
- { name: 'hooks', type: 'object', required: false, constraint: 'Present only when the source plugin declares hooks. {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}. Command targets, lifecycle events, and replacement collisions are validated statically; hook executables are never run.' },
743
+ { name: 'hooks', type: 'object', required: false, constraint: 'Present only when the plugin declares hooks. {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}. Command targets, lifecycle events, and replacement collisions are validated statically; hook executables are never run.' },
733
744
  { name: 'warnings', type: 'string[]', required: false, constraint: 'Advisory missing PATH executable requirements declared by the installed plugin. The install still succeeds and leaves the plugin enabled.' },
734
745
  { name: 'memory', type: 'object', required: false, constraint: 'Present only when the plugin ships a memory store. {docs: integer (documents checked), migrated: string[] (store-relative documents rewritten to reach exact canonical identity), linkedSource?: string (the caller-owned directory converged in place, present only when the install keeps that directory as a live link)}.' },
735
746
  ],
736
747
  outputKind: 'object',
737
748
  effects: [
738
749
  'A ref install clones, links, or copies the plugin into the scope plugins directory and registers it with enabled=true. Marketplace installs refresh the source marketplace before resolving the plugin entry.',
739
- 'An --endpoint install fetches and validates one authenticated uncompressed tar archive before writing. It replaces the complete plugin directory with synthesized provenance and invocation metadata, commands.json, memory docs, any kind-registry entries the bundle.json declares (they join the launch registry below this scope\u2019s own config.json kinds), and any page components it declares (they join the active page-component catalog alongside the user config entries); a fetch or validation failure preserves the prior package.',
750
+ 'An --endpoint install fetches and validates one authenticated uncompressed tar archive before writing. It replaces the complete plugin directory with synthesized provenance and invocation metadata, commands.json, memory docs, and, when declared, hooks.json plus the hooks/ tree; it also copies any kind-registry entries the bundle.json declares (they join the launch registry below this scope\u2019s own config.json kinds), and any page components it declares (they join the active page-component catalog alongside the user config entries); a fetch or validation failure preserves the prior package.',
740
751
  'If the plugin declares a command manifest, its commands go live on the next crtr invocation. Exec commands run trusted local code only when explicitly invoked; HTTP commands call their declared endpoint only when explicitly invoked.',
741
- 'Source plugin command hooks go live on the next crtr invocation. They run implicitly with caller authority, may receive normalized inputs and after results, may block or replace declared targets, and may transmit received data. Lifecycle hooks run unprompted at every declared event before node launch and may transmit node identity and resolved paths. Hook executables are never run during install or update validation.',
752
+ 'Plugin command hooks go live on the next crtr invocation. They run implicitly with caller authority, may receive normalized inputs and after results, may block or replace declared targets, and may transmit received data. Lifecycle hooks run unprompted at every declared event before node launch and may transmit node identity and resolved paths. Hook executables are never run during install or update validation.',
742
753
  'A plugin manifest `requires` declaration is checked against the PATH a node bash receives after install. Missing executables emit a warning with the declared install hint but never fail the install, disable the plugin, or remove its bare-binary contributions.',
743
754
  'Before activation the candidate\u2019s memory corpus is migrated to exact canonical identity and refused if it cannot mount. A staged candidate is migrated in staging and rolls back with the package; a local path or marketplace-relative source stays a live link, so its own directory is rewritten in place, keeps that rewrite whether or not the install completes, and is named as `memory.linkedSource`. A refused corpus writes nothing and installs nothing.',
744
755
  ],
@@ -895,7 +906,7 @@ export const pluginDisable = defineLeaf({
895
906
  export const pluginUpdate = defineLeaf({
896
907
  name: 'update',
897
908
  description: 'update installed plugin content',
898
- whenToUse: 'refreshing one named plugin or all installed plugins: archive plugins replace commands and memory together, while source-installed plugins retain their source update behavior',
909
+ whenToUse: 'refreshing one named plugin or all installed plugins: archive plugins replace their complete package, while source-installed plugins retain their source update behavior',
899
910
  help: {
900
911
  name: 'pkg plugin update',
901
912
  summary: 'refresh one or all installed plugins',
@@ -904,7 +915,7 @@ export const pluginUpdate = defineLeaf({
904
915
  { kind: 'flag', name: 'scope', type: 'enum', choices: ['user', 'project'], required: false, constraint: 'Narrows resolution.' },
905
916
  ],
906
917
  output: [
907
- { name: 'updated', type: 'object[]', required: true, constraint: 'One entry per plugin processed: {name, transport?, updated, sha?, version?, docs?, kinds?, pageComponents?, commands?, hooks?, memory?, warnings?, error?}. memory is present for a plugin shipping a memory store and reports the same corpus migration install performs: {docs, migrated, linkedSource?}. Archive plugins report transport=http and replace their complete directory after an authenticated refetch; version is the archive content identifier, docs is the written memory-document count, kinds is the declared kind-registry entry count, and pageComponents is the declared page-component registration count. sha is present for git updates. A bulk update reports and skips a failed archive plugin. commands is present for validated command plugins: {mounts: string[], issues: object[]}. hooks is present for source hook plugins: {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}; it is static and never executes hooks. warnings lists advisory PATH requirements that remain absent after update.' }
918
+ { name: 'updated', type: 'object[]', required: true, constraint: 'One entry per plugin processed: {name, transport?, updated, sha?, version?, docs?, kinds?, pageComponents?, commands?, hooks?, memory?, warnings?, error?}. memory is present for a plugin shipping a memory store and reports the same corpus migration install performs: {docs, migrated, linkedSource?}. Archive plugins report transport=http and replace their complete directory after an authenticated refetch; version is the archive content identifier, docs is the written memory-document count, kinds is the declared kind-registry entry count, and pageComponents is the declared page-component registration count. sha is present for git updates. A bulk update reports and skips a failed archive plugin. commands is present for validated command plugins: {mounts: string[], issues: object[]}. hooks is present for plugins declaring hooks: {manifestPath?, executablePath?, declarations: {target, phase, op, description, effects}[], lifecycle?: {event, phase, op, description, effects}[], issues: object[], trust: string}; it is static and never executes hooks. warnings lists advisory PATH requirements that remain absent after update.' }
908
919
  ],
909
920
  outputKind: 'object',
910
921
  effects: [
@@ -71,7 +71,7 @@ function makePushLeaf(kind) {
71
71
  ...(kind === 'final'
72
72
  ? [
73
73
  'Marks the node done (status + intent) server-side; its engine shuts down on next stop.',
74
- 'When this node owns a managed worktree with zero commits ahead of its base and no uncommitted changes, the server auto-drops it instead of blocking on `node worktree close`; a worktree with real commits or real uncommitted changes still blocks with open_managed_worktree.',
74
+ 'When this node owns a clean managed worktree already contained in its local base, the server auto-drops it instead of blocking on `node worktree close`. A clean worktree whose exact branch tip is already on origin may also finalize while retaining its branch and checkout; uncommitted changes or a branch tip not on origin still block with open_managed_worktree.',
75
75
  ]
76
76
  : []),
77
77
  ],
@@ -10,6 +10,7 @@ export interface WaitOpts {
10
10
  intervalMs?: number;
11
11
  label?: string;
12
12
  }
13
+ export declare function readLines(path: string): string[];
13
14
  export interface Injected {
14
15
  content: string;
15
16
  deliverAs?: string;
@@ -123,6 +123,18 @@ async function waitFor(probe, opts = {}) {
123
123
  await new Promise((r) => setTimeout(r, intervalMs));
124
124
  }
125
125
  }
126
+ export function readLines(path) {
127
+ try {
128
+ const content = readFileSync(path, 'utf8');
129
+ const lines = content.split('\n');
130
+ if (!content.endsWith('\n'))
131
+ lines.pop();
132
+ return lines.filter((l) => l.trim() !== '');
133
+ }
134
+ catch {
135
+ return [];
136
+ }
137
+ }
126
138
  /** Thin wrapper: a headless-only harness (broker-hosted, paneless nodes). */
127
139
  export async function createHeadlessHarness(opts = {}) {
128
140
  return createHarness({ ...opts, headless: true });
@@ -377,16 +389,6 @@ export async function createHarness(opts = {}) {
377
389
  return [];
378
390
  }
379
391
  }
380
- function readLines(path) {
381
- try {
382
- return readFileSync(path, 'utf8')
383
- .split('\n')
384
- .filter((l) => l.trim() !== '');
385
- }
386
- catch {
387
- return [];
388
- }
389
- }
390
392
  function cli(nodeId, args) {
391
393
  const runtimeArgs = TSX_ESM === null ? [] : ['--import', TSX_ESM];
392
394
  const res = spawnSync(process.execPath, [...runtimeArgs, CLI_ENTRY, ...args], {