@north-light/cli 0.3.740 → 0.3.742

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var Y=Object.defineProperty;var i=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{chmodSync as F,closeSync as L,existsSync as G,mkdirSync as k,openSync as $,unlinkSync as J,writeFileSync as X,rmSync as R}from"node:fs";import{createServer as K}from"node:http";import{dirname as x,join as P}from"node:path";import{spawn as z}from"node:child_process";import{SELF_UPDATE_SCRIPT as C}from"../core/self-update.js";import{apiSocketPath as V,crtrHome as D}from"../core/canvas/paths.js";import{bindDaemonEventSource as W}from"../core/events/source.js";import{emitEvent as u}from"../core/events/emit.js";import{brokerCommandDeclaresCanvasHome as Q}from"../core/runtime/broker-ownership.js";import{createMachineExecutor as Z,findBrokers as q,stopAllBrokers as ee}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as ne}from"../core/checkout-identities.js";import{machineWorktreeHandlers as te}from"../core/worktree-machine.js";import{readPersonCredential as oe}from"../core/directory/person-credential.js";import{socketDir as re}from"../core/layout.js";import{isDaemonRunning as ie,pidfilePath as S,readPidfile as ae}from"./pidfile.js";import{cancelMachineCron as se,runMachineCron as ce,stopOrphanedMachineCrons as de}from"./cron/machine-exec.js";import{startMachineLink as me}from"./machine-link/client.js";import{deleteMoveRecord as O,readMachineConfig as fe,readMachineCredential as j,readMoveRecord as le,writeMoveRecord as ue}from"./machine-link/config.js";import{jobExitReporting as pe,stopMachineJob as he}from"./machine-link/job-sweep.js";import{notifyMoveFinished as ve}from"./machine-link/move-notify.js";import{machineSupervision as we,SUPERVISION_TICK_MS as ye}from"./machine-supervision.js";import{startBrokerMemoryCap as _e}from"./broker-memory-cap.js";const B=10*6e4,Se=3e4,Ie=75;let I=0;function ge(t){if(Date.now()-I<B||!/^\d+\.\d+\.\d+$/.test(t))return;I=Date.now(),u({level:"warn",event:"daemon.machine.updating",fields:{release:t}});const r=P(x(C),"..","bin","crtr"),a=$(P(D(),"crtrd.err"),"a"),n=z("/bin/sh",["-c",'"$0" "$1" --version "$2" && "$0" "$3" sys daemon restart',process.execPath,C,t,r],{detached:!0,stdio:["ignore",a,a]});n.on("exit",d=>{d===Ie&&(I=Date.now()-B+Se)}),n.unref(),L(a)}i(ge,"updateToRelease");const H=1024;function Ee(t,r){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:t,signed_in:r,startup_phase:t?"ready":"recovering"}}i(Ee,"machineHealth");async function Qe(){const t=fe();if(t===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const r=oe()!==void 0;if(r&&j(),ie())throw new Error("a crtrd is already running for this home");W(),r||(await ee(),await de(),u({level:"info",event:"daemon.machine.signed_out",fields:{environment:t.environmentId}})),k(re(),{recursive:!0,mode:493});const a=V();G(a)&&J(a);let n;const d=pe(()=>n),s=K((e,o)=>{const c=(e.url??"").split("?")[0];if(e.method==="POST"&&(c==="/job-exit"||c==="/job-activity")){const T=[];let _=0;e.on("data",m=>{_+=m.length,_<=H&&T.push(m)}),e.on("end",()=>{if(_>H){o.writeHead(413),o.end();return}let m={};try{m=JSON.parse(Buffer.concat(T).toString("utf8"))}catch{}const b=typeof m.node=="string"&&typeof m.job=="string";o.writeHead(b?202:400,{"content-type":"application/json; charset=utf-8"}),o.end("{}"),b&&(c==="/job-exit"?d.notice:d.activity)(m.node,m.job)});return}const M=(e.method??"GET")==="GET"&&(e.url??"/").split("?")[0]==="/healthz";o.writeHead(M?200:404,{"content-type":"application/json; charset=utf-8"}),o.end(JSON.stringify(M?Ee(n?.connected()===!0,r):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((e,o)=>{s.once("error",o),s.listen(a,()=>{s.off("error",o),F(a,384),e()})}),k(x(S()),{recursive:!0}),X(S(),String(process.pid),"utf8");let l;t.runId!==void 0&&await be(t.runId,r,()=>l!==void 0);const p=new Set,v=new Set;let w=!1;const f=Z({apiUrl:t.apiUrl,environmentId:t.environmentId,onExit:i(e=>n?.reportExit(e),"onExit")}),U=i(async(e,o)=>{p.add(e.executionId);for(const c of v)c.add(e.executionId);try{return await f.start(e,o)}finally{p.delete(e.executionId)}},"start");n=r?me({apiUrl:t.apiUrl,environmentId:t.environmentId,credential:j,onOpen:i(()=>{d.onOpen(),w=!0},"onOpen"),onBehind:ge,handlers:{start:U,wake:f.wake,stop:f.stop,status:f.status,delete:f.delete,viewer:f.viewer,"cron.run":ce,"cron.cancel":se,"job.stop":i(e=>he(e),"job.stop"),...te,...ne}}):void 0;const g=n===void 0?void 0:we({link:n,brokers:i(async()=>{const e=new Set(p);v.add(e);const o=await q().finally(()=>v.delete(e));return w&&(w=!1,n?.reportRunning([...new Set([...e,...o.filter(c=>Q(c.command,D())).map(c=>c.execution)])])),o},"brokers"),stop:i((e,o)=>f.stop({execution:{executionId:e,nodeId:o,attempt:0},options:{reason:"yield_stall"}}),"stop")});let y=!1;const A=g===void 0?void 0:setInterval(()=>{y||(y=!0,g(Date.now()).catch(e=>u({level:"error",event:"daemon.machine.supervision_failed",error:e})).finally(()=>{y=!1}))},ye),N=_e();u({level:"info",event:"daemon.machine.started",fields:{environment:t.environmentId}});const E=i(()=>l??=(async()=>{n?.stop(),clearInterval(A),N(),await new Promise(e=>{s.close(()=>e()),s.closeAllConnections()}),ae()===process.pid&&(R(a,{force:!0}),R(S(),{force:!0})),process.off("SIGINT",h),process.off("SIGTERM",h)})(),"teardown"),h=i(()=>{E().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",h),process.on("SIGTERM",h),E}i(Qe,"runMachineDaemon");const Me=5e3,Te=3e5;async function be(t,r,a){let n;try{n=le()}catch(s){u({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:s.message}});return}if(n===void 0||n.state==="running"||n.runId!==t)return;if(n.notified||n.notify===null){O();return}if(n.state==="committed"&&(n={...n,state:"activated"},ue(n)),!r)return;const d=n;(async()=>{let s=Me;for(;;){try{await ve(d),O();return}catch(l){u({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:d.notify??"",error:l.message}})}if(await new Promise(l=>{setTimeout(l,s).unref()}),a())return;s=Math.min(s*2,Te)}})()}i(be,"settleFinishedMove");export{Ee as machineHealth,Qe as runMachineDaemon};
1
+ var A=Object.defineProperty;var r=(t,i)=>A(t,"name",{value:i,configurable:!0});import{chmodSync as N,closeSync as Y,existsSync as F,mkdirSync as k,openSync as L,unlinkSync as G,writeFileSync as J,rmSync as R}from"node:fs";import{createServer as X}from"node:http";import{dirname as K,join as z}from"node:path";import{spawn as V}from"node:child_process";import{SELF_UPDATE_SCRIPT as W}from"../core/self-update.js";import{apiSocketPath as $,crtrHome as b}from"../core/canvas/paths.js";import{bindDaemonEventSource as Q}from"../core/events/source.js";import{emitEvent as d}from"../core/events/emit.js";import{brokerCommandDeclaresCanvasHome as Z}from"../core/runtime/broker-ownership.js";import{createMachineExecutor as q,findBrokers as ee,stopAllBrokers as ne}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as te}from"../core/checkout-identities.js";import{machineWorktreeHandlers as oe}from"../core/worktree-machine.js";import{readPersonCredential as re}from"../core/directory/person-credential.js";import{socketDir as ie}from"../core/layout.js";import{isDaemonRunning as ae,pidfilePath as I,readPidfile as se}from"./pidfile.js";import{spawnDaemon as ce}from"./manage.js";import{cancelMachineCron as de,runMachineCron as me,stopOrphanedMachineCrons as le}from"./cron/machine-exec.js";import{startMachineLink as fe}from"./machine-link/client.js";import{deleteMoveRecord as P,readMachineConfig as pe,readMachineCredential as C,readMoveRecord as ue,writeMoveRecord as he}from"./machine-link/config.js";import{jobExitReporting as ve,stopMachineJob as _e}from"./machine-link/job-sweep.js";import{notifyMoveFinished as we}from"./machine-link/move-notify.js";import{machineSupervision as ye,SUPERVISION_TICK_MS as Se}from"./machine-supervision.js";import{startBrokerMemoryCap as Ie}from"./broker-memory-cap.js";const D=10*6e4,ge=3e4,Ee=75;let g=0;function Me(t,i){if(Date.now()-g<D||!/^\d+\.\d+\.\d+$/.test(t))return;g=Date.now(),d({level:"warn",event:"daemon.machine.updating",fields:{release:t}});const s=L(z(b(),"crtrd.err"),"a"),n=V(process.execPath,[W,"--version",t],{stdio:["ignore",s,s]});Y(s),n.on("error",a=>d({level:"error",event:"daemon.machine.update_failed",fields:{release:t},error:a})),n.on("exit",a=>{if(a===Ee){g=Date.now()-D+ge;return}if(a!==0){d({level:"error",event:"daemon.machine.update_failed",fields:{release:t,exit_code:a}});return}i()})}r(Me,"updateToRelease");const O=1024;function Te(t,i){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:t,signed_in:i,startup_phase:t?"ready":"recovering"}}r(Te,"machineHealth");async function en(){const t=pe();if(t===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const i=re()!==void 0;if(i&&C(),ae())throw new Error("a crtrd is already running for this home");Q(),i||(await ne(),await le(),d({level:"info",event:"daemon.machine.signed_out",fields:{environment:t.environmentId}})),k(ie(),{recursive:!0,mode:493});const s=$();F(s)&&G(s);let n;const a=ve(()=>n),c=X((e,o)=>{const m=(e.url??"").split("?")[0];if(e.method==="POST"&&(m==="/job-exit"||m==="/job-activity")){const T=[];let S=0;e.on("data",l=>{S+=l.length,S<=O&&T.push(l)}),e.on("end",()=>{if(S>O){o.writeHead(413),o.end();return}let l={};try{l=JSON.parse(Buffer.concat(T).toString("utf8"))}catch{}const x=typeof l.node=="string"&&typeof l.job=="string";o.writeHead(x?202:400,{"content-type":"application/json; charset=utf-8"}),o.end("{}"),x&&(m==="/job-exit"?a.notice:a.activity)(l.node,l.job)});return}const M=(e.method??"GET")==="GET"&&(e.url??"/").split("?")[0]==="/healthz";o.writeHead(M?200:404,{"content-type":"application/json; charset=utf-8"}),o.end(JSON.stringify(M?Te(n?.connected()===!0,i):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((e,o)=>{c.once("error",o),c.listen(s,()=>{c.off("error",o),N(s,384),e()})}),k(K(I()),{recursive:!0}),J(I(),String(process.pid),"utf8");let f;t.runId!==void 0&&await Re(t.runId,i,()=>f!==void 0);const u=new Set,v=new Set;let _=!1;const p=q({apiUrl:t.apiUrl,environmentId:t.environmentId,onExit:r(e=>n?.reportExit(e),"onExit")}),j=r(async(e,o)=>{u.add(e.executionId);for(const m of v)m.add(e.executionId);try{return await p.start(e,o)}finally{u.delete(e.executionId)}},"start");n=i?fe({apiUrl:t.apiUrl,environmentId:t.environmentId,credential:C,onOpen:r(()=>{a.onOpen(),_=!0},"onOpen"),onBehind:r(e=>Me(e,U),"onBehind"),handlers:{start:j,wake:p.wake,stop:p.stop,status:p.status,delete:p.delete,viewer:p.viewer,"cron.run":me,"cron.cancel":de,"job.stop":r(e=>_e(e),"job.stop"),...oe,...te}}):void 0;const E=n===void 0?void 0:ye({link:n,brokers:r(async()=>{const e=new Set(u);v.add(e);const o=await ee().finally(()=>v.delete(e));return _&&(_=!1,n?.reportRunning([...new Set([...e,...o.filter(m=>Z(m.command,b())).map(m=>m.execution)])])),o},"brokers"),stop:r((e,o)=>p.stop({execution:{executionId:e,nodeId:o,attempt:0},options:{reason:"yield_stall"}}),"stop")});let w=!1;const B=E===void 0?void 0:setInterval(()=>{w||(w=!0,E(Date.now()).catch(e=>d({level:"error",event:"daemon.machine.supervision_failed",error:e})).finally(()=>{w=!1}))},Se),H=Ie();d({level:"info",event:"daemon.machine.started",fields:{environment:t.environmentId}});const y=r(()=>f??=(async()=>{n?.stop(),clearInterval(B),H(),await new Promise(e=>{c.close(()=>e()),c.closeAllConnections()}),se()===process.pid&&(R(s,{force:!0}),R(I(),{force:!0})),process.off("SIGINT",h),process.off("SIGTERM",h)})(),"teardown"),U=r(async()=>{if(f===void 0){await y();try{const e=await ce();d({level:"info",event:"daemon.machine.replaced",fields:{successor_pid:e.pid??e.existing_pid??null}}),process.exit(0)}catch(e){d({level:"error",event:"daemon.machine.successor_failed",error:e}),process.exit(1)}}},"replaceSelf"),h=r(()=>{y().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",h),process.on("SIGTERM",h),y}r(en,"runMachineDaemon");const xe=5e3,ke=3e5;async function Re(t,i,s){let n;try{n=ue()}catch(c){d({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:c.message}});return}if(n===void 0||n.state==="running"||n.runId!==t)return;if(n.notified||n.notify===null){P();return}if(n.state==="committed"&&(n={...n,state:"activated"},he(n)),!i)return;const a=n;(async()=>{let c=xe;for(;;){try{await we(a),P();return}catch(f){d({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:a.notify??"",error:f.message}})}if(await new Promise(f=>{setTimeout(f,c).unref()}),s())return;c=Math.min(c*2,ke)}})()}r(Re,"settleFinishedMove");export{Te as machineHealth,en as runMachineDaemon};
@@ -1,6 +1,6 @@
1
1
  import { type HealthDTO, type StartupPhaseDTO } from '../api/index.js';
2
2
  import type { DumpResult } from '../core/import/export/dump.js';
3
- /** Env keys that must NEVER reach the daemon process. Restarting crtrd is
3
+ /** Non-`CRTR_*` env keys that must NEVER reach the daemon process. Restarting crtrd is
4
4
  * overwhelmingly done from inside an agent node's own bash tool (`crtr sys
5
5
  * daemon stop && start`), which inherits that node's FULL env — its identity
6
6
  * (`CRTR_NODE_ID`/`CRTR_KIND`/…, the `nodeEnv()` shape in `core/runtime/
@@ -15,10 +15,10 @@ import type { DumpResult } from '../core/import/export/dump.js';
15
15
  * relaunch it ever attempts, for its whole lifetime — the 2026-07-06 diagnosis
16
16
  * root cause behind 19 nodes killed with "failed to relaunch and is now dead". */
17
17
  export declare const DAEMON_ENV_STRIP_KEYS: readonly string[];
18
- /** A copy of `process.env` with every `DAEMON_ENV_STRIP_KEYS` entry removed.
19
- * Deliberate global config the user actually wants the daemon to see —
20
- * `CRTR_HOME`, `CRTR_SUBTREE`, `CRTR_LOG`, `CRTR_DEBUG`, etc. — passes through
21
- * untouched; only the node-identity/engine-poisoning surface is stripped. */
18
+ /** Whether a daemon process inherits this env name. */
19
+ export declare function daemonKeepsEnv(key: string): boolean;
20
+ /** A copy of `process.env` for a daemon process: the ordinary host env and the operator `CRTR_*` settings pass; every
21
+ * per-execution `CRTR_*` name and every `DAEMON_ENV_STRIP_KEYS` entry is dropped. */
22
22
  export declare function sanitizedDaemonEnv(): NodeJS.ProcessEnv;
23
23
  /** A crtrd declares its owning canvas in argv, so ownership is an exact match
24
24
  * on this process's canvas home. Untagged daemons retain their own
@@ -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{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};
1
+ var q=Object.defineProperty;var o=(t,e)=>q(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as J}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as N,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as nt}from"../core/canvas/pid.js";import{bindDaemonEventSource as ot,eventSource as at}from"../core/events/source.js";import{hostExecPath as y}from"../core/runtime/branded-host.js";import{isDaemonRunning as it,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as st,readMachineConfig as ct}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ut}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as lt}from"../core/canvas/paths.js";import{envNoDaemonAutostart as _t}from"../shared/env.js";import{waitForDaemonAvailability as dt}from"../api/index.js";import{localClient as pt}from"../api/node-transport.js";const Rt=["TMUX","TMUX_PANE","NODE_OPTIONS"],ft=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_LAYOUT_REFUSE","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),mt=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function ht(t){return Rt.includes(t)?!1:t.startsWith("CRTR_")?ft.has(t)||mt.some(e=>t.startsWith(e)):!0}o(ht,"daemonKeepsEnv");function g(){const t={};for(const[e,r]of Object.entries(process.env))ht(e)&&(t[e]=r);return t}o(g,"sanitizedDaemonEnv");function Et(){for(let t=N(Z(import.meta.url));;t=N(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(N(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Et,"generationRoot");async function P(){const t=Et(),e=I(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=I(T(t,"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(P,"resolveDaemonLaunch");function Tt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(Tt,"daemonCommandDeclaresCanvasHome");function wt(){const t=nt();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&Tt(a,e)&&n!==process.pid&&r.push(n);return r}o(wt,"findDaemonPids");function Dt(t){const e=wt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)J("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(Dt,"sweepStrayDaemons");async function Qt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=y(),r=await P();return t(e,[e,...r,"--canvas-home",S()],g())}o(Qt,"execDaemon");async function C(t){const e=await P(),r=K(y(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:g()});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,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(u)}o(C,"runDaemonEntry");function Zt(){return C(["export-sqlite"])}o(Zt,"runDaemonExportSqlite");function te(t,e){return C(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return C(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return C(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return pt({autostart:!1,timeoutMs:e}).probeHealthz(e)}o(b,"probeDaemonHealth");function St(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(St,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new O(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function U(t){return new Promise(e=>{setTimeout(e,t)})}o(U,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class O extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function At(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??U,i=r.now??Date.now;let p=null,l=null;return await dt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${t} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${t} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof O&&(l=_),_}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new O(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(At,"verifyDaemonStartup");async function Ct(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??U,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ct,"waitForDaemonExit");const Ot=2e3,xt=5e3;async function z(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??U,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ct(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Ot;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await z(t)==="killed",n=Dt(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Mt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Mt,"readLogTailFrom");async function Nt(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ct()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(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 B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:St(i)}}et(S(),{recursive:!0});const n=await P().catch(i=>{throw new Y(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();at()===void 0&&ot();const c=K(y(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:g()});G(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await At(d,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Mt(a,u),"childStderrTail")},e)}catch(i){const p=ut(lt())===d;if(f===null&&!p&&!(i instanceof O))try{await z(d,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:d,startup_phase:e}}o(Nt,"spawnDaemon");function It(){return _t()||process.argv.includes("--no-autostart")}o(It,"autostartDisabled");const yt=5e3,gt=6e4;let $=!1,A,x=0,M=0;function Pt(t){return Math.min(yt*2**(t-1),gt)}o(Pt,"autostartBackoffMs");function Lt(){A=void 0,x=0,M=0}o(Lt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??it,r=t.spawnDaemon??Nt,n=t.now??Date.now;if(!It()&&!(!t.spawnDaemon&&st())&&!$&&!(n()<M)){if(e()){Lt();return}A=void 0,$=!0,r().then(()=>{A=void 0,x=0,M=0},a=>{(a instanceof k||a instanceof Y)&&(A=a.message),x+=1,M=n()+Pt(x)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{Rt as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,B as DaemonNotPreparedError,O as DaemonStartupBlockedError,It as autostartDisabled,ae as daemonAutostartStartupFailure,Tt as daemonCommandDeclaresCanvasHome,ht as daemonKeepsEnv,ie as ensureDaemon,Qt as execDaemon,wt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,St as probeErrorMessage,Lt as resetDaemonAutostart,ee as runDaemonBodiesDump,Zt as runDaemonExportSqlite,te as runDaemonImportDump,re as runDaemonInstallId,g as sanitizedDaemonEnv,Nt as spawnDaemon,oe as stopAllDaemons,z as stopDaemonProcess,Dt as sweepStrayDaemons,At as verifyDaemonStartup,Ct as waitForDaemonExit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.740",
3
+ "version": "0.3.742",
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.740",
162
- "@north-light/plugin": "0.3.740",
161
+ "@north-light/identity": "0.3.742",
162
+ "@north-light/plugin": "0.3.742",
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",
@@ -23,7 +23,7 @@ import { envNoDaemonAutostart } from '../shared/env.js';
23
23
  import { waitForDaemonAvailability } from '../api/index.js';
24
24
  import { localClient } from '../api/node-transport.js';
25
25
  // Daemon env sanitization
26
- /** Env keys that must NEVER reach the daemon process. Restarting crtrd is
26
+ /** Non-`CRTR_*` env keys that must NEVER reach the daemon process. Restarting crtrd is
27
27
  * overwhelmingly done from inside an agent node's own bash tool (`crtr sys
28
28
  * daemon stop && start`), which inherits that node's FULL env — its identity
29
29
  * (`CRTR_NODE_ID`/`CRTR_KIND`/…, the `nodeEnv()` shape in `core/runtime/
@@ -38,19 +38,6 @@ import { localClient } from '../api/node-transport.js';
38
38
  * relaunch it ever attempts, for its whole lifetime — the 2026-07-06 diagnosis
39
39
  * root cause behind 19 nodes killed with "failed to relaunch and is now dead". */
40
40
  export const DAEMON_ENV_STRIP_KEYS = [
41
- // Node identity (nodeEnv() shape) — meaningless for a process supervising
42
- // many nodes rather than being one.
43
- 'CRTR_NODE_ID',
44
- 'CRTR_KIND',
45
- 'CRTR_MODE',
46
- 'CRTR_LIFECYCLE',
47
- 'CRTR_NODE_CWD',
48
- 'CRTR_CONTEXT_DIR',
49
- 'CRTR_CYCLES',
50
- 'CRTR_PROFILE_ID',
51
- 'CRTR_PARENT_NODE_ID',
52
- // Recursion-guard flag — only meaningful inside a pi engine process.
53
- 'CRTR_FRONT_DOOR',
54
41
  // Ambient tmux identity of whatever shell first autostarted the daemon. The
55
42
  // daemon is a headless supervisor with no pane of its own, but `spawnNode`
56
43
  // reads `currentTmux()` for a --root's foreground viewer placement; a stale
@@ -63,22 +50,46 @@ export const DAEMON_ENV_STRIP_KEYS = [
63
50
  // unaffected — the tmux CLI reaches the server via its default socket.
64
51
  'TMUX',
65
52
  'TMUX_PANE',
66
- // Engine-resolution seams NOT overridden per child launch — the proven and
67
- // suspected poison vectors.
68
- 'CRTR_BROKER_ENGINE',
69
- 'CRTR_PI_BINARY',
70
53
  // Generic Node.js env poisoning (a stray dev/debug flag from the restarting
71
54
  // shell).
72
55
  'NODE_OPTIONS',
73
56
  ];
74
- /** A copy of `process.env` with every `DAEMON_ENV_STRIP_KEYS` entry removed.
75
- * Deliberate global config the user actually wants the daemon to see —
76
- * `CRTR_HOME`, `CRTR_SUBTREE`, `CRTR_LOG`, `CRTR_DEBUG`, etc. — passes through
77
- * untouched; only the node-identity/engine-poisoning surface is stripped. */
57
+ /** The `CRTR_*` names the daemon keeps: deployment and operator settings for the whole canvas. Every other `CRTR_*` name is
58
+ * dropped, because crtr sets the rest on one node, cron, job or broker (its identity, its relay socket, its tokens, its
59
+ * model), and a daemon started from that shell would otherwise act as that one execution. `CRTR_API_SOCKET` reaching the
60
+ * daemon made a Mac's self-update restart refuse with `no_local_daemon`. `CRTR_BROKER_ENGINE` and `CRTR_PI_BINARY` stay
61
+ * out on purpose: an inherited engine override broke every broker relaunch on 2026-07-06. A new operator setting the
62
+ * daemon must read is added here; a new per-execution name needs nothing. */
63
+ const DAEMON_CRTR_ENV_NAMES = new Set([
64
+ 'CRTR_HOME', 'CRTR_RUNTIME_HOME', 'CRTR_PIDFILE', 'CRTR_RUNTIME', 'CRTR_INSTALL_ID',
65
+ 'CRTR_LOG', 'CRTR_DEBUG', 'CRTR_DEBUG_PID_LIVENESS', 'CRTR_TIMING', 'CRTR_TIMING_PROC',
66
+ 'CRTR_NO_DAEMON_AUTOSTART', 'CRTR_NO_AUTO_UPDATE', 'CRTR_NO_AUTO_INIT', 'CRTR_NO_EXPORTS', 'CRTR_LAYOUT_REFUSE',
67
+ 'CRTR_POSTGRES_HOME', 'CRTR_DATABASE_URL', 'CRTR_DATABASE_SCHEMA', 'CRTR_DATABASE_POOL_MAX', 'CRTR_SCHEMA_DATABASE_URL',
68
+ 'CRTR_DOCUMENT_PORT', 'CRTR_LAUNCHER_SOCKET', 'CRTR_API_ADDRESS', 'CRTR_DIRECTORY_URL', 'CRTR_PUBLIC_API_URL',
69
+ 'CRTR_CANVAS_URL', 'CRTR_CANVAS_CLIENT_ID', 'CRTR_CANVAS_JWK_FILE', 'CRTR_SECRETS_KEY', 'CRTR_IMPORT_SERVICE_TOKEN',
70
+ 'CRTR_PACKAGES_TOKEN', 'CRTR_FEEDBACK_ENDPOINT', 'CRTR_FEEDBACK_TOKEN', 'CRTR_SUPPORT_REPO',
71
+ 'CRTR_BRANDED_HOST', 'CRTR_CODESIGN_IDENTITY', 'CRTR_PLUGIN_REVALIDATE_TTL_MS', 'CRTR_IMPORT_BLOB_WORKERS',
72
+ 'CRTR_MAX_LIVE_BROKERS', 'CRTR_WARN_LIVE_BROKERS', 'CRTR_BROKER_RSS_CAP_MB', 'CRTR_UNATTENDED_PARK_MS', 'CRTR_WARM_POOL',
73
+ 'CRTR_STREAM_WATCHDOG_MS', 'CRTR_CONVERSATION_COMMIT_DEADLINE_MS', 'CRTR_NAME_MODEL', 'CRTR_MODEL_PROVIDER',
74
+ 'CRTR_BROKER_SIGNAL_LONG_PROOF',
75
+ ]);
76
+ /** Operator setting families the daemon keeps whole. `CRTR_TEST_` and `CRTR_FAULT_` are test-lane settings a lane exports for the daemon it starts. */
77
+ const DAEMON_CRTR_ENV_PREFIXES = ['CRTR_DB_', 'CRTR_BOOT_', 'CRTR_R2_', 'CRTR_LEDGER_', 'CRTR_BASH_', 'CRTR_WATCHER_', 'CRTR_RECAP_', 'CRTR_MODEL_AUTH_', 'CRTR_TEST_', 'CRTR_FAULT_'];
78
+ /** Whether a daemon process inherits this env name. */
79
+ export function daemonKeepsEnv(key) {
80
+ if (DAEMON_ENV_STRIP_KEYS.includes(key))
81
+ return false;
82
+ if (!key.startsWith('CRTR_'))
83
+ return true;
84
+ return DAEMON_CRTR_ENV_NAMES.has(key) || DAEMON_CRTR_ENV_PREFIXES.some((prefix) => key.startsWith(prefix));
85
+ }
86
+ /** A copy of `process.env` for a daemon process: the ordinary host env and the operator `CRTR_*` settings pass; every
87
+ * per-execution `CRTR_*` name and every `DAEMON_ENV_STRIP_KEYS` entry is dropped. */
78
88
  export function sanitizedDaemonEnv() {
79
- const env = { ...process.env };
80
- for (const key of DAEMON_ENV_STRIP_KEYS)
81
- delete env[key];
89
+ const env = {};
90
+ for (const [key, value] of Object.entries(process.env))
91
+ if (daemonKeepsEnv(key))
92
+ env[key] = value;
82
93
  return env;
83
94
  }
84
95
  // Entry point resolution
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.740",
3
+ "version": "0.3.742",
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.740",
3
+ "version": "0.3.742",
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.740",
3
+ "version": "0.3.742",
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.740",
31
- "@north-light/identity": "0.3.740"
30
+ "@north-light/api": "0.3.742",
31
+ "@north-light/identity": "0.3.742"
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.740",
3
+ "version": "0.3.742",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.740",
9
+ "version": "0.3.742",
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.740",
32
- "@north-light/plugin": "0.3.740",
31
+ "@north-light/identity": "0.3.742",
32
+ "@north-light/plugin": "0.3.742",
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.740",
11905
+ "version": "0.3.742",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.740",
11910
+ "version": "0.3.742",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.740",
11915
+ "version": "0.3.742",
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.740",
11923
+ "version": "0.3.742",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.740",
11927
- "@north-light/identity": "0.3.740"
11926
+ "@north-light/api": "0.3.742",
11927
+ "@north-light/identity": "0.3.742"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.740",
11932
+ "version": "0.3.742",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.740",
11936
- "@north-light/identity": "0.3.740",
11937
- "@north-light/plugin": "0.3.740",
11935
+ "@north-light/api": "0.3.742",
11936
+ "@north-light/identity": "0.3.742",
11937
+ "@north-light/plugin": "0.3.742",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {