@north-light/cli 0.3.647 → 0.3.648
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 +344 -344
- package/dist/core/canvas/pid.d.ts +7 -0
- package/dist/core/canvas/pid.js +5 -5
- package/dist/core/runtime/runner/machine/executor.d.ts +2 -2
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +20 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/scripts/install-runtime.mjs +3 -0
|
@@ -214,6 +214,13 @@ export declare function listProcessTable(): {
|
|
|
214
214
|
ppid: number;
|
|
215
215
|
command: string;
|
|
216
216
|
}[] | null;
|
|
217
|
+
/** `listProcessTable` without blocking the event loop, and with room for a loaded computer: `ps` gets `timeoutMs` (default 10 s) instead of
|
|
218
|
+
* 2 s. For a process that must keep serving while it samples (a machine-role crtrd answering its link). */
|
|
219
|
+
export declare function listProcessTableAsync(timeoutMs?: number): Promise<{
|
|
220
|
+
pid: number;
|
|
221
|
+
ppid: number;
|
|
222
|
+
command: string;
|
|
223
|
+
}[] | null>;
|
|
217
224
|
/** Test seam: exercise the `/proc` backend against a fake tree. */
|
|
218
225
|
export declare const procfsBackendForTest: {
|
|
219
226
|
procIdentities: typeof procIdentities;
|
package/dist/core/canvas/pid.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}s(
|
|
3
|
-
`)){const r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);r!==null&&e.push({pid:Number(r[1]),ppid:Number(r[2]),command:r[3].trim()})}return e}
|
|
4
|
-
`)){const o=r.trim();if(o==="")continue;const i=/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+(?:\s+\S+){4})\s+(.+)$/.exec(o);if(i===null)continue;const u=Number(i[1]),c=Number(i[2]),l=Number(i[3]),f=i[4],d=i[5],
|
|
5
|
-
`)){const i=o.trim();if(i==="")continue;const u=i.indexOf(" ");if(u===-1)continue;const c=Number(i.slice(0,u)),l=i.slice(u+1).trim();!Number.isInteger(c)||c<=0||l===""||t.set(c,
|
|
1
|
+
var K=Object.defineProperty;var s=(n,e)=>K(n,"name",{value:e,configurable:!0});import{execFile as X,spawn as q,spawnSync as g}from"node:child_process";import{readFileSync as h,readdirSync as W,statSync as Q}from"node:fs";import{readFile as T}from"node:fs/promises";import{readKernelBootId as v}from"./boot-id.js";function Y(n){if(p())return D(n);try{const e=g("ps",["-o","stat=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.error!=null||e.signal!=null||typeof e.stdout!="string"||typeof e.stderr=="string"&&e.stderr.trim()!=="")return"unknown";const t=e.stdout.trim();return t===""?"gone":t.charAt(0)==="Z"?"zombie":"live"}catch{return"unknown"}}s(Y,"psProcessState");function y(n){if(n==null)return!1;try{process.kill(n,0)}catch(t){return t.code==="EPERM"}const e=Y(n);return e!=="zombie"&&e!=="gone"}s(y,"isPidAlive");function mn(n){if(n==null)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}s(mn,"isPidPresent");const S=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function w(n){const e=n.indexOf("#");if(e===-1)return{base:n,ticks:void 0};const t=n.slice(e+1);return{base:n.slice(0,e),ticks:/^\d+$/.test(t)?t:void 0}}s(w,"splitIdentity");function k(n,e){const t=w(n),r=w(e);return t.ticks!==void 0&&r.ticks!==void 0?S.test(t.base)&&S.test(r.base)?t.base===r.base&&t.ticks===r.ticks:t.ticks===r.ticks:t.base===r.base}s(k,"identitiesMatch");function gn(n,e,t){const r=!!process.env.CRTR_DEBUG_PID_LIVENESS;if(n==null)return"dead";if(t===null)return r&&m(n,!1,e,"probe-null","ps snapshot failed \u2192 indeterminate","indeterminate"),"indeterminate";const o=t?.processes.get(n),i=t===void 0?y(n):o!==void 0&&!o.zombie;if(!i)return r&&m(n,i,e,t===void 0?"no-probe":"no-entry","process absent/zombie \u2192 dead","dead"),"dead";if(e==null)return r&&m(n,i,e,"no-probe","no baseline \u2192 trust process presence","alive"),"alive";let u;if(t===void 0){const l=V([n]);if(l==null)return r&&m(n,i,e,"probe-null","ps probe failed \u2192 indeterminate","indeterminate"),"indeterminate";if(u=l.get(n),u===void 0)return r&&m(n,i,e,"no-entry","no identity row for pid (race) \u2192 dead","dead"),"dead"}else u=o.identity;const c=k(u,e);return r&&m(n,i,e,"value",c?"identity matches expected \u2192 alive":"identity differs from expected \u2192 REUSED \u2192 dead",c?"alive":"dead",u),c?"alive":"dead"}s(gn,"recordedPidLiveness");function m(n,e,t,r,o,i,u){const c=[`pid=${String(n)}`,`isPidAlive=${e}`,`expectedIdentity=${t===void 0?"undefined":t===null?"null":JSON.stringify(t)}`,`capturePidIdentities=${r}${r==="value"?`(${JSON.stringify(u)})`:""}`,`branch=${JSON.stringify(o)}`,`returned=${i}`];process.stderr.write(`[recordedPidLiveness] ${c.join(" ")}
|
|
2
|
+
`)}s(m,"logPidLivenessDecision");function nn(n,e="SIGTERM"){if(!(!Number.isInteger(n)||n<=0))try{process.kill(-n,e)}catch{}}s(nn,"killProcessGroup");function en(n){try{const e=h(`/proc/${n}/stat`,"utf8"),t=e.lastIndexOf(")");if(t===-1)return null;const o=e.slice(t+2).trim().split(/\s+/)[19];return o!==void 0&&/^\d+$/.test(o)?o:null}catch{return null}}s(en,"procStartTicks");const tn=6e4;function rn(n,e=Date.now,t=tn){let r=null,o=0;return()=>{if(r!==null)return r;const i=e();if(i<o)return null;const u=n();return u!==null?r=u:(o=i+t,null)}}s(rn,"makeBootIdCache");const A=rn(v);function bn(n){const{base:e,ticks:t}=w(n);return t!==void 0&&!S.test(e)}s(bn,"isLegacyTicksIdentity");function hn(n){const{base:e,ticks:t}=w(n);return t!==void 0&&S.test(e)}s(hn,"isBootScopedIdentity");function M(n,e,t={}){const r=t.ticks!==void 0?t.ticks:en(n);return r===null?e:`${(t.bootId!==void 0?t.bootId:A())??e}#${r}`}s(M,"composeIdentity");const R=["-Ao","pid=,ppid=,pgid=,stat=,lstart=,command="],_=2e3;function I(){if(p())return x();let n;try{const e=g("ps",[...R],{encoding:"utf8",timeout:_,maxBuffer:8388608});if(e.status!==0||typeof e.stdout!="string")return null;n=e.stdout}catch{return null}return J(n)}s(I,"captureLivenessSnapshot");async function yn(){if(p())return j();const n=await new Promise(e=>{let t;try{t=q("ps",[...R])}catch{return e(null)}let r="",o=!1;const i=s(c=>{o||(o=!0,clearTimeout(u),e(c))},"settle"),u=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}i(null)},_);u.unref?.(),t.stdout.on("data",c=>r+=c.toString()),t.stderr.on("data",()=>{}),t.on("error",()=>i(null)),t.on("close",c=>i(c===0?r:null))});return n===null?null:J(n)}s(yn,"captureLivenessSnapshotAsync");function B(n){const e=n.indexOf("("),t=n.lastIndexOf(")");if(e===-1||t===-1||t<e)return null;const r=n.slice(t+2).trim().split(/\s+/),o=r[0],i=Number(r[1]),u=Number(r[2]),c=r[19];return o===void 0||o===""||!Number.isInteger(i)||i<0||!Number.isInteger(u)||u<0||c===void 0||!/^\d+$/.test(c)?null:{comm:n.slice(e+1,t),state:o,ppid:i,pgid:u,starttime:c}}s(B,"parseProcStat");function L(n,e){const t=n.replace(/\0+$/,"").split("\0").join(" ").trim();return t===""?`[${e}]`:t}s(L,"procCommandLine");let $;function p(){return $===void 0&&($=process.platform==="linux"&&v()!==null&&on(process.pid)!==null),$}s(p,"procfsUsable");const a={root:"/proc",bootId:s(()=>A(),"bootId")};function on(n,e=a){const t=b(n,e);return t==="unreadable"||t==="denied"||t==="gone"?null:t}s(on,"procStatOf");function b(n,e=a){let t;try{t=h(`${e.root}/${n}/stat`,"utf8")}catch(r){return N(r)}return B(t)??"unreadable"}s(b,"readProcStat");function N(n){const e=n.code;return e==="ENOENT"||e==="ESRCH"?"gone":e==="EACCES"||e==="EPERM"?"denied":"unreadable"}s(N,"classifyProcReadError");function sn(n,e){const t=e.selfUid!==void 0?e.selfUid():process.getuid?.()??null;if(t===null)return"own-or-unknown";try{return Q(`${e.root}/${n}`).uid===t?"own-or-unknown":"foreign"}catch(r){return N(r)==="gone"?"gone":"own-or-unknown"}}s(sn,"procOwnership");function C(n,e,t){return n==="gone"?"skip":n==="unreadable"||sn(e,t)==="own-or-unknown"?"fail":"skip"}s(C,"scanDisposition");function z(n,e=a){const t=e.bootId();return t===null?null:`${t}#${n.starttime}`}s(z,"procIdentity");function D(n,e=a){const t=b(n,e);return t==="gone"?"gone":t==="denied"||t==="unreadable"?"unknown":t.state==="Z"||t.state==="X"?"zombie":"live"}s(D,"procProcessState");function G(n,e=a){const t=new Map;for(const r of n){const o=b(r,e);if(o==="gone")continue;if(o==="unreadable"||o==="denied")return null;const i=z(o,e);if(i===null)return null;t.set(r,i)}return t}s(G,"procIdentities");function H(n,e=a){const t=b(n,e);if(t==="gone"||t==="unreadable"||t==="denied")return null;try{const r=L(h(`${e.root}/${n}/cmdline`,"utf8"),t.comm);return r===""?null:r}catch{return null}}s(H,"procCommand");function U(n,e,t,r,o){const i=z(r,n);if(i===null)return!1;e.processes.set(t,{zombie:r.state==="Z"||r.state==="X",pgid:r.pgid,identity:i,command:L(o,r.comm)});const u=e.childrenOf.get(r.ppid);return u===void 0?e.childrenOf.set(r.ppid,[t]):u.push(t),!0}s(U,"addProcfsRow");function F(n){try{return W(n).filter(e=>/^\d+$/.test(e)).map(Number).filter(e=>e>0)}catch{return null}}s(F,"procPids");function x(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map};for(const r of e){const o=b(r,n);if(o==="gone"||o==="denied"||o==="unreadable"){if(C(o==="gone"?"gone":o,r,n)==="skip")continue;return null}let i="";try{i=h(`${n.root}/${r}/cmdline`,"utf8")}catch(u){const c=u.code;if(c==="ENOENT"||c==="ESRCH")continue}if(!U(n,t,r,o,i))return null}return t}s(x,"readProcfsSnapshot");async function j(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map},r=64;for(let o=0;o<e.length;o+=r){const i=e.slice(o,o+r),u=await Promise.all(i.map(async c=>{try{const l=B(await T(`${n.root}/${c}/stat`,"utf8"));if(l===null)return"failed";const f=await T(`${n.root}/${c}/cmdline`,"utf8").catch(d=>{if(d.code==="ENOENT"||d.code==="ESRCH")throw d;return""});return{pid:c,stat:l,cmdline:f}}catch(l){return C(N(l),c,n)==="skip"?"gone":"failed"}}));for(const c of u)if(c!=="gone"&&(c==="failed"||!U(n,t,c.pid,c.stat,c.cmdline)))return null}return t}s(j,"readProcfsSnapshotAsync");function un(){if(p()){const n=x();if(n===null)return null;const e=new Map;for(const[t,r]of n.childrenOf)for(const o of r)e.set(o,t);return[...n.processes].map(([t,r])=>({pid:t,ppid:e.get(t)??0,command:r.command}))}try{const n=g("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:2e3,maxBuffer:8388608});return n.status!==0||typeof n.stdout!="string"?null:Z(n.stdout)}catch{return null}}s(un,"listProcessTable");function Z(n){const e=[];for(const t of n.split(`
|
|
3
|
+
`)){const r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);r!==null&&e.push({pid:Number(r[1]),ppid:Number(r[2]),command:r[3].trim()})}return e}s(Z,"parseProcessTable");async function Sn(n=1e4){return p()?un():await new Promise(e=>{try{X("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:n,maxBuffer:8*1024*1024},(t,r)=>{e(t===null&&typeof r=="string"?Z(r):null)})}catch{e(null)}})}s(Sn,"listProcessTableAsync");const wn={procIdentities:G,procProcessState:D,procCommand:H,readProcfsSnapshot:x,readProcfsSnapshotAsync:j};function J(n){const e=new Map,t=new Map;for(const r of n.split(`
|
|
4
|
+
`)){const o=r.trim();if(o==="")continue;const i=/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+(?:\s+\S+){4})\s+(.+)$/.exec(o);if(i===null)continue;const u=Number(i[1]),c=Number(i[2]),l=Number(i[3]),f=i[4],d=i[5],E=i[6].trim();if(!Number.isInteger(u)||u<=0||!Number.isInteger(c)||c<0||E==="")continue;e.set(u,{zombie:f.startsWith("Z"),pgid:l,identity:M(u,d),command:E});const O=t.get(c);O===void 0?t.set(c,[u]):O.push(u)}return{processes:e,childrenOf:t}}s(J,"parseLivenessTable");function P(n,e){const t=[],r=new Set([n]),o=[...e.get(n)??[]];for(;o.length>0;){const i=o.shift();if(r.has(i))continue;r.add(i),t.push(i);const u=e.get(i);u!==void 0&&o.push(...u)}return t}s(P,"descendantPidsFrom");function cn(n){if(!Number.isInteger(n)||n<=0)return[];const e=I();return e===null?[]:P(n,e.childrenOf)}s(cn,"descendantPids");function kn(n){const e=I();return e===null?null:[...e.processes].filter(([,t])=>t.pgid===n&&!t.zombie).map(([t])=>t)}s(kn,"pidsInProcessGroup");function V(n){const e=n.filter(r=>Number.isInteger(r)&&r>0),t=new Map;if(e.length===0)return t;if(p())return G(e);try{const r=g("ps",["-o","pid=,lstart=","-p",e.join(",")],{encoding:"utf8",timeout:2e3});if(r.error!=null||r.signal!=null||typeof r.stdout!="string"||typeof r.stderr=="string"&&r.stderr.trim()!=="")return null;for(const o of r.stdout.split(`
|
|
5
|
+
`)){const i=o.trim();if(i==="")continue;const u=i.indexOf(" ");if(u===-1)continue;const c=Number(i.slice(0,u)),l=i.slice(u+1).trim();!Number.isInteger(c)||c<=0||l===""||t.set(c,M(c,l))}return t}catch{return null}}s(V,"capturePidIdentities");function In(n){if(!Number.isInteger(n)||n<=0)return null;if(p())return H(n);try{const e=g("ps",["-o","command=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.status!==0||typeof e.stdout!="string")return null;const t=e.stdout.trim();return t===""?null:t}catch{return null}}s(In,"capturePidCommand");function $n(n,e,t){if(!Number.isInteger(n)||n<=0)return{tree:[],identities:null,reused:!1};const r=I();if(r===null)return{tree:[n],identities:null,reused:!1};const o=r.processes.get(n)?.identity;if(e!=null&&o!==void 0&&!k(o,e))return{tree:[],identities:null,reused:!0};const u=t!==void 0&&Number.isInteger(t)&&t>0?new Set([t,...P(t,r.childrenOf)]):void 0,c=[n,...P(n,r.childrenOf)].filter(f=>!u?.has(f)),l=new Map;for(const f of c){const d=r.processes.get(f)?.identity;d!==void 0&&l.set(f,d)}return{tree:c,identities:l,reused:!1}}s($n,"captureTeardownSnapshot");function Nn(n,e="SIGTERM",t){const r=t!=null?V(n):void 0;for(const o of n){if(t!=null&&r!=null){const i=t.get(o),u=r.get(o);if(i!==void 0&&u!==void 0&&!k(u,i))continue}if(nn(o,e),!(!Number.isInteger(o)||o<=0))try{process.kill(o,e)}catch{}}}s(Nn,"killProcessTreePids");function xn(n){return y(n)?!0:cn(n).some(e=>y(e))}s(xn,"isProcessTreeAlive");function Pn(n){return n.some(e=>y(e))}s(Pn,"isAnyPidAlive");export{I as captureLivenessSnapshot,yn as captureLivenessSnapshotAsync,In as capturePidCommand,V as capturePidIdentities,$n as captureTeardownSnapshot,M as composeIdentity,cn as descendantPids,k as identitiesMatch,Pn as isAnyPidAlive,hn as isBootScopedIdentity,bn as isLegacyTicksIdentity,y as isPidAlive,mn as isPidPresent,xn as isProcessTreeAlive,nn as killProcessGroup,Nn as killProcessTreePids,un as listProcessTable,Sn as listProcessTableAsync,rn as makeBootIdCache,B as parseProcStat,kn as pidsInProcessGroup,L as procCommandLine,wn as procfsBackendForTest,x as readProcfsSnapshot,j as readProcfsSnapshotAsync,gn as recordedPidLiveness};
|
|
@@ -10,12 +10,12 @@ export interface MachineExecutorDeps {
|
|
|
10
10
|
}
|
|
11
11
|
/** Broker processes: `{pid, execution, node}` for each `broker-cli.js ... --epoch <execution> <node>` command line. Throws when the process table cannot
|
|
12
12
|
* be read: an unreadable table is not an empty one, and a caller that read it as "no brokers" would start a second broker or report a stop that did not happen. */
|
|
13
|
-
export declare function findBrokers(): Array<{
|
|
13
|
+
export declare function findBrokers(): Promise<Array<{
|
|
14
14
|
pid: number;
|
|
15
15
|
execution: string;
|
|
16
16
|
node: string;
|
|
17
17
|
command: string;
|
|
18
|
-
}
|
|
18
|
+
}>>;
|
|
19
19
|
/** Reads the start bundle. A transient failure (connection error, timeout, 502/503/504) is asked again with doubling backoff until the budget above is spent, so a brief
|
|
20
20
|
* control-plane restart does not end the launch; any other non-2xx answer is permanent and fails at once with its status. The link dropping (`signal`) ends the wait. */
|
|
21
21
|
export declare function fetchBundle(apiUrl: string, executionId: string, token: string, signal?: AbortSignal): Promise<StartBundleDTO>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var P=Object.defineProperty;var s=(o,n)=>P(o,"name",{value:n,configurable:!0});import{spawn as U}from"node:child_process";import{closeSync as $,existsSync as
|
|
1
|
+
var P=Object.defineProperty;var s=(o,n)=>P(o,"name",{value:n,configurable:!0});import{spawn as U}from"node:child_process";import{closeSync as $,existsSync as E,mkdirSync as _,openSync as B,statSync as G}from"node:fs";import{rm as H}from"node:fs/promises";import{basename as S,dirname as I,join as R}from"node:path";import{fileURLToPath as F}from"node:url";import{contextDir as j,jobDir as K,nodeRunDir as k,crtrHome as b,viewSocketPath as X}from"../../../canvas/paths.js";import{captureTeardownSnapshot as J,isAnyPidAlive as V,killProcessTreePids as y,listProcessTableAsync as Y}from"../../../canvas/pid.js";import{scopesFilePath as v}from"../../../canvas/paths.js";import{writeFileBeneath as x}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as W}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as z}from"../../broker-ownership.js";import{isShippedCanvasExtension as Q}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as q,mergeCanvasExtensions as Z}from"../../canvas-extensions.js";import{layoutRoot as g,runtimeRoot as ee}from"../../../layout.js";import{composeAppProcessEnv as oe,overlayBrokerEnv as te}from"../../spawn-env.js";const T=s(()=>R(I(F(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),C=s(o=>{if(o!==void 0)try{process.kill(-o,"SIGKILL")}catch{}},"killGroup"),re=s(o=>new Promise(n=>setTimeout(n,o)),"sleep");async function N(){const o=[],n=await Y();if(n===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:r,command:e}of n){const t=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);t!==null&&o.push({pid:r,execution:t[1],node:t[2],command:e})}return o}s(N,"findBrokers");const ne=new Set([502,503,504]),ie=1e3,ce=3e4,se=3e4,A=9e4;async function ae(o,n,r,e){const t=Date.now()+A;for(let c=ie;;c=Math.min(c*2,ce)){e?.throwIfAborted();const i=AbortSignal.timeout(Math.min(se,Math.max(1,t-Date.now())));let a,d;try{a=await fetch(`${o.replace(/\/$/,"")}/v1/executions/${n}/start`,{headers:{authorization:`Bearer ${r}`},signal:e===void 0?i:AbortSignal.any([i,e])}),d=`the control plane answered ${a.status} for the start bundle of ${n}`}catch(u){e?.throwIfAborted(),d=`the control plane could not be reached for the start bundle of ${n}: ${u instanceof Error?u.message:String(u)}`}if(a?.ok)return await a.json();if(a!==void 0&&!ne.has(a.status))throw new Error(d);if(Date.now()+c>=t)throw new Error(`${d} (gave up after ${A/1e3} seconds of retries)`);e?.throwIfAborted(),await new Promise(u=>{const m=setTimeout(l,c);function l(){clearTimeout(m),e?.removeEventListener("abort",l),u()}s(l,"done"),e?.addEventListener("abort",l,{once:!0})})}}s(ae,"fetchBundle");const de=["CRTR_HOME","CRTR_RUNTIME_HOME"];function O(o,n){const r={...o};for(const e of de)delete r[e];return r.CRTR_CONTEXT_DIR!==void 0&&(r.CRTR_CONTEXT_DIR=j(n.id,r.CRTR_GRANTEE??n.app)),r.CRTR_SCOPES_FILE!==void 0&&(r.CRTR_SCOPES_FILE=v(n.id)),r}s(O,"localLaunchEnv");function ue(o){const n=s(i=>S(i).replace(/\.[jt]s$/,""),"stem"),r=new Set(q.map(n)),e=s(i=>Q(i)||S(I(i))==="pi-extensions"&&(r.has(n(i))||n(i).startsWith("canvas-")&&!E(i)),"shipped"),t=[],c=[];for(let i=0;i<o.length;i++)if(o[i]==="-e"&&o[i+1]!==void 0){const a=o[++i];if(e(a))continue;if(!E(a))throw new Error(`extension ${a} does not exist on this machine`);c.push(a)}else t.push(o[i]);return[...Z(c).flatMap(i=>["-e",i]),...t]}s(ue,"localExtensionArgv");function fe(o,n){const r=JSON.parse(o);return JSON.stringify({...r,argv:ue(r.argv),env:O(r.env??{},n)})}s(fe,"machineLaunchRecipe");function le(o,n,r){const e=o.launch,t=te({argv:[],env:O(e.env??{},o.node)},oe(o.node.cwd,null,o.node.app,o.machine_env??{},{}));return Object.assign(t,{CRTR_HOME:g(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ee(),CRTR_API_URL:n.apiUrl,CRTR_EXECUTION_ID:r,CRTR_ENVIRONMENT_ID:n.environmentId,CRTR_VIEW_WSS:"0",[W]:"1"})}s(le,"machineBrokerEnv");async function M(o,n,r){const{tree:e,identities:t}=J(o,null,r);if(t===null)return{confirmed:!1,error:`the process tree of broker ${o} could not be read, so shutdown cannot be confirmed`};const c=s(async(i,a)=>{for(let d=0;V(i);d+=100){if(d>=a)return!1;await re(100)}return!0},"waitUntilDead");try{process.kill(o,"SIGTERM")}catch{}return await c([o],n),y(e,"SIGTERM",t),await c(e,2e3)?{confirmed:!0}:(y(e,"SIGKILL",t),await c(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${o} survived SIGKILL`})}s(M,"stopBroker");async function Ne(o=1e4){const r=(await Promise.all((await N()).filter(e=>z(e.command,b())).map(e=>M(e.pid,o)))).filter(e=>!e.confirmed);if(r.length>0)throw new Error(r.map(e=>e.error??"a broker did not stop").join("; "))}s(Ne,"stopAllBrokers");function Ae(o){const n=(o.stopGraceS??10)*1e3,r=s(async e=>(await N()).find(t=>t.execution===e),"brokerOf");return{async start(e,t){const c=await r(e.executionId);if(c!==void 0)return{pid:c.pid};if(t?.throwIfAborted(),!E(e.cwd)||!G(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!E(T()))throw new Error(`the broker entry ${T()} does not exist`);const i=await ae(o.apiUrl,e.executionId,e.nodeToken,t);t?.throwIfAborted();const a=i.launch,d=k(e.nodeId);_(d,{recursive:!0}),x(d,R(d,"broker-launch.json"),fe(e.launchJson,i.node),{atomic:!0}),a.env?.CRTR_SCOPES_FILE!==void 0&&x(d,v(e.nodeId),JSON.stringify(a.scopes??[]),{atomic:!0});const u=K(e.nodeId);_(u,{recursive:!0});const m=B(R(u,"broker.log"),"a"),l=le(i,o,e.executionId);delete l.CRTR_NODE_TOKEN;try{t?.throwIfAborted();const f=U(process.execPath,[T(),"--canvas-home",b(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",m,m,"pipe"],env:l}),p=f.stdio[3];if(p==null||!("end"in p))throw C(f.pid),new Error("broker token pipe did not open");const D=await new Promise((L,h)=>{f.once("error",h),f.once("spawn",()=>{f.off("error",h),p.once("error",w=>{C(f.pid),h(w)}),p.end(e.nodeToken,w=>{w?h(w):L(f.pid)})})});return f.unref(),{pid:D}}finally{$(m)}},async wake({execution:e}){const t=await r(e.executionId);if(t===void 0)return"no_broker";try{return process.kill(t.pid,"SIGUSR1"),"signalled"}catch(c){if(c.code==="ESRCH")return"no_broker";throw c}},async stop({execution:e,options:t}){const c=await r(e.executionId);return c===void 0?{confirmed:!0}:await M(c.pid,n,t.excludePid)},async status({execution:e}){const t=await r(e.executionId);return t===void 0?{state:"gone"}:{state:"running",pid:t.pid}},async delete({nodeId:e}){return await H(k(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:X(e.nodeId)}}}}s(Ae,"createMachineExecutor");export{Ae as createMachineExecutor,ae as fetchBundle,N as findBrokers,ue as localExtensionArgv,le as machineBrokerEnv,fe as machineLaunchRecipe,Ne as stopAllBrokers};
|
|
@@ -4,6 +4,9 @@ export declare const LINK_BACKOFF_MIN_MS = 1000;
|
|
|
4
4
|
export declare const LINK_BACKOFF_MAX_MS = 60000;
|
|
5
5
|
/** Bytes written to a view.sock that its peer has not yet accepted, above which the channel is closed. */
|
|
6
6
|
export declare const VIEW_WRITE_LIMIT_BYTES: number;
|
|
7
|
+
/** Silence after which the link is presumed dead and terminated. The holder pings every 30 s; a socket orphaned by a network change
|
|
8
|
+
* (old address gone, no FIN ever arrives) stays ESTABLISHED locally forever, so only missing pings reveal it. */
|
|
9
|
+
export declare const LINK_SILENCE_MS = 75000;
|
|
7
10
|
/** One function per op; a machine-role crtrd injects the executor and the cron runner. */
|
|
8
11
|
export type MachineHandlers = {
|
|
9
12
|
[O in MachineOp]?: (args: never, signal: AbortSignal) => Promise<unknown>;
|
|
@@ -20,10 +23,27 @@ export interface MachineLinkOptions {
|
|
|
20
23
|
openView?: (node: string) => Socket;
|
|
21
24
|
backoffMinMs?: number;
|
|
22
25
|
backoffMaxMs?: number;
|
|
26
|
+
silenceMs?: number;
|
|
23
27
|
}
|
|
24
28
|
export interface MachineLink {
|
|
25
29
|
stop(): void;
|
|
26
30
|
connected(): boolean;
|
|
27
31
|
}
|
|
32
|
+
export interface ViewSink {
|
|
33
|
+
readonly bufferedAmount: number;
|
|
34
|
+
open(): boolean;
|
|
35
|
+
send(data: string, done: () => void): void;
|
|
36
|
+
}
|
|
37
|
+
export interface ViewSource {
|
|
38
|
+
pause(): void;
|
|
39
|
+
resume(): void;
|
|
40
|
+
}
|
|
41
|
+
/** Viewer frames, in order (a channel's view.close stays behind its data), fed into the link only while it holds fewer than
|
|
42
|
+
* VIEW_SEND_LOW_WATER unsent bytes; anything sent on the sink directly (a call result) therefore goes ahead of the queue. A source is
|
|
43
|
+
* paused while the queue is deep, so a slow link never buffers a pane stream in memory. */
|
|
44
|
+
export declare function createViewQueue(sink: ViewSink): {
|
|
45
|
+
push(data: string, source?: ViewSource): void;
|
|
46
|
+
forget(source: ViewSource): void;
|
|
47
|
+
};
|
|
28
48
|
export declare function linkUrl(apiUrl: string, environmentId: string): string;
|
|
29
49
|
export declare function startMachineLink(options: MachineLinkOptions): MachineLink;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var r=(t,l)=>O(t,"name",{value:l,configurable:!0});import{WebSocket as g}from"ws";import{emitEvent as b}from"../../core/events/emit.js";import{connectViewSocket as C}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as V,LINK_MAX_PAYLOAD_BYTES as B,parseFrame as W}from"./frames.js";const K=1e3,P=6e4,R=64*1024,U=4*1024*1024,F=1024*1024,Y=8*1024*1024,D=75e3;function $(t){const l=[];let s=0;const u=new Set,w=r(()=>{for(;l.length>0&&t.open()&&t.bufferedAmount<R;){const i=l.shift();s-=i.length,t.send(i,w)}if(s<F&&u.size>0){for(const i of u)i.resume();u.clear()}},"pump");return{push(i,a){t.open()&&(l.push(i),s+=i.length,a!==void 0&&s>U&&(a.pause(),u.add(a)),w())},forget(i){u.delete(i)}}}r($,"createViewQueue");function q(t,l){const s=new URL(`/v1/machines/${encodeURIComponent(l)}/link`,t);return s.protocol=s.protocol==="https:"?"wss:":s.protocol==="http:"?"ws:":s.protocol,s.toString()}r(q,"linkUrl");function G(t){const l=t.backoffMinMs??K,s=t.backoffMaxMs??P,u=t.openView??C,w=t.silenceMs??D;let i=!1,a,f=l,v;const A=r((E,o)=>{b({level:"error",event:E,fields:{environment:t.environmentId},error:o})},"fault");let y;const S=r(()=>{if(i)return;if(y!==void 0){if(t.credential()===y){v=setTimeout(S,f),f=Math.min(f*2,s);return}y=void 0}const E=t.credential(),o=new g(q(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${E}`},maxPayload:B});a=o;const d=new Map,h=new Map,M=r(e=>{o.readyState===g.OPEN&&o.send(JSON.stringify(e))},"send"),k=$({get bufferedAmount(){return o.bufferedAmount},open:r(()=>o.readyState===g.OPEN,"open"),send:r((e,n)=>o.send(e,n),"send")}),p=r((e,n)=>k.push(JSON.stringify(e),n),"sendView"),L=r(async e=>{const n=t.handlers[e.op];if(n===void 0){M({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const c=new AbortController,_=r(()=>c.abort(new Error("the machine link closed")),"onClose");o.once("close",_);try{M({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,c.signal)??null})}catch(T){M({type:"result",call_id:e.call_id,ok:!1,error:T instanceof Error?T.message:String(T)})}finally{o.off("close",_)}},"runCall"),N=r(e=>{const n=u(e.node);d.set(e.channel,n),n.once("connect",()=>p({type:"view.ready",channel:e.channel})),n.on("data",c=>p({type:"view.data",channel:e.channel,bytes:c.toString("base64")},n)),n.once("error",c=>{k.forget(n),d.delete(e.channel)&&p({type:"view.close",channel:e.channel,error:c.message})}),n.once("close",()=>{k.forget(n),d.delete(e.channel)&&p({type:"view.close",channel:e.channel})})},"openChannel"),x=r((e,n)=>{const c=d.get(e);if(c===void 0||c.write(n))return;const _=(h.get(e)??0)+n.length;if(_>Y){d.delete(e),h.delete(e),c.destroy(),p({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}h.has(e)||c.once("drain",()=>h.delete(e)),h.set(e,_)},"writeToChannel");let m;const I=r(()=>{m!==void 0&&clearTimeout(m),m=setTimeout(()=>{b({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),o.terminate()},w)},"heard");o.on("open",()=>{f=l,I()}),o.on("ping",I),o.on("message",e=>{I();const n=W(e);if(n!==null)try{switch(n.type){case"call":L(n);return;case"view.open":N(n);return;case"view.data":x(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const c=d.get(n.channel);d.delete(n.channel),c?.destroy();return}default:return}}catch(c){A("daemon.machine_link.frame_failed",c)}}),o.on("error",e=>A("daemon.machine_link.client_error",e)),o.on("close",e=>{m!==void 0&&clearTimeout(m);for(const n of d.values())n.destroy();d.clear(),a===o&&(a=void 0),!i&&(e===V&&(b({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),y=E),v=setTimeout(S,f),f=Math.min(f*2,s))})},"connect");return S(),{stop(){i=!0,v!==void 0&&clearTimeout(v),a?.close()},connected:r(()=>a?.readyState===g.OPEN,"connected")}}r(G,"startMachineLink");export{P as LINK_BACKOFF_MAX_MS,K as LINK_BACKOFF_MIN_MS,D as LINK_SILENCE_MS,Y as VIEW_WRITE_LIMIT_BYTES,$ as createViewQueue,q as linkUrl,G as startMachineLink};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.648",
|
|
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.648",
|
|
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.648",
|
|
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.648",
|
|
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.648",
|
|
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.648",
|
|
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.648",
|
|
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.648",
|
|
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.648",
|
|
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.648",
|
|
11981
|
+
"@north-light/identity": "0.3.648"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.648",
|
|
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.648",
|
|
11990
|
+
"@north-light/identity": "0.3.648",
|
|
11991
|
+
"@north-light/plugin": "0.3.648",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|
|
@@ -172,6 +172,9 @@ async function assertCanvasSchemaCompatible(stage) {
|
|
|
172
172
|
|
|
173
173
|
const root = process.env.CRTR_HOME || (process.platform === 'linux' ? '/' : join(homedir(), '.crouter'));
|
|
174
174
|
const runtime = join(root, 'runtime');
|
|
175
|
+
// A machine (runtime/machine.json, written by the import) runs no canvas database: its control plane is the cloud's, and the cluster
|
|
176
|
+
// the import left behind is never started again, so there is no schema here to be compatible with.
|
|
177
|
+
if (!process.env.CRTR_DATABASE_URL && existsSync(join(runtime, 'machine.json'))) return;
|
|
175
178
|
if (process.env.CRTR_DATABASE_URL || existsSync(join(runtime, 'pg', 'data'))) {
|
|
176
179
|
await assertPostgresSchemaCompatible(stage, runtime);
|
|
177
180
|
return;
|