@north-light/cli 0.3.649 → 0.3.651
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/viewer.js +475 -475
- package/dist/clients/inbox/controller.js +1 -1
- package/dist/commands/chord.js +1 -1
- package/dist/commands/node/bash.js +3 -3
- package/dist/core/grants/mirror.d.ts +4 -1
- package/dist/core/grants/mirror.js +2 -2
- package/dist/core/grants/sync.d.ts +3 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/claim.d.ts +3 -3
- package/dist/core/human/claim.js +3 -3
- package/dist/core/peer/client.d.ts +2 -0
- package/dist/core/peer/client.js +1 -1
- package/dist/core/peer/directory.d.ts +5 -1
- package/dist/core/peer/directory.js +1 -1
- package/dist/core/peer/token.d.ts +3 -3
- package/dist/core/peer/token.js +3 -2
- package/dist/core/runtime/tmux-bindings.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +2 -2
- package/dist/daemon/api/handlers/providers.js +1 -1
- package/dist/daemon/crtrd.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Q=Object.defineProperty;var u=(e,n)=>Q(e,"name",{value:n,configurable:!0});import{mkdtempSync as Y,rmSync as Z,writeFileSync as V}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ee,encodeAttachControlInput as ne,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as q}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as k}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"command",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"command",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"command",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"command",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"command",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.file-review":{description:"review a file",action:{kind:"raw-keys",keys:"M-S-r"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.fold-tools":{description:"fold finished tool calls",action:{kind:"keys",keys:"/fold-tools"}},"crtr.tmux.menu.show-working":{description:"show/hide working",action:{kind:"keys",keys:"/show-working"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"command",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"direct",run:"surface reload --pane {pane}"}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(k).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function G(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${k(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${k(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${k(`${r} >/dev/null 2>&1`)}`}}u(G,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${k(t)}`}}u(de,"directCommand");function j(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${k(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${k(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${k(n)}`}}case"command":return G(e.run);case"direct":return de(e.run);case"popup":return G(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(j,"menuActionCommand");function me(e){return j(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function z(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(z,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=z(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=z(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function F(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const x=_.find(w=>w.id===l);if(x===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:x.name.toLowerCase(),action:{kind:"literal-input",input:ne(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.fold-tools","crtr.tmux.menu.show-working"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(F,"resolvedMenuActions");function K(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.file-review","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(K,"menuItems");function Pe(e){const n=e??q().bindings;return N(" crtr ",K(n,F(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
|
|
1
|
+
var Q=Object.defineProperty;var u=(e,n)=>Q(e,"name",{value:n,configurable:!0});import{mkdtempSync as Y,rmSync as Z,writeFileSync as V}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ee,encodeAttachControlInput as ne,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as q}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as k}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"direct",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"direct",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"direct",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"direct",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"direct",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.file-review":{description:"review a file",action:{kind:"raw-keys",keys:"M-S-r"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.fold-tools":{description:"fold finished tool calls",action:{kind:"keys",keys:"/fold-tools"}},"crtr.tmux.menu.show-working":{description:"show/hide working",action:{kind:"keys",keys:"/show-working"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"direct",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"direct",run:"surface reload --pane {pane}"}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(k).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function G(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${k(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${k(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${k(`${r} >/dev/null 2>&1`)}`}}u(G,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${k(t)}`}}u(de,"directCommand");function j(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${k(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${k(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${k(n)}`}}case"command":return G(e.run);case"direct":return de(e.run);case"popup":return G(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(j,"menuActionCommand");function me(e){return j(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function z(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(z,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=z(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=z(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function F(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const x=_.find(w=>w.id===l);if(x===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:x.name.toLowerCase(),action:{kind:"literal-input",input:ne(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.fold-tools","crtr.tmux.menu.show-working"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(F,"resolvedMenuActions");function K(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.file-review","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(K,"menuItems");function Pe(e){const n=e??q().bindings;return N(" crtr ",K(n,F(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
|
|
2
2
|
`).find(r=>{const s=B(r);return s?.table===e&&s.key===n})??null:null}u($,"bindingAt");function Le(e){const n=f(["list-keys","-T",p]);if(!n.ok)return[];const t=new Set(n.stdout.split(`
|
|
3
3
|
`).flatMap(r=>{const s=B(r);return s?.table===p?[s.key]:[]}));return e.filter(r=>!r.includes(" > ")&&v(r).some(s=>t.has(s)))}u(Le,"occupiedTmuxRootGestures");function R(e){return typeof e=="object"&&e!==null&&typeof e.table=="string"&&typeof e.key=="string"}u(R,"isInstalledPair");function he(e){if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.bindingId=="string"&&ee.has(n.bindingId)&&typeof n.gesture=="string"&&typeof n.key=="string"&&(typeof n.original=="string"||n.original===null)&&typeof n.wrapper=="string"&&(n.state==="owned"||n.state==="relinquished")}u(he,"isWrappedRootBinding");function ke(){const e=f(["show-options","-s","-q",A]);if(!e.ok)return null;if(e.stdout==="")return{pairs:[],wrappers:[]};const n=f(["show-options","-s","-qv",A]);if(!n.ok)return null;try{const t=JSON.parse(n.stdout);if(Array.isArray(t))return t.every(R)?{pairs:t,wrappers:[]}:null;if(typeof t!="object"||t===null)return null;const r=t;return!Array.isArray(r.pairs)||!r.pairs.every(R)||!Array.isArray(r.wrappers)||!r.wrappers.every(he)?null:{pairs:r.pairs,wrappers:r.wrappers}}catch{return null}}u(ke,"readManifest");function W(e){return f(["set-option","-s",A,JSON.stringify(e)])}u(W,"writeManifest");function C(e){return e.replace(/\\/g,"\\\\").replace(/;/g,"\\;")}u(C,"tmuxKeyArgument");function xe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/;/g,"\\;")}"`}u(xe,"tmuxCommandToken");function ye(e){let n=null,t="";for(let r=0;r<e.length;r+=1){const s=e[r];if(n===null&&(s==="'"||s==='"')){n=s,t+=s;continue}if(n===s){n=null,t+=s;continue}if(s==="\\"&&r+1<e.length){const o=e[r+1];n===null&&o===";"?t+=";":t+=s+o,r+=1;continue}t+=s}return t}u(ye,"bindingCommandForBranch");function be(e){const n=Y(M(O(),"crtr-tmux-binding-")),t=M(n,"binding.conf");try{return V(t,`${e}
|
|
4
4
|
`,"utf8"),f(["source-file",t])}finally{Z(n,{recursive:!0,force:!0})}}u(be,"sourceBindingLine");function X(e){return e.original===null?f(["unbind-key","-T",p,C(e.key)]):be(e.original)}u(X,"restoreWrappedBinding");function we(){return["run-shell","-b",'crtr surface inbox --quiet --tmux-socket "#{socket_path}" --tmux-client "#{client_name}" --target-pane "#{pane_id}"']}u(we,"inboxToggleTmuxCommand");function ve(e){switch(e){case"crtr.tmux.node.next":return["run-shell","crtr surface node cycle --dir next --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.node.previous":return["run-shell","crtr surface node cycle --dir prev --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.inbox.toggle":return we();default:throw new Error(`no tmux command for ${e}`)}}u(ve,"actionCommand");function $e(){const e=process.env.TMUX?.split(",")[0]?.trim();if(e!==void 0&&e!=="")return`${e}.crtr-keybindings.lock`;const n=f(["display-message","-p","#{socket_path}"]);if(n.ok&&n.stdout!=="")return`${n.stdout}.crtr-keybindings.lock`;const t=typeof process.getuid=="function"?process.getuid():"user";return M(O(),`crtr-tmux-keybindings-${t}.lock`)}u($e,"tmuxBindingLockPath");function De(e,n=[]){return oe($e(),()=>Ie(e,n))}u(De,"installTmuxBindings");function Ie(e,n=[]){const t=e===void 0?q():void 0,r=e??t.bindings,s=e===void 0?t.tmuxPassthrough:ie(n),o=[],c=[],l=ke();if(l===null)return o.push({code:"tmux-error",message:`tmux is unavailable or ${A} is malformed`}),{ok:!1,installed:c,diagnostics:o};const x=new Map;for(const i of s){const a=_.find(d=>d.id===i);if(!(a===void 0||!re(a))){for(const d of r.gestures(i))if(!d.includes(" > "))for(const m of v(d))x.has(m)||x.set(m,{bindingId:i,gesture:d})}}const w=new Set,I=[];for(const i of l.wrappers){const a=x.get(i.key),d=$(p,i.key);if(d!==null&&d===i.original)continue;if(i.state==="relinquished"||d!==i.wrapper){w.add(i.key),a!==void 0&&I.push({...i,...a,state:"relinquished"});continue}const m=X(i);m.ok||(w.add(i.key),I.push(i),o.push({code:"tmux-error",bindingId:i.bindingId,gesture:i.gesture,message:`could not restore tmux binding ${p}:${i.key}: ${m.stderr}`}))}for(const i of l.pairs){if(i.table===p&&w.has(i.key))continue;const a=f(["unbind-key","-T",i.table,C(i.key)]);!a.ok&&$(i.table,i.key)!==null&&o.push({code:"tmux-error",message:`could not remove crouter binding ${i.table}:${i.key}: ${a.stderr}`})}if(o.some(i=>i.code==="tmux-error")){const i=W({pairs:l.pairs,wrappers:I});return i.ok||o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${i.stderr}`}),{ok:!1,installed:c,diagnostics:o}}const E=u((i,a,d,m,h)=>{if($(i,a)!==null)return o.push({code:"occupied",bindingId:m,gesture:h,message:`${i}:${a} is already bound by tmux; ${m} was not installed`}),!1;const g=f(["bind-key","-T",i,C(a),...d]);return g.ok?(c.push({table:i,key:a}),!0):(o.push({code:"tmux-error",bindingId:m,gesture:h,message:`could not install ${m}: ${g.stderr}`}),!1)},"install"),P=F(r),H=N(" crtr ",K(r,P));for(const i of r.gestures("crtr.tmux.menu.open"))for(const a of v(i))E(p,a,H,"crtr.tmux.menu.open",i);for(const i of _){if(i.pair?.field!=="menu")continue;const a=_.find(y=>y.id===i.pair?.pairedId);if(a?.pair?.field!=="global")continue;const d=i.id,m=a.id,h=P.get(d),g=h===void 0?null:j(h.action);if(g===null)throw new Error(`no direct tmux action for paired menu binding ${d}`);for(const y of r.gestures(m))for(const J of v(y))E(p,J,g.argv,m,y)}for(const i of["crtr.tmux.node.next","crtr.tmux.node.previous","crtr.tmux.inbox.toggle"])for(const a of r.gestures(i))for(const d of v(a))E(p,d,ve(i),i,a);const L=[];for(const[i,a]of x){if(w.has(i))continue;const d=$(p,i);if(d===null)continue;const m=B(d);if(m===null||m.command===""){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not parse occupied tmux binding ${p}:${i}`});continue}const h=f(["bind-key",...m.repeat?["-r"]:[],"-T",p,C(i),"if-shell","-F","#{!=:#{@crtr_attach},}",`send-keys ${xe(i)}`,ye(m.command)]);if(!h.ok){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not wrap ${p}:${i}: ${h.stderr}`});continue}const g=$(p,i);if(g===null||!g.includes("@crtr_attach")){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not fingerprint wrapped tmux binding ${p}:${i}`});continue}const y={...a,key:i,original:d,wrapper:g,state:"owned"};I.push(y),L.push(y)}const D=W({pairs:c,wrappers:I});if(!D.ok){o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${D.stderr}`});for(const i of L)$(p,i.key)===i.wrapper&&X(i)}return{ok:o.every(i=>i.code!=="tmux-error"),installed:c,diagnostics:o}}u(Ie,"reconcileTmuxBindings");export{Pe as crouterMenuTmuxArgs,we as inboxToggleTmuxCommand,De as installTmuxBindings,Le as occupiedTmuxRootGestures};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var M=Object.defineProperty;var m=(o,t)=>M(o,"name",{value:t,configurable:!0});import{killBashJobObject as C,recordBashJobObject as D}from"../../../core/spaces/stop.js";import{readerFor as L}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as x,appProcessSandboxed as z}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as G}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as q}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as
|
|
1
|
+
var M=Object.defineProperty;var m=(o,t)=>M(o,"name",{value:t,configurable:!0});import{killBashJobObject as C,recordBashJobObject as D}from"../../../core/spaces/stop.js";import{readerFor as L}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as x,appProcessSandboxed as z}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as G}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as q}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as J}from"../../../core/canvas/node-agent-paths.js";import{getNode as S}from"../../../core/canvas/canvas.js";import{isBrokerLive as Q}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as W}from"../../../core/runtime/reopen.js";import{reviveNode as Y}from"../../../core/runtime/revive.js";import{checkStart as Z}from"../../../core/runtime/start-check.js";import{bashJobPaths as N,isBashJobProcessGroupAlive as V,isSafeBashJobId as O,readBashNiceness as tt,signalBashJob as et,stopBackgroundBashJob as ot}from"../../../core/bash-jobs.js";import{applyJobReport as nt,jobRow as it,ownerRunsRemotely as A,runningJobs as I,setJobDeadline as T,markJobQuietOk as rt}from"../../../core/graph/jobs.js";import{withCanvasWrite as E,openDb as h}from"../../../core/canvas/db.js";import{getById as B}from"../../../core/graph/objects.js";import{blobStore as P}from"../../../core/blobs/index.js";import{ApiError as a}from"../../../api/index.js";import{BASH_JOB_OUTPUT_DEFAULT_BYTES as at,BASH_JOB_OUTPUT_MAX_BYTES as st}from"../../../api/index.js";import{notFound as dt}from"../../../core/errors.js";import{freshChildNodeExecPath as ut}from"../../../core/runtime/branded-host.js";async function g(o){const t=o.params.id;if(t===void 0||!K(t))throw new a(400,"invalid_node_id",`invalid node id: ${JSON.stringify(t)}`);if(await S(t)===null)throw dt(`unknown node: ${t}`,{received:t});const e=o.params.jobId;if(e!==void 0){if(!O(e))throw new a(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return{nodeId:t,jobId:e,dir:await J(t)}}return{nodeId:t,dir:await J(t)}}m(g,"requireTarget");async function pt(o){const{nodeId:t,dir:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may start a job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.start requires a JSON body");const s=e;await q(t,s.expected_execution_id);const n=s.job_id,r=s.cwd,d=s.env;if(typeof n!="string"||!O(n)||typeof r!="string"||!d||typeof d!="object"||Array.isArray(d)||Object.entries(d).some(([l,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l)||typeof p!="string"))throw new a(400,"invalid_request","invalid job id, cwd or environment");const b=await S(t);if(await Z({grantee:b.grantee??"app:terminal",sub:b.sub,grant_id:b.grant_id}),!z())throw new a(400,"invalid_request","job.start is only used with the root launcher");const u=N(i,n);if(!(k(u.root,u.jobRun)||k(u.root,u.jobBg))||![u.cmdSh,u.jobLog].every(l=>k(u.root,l)))throw new a(404,"job_not_found","job was not prepared by this node");const f=H(u.dir,"job.starting");try{$(u.root,f,"")}catch(l){throw l.code==="EEXIST"?new a(409,"job_already_started","job was already started"):l}let _;try{const l=d,p=X("bash",l,r),j=await S(t),v=await ut();return _=await x({nodeId:t,app:j.grantee??"app:terminal",isolated:j.isolated,cwd:r,env:l,capture:!1,command:[p,"-c",G,"--",u.cmdSh,u.jobLog,u.jobExit,u.jobRun,u.jobDone,p,String(tt(i)),v,u.jobActivity]}),$(u.root,u.jobPgid,String(_.pid),384),$(u.root,u.jobPgidIdentity,`launcher:${_.pid}`,384),{status:201,body:{pid:_.pid}}}catch(l){if(_!==void 0)try{await _.stop()}catch(p){throw new AggregateError([l,p],`job ${n} launched but could not be recorded or stopped`)}try{U(u.root,f)}catch(p){if(p.code!=="ENOENT")throw p}throw l}}m(pt,"handleStart");async function lt(o){const{nodeId:t}=await g(o),i=Date.now(),e=await A(await h(),t);return{status:200,body:(await I(await h(),t)).map(n=>({job_id:n.jobId,command:n.command,purpose:n.purpose,started_at:new Date(n.startedAtMs).toISOString(),elapsed_ms:Math.max(0,i-n.startedAtMs),output_key:n.outputKey,deadline_at:n.deadlineAtMs===null?null:new Date(n.deadlineAtMs).toISOString(),pgid:n.pgid,pgid_alive:!e&&n.pgid!==null&&n.pgidIdentity!==null&&V(n.pgid,n.pgidIdentity)}))}}m(lt,"handleList");function R(o,t,i){const e=o.query.get(t);if(e===null)return;const s=Number(e);if(!/^[0-9]+$/.test(e)||!Number.isSafeInteger(s)||s<1||s>i)throw new a(400,"invalid_request",`${t} must be an integer from 1 to ${i}`);return s}m(R,"boundedQueryInt");async function ct(o){const{nodeId:t,jobId:i}=await g(o),e=R(o,"tail_lines",Number.MAX_SAFE_INTEGER),s=R(o,"max_bytes",st)??at,n=await h(),r=await B(n,i??"");if(r===null||r.type!=="job"||r.owner!==t||r.deleted_at!==null)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);const d=await it(n,r);if(d===null)throw new Error(`job object ${r.id} has no jobs row`);const b=await P(),u=await b.list(`${d.output_key}/`),w=[];let f=0,_=0,l=u.length;for(;l>0&&f<=s&&(e===void 0||_<=e+1);){const c=u[--l],y=await b.get(c);if(y===null)throw new Error(`job ${r.id} output chunk ${c} is listed but cannot be read`);w.unshift(y),f+=y.length;for(const F of y)F===10&&_++}let p=Buffer.concat(w),j=l>0;if(p.length>s){p=p.subarray(p.length-s);let c=0;for(;c<p.length&&(p[c]&192)===128;)c++;p=p.subarray(c),j=!0}let v=p.toString("utf8");if(e!==void 0){const c=v.split(`
|
|
2
2
|
`),y=c[c.length-1]===""?e+1:e;c.length>y&&(v=c.slice(c.length-y).join(`
|
|
3
|
-
`),j=!0)}return{status:200,body:{job_id:r.id,output:v,truncated:j}}}m(ct,"handleOutput");async function bt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.query.get("foreground")==="1"){if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await q(t,o.body?.expected_execution_id);const w=await ot(e,i,!0,t);if(w.kind==="missing")throw new a(404,"job_not_found",`no job ${i} for ${t}`);if(w.kind==="retired")throw new a(404,"job_not_found",`job ${i} for ${t} is no longer running`);if(w.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${i} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:i,signaled:w.signaled}}}const n=(await I(await
|
|
3
|
+
`),j=!0)}return{status:200,body:{job_id:r.id,output:v,truncated:j}}}m(ct,"handleOutput");async function bt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.query.get("foreground")==="1"){if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await q(t,o.body?.expected_execution_id);const w=await ot(e,i,!0,t);if(w.kind==="missing")throw new a(404,"job_not_found",`no job ${i} for ${t}`);if(w.kind==="retired")throw new a(404,"job_not_found",`job ${i} for ${t} is no longer running`);if(w.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${i} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:i,signaled:w.signaled}}}const n=(await I(await h(),t)).find(w=>w.jobId===i);if(n===void 0)throw new a(404,"job_not_found",`no running background job ${i} for ${t}`);const r=await A(await h(),t);if(!r&&(n.pgid===null||n.pgidIdentity===null))throw new a(409,"job_not_stoppable",`job ${i} reported no trusted process identity`);await W(t);const d=r?!0:await et(n.pgid,n.pgidIdentity,t);await C(i,async w=>{const f=await L(w,o);return f.class==="person"?f.person:f.class==="app"?f.app:f.node});const b=await S(t);if(b!==null&&!Q(b))try{await Y(t,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:t,job_id:i,signaled:d}}}m(bt,"handleStop");async function wt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may record its job");const s=o.body,n=N(e,i),r=s?.purpose,d=s?.deadline_at_ms;if(typeof s?.command!="string"||r!=null&&typeof r!="string"||d!=null&&!Number.isFinite(d))throw new a(400,"invalid_request","job.background requires command, and optionally purpose and deadline_at_ms");if(!await A(await h(),t)&&!k(n.root,n.jobBg))throw new a(404,"job_not_found",`job ${i} of ${t} is not backgrounded`);return{status:201,body:{id:(await D(t,i,{command:s.command,purpose:r??null,deadlineAtMs:d??null})).id}}}m(wt,"handleBackground");async function ft(o,t){if(t===void 0)throw new a(400,"invalid_request","a job id is required");const i=await B(await h(),t);if(i===null||i.type!=="job"||i.owner!==o)throw new a(404,"job_not_found",`no job ${t} for ${o}`);if(!(await I(await h(),o)).some(e=>e.jobId===t))throw new a(409,"job_not_running",`job ${t} for ${o} is no longer running`);return t}m(ft,"requireRunningJob");async function mt(o){const{nodeId:t,jobId:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may report its job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.report requires a JSON body");await q(t,e.expected_execution_id);const s=await B(await h(),i??"");if(s===null||s.type!=="job"||s.owner!==t)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);if(!(await I(await h(),t)).some(d=>d.jobId===i))throw new a(409,"job_not_running",`job ${String(i)} for ${t} is no longer running`);const n=e.output;if(n!==void 0){if(!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.data_base64!="string")throw new a(400,"invalid_request","output requires seq and data_base64");const d=await E(async b=>await b.prepare("SELECT output_key FROM jobs WHERE object = ?").get(i));await(await P()).put(`${d.output_key}/${String(n.seq).padStart(8,"0")}`,Buffer.from(n.data_base64,"base64"))}const r=e.activity;if(r!==void 0&&(!Number.isFinite(r.last_ms)||!Number.isFinite(r.sampled_ms)||!Array.isArray(r.files)))throw new a(400,"invalid_request","activity requires last_ms, sampled_ms and files");return await E(async d=>nt(d,i,{...typeof e.pgid=="number"?{pgid:e.pgid}:{},...typeof e.pgid_identity=="string"?{pgidIdentity:e.pgid_identity}:{},...typeof e.exit_code=="number"?{exitCode:e.exit_code}:{},...e.vanished===!0?{vanished:!0}:{},...r===void 0?{}:{activity:{lastActivityMs:r.last_ms,sampledAtMs:r.sampled_ms,files:r.files}}})),{status:204}}m(mt,"handleReport");async function ht(o){const{nodeId:t,jobId:i}=await g(o),e=await ft(t,i),s=o.body,n=s?.deadline_at_ms,r=s?.keep===!0;if(s?.quiet_ok!==!0&&!r&&!Number.isFinite(n))throw new a(400,"invalid_request","patch requires quiet_ok, keep or deadline_at_ms");if(r&&n!==void 0)throw new a(400,"invalid_request","keep and deadline_at_ms are exclusive");return await E(async d=>{s?.quiet_ok===!0&&await rt(d,e),r?await T(d,e,null):Number.isFinite(n)&&await T(d,e,n)}),{status:204}}m(ht,"handlePatch");const xt=[{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/background",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/report",handler:mt},{method:"PATCH",pattern:"/v1/nodes/:id/jobs/:jobId",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:pt},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:lt},{method:"GET",pattern:"/v1/nodes/:id/jobs/:jobId/output",handler:ct},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:bt}];export{xt as bashJobRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=Object.defineProperty;var s=(e,r)=>q(e,"name",{value:r,configurable:!0});import{randomUUID as G}from"node:crypto";import{cloudPersonScope as N}from"../../../core/runs/operations.js";import{directoryIssuer as T}from"../../../core/directory/issuer.js";import{activeGrantForApp as F,
|
|
1
|
+
var q=Object.defineProperty;var s=(e,r)=>q(e,"name",{value:r,configurable:!0});import{randomUUID as G}from"node:crypto";import{cloudPersonScope as N}from"../../../core/runs/operations.js";import{directoryIssuer as T}from"../../../core/directory/issuer.js";import{activeGrantForApp as F,grantFor as x,grantsOfPerson as C,localGrants as j,providerIdsFromGrants as S}from"../../../core/grants/mirror.js";import{getNode as k}from"../../../core/canvas/canvas.js";import{scopeAllowed as B}from"../../../core/scopes.js";import{ProviderError as f,providerErrorBody as D,scopeMissing as M}from"../../../core/providers/errors.js";import{callProvider as U,providerTools as z}from"../../../core/providers/call.js";import{providerInstallState as L}from"../../../core/providers/bundles.js";import{installedProviderPlugins as V,providerRootClaims as Z,resolveProviderRef as W}from"../../../core/providers/roots.js";import{isCloudRole as h}from"../../../core/canvas/person-state.js";import{listAudit as J,writeProviderAudit as X}from"../../../core/providers/audit.js";import{emitEvent as P}from"../../../core/events/emit.js";import{resolvedScopes as _}from"../router.js";const Ae=new Set(["provider.tools","provider.call","audit.list"]);async function H(e){if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null,origin:{node:null,run:null,machine:e.via}};const r=await x(e.actor.app,e.sub);if(!r)throw new f("grant_revoked",`app ${e.actor.app} has no active grant`);return{class:"app",sub:e.sub,grantee:e.actor.app,client_id:null,resolved:r.resolved,nodeScopes:e.actor.node_scopes,run_id:null,node_id:null,origin:{node:e.actor.node,run:e.actor.place?.run??null,machine:e.via}}}if(e.class==="machine"||e.class==="import")throw new f("permission_error","this operation is not available to the caller");if(e.class==="person"&&e.sub!==void 0){if(!h())throw new f("permission_error","provider calls are made by the install's person, a node or an app");return{class:"person",sub:e.sub,grantee:null,client_id:null,resolved:await _(e),nodeScopes:null,run_id:null,node_id:null}}if(e.class==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null};if(e.class==="app"){const r=await F(e.app);if(!r)throw new f("grant_revoked",`app ${e.app} has no active grant`);return{class:"app",sub:r.sub,grantee:e.app,client_id:null,resolved:r.resolved,nodeScopes:e.scopes,run_id:null,node_id:null}}return e.class==="cron"?{class:"app",sub:e.sub,grantee:e.app,client_id:null,resolved:await _(e),nodeScopes:e.scopes,run_id:e.origin_run,node_id:null}:{class:"broker",sub:e.sub,grantee:e.app,client_id:e.client_id,resolved:await _(e),nodeScopes:e.scopes,run_id:e.run??(await k(e.node))?.run_id??null,node_id:e.node}}s(H,"callerFromRequest");function Ee(e){return{class:"app",sub:e.sub,grantee:e.grantee,client_id:e.client_id,resolved:e.resolved,nodeScopes:null,run_id:null,node_id:null}}s(Ee,"callerFromApp");const K=/^([A-Za-z0-9_-]{1,64}):([A-Za-z0-9_-]{1,64})$/;function Q(e){const r=K.exec(e);return r!==null&&r[1]!=="crtr"}s(Q,"isProviderScope");const A=new WeakMap;function Y(e){let r=A.get(e);return r===void 0&&(r=new Set(e),A.set(e,r)),r}s(Y,"heldSet");function E(e,r){return e===null?!0:Q(r)?Y(e).has(r):B(e,r)}s(E,"holds");function R(e,r){return e.class==="person"&&e.resolved===null?!0:E(e.resolved??[],r)&&E(e.nodeScopes,r)}s(R,"callerAllows");function Re(e,r,n){const o=`${r}:${n}`;if(!R(e,o))throw M(o)}s(Re,"requireGroup");function ee(){return!!T()}s(ee,"providerOperationsEnabled");const re=/^[A-Za-z0-9_-]{1,64}$/;function v(e,r){return new f("invalid_request",e,{param:r})}s(v,"invalid");function I(e){if(typeof e!="string"||!re.test(e)||e==="crtr")throw v("provider must be a provider id","provider");return e}s(I,"parseProvider");function oe(e){if(!e||typeof e!="object"||Array.isArray(e))throw new f("invalid_request","a JSON object is required");const r=e,n=I(r.provider),o=r.tool;if(typeof o!="string"||!o.trim())throw v("tool must be a non-empty string","tool");const i=r.arguments??{};if(!i||typeof i!="object"||Array.isArray(i))throw v("arguments must be an object","arguments");const d=r.version;if(d!==void 0&&(typeof d!="number"||!Number.isInteger(d)||d<1))throw v("version must be an integer >= 1","version");const a=r.approval;if(a!==void 0&&(typeof a!="string"||!a))throw v("approval must be a question id","approval");const u=r.machine;if(u!==void 0&&(typeof u!="string"||!u.trim()))throw v("machine must be a machine id","machine");return{provider:n,tool:o.trim(),arguments:i,...d===void 0?{}:{version:d},...a===void 0?{}:{approval:a},...u===void 0?{}:{machine:u.trim()}}}s(oe,"parseCallInput");async function te(e,r=new URLSearchParams){const n=s((l,p,b)=>{const m=r.get(l);if(m===null)return p;if(!/^\d+$/.test(m)||Number(m)>b||Number(m)<1)throw v(`invalid ${l}`,l);return Number(m)},"numeric"),o=r.has("after")?n("after",0,Number.MAX_SAFE_INTEGER):void 0,i=n("limit",100,1e3),d=Object.fromEntries(["operation","outcome","run_id","since","until"].filter(l=>r.has(l)).map(l=>[l,r.get(l)])),a=N(e.sub),u=a===void 0?{}:{sub:a};return{status:200,body:await J(e.class==="person"?null:e.grantee,{after:o,limit:i,...u,...d})}}s(te,"auditList");async function ne(e,r,n){let o=r;const i=performance.now(),d=V(),{skipped:a}=Z(d),u=h()?e.sub?await C(e.sub):[]:await j(),l=h()?new Set(S(u.filter(t=>t.sub===e.sub))):null,p=s(t=>!a.has(t)&&(l===null||l.has(t)),"shown"),b=new Set(d.filter(t=>t.enabled&&t.manifest.provider?.id===t.name&&p(t.name)).map(t=>t.name)),m=S(u).filter(p),g=[...new Set([...b,...m])].sort();if(o!==void 0){const t=W(o);if(t===null)throw new f("not_found",`provider "${o}" is not available`);o=t}if(o!==void 0&&!g.includes(o))throw new f("not_found",`provider "${o}" is not available`);const O=o===void 0?g:[o],$=e.class==="person"?u.flatMap(t=>t.status==="active"&&(!h()||t.sub===e.sub)?t.resolved_scopes.map(({scope:c})=>c):[]):e.resolved??[],w=await Promise.all(O.map(async t=>{if(b.has(t))return z(e,t);if(!$.some(y=>y.startsWith(`${t}:`)&&R(e,y)))return null;const c=L(t);return c===void 0?null:{provider:t,display_name:t,status:c.status,...c.error?{error:c.error}:{},groups:[],commands:[]}})).then(t=>t.filter(c=>c!==null));if(P({level:"debug",event:"api.provider.tools",duration_ms:performance.now()-i,fields:{caller:e.class,provider:o??null,providers:w.length}}),o!==void 0){if(w.length===0)throw new f("not_found",`provider "${o}" is not available`);return{status:200,body:w[0]}}return{status:200,body:{providers:w}}}s(ne,"providerTools");async function se(e,r,n){return U(e,r,n)}s(se,"providerCall");async function ie(e,r,n,o){if(!ee())throw new f("not_found","provider operations need a directory-connected runtime");if(e==="audit.list")return await te(r,n.query);if(e==="provider.tools")return ne(r,n.params.provider===void 0?void 0:I(n.params.provider),o);if(e==="provider.call"){let i;try{i=oe(n.body)}catch(d){const a=n.body&&typeof n.body=="object"&&!Array.isArray(n.body)?n.body:{};throw await X({request_id:o.requestId,caller:r,provider:typeof a.provider=="string"?a.provider:"",tool:typeof a.tool=="string"?a.tool:"",outcome:`refused:${d instanceof f?d.code:"invalid_request"}`}),d}return se(r,i,o)}throw new f("not_found","unknown operation")}s(ie,"handleProviderOperation");function de(e){const r=new AbortController,n=s(()=>{e.writableFinished||r.abort()},"abort");return e.on("close",n),{signal:r.signal,release:s(()=>e.off("close",n),"release")}}s(de,"abortOnClose");function ae(e,r,n,o){const i=D(e,r,n,o??void 0);return i.status>=500&&!(e instanceof f)&&P({event:"api.provider.failed",level:"error",error:e instanceof Error?e:new Error(String(e)),fields:{request_id:r}}),i}s(ae,"providerFailure");const Ie=[{method:"GET",pattern:"/v1/audit",name:"audit.list"},{method:"GET",pattern:"/v1/providers/tools",name:"provider.tools"},{method:"GET",pattern:"/v1/providers/:provider/tools",name:"provider.tools"},{method:"POST",pattern:"/v1/provider/call",name:"provider.call"}].map(({method:e,pattern:r,name:n})=>({method:e,pattern:r,handler:s(async o=>{const i=G(),{signal:d,release:a}=de(o.res);let u=null;try{return u=await H(o.principal),{...await ie(n,u,{params:o.params,body:o.body,query:new URL(o.req.url??"/","http://runtime.local").searchParams},{requestId:i,signal:d,...o.causedBy===void 0?{}:{causedBy:o.causedBy}}),headers:{"Request-Id":i}}}catch(l){return ae(l,i,!1,u?.run_id)}finally{a()}},"handler")}));export{Ae as PROVIDER_OPERATIONS,de as abortOnClose,R as callerAllows,Ee as callerFromApp,H as callerFromRequest,ie as handleProviderOperation,oe as parseCallInput,I as parseProvider,ae as providerFailure,ee as providerOperationsEnabled,Ie as providerRoutes,Re as requireGroup};
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -16,4 +16,4 @@ ${a}
|
|
|
16
16
|
`),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Gt();const n=await Ot({waitForJoinLock:!0});_.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
|
|
17
17
|
`),process.exit(1)}process.exit(0)}s(rr,"performHandover");function x(){if(E!==void 0)return E;const n=Ze();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function tr(){S={phase:"initializing",message:qn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:zn}))}s(tr,"drainApi");async function Se(n){try{n==="SIGTERM"&&e.role==="api"&&await tr(),await x(),await Vt({claimed:s(async()=>{try{return p&&await Ut()}finally{await pe()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
|
|
18
18
|
${w}
|
|
19
|
-
`),process.exit(1)}}s(Se,"handleSignal");function ye(){Se("SIGINT")}s(ye,"onSigint");function _e(){Se("SIGTERM")}s(_e,"onSigterm");function be(){x().catch(()=>{})}s(be,"onExit");async function ce(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(ce,"enqueue");async function V(){!T||Z||(Ye.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Kt({log:c}),await jn(Date.now(),ve)}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(V,"enqueueTick");let B=null;async function nr(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const n=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw B=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(nr,"admitStartup");async function or(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await fn({dryRun:n.dryRun});if(n.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(or,"repairMigrations");async function ir(){X=e.intervalMs??nt;const n=g.token;C=new sn({epoch:n,enqueue:ce}),$t(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const a=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Gr(a);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=tt()}catch{return}t!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),yt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Or(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await rt(),await Xr(),await Zr(Date.now()),await et(Date.now())}),await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ft(ut);t.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await Me();for(const o of await Ce())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Le(o.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Tt();for(const t of ln){const o=await t.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(Yr()),I){const t=s(()=>{k(I().catch(()=>{})),k(lr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Vr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),G=setInterval(t,Ne*1e3),G.unref(),se=cr({joined:!0,register:k})}await ce(async()=>{await an(),await on()}),U=setInterval(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},X),ee=await Dt(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))}),re=await H.subscribe(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>m({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(ir,"completeStartup");function le(){return Qe??=ir().catch(n=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),dn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...r}}),f!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:f.person,joined_from:f.joinedFrom,retired:f.retired,columns:f.columns}}),N(e.role)?J=await vr():gr(wr());const n=g.token;Nt({epoch:n,requestHandover:er,registerDetached:k,startupBlock:Xe,admitStartup:nr,repairMigrations:or}),Je(),L=N(e.role)?Cr({tcp:e.tcp}):Un(e),await L.ready;const a=hr()??de("user").document_port;if(N(e.role)){const t=Ar(a,Nr());try{await t.ready,ne=t}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=de("user").runtime;if(w?.issuer&&(I=Kr(w.issuer,k),w.unsandboxed===!0&&(F=dr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Wr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),O=setInterval(t,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await Ur()),j(e.role)&&(ie=Jr()),ae=await qr({serves:N(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(M=await Mr(w,async()=>await Qr(w.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await mn()}catch(t){if($=null,t instanceof pn)return S={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(kr(),await br("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Jn,"runDaemon");var Ki=Jn;export{zn as API_DRAIN_GRACE_MS,Qi as brokerCommandDeclaresCanvasHome,he as brokerCommandEpoch,Ki as default,j as roleRunsLanes,N as roleServesRequests,Jn as runDaemon,jn as superviseTick,bn as teardownFleet};
|
|
19
|
+
`),process.exit(1)}}s(Se,"handleSignal");function ye(){Se("SIGINT")}s(ye,"onSigint");function _e(){Se("SIGTERM")}s(_e,"onSigterm");function be(){x().catch(()=>{})}s(be,"onExit");async function ce(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(ce,"enqueue");async function V(){!T||Z||(Ye.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Kt({log:c}),await jn(Date.now(),ve)}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(V,"enqueueTick");let B=null;async function nr(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const n=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw B=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(nr,"admitStartup");async function or(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await fn({dryRun:n.dryRun});if(n.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(or,"repairMigrations");async function ir(){X=e.intervalMs??nt;const n=g.token;C=new sn({epoch:n,enqueue:ce}),$t(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const a=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Gr(a);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=tt()}catch{return}t!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),yt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Or(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await rt(),await Xr(),await Zr(Date.now()),await et(Date.now())}),e.role===void 0&&await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ft(ut);t.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await Me();for(const o of await Ce())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Le(o.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Tt();for(const t of ln){const o=await t.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(Yr()),I){const t=s(()=>{k(I().catch(()=>{})),k(lr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Vr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),G=setInterval(t,Ne*1e3),G.unref(),se=cr({joined:!0,register:k})}await ce(async()=>{await an(),await on()}),U=setInterval(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},X),ee=await Dt(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))}),re=await H.subscribe(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>m({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(ir,"completeStartup");function le(){return Qe??=ir().catch(n=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),dn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...r}}),f!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:f.person,joined_from:f.joinedFrom,retired:f.retired,columns:f.columns}}),N(e.role)?J=await vr():gr(wr());const n=g.token;Nt({epoch:n,requestHandover:er,registerDetached:k,startupBlock:Xe,admitStartup:nr,repairMigrations:or}),Je(),L=N(e.role)?Cr({tcp:e.tcp}):Un(e),await L.ready;const a=hr()??de("user").document_port;if(N(e.role)){const t=Ar(a,Nr());try{await t.ready,ne=t}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=de("user").runtime;if(w?.issuer&&(I=Kr(w.issuer,k),w.unsandboxed===!0&&(F=dr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Wr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),O=setInterval(t,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await Ur()),j(e.role)&&(ie=Jr()),ae=await qr({serves:N(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(M=await Mr(w,async()=>await Qr(w.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await mn()}catch(t){if($=null,t instanceof pn)return S={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(kr(),await br("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Jn,"runDaemon");var Ki=Jn;export{zn as API_DRAIN_GRACE_MS,Qi as brokerCommandDeclaresCanvasHome,he as brokerCommandEpoch,Ki as default,j as roleRunsLanes,N as roleServesRequests,Jn as runDaemon,jn as superviseTick,bn as teardownFleet};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.651",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
},
|
|
146
146
|
"license": "UNLICENSED",
|
|
147
147
|
"dependencies": {
|
|
148
|
-
"@north-light/identity": "0.3.
|
|
148
|
+
"@north-light/identity": "0.3.651",
|
|
149
149
|
"@earendil-works/chord": "1.1.0",
|
|
150
150
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
151
151
|
"@earendil-works/pi-ai": "1.1.0",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.651",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.651",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.651",
|
|
32
32
|
"cron-parser": "^5.6.0",
|
|
33
33
|
"esbuild": "^0.27.7",
|
|
34
34
|
"jose": "^6.2.12",
|
|
@@ -11956,17 +11956,17 @@
|
|
|
11956
11956
|
},
|
|
11957
11957
|
"packages/crouter-api": {
|
|
11958
11958
|
"name": "@north-light/api",
|
|
11959
|
-
"version": "0.3.
|
|
11959
|
+
"version": "0.3.651",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.651",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.651",
|
|
11970
11970
|
"license": "UNLICENSED",
|
|
11971
11971
|
"dependencies": {
|
|
11972
11972
|
"jose": "^6.2.1"
|
|
@@ -11974,21 +11974,21 @@
|
|
|
11974
11974
|
},
|
|
11975
11975
|
"packages/crouter-plugin": {
|
|
11976
11976
|
"name": "@north-light/plugin",
|
|
11977
|
-
"version": "0.3.
|
|
11977
|
+
"version": "0.3.651",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.651",
|
|
11981
|
+
"@north-light/identity": "0.3.651"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.651",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.651",
|
|
11990
|
+
"@north-light/identity": "0.3.651",
|
|
11991
|
+
"@north-light/plugin": "0.3.651",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|