@north-light/cli 0.3.738 → 0.3.740

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- var V=Object.defineProperty;var o=(e,t)=>V(e,"name",{value:t,configurable:!0});import{spawn as U,execFileSync as J}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as M,join as D}from"node:path";import{fileURLToPath as Z,pathToFileURL as O}from"node:url";import{existsSync as W,lstatSync as ee,mkdirSync as te,openSync as H,closeSync as K,fstatSync as G,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as k}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as x,isPidAlive as m}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as j}from"./startup-policy.js";import{readMachineConfig as se}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ce}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ue}from"../core/canvas/paths.js";import{envNoDaemonAutostart as le}from"../shared/env.js";import{waitForDaemonAvailability as de}from"../api/index.js";import{localClient as pe}from"../api/node-transport.js";const fe=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function A(){const e={...process.env};for(const t of fe)delete e[t];return e}o(A,"sanitizedDaemonEnv");function me(){for(let e=M(Z(import.meta.url));;e=M(e)){if(W(D(e,"bin","runtime-generation-manifest.mjs")))return e;if(M(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(me,"generationRoot");async function I(){const e=me(),t=O(D(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(D(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",O(Q(import.meta.url).resolve("tsx/esm")).href,D(e,"src","daemon","crtrd-cli.ts")]}const n=O(D(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(I,"resolveDaemonLaunch");function he(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(he,"daemonCommandDeclaresCanvasHome");function we(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&he(a,t)&&n!==process.pid&&r.push(n);return r}o(we,"findDaemonPids");function _e(e){const t=we().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>m(n));)J("sleep",["0.1"]);for(const n of t)if(m(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(_e,"sweepStrayDaemons");async function Xe(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=k(),r=await I();return e(t,[t,...r,"--canvas-home",g()],A())}o(Xe,"execDaemon");async function R(e){const t=await I(),r=U(k(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:A()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,p)=>{r.once("error",p),r.once("close",h=>c(h))});if(s!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${s}`);const u=n.trim().split(`
2
- `).at(-1)??"";return JSON.parse(u)}o(R,"runDaemonEntry");function qe(){return R(["export-sqlite"])}o(qe,"runDaemonExportSqlite");function Ve(e,t){return R(["import-dump",e,t])}o(Ve,"runDaemonImportDump");function Je(e){return R(["import-dump",e,"bodies"])}o(Je,"runDaemonBodiesDump");function Qe(){return R(["import-dump","","install-id"])}o(Qe,"runDaemonInstallId");const z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return pe({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function Ee(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(Ee,"probeErrorMessage");async function Y(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=x()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(Y,"probeDaemonServing");async function Ze(){try{return await Y(),!0}catch{return!1}}o(Ze,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
- ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class X extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function De(e,t=j,r={},n="ready"){const a=r.readPidfile??x,s=r.isPidAlive??m,u=r.childExited,c=r.isDaemonServing,p=r.probeDaemonServing??(async _=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await Y(_)}),h=r.probeDaemonHealth??L,y=r.sleepMs??$,i=r.now??Date.now;let f=null,l=null;return await de({windowMs:t,pollIntervalMs:N,now:i,sleep:y,retry:o(_=>_!==l,"retry"),probe:o(async _=>{const w=a();if(w===null||!s(w)){const d=u?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await p(_)}catch(d){throw d instanceof v&&(l=d),d}f=w;return}const E=await h(_);if(E.startup_phase==="prepared"){f=w;return}throw E.startup_phase==="blocked"?(l=new v(w,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new F(w,E.startup_phase),l):new Error(`daemon ${w} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),f===e?null:f}o(De,"verifyDaemonStartup");async function xe(e,t=z,r={}){const n=r.readPidfile??x,a=r.isPidAlive??m,s=r.sleepMs??$,u=r.now??Date.now,c=u()+t;for(;u()<=c;){if(!a(e)&&n()!==e)return;await s(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(xe,"waitForDaemonExit");const ye=2e3,ge=5e3;async function q(e,t=z,r={}){const n=r.isPidAlive??m,a=r.sleepMs??$,s=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await xe(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const u=s()+ye;for(;s()<=u;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(q,"stopDaemonProcess");async function et(){const e=x(),t=e!==null&&m(e),r=t&&await q(e)==="killed",n=_e(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(et,"stopAllDaemons");function Se(e,t,r=2048){let n;try{n=H(e,"r");const{size:a}=G(n),s=Math.max(t,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return re(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{K(n)}catch{}}}o(Se,"readLogTailFrom");async function Re(e={}){if(process.platform==="linux"&&W("/run/crtr/launcher.sock")&&!m(x()??-1)&&se()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=x();if(r!==null&&m(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:Ee(i)}}te(g(),{recursive:!0});const n=await I().catch(i=>{throw new X(i)}),a=D(g(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return G(s).size}catch{return 0}})();ae()===void 0&&oe();const c=U(k(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:A()});K(s);const p=c.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let h=null;c.once("exit",(i,f)=>{h={code:i,signal:f}}),c.unref();let y;try{y=await De(p,j,{childExited:o(()=>h,"childExited"),childStderrTail:o(()=>Se(a,u),"childStderrTail")},t)}catch(i){const f=ce(ue())===p;if(h===null&&!f&&!(i instanceof v))try{await q(p,ge)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(Re,"spawnDaemon");function ve(){return le()||process.argv.includes("--no-autostart")}o(ve,"autostartDisabled");const Te=5e3,be=6e4;let B=!1,S,T=0,b=0;function Me(e){return Math.min(Te*2**(e-1),be)}o(Me,"autostartBackoffMs");function Oe(){S=void 0,T=0,b=0}o(Oe,"resetDaemonAutostart");function tt(){return S}o(tt,"daemonAutostartStartupFailure");function rt(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??Re,n=e.now??Date.now;if(!ve()&&!B&&!(n()<b)){if(t()){Oe();return}S=void 0,B=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof X)&&(S=a.message),T+=1,b=n()+Me(T)}).finally(()=>{B=!1})}}o(rt,"ensureDaemon");export{fe as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,X as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,ve as autostartDisabled,tt as daemonAutostartStartupFailure,he as daemonCommandDeclaresCanvasHome,rt as ensureDaemon,Xe as execDaemon,we as findDaemonPids,Ze as isDaemonServing,L as probeDaemonHealth,Y as probeDaemonServing,Ee as probeErrorMessage,Oe as resetDaemonAutostart,Je as runDaemonBodiesDump,qe as runDaemonExportSqlite,Ve as runDaemonImportDump,Qe as runDaemonInstallId,A as sanitizedDaemonEnv,Re as spawnDaemon,et as stopAllDaemons,q as stopDaemonProcess,_e as sweepStrayDaemons,De as verifyDaemonStartup,xe as waitForDaemonExit};
1
+ var V=Object.defineProperty;var o=(e,t)=>V(e,"name",{value:t,configurable:!0});import{spawn as U,execFileSync as J}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as M,join as D}from"node:path";import{fileURLToPath as Z,pathToFileURL as O}from"node:url";import{existsSync as W,lstatSync as ee,mkdirSync as te,openSync as H,closeSync as K,fstatSync as G,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as k}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as x,isPidAlive as m}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as j}from"./startup-policy.js";import{computerIsUnset as se,readMachineConfig as ce}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ue}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as le}from"../core/canvas/paths.js";import{envNoDaemonAutostart as de}from"../shared/env.js";import{waitForDaemonAvailability as pe}from"../api/index.js";import{localClient as fe}from"../api/node-transport.js";const me=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function A(){const e={...process.env};for(const t of me)delete e[t];return e}o(A,"sanitizedDaemonEnv");function he(){for(let e=M(Z(import.meta.url));;e=M(e)){if(W(D(e,"bin","runtime-generation-manifest.mjs")))return e;if(M(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(he,"generationRoot");async function I(){const e=he(),t=O(D(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(D(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",O(Q(import.meta.url).resolve("tsx/esm")).href,D(e,"src","daemon","crtrd-cli.ts")]}const n=O(D(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(I,"resolveDaemonLaunch");function we(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(we,"daemonCommandDeclaresCanvasHome");function _e(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&we(a,t)&&n!==process.pid&&r.push(n);return r}o(_e,"findDaemonPids");function Ee(e){const t=_e().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>m(n));)J("sleep",["0.1"]);for(const n of t)if(m(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(Ee,"sweepStrayDaemons");async function qe(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=k(),r=await I();return e(t,[t,...r,"--canvas-home",g()],A())}o(qe,"execDaemon");async function R(e){const t=await I(),r=U(k(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:A()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,p)=>{r.once("error",p),r.once("close",h=>c(h))});if(s!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${s}`);const u=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(u)}o(R,"runDaemonEntry");function Ve(){return R(["export-sqlite"])}o(Ve,"runDaemonExportSqlite");function Je(e,t){return R(["import-dump",e,t])}o(Je,"runDaemonImportDump");function Qe(e){return R(["import-dump",e,"bodies"])}o(Qe,"runDaemonBodiesDump");function Ze(){return R(["import-dump","","install-id"])}o(Ze,"runDaemonInstallId");const z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return fe({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function De(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(De,"probeErrorMessage");async function Y(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=x()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(Y,"probeDaemonServing");async function et(){try{return await Y(),!0}catch{return!1}}o(et,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class X extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function xe(e,t=j,r={},n="ready"){const a=r.readPidfile??x,s=r.isPidAlive??m,u=r.childExited,c=r.isDaemonServing,p=r.probeDaemonServing??(async _=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await Y(_)}),h=r.probeDaemonHealth??L,y=r.sleepMs??$,i=r.now??Date.now;let f=null,l=null;return await pe({windowMs:t,pollIntervalMs:N,now:i,sleep:y,retry:o(_=>_!==l,"retry"),probe:o(async _=>{const w=a();if(w===null||!s(w)){const d=u?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await p(_)}catch(d){throw d instanceof v&&(l=d),d}f=w;return}const E=await h(_);if(E.startup_phase==="prepared"){f=w;return}throw E.startup_phase==="blocked"?(l=new v(w,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new F(w,E.startup_phase),l):new Error(`daemon ${w} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),f===e?null:f}o(xe,"verifyDaemonStartup");async function ye(e,t=z,r={}){const n=r.readPidfile??x,a=r.isPidAlive??m,s=r.sleepMs??$,u=r.now??Date.now,c=u()+t;for(;u()<=c;){if(!a(e)&&n()!==e)return;await s(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(ye,"waitForDaemonExit");const ge=2e3,Se=5e3;async function q(e,t=z,r={}){const n=r.isPidAlive??m,a=r.sleepMs??$,s=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await ye(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const u=s()+ge;for(;s()<=u;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(q,"stopDaemonProcess");async function tt(){const e=x(),t=e!==null&&m(e),r=t&&await q(e)==="killed",n=Ee(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(tt,"stopAllDaemons");function Re(e,t,r=2048){let n;try{n=H(e,"r");const{size:a}=G(n),s=Math.max(t,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return re(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{K(n)}catch{}}}o(Re,"readLogTailFrom");async function ve(e={}){if(process.platform==="linux"&&W("/run/crtr/launcher.sock")&&!m(x()??-1)&&ce()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=x();if(r!==null&&m(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:De(i)}}te(g(),{recursive:!0});const n=await I().catch(i=>{throw new X(i)}),a=D(g(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return G(s).size}catch{return 0}})();ae()===void 0&&oe();const c=U(k(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:A()});K(s);const p=c.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let h=null;c.once("exit",(i,f)=>{h={code:i,signal:f}}),c.unref();let y;try{y=await xe(p,j,{childExited:o(()=>h,"childExited"),childStderrTail:o(()=>Re(a,u),"childStderrTail")},t)}catch(i){const f=ue(le())===p;if(h===null&&!f&&!(i instanceof v))try{await q(p,Se)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(ve,"spawnDaemon");function Te(){return de()||process.argv.includes("--no-autostart")}o(Te,"autostartDisabled");const be=5e3,Me=6e4;let B=!1,S,T=0,b=0;function Oe(e){return Math.min(be*2**(e-1),Me)}o(Oe,"autostartBackoffMs");function ke(){S=void 0,T=0,b=0}o(ke,"resetDaemonAutostart");function rt(){return S}o(rt,"daemonAutostartStartupFailure");function nt(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??ve,n=e.now??Date.now;if(!Te()&&!(!e.spawnDaemon&&se())&&!B&&!(n()<b)){if(t()){ke();return}S=void 0,B=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof X)&&(S=a.message),T+=1,b=n()+Oe(T)}).finally(()=>{B=!1})}}o(nt,"ensureDaemon");export{me as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,X as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,Te as autostartDisabled,rt as daemonAutostartStartupFailure,we as daemonCommandDeclaresCanvasHome,nt as ensureDaemon,qe as execDaemon,_e as findDaemonPids,et as isDaemonServing,L as probeDaemonHealth,Y as probeDaemonServing,De as probeErrorMessage,ke as resetDaemonAutostart,Qe as runDaemonBodiesDump,Ve as runDaemonExportSqlite,Je as runDaemonImportDump,Ze as runDaemonInstallId,A as sanitizedDaemonEnv,ve as spawnDaemon,tt as stopAllDaemons,q as stopDaemonProcess,Ee as sweepStrayDaemons,xe as verifyDaemonStartup,ye as waitForDaemonExit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.738",
3
+ "version": "0.3.740",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.738",
162
- "@north-light/plugin": "0.3.738",
161
+ "@north-light/identity": "0.3.740",
162
+ "@north-light/plugin": "0.3.740",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -5,7 +5,7 @@ import { piAgentDir } from '../../core/runtime/package-health.js';
5
5
  import { basename, dirname, join, relative, resolve } from 'node:path';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
7
  import { BINDING_CATALOG, normalizeGesture, splitGestureExpression, inboxShortcut, resolveKeybindings, } from '../../core/keybindings/index.js';
8
- import { runtimeManifest } from './shared.js';
8
+ import { builtinPiPackageDir } from '../../core/scope.js';
9
9
  import { atomicWriteJson, readJsonIfExists, readJsonOrNull } from '../../core/fs-utils.js';
10
10
  import { resolveBundledPiCliPath } from '../../core/runtime/pi-cli.js';
11
11
  import { crtrVersion } from '../../shared/crtr-version.js';
@@ -272,7 +272,7 @@ const LOCAL_PACKAGE_NAME_ALIASES = {
272
272
  'dev-plugin': [],
273
273
  };
274
274
  function selectedPiPackageDir(name) {
275
- return join(runtimeManifest.runtimeHome(), 'selected', 'dist', 'builtin-pi-packages', name);
275
+ return builtinPiPackageDir(name);
276
276
  }
277
277
  export function buildSetupManifest(resolveBuiltinPackageDir = selectedPiPackageDir) {
278
278
  // Order matters at execution: the marketplace source registers before the
@@ -123,8 +123,9 @@ export const sysSigninLeaf = defineLeaf({
123
123
  ],
124
124
  },
125
125
  run: async (input) => {
126
- // A fresh home has no daemon yet, and the move reads the canvas through it: start it (a no-op when it already serves) before anything else.
127
- await spawnDaemon();
126
+ // A computer with local records needs its daemon (the move reads the canvas through it) and a machine's daemon is the machine role; a fresh computer starts none until it is registered.
127
+ if (readMachineConfig() !== undefined || hasLocalCanvas())
128
+ await spawnDaemon();
128
129
  const oldPackage = oldPackageInstalled();
129
130
  if (oldPackage !== undefined)
130
131
  process.stderr.write(`${oldPackage.message}\n`);
@@ -112,6 +112,14 @@ export async function renameClashingLegacyCharges(db, schema, target, installId)
112
112
  WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(installId);
113
113
  return Number(done.changes);
114
114
  }
115
+ /** A staged watch whose (watcher, object) the target already holds is already imported (a hosted person's nodes watching shared objects): it and its subscriptions are
116
+ * dropped, the target's rows stand. Only this key is skipped; any other unique conflict still fails the pre-check. Returns the dropped watches and subscriptions. Runs before the pre-check. */
117
+ export async function dropExistingWatches(db, schema, target) {
118
+ const same = `FROM ${sq(target, 'watches')} t WHERE t.watcher = s.watcher AND t.object = s.object`;
119
+ const subs = await db.prepareUncached(`DELETE FROM ${sq(schema, 'watch_subscriptions')} u USING ${sq(schema, 'watches')} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${same})`).run();
120
+ const watches = await db.prepareUncached(`DELETE FROM ${sq(schema, 'watches')} s WHERE EXISTS (SELECT 1 ${same})`).run();
121
+ return { watches: Number(watches.changes), watch_subscriptions: Number(subs.changes) };
122
+ }
115
123
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
116
124
  * absent). Runs in the copy transaction: it writes target objects. */
117
125
  export async function fillEnvironments(tx, schema, target, source, person) {
@@ -237,9 +237,12 @@ export async function ensureRootProfile() {
237
237
  }
238
238
  return await createProfile(ROOT_PROFILE_NAME, [], { grantee: 'app:terminal' });
239
239
  }
240
- const existing = getStoredProfile(ROOT_PROFILE_ID);
240
+ // A computer signed in to an account that already has a root profile (made on another computer, so with another id) uses that one.
241
+ const existing = getStoredProfile(ROOT_PROFILE_ID)
242
+ ?? listProfiles().find((p) => p.manifest.name === ROOT_PROFILE_NAME && profileApp(p.manifest) === 'app:terminal')
243
+ ?? null;
241
244
  if (existing !== null) {
242
- scaffoldProfile(ROOT_PROFILE_ID, existing.manifest);
245
+ scaffoldProfile(existing.profileId, existing.manifest);
243
246
  return existing;
244
247
  }
245
248
  const next = {
@@ -7,6 +7,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync }
7
7
  import { randomBytes } from 'node:crypto';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { runtimeRoot, secretsDir } from '../../core/layout.js';
10
+ import { joinedIssuer } from '../../core/directory/join.js';
10
11
  import { CrtrError } from '../../core/errors.js';
11
12
  import { atomicWriteJson } from '../../core/fs-utils.js';
12
13
  import { ExitCode } from '../../types.js';
@@ -75,3 +76,5 @@ export function readOrCreateInstallId() {
75
76
  }
76
77
  /** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
77
78
  export const hasLocalCanvas = () => ['pg', 'canvas.db', 'canvas.db.imported'].some((name) => existsSync(join(runtimeRoot(), name)));
79
+ /** A computer with no `machine.json`, no local records and no join registration has not been set up: it has no control plane to reach until `crtr sys signin`. */
80
+ export const computerIsUnset = () => readMachineConfig() === undefined && !hasLocalCanvas() && joinedIssuer() === null;
@@ -16,7 +16,7 @@ import { hostExecPath } from '../core/runtime/branded-host.js';
16
16
  // reaches openDb) so the CLI daemon front door stays canvas.db-free (plan B-0).
17
17
  import { isDaemonRunning, readPidfile, isPidAlive } from './pidfile.js';
18
18
  import { DAEMON_STARTUP_WINDOW_MS } from './startup-policy.js';
19
- import { readMachineConfig } from './machine-link/config.js';
19
+ import { computerIsUnset, readMachineConfig } from './machine-link/config.js';
20
20
  import { exclusiveLockOwnerPid } from '../core/exclusive-lock.js';
21
21
  import { onDiskMigrationLockPath } from '../core/canvas/paths.js';
22
22
  import { envNoDaemonAutostart } from '../shared/env.js';
@@ -694,6 +694,9 @@ export function ensureDaemon(deps = {}) {
694
694
  const now = deps.now ?? Date.now;
695
695
  if (autostartDisabled())
696
696
  return;
697
+ // A computer with no `machine.json` and no local records is not set up: no command starts a local control plane there (`crtr sys signin` comes first).
698
+ if (!deps.spawnDaemon && computerIsUnset())
699
+ return;
697
700
  if (autostartInFlight)
698
701
  return;
699
702
  if (now() < autostartNextAttemptAt)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.738",
3
+ "version": "0.3.740",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.738",
3
+ "version": "0.3.740",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.738",
3
+ "version": "0.3.740",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.738",
31
- "@north-light/identity": "0.3.738"
30
+ "@north-light/api": "0.3.740",
31
+ "@north-light/identity": "0.3.740"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.738",
3
+ "version": "0.3.740",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.738",
9
+ "version": "0.3.740",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
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.738",
32
- "@north-light/plugin": "0.3.738",
31
+ "@north-light/identity": "0.3.740",
32
+ "@north-light/plugin": "0.3.740",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.738",
11905
+ "version": "0.3.740",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.738",
11910
+ "version": "0.3.740",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.738",
11915
+ "version": "0.3.740",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.738",
11923
+ "version": "0.3.740",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.738",
11927
- "@north-light/identity": "0.3.738"
11926
+ "@north-light/api": "0.3.740",
11927
+ "@north-light/identity": "0.3.740"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.738",
11932
+ "version": "0.3.740",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.738",
11936
- "@north-light/identity": "0.3.738",
11937
- "@north-light/plugin": "0.3.738",
11935
+ "@north-light/api": "0.3.740",
11936
+ "@north-light/identity": "0.3.740",
11937
+ "@north-light/plugin": "0.3.740",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {