@north-light/cli 0.3.662 → 0.3.663
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 +1 -1
- package/dist/core/canvas/schema-pg/020-machine-calls-status-all.sql +8 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/executor.d.ts +7 -0
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +14 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/daemon/broker-signals/bus.d.ts +3 -2
- package/dist/daemon/broker-signals/bus.js +1 -1
- package/dist/daemon/crtrd.d.ts +4 -0
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +9 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +8 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +11 -0
- package/dist/daemon/machine-link/holder.js +4 -4
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +5 -0
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +4 -0
- package/dist/daemon/reconcilers/node-lifecycle/tick.d.ts +3 -0
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var B=Object.defineProperty;var s=(o,r)=>B(o,"name",{value:r,configurable:!0});import{spawn as G}from"node:child_process";import{closeSync as H,existsSync as E,mkdirSync as y,openSync as F,statSync as j}from"node:fs";import{rm as K}from"node:fs/promises";import{basename as b,dirname as v,join as T}from"node:path";import{fileURLToPath as X}from"node:url";import{contextDir as J,jobDir as V,nodeRunDir as C,crtrHome as N,viewSocketPath as Y}from"../../../canvas/paths.js";import{captureTeardownSnapshot as W,isAnyPidAlive as z,killProcessTreePids as A,listProcessTableAsync as Q}from"../../../canvas/pid.js";import{scopesFilePath as O}from"../../../canvas/paths.js";import{writeFileBeneath as M}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as q}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as Z}from"../../broker-ownership.js";import{isShippedCanvasExtension as g}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as ee,mergeCanvasExtensions as oe}from"../../canvas-extensions.js";import{layoutRoot as te,runtimeRoot as ne}from"../../../layout.js";import{composeAppProcessEnv as re,overlayBrokerEnv as ie}from"../../spawn-env.js";const S=s(()=>T(v(X(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),D=s(o=>{if(o!==void 0)try{process.kill(-o,"SIGKILL")}catch{}},"killGroup"),ce=s(o=>new Promise(r=>setTimeout(r,o)),"sleep");async function I(){const o=[],r=await Q();if(r===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:n,command:e}of r){const t=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);t!==null&&o.push({pid:n,execution:t[1],node:t[2],command:e})}return o}s(I,"findBrokers");const se=new Set([502,503,504]),ae=1e3,de=3e4,ue=3e4,L=9e4;async function fe(o,r,n,e){const t=Date.now()+L;for(let c=ae;;c=Math.min(c*2,de)){e?.throwIfAborted();const i=AbortSignal.timeout(Math.min(ue,Math.max(1,t-Date.now())));let a,d;try{a=await fetch(`${o.replace(/\/$/,"")}/v1/executions/${r}/start`,{headers:{authorization:`Bearer ${n}`},signal:e===void 0?i:AbortSignal.any([i,e])}),d=`the control plane answered ${a.status} for the start bundle of ${r}`}catch(f){e?.throwIfAborted(),d=`the control plane could not be reached for the start bundle of ${r}: ${f instanceof Error?f.message:String(f)}`}if(a?.ok)return await a.json();if(a!==void 0&&!se.has(a.status))throw new Error(d);if(Date.now()+c>=t)throw new Error(`${d} (gave up after ${L/1e3} seconds of retries)`);e?.throwIfAborted(),await new Promise(f=>{const m=setTimeout(l,c);function l(){clearTimeout(m),e?.removeEventListener("abort",l),f()}s(l,"done"),e?.addEventListener("abort",l,{once:!0})})}}s(fe,"fetchBundle");const le=["CRTR_HOME","CRTR_RUNTIME_HOME"];function P(o,r){const n={...o};for(const e of le)delete n[e];return n.CRTR_CONTEXT_DIR!==void 0&&(n.CRTR_CONTEXT_DIR=J(r.id,n.CRTR_GRANTEE??r.app)),n.CRTR_SCOPES_FILE!==void 0&&(n.CRTR_SCOPES_FILE=O(r.id)),n}s(P,"localLaunchEnv");function pe(o){const r=s(i=>b(i).replace(/\.[jt]s$/,""),"stem"),n=new Set(ee.map(r)),e=s(i=>g(i)||b(v(i))==="pi-extensions"&&(n.has(r(i))||r(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[...oe(c).flatMap(i=>["-e",i]),...t]}s(pe,"localExtensionArgv");function me(o,r){const n=JSON.parse(o);return JSON.stringify({...n,argv:pe(n.argv),env:P(n.env??{},r)})}s(me,"machineLaunchRecipe");function he(o,r,n){const e=o.launch,t=ie({argv:[],env:P(e.env??{},o.node)},re(o.node.cwd,null,o.node.app,o.machine_env??{},{}));return Object.assign(t,{CRTR_HOME:te(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ne(),CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:n,CRTR_ENVIRONMENT_ID:r.environmentId,CRTR_VIEW_WSS:"0",[q]:"1"})}s(he,"machineBrokerEnv");async function U(o,r,n){const{tree:e,identities:t}=W(o,null,n);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;z(i);d+=100){if(d>=a)return!1;await ce(100)}return!0},"waitUntilDead");try{process.kill(o,"SIGTERM")}catch{}return await c([o],r),A(e,"SIGTERM",t),await c(e,2e3)?{confirmed:!0}:(A(e,"SIGKILL",t),await c(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${o} survived SIGKILL`})}s(U,"stopBroker");async function Me(o=1e4){const n=(await Promise.all((await I()).filter(e=>Z(e.command,N())).map(e=>U(e.pid,o)))).filter(e=>!e.confirmed);if(n.length>0)throw new Error(n.map(e=>e.error??"a broker did not stop").join("; "))}s(Me,"stopAllBrokers");function De(o){const r=(o.stopGraceS??10)*1e3,n=s(async e=>(await I()).find(t=>t.execution===e),"brokerOf");return{async start(e,t){const c=await n(e.executionId);if(c!==void 0)return{pid:c.pid};if(t?.throwIfAborted(),!E(e.cwd)||!j(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!E(S()))throw new Error(`the broker entry ${S()} does not exist`);const i=await fe(o.apiUrl,e.executionId,e.nodeToken,t);t?.throwIfAborted();const a=i.launch,d=C(e.nodeId);y(d,{recursive:!0}),M(d,T(d,"broker-launch.json"),me(e.launchJson,i.node),{atomic:!0}),a.env?.CRTR_SCOPES_FILE!==void 0&&M(d,O(e.nodeId),JSON.stringify(a.scopes??[]),{atomic:!0});const f=V(e.nodeId);y(f,{recursive:!0});const m=F(T(f,"broker.log"),"a"),l=he(i,o,e.executionId);delete l.CRTR_NODE_TOKEN;try{t?.throwIfAborted();const u=G(process.execPath,[S(),"--canvas-home",N(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",m,m,"pipe"],env:l});let R,k=!1;const x=s(()=>{R!==void 0&&o.onExit?.({execution:e.executionId,node:e.nodeId,...R})},"report");u.once("exit",(_,p)=>{R={code:_,signal:p},k&&x()});const h=u.stdio[3];if(h==null||!("end"in h))throw D(u.pid),new Error("broker token pipe did not open");const $=await new Promise((_,p)=>{u.once("error",p),u.once("spawn",()=>{u.off("error",p),h.once("error",w=>{D(u.pid),p(w)}),h.end(e.nodeToken,w=>{w?p(w):_(u.pid)})})});return k=!0,x(),u.unref(),{pid:$}}finally{H(m)}},async wake({execution:e}){const t=await n(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 n(e.executionId);return c===void 0?{confirmed:!0}:await U(c.pid,r,t.excludePid)},async status({execution:e}){const t=await n(e.executionId);return t===void 0?{state:"gone"}:{state:"running",pid:t.pid}},async"status.all"(e){return{running:(await I()).map(t=>({execution:t.execution,pid:t.pid}))}},async delete({nodeId:e}){return await K(C(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:Y(e.nodeId)}}}}s(De,"createMachineExecutor");export{De as createMachineExecutor,fe as fetchBundle,I as findBrokers,pe as localExtensionArgv,he as machineBrokerEnv,me as machineLaunchRecipe,Me as stopAllBrokers};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var N=Object.defineProperty;var
|
|
1
|
+
var N=Object.defineProperty;var u=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as d}from"node:test";import e from"node:assert/strict";import{spawn as P}from"node:child_process";import{mkdirSync as R,mkdtempSync as E,readFileSync as k,rmSync as v,writeFileSync as _}from"node:fs";import{tmpdir as w}from"node:os";import{join as l}from"node:path";import{EventEmitter as A}from"node:events";import{Readable as D}from"node:stream";import{createServer as H}from"node:http";import{createNode as M}from"../../../canvas/canvas.js";import{closeDb as L,openDb as T}from"../../../canvas/db.js";import{isPidAlive as h}from"../../../canvas/pid.js";import{bindPerson as F,installTerminalGrant as j,useEmptyPersonSettings as U}from"../../../__tests__/helpers/person.js";import{setAppEnvVar as g}from"../../../profiles/app-env-store.js";import{setProfileEnvVar as O}from"../../../profiles/env-store.js";import{createProfile as V}from"../../../profiles/manifest.js";import{putEnvRow as G}from"../../../secrets/env-rows.js";import{appSpace as J}from"../../../layout.js";import{executionStartRoutes as $}from"../../../../daemon/api/handlers/execution-start.js";import{Router as X}from"../../../../daemon/api/router.js";import{contextDir as S,scopesFilePath as C}from"../../../canvas/paths.js";import{layoutRoot as B,runtimeRoot as K}from"../../../layout.js";import{CANVAS_EXTENSIONS as m}from"../../canvas-extensions.js";import{createMachineExecutor as Y,fetchBundle as I,localExtensionArgv as z,machineBrokerEnv as f,machineLaunchRecipe as b}from"./executor.js";let p;const Q={HOME:process.env.HOME,CRTR_HOME:process.env.CRTR_HOME};x(()=>{process.env.HOME=p=E(l(w(),"crtr-machine-exec-")),process.env.CRTR_HOME=l(p,".crouter"),R(process.env.CRTR_HOME,{recursive:!0})}),q(async()=>{await L(),v(p,{recursive:!0,force:!0});for(const[n,o]of Object.entries(Q))o===void 0?delete process.env[n]:process.env[n]=o});async function W(n,o){const i=new X().registerAll($),a=Object.assign(D.from([]),{method:"GET",url:`/v1/executions/${o}/start`,headers:{}});let r="";const t=Object.assign(new A,{headersSent:!1,writableEnded:!1,writableFinished:!1});return t.setHeader=()=>t,t.writeHead=()=>(t.headersSent=!0,t),t.end=s=>(s&&(r+=s),t.writableEnded=!0,t.writableFinished=!0,t),await i.handle(a,t,null,n),JSON.parse(r)}u(W,"bundleFor"),d("a machine broker gets the profile, app and deployment rows, the app pi dir and the launch env, with the process runner's precedence",async()=>{await U(),await T();const n=await j(),o=(await V("machine-env")).profileId;await g("app:terminal","SHARED","from-app",n),await g("app:terminal","APP_SECRET","app-secret",n),await O(o,"SHARED","from-profile",n),await O(o,"PROFILE_VAR","profile-value",n),await G({person:null,kind:"deployment",id:"_deployment"},"DEPLOY_VAR","deploy-value");const i=l(p,"work");R(i,{recursive:!0}),await M({node_id:"m1",name:"m1",created:new Date().toISOString(),cwd:i,kind:"general",mode:"base",lifecycle:"resident",status:"active",parent:null,profile_id:o,grantee:"app:terminal"}),await(await T()).prepare("INSERT INTO executions (execution_id, node_id, state, started_at, launch_json, runner) VALUES ('em1', 'm1', 'launching', 't', ?, 'machine')").run(JSON.stringify({argv:["x"],env:{LAUNCH_VAR:"launch",CRTR_NODE_ID:"m1"}}));const a={class:"broker",app:"app:terminal",node:"m1",run:null,uid:process.getuid?.()??0,sub:await F(),grant:null,client_id:null,scopes:null},r=await W(a,"em1");e.equal(r.machine_env?.APP_SECRET,"app-secret");const t=f(r,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1");e.equal(t.APP_SECRET,"app-secret"),e.equal(t.PROFILE_VAR,"profile-value"),e.equal(t.DEPLOY_VAR,"deploy-value"),e.equal(t.SHARED,"from-profile","the profile's row wins over the app's"),e.equal(t.LAUNCH_VAR,"launch"),e.equal(t.PI_CODING_AGENT_DIR,l(J("app:terminal").home,".pi","agent")),e.equal(t.CRTR_API_URL,"http://cloud.invalid"),e.equal(t.CRTR_EXECUTION_ID,"em1"),e.doesNotThrow(()=>f({...r,node:{...r.node,profile:"profile-the-mac-does-not-hold"}},{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1")),e.equal(t.GITHUB_TOKEN,void 0)}),d("stop ends the broker and the detached command it left behind, and confirms both gone",async()=>{const n=E(l(w(),"crtr-machine-stop-")),o=l(n,"child.pid"),i=l(n,"broker-cli.js");_(i,`const { spawn } = require('node:child_process');
|
|
2
2
|
const c = spawn('sleep', ['300'], { detached: true, stdio: 'ignore' }); c.unref();
|
|
3
3
|
require('node:fs').writeFileSync(${JSON.stringify(o)}, String(c.pid));
|
|
4
|
-
setInterval(() => {}, 1000);`);const
|
|
4
|
+
setInterval(() => {}, 1000);`);const a=P(process.execPath,[i,"--canvas-home",n,"--epoch","exec-stop-1","node-stop-1"],{detached:!0,stdio:"ignore"});a.unref();try{let r=0;for(let c=0;c<100&&r===0;c++)try{r=Number(k(o,"utf8"))}catch{await new Promise(y=>setTimeout(y,50))}e.ok(r>0&&h(r),"the detached child is running");const t=Y({apiUrl:"http://cloud.invalid",environmentId:"env1",stopGraceS:3});e.ok((await t["status.all"]({})).running.some(c=>c.execution==="exec-stop-1"&&c.pid===a.pid),"status.all lists the running broker");const s=await t.stop({execution:{executionId:"exec-stop-1",nodeId:"node-stop-1"},options:{reason:"test"}});e.deepEqual(s,{confirmed:!0}),e.equal(h(a.pid),!1,"the broker is gone"),e.equal(h(r),!1,"the detached child is gone")}finally{try{process.kill(-a.pid,"SIGKILL")}catch{}v(n,{recursive:!0,force:!0})}}),d("a bundle the control plane built on its Linux layout starts a broker on this machine's own home, runtime, context, scopes and extension paths",()=>{const n={CRTR_HOME:"/work/crtr",CRTR_RUNTIME_HOME:"/opt/crouter/runtime",CRTR_CONTEXT_DIR:"/work/crtr/apps/terminal/nodes/m2/context",CRTR_SCOPES_FILE:"/work/crtr/runtime/nodes/m2/run/scopes.json",CRTR_NODE_ID:"m2",CRTR_KIND:"general",CRTR_GRANTEE:"app:terminal",CRTR_PROFILE_ID:"p-1"},i={launch:{argv:[...m.flatMap(t=>["-e",`/opt/crouter/runtime/generations/96276ec4/dist/pi-extensions/${t.split("/").pop()}`]),"-n","m2"],env:n,scopes:["a:b"]},node:{id:"m2",app:"app:terminal",cwd:p,profile:null},machine_env:{APP_SECRET:"s"}},a=f(i,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em2");e.equal(a.CRTR_HOME,B()),e.equal(a.CRTR_RUNTIME_HOME,process.env.CRTR_RUNTIME_HOME??K()),e.equal(a.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(a.CRTR_SCOPES_FILE,C("m2")),e.equal(a.CRTR_NODE_ID,"m2"),e.equal(a.CRTR_PROFILE_ID,"p-1"),e.equal(a.APP_SECRET,"s");for(const[t,s]of Object.entries(a))e.ok(!/\/work\/crtr|\/opt\/crouter/.test(s??""),`${t} names a control plane path: ${s}`);const r=JSON.parse(b(JSON.stringify(i.launch),i.node));e.deepEqual(r.argv.filter((t,s)=>r.argv[s-1]==="-e"),m),e.equal(r.argv.at(-1),"m2"),e.equal(r.env.CRTR_HOME,void 0),e.equal(r.env.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(r.env.CRTR_SCOPES_FILE,C("m2")),e.deepEqual(r.scopes,["a:b"]),e.ok(!/\/work\/crtr|\/opt\/crouter/.test(JSON.stringify(r))),e.throws(()=>b(JSON.stringify({argv:["-e","/opt/crouter/runtime/generations/x/custom.js"],env:{}}),{id:"m2",app:"app:terminal"}),/does not exist on this machine/)}),d("the broker's mandatory extensions are this install's complete list, whatever set the control plane's release shipped",()=>{const n=u(t=>["-e",`/opt/crouter/runtime/generations/old/dist/pi-extensions/${t}.js`],"server"),o=l(p,"custom-ext.js");_(o,"");const i=[...m,o].flatMap(t=>["-e",t]),r=[...m.map(t=>t.split("/").pop().replace(/\.[jt]s$/,"")).slice(1).flatMap(n),...n("canvas-retired-hook"),"-e",o,"-n","label","prompt text"];e.deepEqual(z(r),[...i,"-n","label","prompt text"])}),d("a control plane that answers 502 and then 200 still gives the start bundle, while a 404 fails at once with its status",async()=>{const n=[502,200],o=H((i,a)=>{const r=i.url?.includes("/gone/")?404:n.shift()??200;a.writeHead(r,{"content-type":"application/json"}),a.end(JSON.stringify(r===200?{launch:{argv:[]},node:{id:"n"}}:{error:"x"}))});await new Promise(i=>o.listen(0,"127.0.0.1",i));try{const i=`http://127.0.0.1:${o.address().port}`;e.deepEqual((await I(i,"exec-502","token")).node,{id:"n"}),e.deepEqual(n,[],"the 502 was asked again"),await e.rejects(I(i,"gone","token"),/answered 404/)}finally{o.close()}});
|
|
@@ -3,7 +3,7 @@ import type { AutoDroppedWorktree, AbandonManagedWorktreeResult } from '../../..
|
|
|
3
3
|
import type { CloseOnHostOutcome } from '../../../worktree-close.js';
|
|
4
4
|
import type { AbandonOutcome, FinalizeWorktreeOutcome } from '../../../worktree-mutation-async.js';
|
|
5
5
|
import type { RunnerExecution, RunnerStartInput, RunnerStatus, RunnerStopOptions, RunnerStopResult, RunnerViewerAddress, RunnerWakeResult } from '../types.js';
|
|
6
|
-
export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "delete", "viewer", "cron.run", "cron.cancel", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize"];
|
|
6
|
+
export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "status.all", "delete", "viewer", "cron.run", "cron.cancel", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize"];
|
|
7
7
|
export type MachineOp = (typeof MACHINE_OPS)[number];
|
|
8
8
|
/** A `start` call carries the whole start input and the node token the control plane minted: the Mac has no database, so it cannot mint one.
|
|
9
9
|
* The token sits in `machine_calls.args_json` until the row is deleted a day after it finishes; the execution's token row holds its hash. */
|
|
@@ -23,6 +23,15 @@ export interface MachineStopArgs {
|
|
|
23
23
|
export interface MachineStatusArgs {
|
|
24
24
|
execution: RunnerExecution;
|
|
25
25
|
}
|
|
26
|
+
/** Every broker running on the machine, from one scan of its process table: the control plane's timed check of all its executions
|
|
27
|
+
* there in one call. A machine on a release before this op answers `this machine does not execute status.all`. */
|
|
28
|
+
export type MachineStatusAllArgs = Record<string, never>;
|
|
29
|
+
export interface MachineStatusAllResult {
|
|
30
|
+
running: Array<{
|
|
31
|
+
execution: string;
|
|
32
|
+
pid: number;
|
|
33
|
+
}>;
|
|
34
|
+
}
|
|
26
35
|
export interface MachineDeleteArgs {
|
|
27
36
|
nodeId: string;
|
|
28
37
|
}
|
|
@@ -118,6 +127,10 @@ export interface MachineOpTable {
|
|
|
118
127
|
args: MachineStatusArgs;
|
|
119
128
|
result: RunnerStatus;
|
|
120
129
|
};
|
|
130
|
+
'status.all': {
|
|
131
|
+
args: MachineStatusAllArgs;
|
|
132
|
+
result: MachineStatusAllResult;
|
|
133
|
+
};
|
|
121
134
|
delete: {
|
|
122
135
|
args: MachineDeleteArgs;
|
|
123
136
|
result: null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var s=Object.defineProperty;var n=(t,e)=>s(t,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","delete","viewer","cron.run","cron.cancel","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize"];class c extends Error{static{n(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,o=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=o}}class l extends c{static{n(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{n(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{n(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,o){super(`${r} on machine ${e} failed: ${o}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};
|
|
1
|
+
var s=Object.defineProperty;var n=(t,e)=>s(t,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","status.all","delete","viewer","cron.run","cron.cancel","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize"];class c extends Error{static{n(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,o=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=o}}class l extends c{static{n(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{n(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{n(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,o){super(`${r} on machine ${e} failed: ${o}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};
|
|
@@ -11,10 +11,11 @@ export declare function cachedBrokerNodeFields(node: BrokerExtensionNodeDTO): Br
|
|
|
11
11
|
* (D39): a grant id, run or node id, structured request, queue, limit, or environment object. `fault_retry` carries a node id: the
|
|
12
12
|
* fault-retry backstop publishes it in the commit that claims the nudge, and the API process holding that node's stream turns it
|
|
13
13
|
* into a `fault-retry` line. `machine` carries a machine environment object id (a call is pending for the API process holding its link);
|
|
14
|
-
* `machine_call` carries a call id (the caller waiting on it re-reads the row)
|
|
14
|
+
* `machine_call` carries a call id (the caller waiting on it re-reads the row); `execution_exit` carries a node id whose machine broker
|
|
15
|
+
* exited (the lane processes run that node's lifecycle pass). `document` carries a document object id: it was edited or
|
|
15
16
|
* deleted, and a browser document stream re-reads it. The writers fire them (the
|
|
16
17
|
* schema's triggers, or the unit that owns the writer); the bus only delivers. */
|
|
17
|
-
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document"];
|
|
18
|
+
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document", "execution_exit"];
|
|
18
19
|
export type BrokerSignalKind = (typeof BROKER_SIGNAL_KINDS)[number];
|
|
19
20
|
export type BrokerSignalSubscriber = (id: string, kind: BrokerSignalKind) => void;
|
|
20
21
|
export interface BrokerSignalSubscription {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|
|
1
|
+
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","execution_exit"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|
package/dist/daemon/crtrd.d.ts
CHANGED
|
@@ -9,6 +9,10 @@ interface DaemonTickLifecycle extends DetachedWorkLifecycle {
|
|
|
9
9
|
}
|
|
10
10
|
/** Supervision tick over the daemon's current live set. */
|
|
11
11
|
export declare function superviseTick(now?: number, lifecycle?: DaemonTickLifecycle): Promise<void>;
|
|
12
|
+
/** The node-lifecycle pass for one node whose machine broker exit was just reported (`execution_exit`), as the tick would run it.
|
|
13
|
+
* Every lane process hears the signal; only a pass that still finds the exit unconsumed runs, because the one that consumed it already
|
|
14
|
+
* decided (a later one would read the cleared pid as a stranded launch). A node whose stop is held is left to its stopper by the pass. */
|
|
15
|
+
export declare function exitedNodePass(nodeId: string, now?: number): Promise<void>;
|
|
12
16
|
export interface DaemonOpts {
|
|
13
17
|
/** Milliseconds between supervision polls. Default 2000. */
|
|
14
18
|
intervalMs?: number;
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var ar=Object.defineProperty;var s=(e,c)=>ar(e,"name",{value:c,configurable:!0});import{applyBootSettings as sr}from"./boot-settings.js";import{startPeerOutbox as cr}from"./peer/outbox.js";import{reportMachineStatus as lr}from"../core/peer/directory.js";import{createPeerRelay as dr}from"./peer/relay-service.js";import{writeFileSync as mr,readFileSync as pr,rmSync as fr,mkdirSync as Re,existsSync as R,unlinkSync as Pe,chmodSync as Ee}from"node:fs";import{createServer as Y}from"node:http";import{dirname as ur}from"node:path";import{envCrtrdTcp as Ie,envDocumentPort as hr}from"../shared/env.js";import{openCanvasConversationStore as wr,serveCanvasConversationStore as vr}from"../core/canvas/sessions.js";import{installConversationStore as gr}from"../core/conversation-store/index.js";import{pollRunObservers as Sr}from"./runs/observer.js";import{randomBytes as xe}from"node:crypto";import{apiSocketPath as De,crtrHome as yr}from"../core/canvas/paths.js";import{activeAppUsers as _r}from"../core/spaces/users.js";import{ensureAppSpace as br,ensureUserFiles as kr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Rr}from"./launcher-events.js";import{initializeEmptyLayout as Pr,layoutNeedsMigration as Er,socketDir as Te}from"../core/layout.js";import{migrateLooseKeys as Ir}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as xr}from"../core/profiles/relocate.js";import{getNode as Dr,listNodesForSupervision as Ce,listParkedResidentsWithWakeMail as Tr,setFrozen as Le}from"../core/canvas/index.js";import{createApiServer as Cr,closeServer as $e}from"./api/server.js";import{Router as Lr}from"./api/router.js";import{healthRoutes as $r}from"./api/handlers/health.js";import{createDocumentListener as Ar}from"./api/document-listener.js";import{documentSecret as Nr}from"./api/document-secret.js";import{createAppListener as Mr}from"./api/app-listener.js";import{registerMachineEnvironment as Gr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markCloudRole as Fr,resolvePerson as Br,retireLocalPerson as Hr,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Ae,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as Ur}from"./run-notices.js";import{startGrantEffects as qr}from"./reconcilers/grant-effects.js";import{syncPackages as Wr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Kr,GRANT_SYNC_INTERVAL_S as Ne}from"../core/grants/sync.js";import{sweepSandboxes as Vr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Yr}from"./cron/run-socket.js";import{hasSyncedGrants as Qr}from"../core/grants/mirror.js";import{readConfig as de}from"../core/config.js";import{reconcileUndeliveredTickets as Xr}from"./human/sweep.js";import{resetHandedOffDeliveries as Zr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as et}from"../core/canvas/daemon-actions.js";import{sweepReviews as rt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as tt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as nt}from"./supervise-cadence.js";import{createResumeDetector as ot}from"./resume-detector.js";import{setFatalFaultAnnouncer as it}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as at}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as st}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ct}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as lt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as dt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as mt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as pt}from"./reconcilers/action-lane.js";import{endLiveExecution as ft,migrateLegacyExecutionIdentities as ut}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as ht}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as wt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as vt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as gt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as St}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as yt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as _t}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as bt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as kt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as Me}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Rt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Pt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Et}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as It}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as xt,subscribeImageBuilt as Dt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Tt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ge,capturePidCommand as Ct,captureTeardownSnapshot as Oe,isPidAlive as Lt,isAnyPidAlive as Fe,killProcessTreePids as Be}from"../core/canvas/pid.js";import{bindFleet as $t,boundFleet as At}from"../core/runtime/fleet.js";import{bindDaemonControl as Nt,clearDaemonControl as Mt}from"./control.js";import{execDaemon as Gt,spawnDaemon as Ot}from"./manage.js";import{reconcileAndMigrateBoot as Ft}from"../core/canvas/boot.js";import{resolveInstallId as Bt}from"../core/canvas/install-id.js";import{setInstallId as Ht}from"../core/runtime/nodes.js";import{claimDaemonOwnership as jt,daemonOwnershipApplies as zt,daemonOwnershipClaimed as Ut,releaseDaemonOwnership as He}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as qt,closeAllDbs as pe,openDb as je,withCanvasWrite as fe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Wt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Jt,ensurePostgresHealthy as Kt,stopPostgres as Vt,withPostgresStartLock as Yt}from"./postgres/index.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Xt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Zt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as en}from"../core/scoped-state/migrate-app-installs.js";import{publish as rn,readBuiltinSnapshot as tn}from"../core/graph/package-publish.js";import{startRepoSync as nn}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as on,reapStaleSpares as an}from"../core/runtime/warm-pool.js";import{DaemonFleet as sn}from"./fleet.js";import{copyNodeFilesToRows as cn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as ln}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as dn}from"../core/events/source.js";import{activateCanvasImport as mn,MigrationBlockedError as pn,runForcedCanvasImport as fn}from"../migrations/activation.js";import{adoptInstallPerson as un,convertLegacyScopedStore as hn,personStoresCopied as wn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as vn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as ze,installPreludeSnapshot as gn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as Ue}from"../core/scoped-state/person-rows.js";import{userScopeRoot as qe}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ue}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Qi}from"../core/runtime/broker-ownership.js";function he(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(he,"brokerCommandEpoch");const Sn=5e3,We=150;async function yn(e){const c=Ge();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const u=yr(),p=[];for(const[r,l]of c.processes){const y=l.command;if(l.zombie||!y.includes("broker-cli.js")||!ue(y,u)||he(y)===e)continue;const P=y.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||p.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of p){const l=Ct(r.pid);if(l===null||!l.includes("broker-cli.js")||!ue(l,u)||he(l)===e||l.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const y=Oe(r.pid,null);if(!y.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:y})}}const h=Date.now()+Sn;for(;Date.now()<h&&i.some(r=>Fe(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,We));let g=0;for(const r of i){const l=r.snap.tree.length>0?r.snap.tree:[r.pid];Fe(l)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):Be(l,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,We));const d=Ge();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const f=[];for(const[r,l]of d.processes){const y=l.command;l.zombie||!y.includes("broker-cli.js")||ue(y,u)&&he(y)!==e&&f.push(r)}if(f.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${f.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:v,sigkilled:g}})}s(yn,"reapPriorEpochBrokers");const _n=5e3;async function bn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Dr(i))?.status;(h==="active"||h==="idle")&&await Le(i,new Date().toISOString())}const u=c.map(([,i])=>({pid:i.pid,snap:Oe(i.pid,null),exited:i.handle.exited}));for(const i of u)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const p=new Promise(i=>{setTimeout(i,_n).unref()});await Promise.allSettled(u.map(i=>Promise.race([i.exited.then(()=>{}),p])));const v=[];for(const i of u)Lt(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):Be(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await ft(i,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:u.length,sigkilled:v.length}})}s(bn,"teardownFleet");function Je(){Re(ur(me()),{recursive:!0}),mr(me(),String(process.pid),"utf8")}s(Je,"writePidfile");function Ke(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ke,"isMissingPathError");function Ve(e){const c=me();let u;try{u=pr(c,"utf8")}catch(p){if(Ke(p))return;throw p}if(u.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{fr(c)}catch(p){if(Ke(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const kn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},Q=new at;it(e=>Q.handleFatalFault(e,!1));const Rn=new st,Pn=new ct,En=new lt,In=new dt,xn=new mt,Dn=new pt,Tn=new wt,Cn=new vt,Ln=new gt,$n=new St,An=new _t,Nn=new bt,Mn=new kt,Gn=new Rt,On=new Pt,Fn=new Et,Bn=new It,Hn=new xt;async function jn(e=Date.now(),c=kn){const u=At(),p=await Q.runFleetPreamble(u);let v,i,h;try{i=await Me();const d=(await Ce()).filter(r=>!i.has(r.node_id));v=d.filter(r=>r.status==="active"||r.status==="idle"),h=d.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const f=new Set(h.map(r=>r.node_id));h.push(...(await Tr()).filter(r=>!f.has(r.node_id)&&!i.has(r.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await Q.run(e,{rows:v,fleet:u,lifecycle:c,held:i}),await Rn.run(e,{rows:v,held:i});const g=await Pn.run(e,{rows:[...v,...h],fleet:u});await En.run(e,i),await Bn.run(e,i),await Hn.run(e,{lifecycle:c}),await In.run(e,{lifecycle:c,held:i}),await xn.run(e,{lifecycle:c}),await Dn.run(e,{lifecycle:c}),await Tn.run(e,{lifecycle:c}),await Cn.run(e,{lifecycle:c,fleet:u,held:i}),Ln.run(e,{lifecycle:c}),$n.run(e,{lifecycle:c}),An.run(e,{lifecycle:c}),Nn.run(e,{lifecycle:c}),Mn.run(e,{lifecycle:c}),Gn.run(e,{lifecycle:c}),await Sr(),Fn.run(e,{fleet:u,lifecycle:c}),await On.run(e,{rows:v}),Q.warnIfSaturated({fleet:u,lifecycle:c,thresholds:p,frozen:g})}s(jn,"superviseTick");function j(e){return e===void 0||e==="reconcile"}s(j,"roleRunsLanes");function N(e){return e===void 0||e==="api"}s(N,"roleServesRequests");const zn=66e4;function Un(e){const c=new Lr().registerAll($r(()=>null).filter(r=>r.pattern==="/healthz")),u=s((r,l)=>{const y=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&y==="/healthz"){c.handle(r,l,null,{class:"person"});return}l.writeHead(404,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=De();R(p)&&Pe(p);const v=Y(u),i=new Promise((r,l)=>{v.once("error",l),v.listen(p,()=>{v.off("error",l),Ee(p,384),r()})});let h,g=null;const d=e.tcp??Ie()??de("user").api.tcp;if(d!==void 0&&d!==""){const r=/^(.*):(\d+)$/.exec(d.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${d}`);const l=Y(u);l.on("error",y=>m({event:"api.server.failed",level:"error",error:y})),l.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=l}let f=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!f){f=!0,await Promise.all([$e(v,new Set,r.graceMs),h===void 0?Promise.resolve():$e(h,new Set,r.graceMs)]);try{R(p)&&Pe(p)}catch{}}}}}s(Un,"createProbeServer");const qn="daemon is draining for shutdown and admits no new work";async function Wn(e){Re(Te(),{recursive:!0,mode:493}),process.platform==="linux"&&Ee(Te(),493);const c=De();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const u=Y((d,f)=>{if(d.method==="GET"&&d.url==="/healthz"){f.writeHead(200,{"content-type":"application/json; charset=utf-8"}),f.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}f.writeHead(503,{"content-type":"application/json; charset=utf-8"}),f.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,f)=>{u.once("error",f),u.listen(c,()=>{u.off("error",f),d()})});let p;const v=e.tcp??Ie();if(v){const d=/^(.*):(\d+)$/.exec(v);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const f=Y(u.listeners("request")[0]);await new Promise((r,l)=>{f.once("error",l),f.listen(Number(d[2]),d[1],()=>{f.off("error",l),r()})}),p=f}Je();let i;const h=s(()=>(i??=(async()=>{u.closeAllConnections(),p?.closeAllConnections(),await Promise.all([u,p].filter(d=>d!==void 0).map(d=>new Promise((f,r)=>d.close(l=>l?r(l):f())))),Ve(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
|
|
2
|
-
`),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}s(
|
|
3
|
-
`)},"logPostgres"),
|
|
1
|
+
var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as pr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Ee,existsSync as R,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Q}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as De,envDocumentPort as gr}from"../shared/env.js";import{openCanvasConversationStore as yr,serveCanvasConversationStore as Sr}from"../core/canvas/sessions.js";import{installConversationStore as _r}from"../core/conversation-store/index.js";import{pollRunObservers as br}from"./runs/observer.js";import{randomBytes as Te}from"node:crypto";import{apiSocketPath as Ce,crtrHome as kr}from"../core/canvas/paths.js";import{activeAppUsers as Rr}from"../core/spaces/users.js";import{ensureAppSpace as Pr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Ir}from"./launcher-events.js";import{initializeEmptyLayout as xr,layoutNeedsMigration as Dr,socketDir as Le}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Cr}from"../core/profiles/relocate.js";import{getNode as Lr,getRow as $r,listNodesForSupervision as $e,listParkedResidentsWithWakeMail as Ar,setFrozen as Ae}from"../core/canvas/index.js";import{createApiServer as Nr,closeServer as Ne}from"./api/server.js";import{Router as Mr}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Fr}from"./api/document-secret.js";import{createAppListener as Br}from"./api/app-listener.js";import{registerMachineEnvironment as Hr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as jr}from"../core/secrets/blaxel-register.js";import{markCloudRole as zr,resolvePerson as Ur,retireLocalPerson as qr,setPersonId as Wr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as Jr}from"../core/permissions/boot.js";import{startRunNotices as Kr}from"./run-notices.js";import{startGrantEffects as Vr}from"./reconcilers/grant-effects.js";import{syncPackages as Yr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Qr}from"../core/model-auth/activations.js";import{createGrantSync as Xr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Zr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as et}from"./cron/run-socket.js";import{hasSyncedGrants as rt}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as tt}from"./human/sweep.js";import{resetHandedOffDeliveries as nt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as ot}from"../core/canvas/daemon-actions.js";import{sweepReviews as it}from"./review/sweep.js";import{pidfilePath as pe}from"./pidfile.js";import{rendererWarning as at}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as st}from"./supervise-cadence.js";import{createResumeDetector as ct}from"./resume-detector.js";import{setFatalFaultAnnouncer as lt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as dt}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as mt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as pt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as yt,migrateLegacyExecutionIdentities as St}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as Pt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as It}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as xt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Dt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Ct}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Lt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as $t}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as At,subscribeImageBuilt as Nt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Mt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Oe,capturePidCommand as Gt,captureTeardownSnapshot as Fe,isPidAlive as Ot,isAnyPidAlive as Be,killProcessTreePids as He}from"../core/canvas/pid.js";import{bindFleet as Ft,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Bt,clearDaemonControl as Ht}from"./control.js";import{execDaemon as jt,spawnDaemon as zt}from"./manage.js";import{reconcileAndMigrateBoot as Ut}from"../core/canvas/boot.js";import{resolveInstallId as qt}from"../core/canvas/install-id.js";import{setInstallId as Wt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Jt,daemonOwnershipApplies as Kt,daemonOwnershipClaimed as Vt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Yt,closeAllDbs as ue,openDb as Ue,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Xt,ensurePostgresHealthy as Zt,stopPostgres as en,withPostgresStartLock as rn}from"./postgres/index.js";import{brokerSignalBus as N}from"./broker-signals/bus.js";import{brokerSignalStreams as tn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as nn}from"./api/handlers/broker-ops.js";import{reconcilePackages as on}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as an}from"../core/scoped-state/migrate-app-installs.js";import{publish as sn,readBuiltinSnapshot as cn}from"../core/graph/package-publish.js";import{startRepoSync as ln}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as dn,reapStaleSpares as mn}from"../core/runtime/warm-pool.js";import{DaemonFleet as pn}from"./fleet.js";import{copyNodeFilesToRows as fn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as un}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as hn}from"../core/events/source.js";import{activateCanvasImport as wn,MigrationBlockedError as vn,runForcedCanvasImport as gn}from"../migrations/activation.js";import{adoptInstallPerson as yn,convertLegacyScopedStore as Sn,personStoresCopied as _n}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as bn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as kn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as We}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Je}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as we}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as ta}from"../core/runtime/broker-ownership.js";function ve(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ve,"brokerCommandEpoch");const Rn=5e3,Ke=150;async function Pn(e){const c=Oe();if(c===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=kr(),d=[];for(const[r,l]of c.processes){const S=l.command;if(l.zombie||!S.includes("broker-cli.js")||!we(S,f)||ve(S)===e)continue;const P=S.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||d.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of d){const l=Gt(r.pid);if(l===null||!l.includes("broker-cli.js")||!we(l,f)||ve(l)===e||l.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const S=Fe(r.pid,null);if(!S.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:S})}}const h=Date.now()+Rn;for(;Date.now()<h&&i.some(r=>Be(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,Ke));let g=0;for(const r of i){const l=r.snap.tree.length>0?r.snap.tree:[r.pid];Be(l)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):He(l,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,Ke));const m=Oe();if(m===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[r,l]of m.processes){const S=l.command;l.zombie||!S.includes("broker-cli.js")||we(S,f)&&ve(S)!==e&&u.push(r)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:d.length,sigtermed:v,sigkilled:g}})}s(Pn,"reapPriorEpochBrokers");const En=5e3;async function In(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Lr(i))?.status;(h==="active"||h==="idle")&&await Ae(i,new Date().toISOString())}const f=c.map(([,i])=>({pid:i.pid,snap:Fe(i.pid,null),exited:i.handle.exited}));for(const i of f)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const d=new Promise(i=>{setTimeout(i,En).unref()});await Promise.allSettled(f.map(i=>Promise.race([i.exited.then(()=>{}),d])));const v=[];for(const i of f)Ot(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):He(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await vt(i,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:v.length}})}s(In,"teardownFleet");function Ve(){Ee(vr(pe()),{recursive:!0}),ur(pe(),String(process.pid),"utf8")}s(Ve,"writePidfile");function Ye(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ye,"isMissingPathError");function Qe(e){const c=pe();let f;try{f=hr(c,"utf8")}catch(d){if(Ye(d))return;throw d}if(f.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(d){if(Ye(d))return;throw d}}s(Qe,"removeOwnedPidfileMirror");const xn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new dt;lt(e=>X.handleFatalFault(e,!1));const Dn=new mt,Xe=new pt,Tn=new ft,Cn=new ut,Ln=new ht,$n=new wt,An=new bt,Nn=new kt,Mn=new Rt,Gn=new Pt,On=new It,Fn=new xt,Bn=new Dt,Hn=new Tt,jn=new Ct,zn=new Lt,Un=new $t,qn=new At;async function Wn(e=Date.now(),c=xn){const f=je(),d=await X.runFleetPreamble(f);let v,i,h;try{i=await fe();const m=(await $e()).filter(r=>!i.has(r.node_id));v=m.filter(r=>r.status==="active"||r.status==="idle"),h=m.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const u=new Set(h.map(r=>r.node_id));h.push(...(await Ar()).filter(r=>!u.has(r.node_id)&&!i.has(r.node_id)))}catch(m){p({level:"error",event:"canvas.node_list.failed",error:m});return}await X.run(e,{rows:v,fleet:f,lifecycle:c,held:i}),await Dn.run(e,{rows:v,held:i});const g=await Xe.run(e,{rows:[...v,...h],fleet:f});await Tn.run(e,i),await Un.run(e,i),await qn.run(e,{lifecycle:c}),await Cn.run(e,{lifecycle:c,held:i}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c,fleet:f,held:i}),Mn.run(e,{lifecycle:c}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),await br(),zn.run(e,{fleet:f,lifecycle:c}),await jn.run(e,{rows:v}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:d,frozen:g})}s(Wn,"superviseTick");async function Jn(e,c=Date.now()){if((await fe()).has(e))return;const f=await yt(e);if(f===null||!gt(f))return;const d=await $r(e);d===null||d.kind==="human"||await Xe.runNode(c,d,je())}s(Jn,"exitedNodePass");function j(e){return e===void 0||e==="reconcile"}s(j,"roleRunsLanes");function M(e){return e===void 0||e==="api"}s(M,"roleServesRequests");const Kn=66e4;function Vn(e){const c=new Mr().registerAll(Gr(()=>null).filter(r=>r.pattern==="/healthz")),f=s((r,l)=>{const S=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&S==="/healthz"){c.handle(r,l,null,{class:"person"});return}l.writeHead(404,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),d=Ce();R(d)&&Ie(d);const v=Q(f),i=new Promise((r,l)=>{v.once("error",l),v.listen(d,()=>{v.off("error",l),xe(d,384),r()})});let h,g=null;const m=e.tcp??De()??me("user").api.tcp;if(m!==void 0&&m!==""){const r=/^(.*):(\d+)$/.exec(m.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${m}`);const l=Q(f);l.on("error",S=>p({event:"api.server.failed",level:"error",error:S})),l.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=l}let u=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!u){u=!0,await Promise.all([Ne(v,new Set,r.graceMs),h===void 0?Promise.resolve():Ne(h,new Set,r.graceMs)]);try{R(d)&&Ie(d)}catch{}}}}}s(Vn,"createProbeServer");const Yn="daemon is draining for shutdown and admits no new work";async function Qn(e){Ee(Le(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Le(),493);const c=Ce();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Q((m,u)=>{if(m.method==="GET"&&m.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((m,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),m()})});let d;const v=e.tcp??De();if(v){const m=/^(.*):(\d+)$/.exec(v);if(!m||Number(m[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const u=Q(f.listeners("request")[0]);await new Promise((r,l)=>{u.once("error",l),u.listen(Number(m[2]),m[1],()=>{u.off("error",l),r()})}),d=u}Ve();let i;const h=s(()=>(i??=(async()=>{f.closeAllConnections(),d?.closeAllConnections(),await Promise.all([f,d].filter(m=>m!==void 0).map(m=>new Promise((u,r)=>m.close(l=>l?r(l):u())))),Qe(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),m=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(m)}
|
|
2
|
+
`),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}s(Qn,"serveLayoutRefusal");async function Xn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Dr())return Qn(e);xr();const c=s(n=>{process.stderr.write(`[crtrd] ${n}
|
|
3
|
+
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,d=Kt(e.role);nn(j(e.role));const v=s(async()=>d?await Jt(Te(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Te(16).toString("hex")}},"claimOwnership"),{database:i,ownership:h}=f?{database:{url:await Yt()},ownership:await v()}:await rn(async()=>({database:await Xt({log:c,startLockHeld:!0}),ownership:await v()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
|
|
4
4
|
`);else{const n=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(w=>w!==void 0),a=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
|
|
5
|
-
`),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const g=h.claim;let
|
|
6
|
-
`);for(const t of await
|
|
7
|
-
`);await
|
|
8
|
-
`)}else{const t=await
|
|
5
|
+
`),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const g=h.claim;let m=null,u=null,r=null,l=null,S,P="";try{d&&await Pn(g.token);for(const t of Cr())process.stderr.write(`[crtrd] ${t}
|
|
6
|
+
`);for(const t of await Tr())process.stderr.write(`[crtrd] ${t}
|
|
7
|
+
`);await Ue(),await Qt(i.url,c);const n=e.role===void 0&&!await _n();let a=null;n&&(Sn({kind:"user",root:Je()}),a=bn(Je())),e.role===void 0&&kn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await N.listen(i.url);const w=s(t=>{We(t).catch(o=>p({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(S=await N.subscribe(t=>{qe().includes(t)&&w(t)},{kinds:["settings"],onListenStart:s(()=>{for(const t of qe())w(t)},"onListenStart")}),e.role!==void 0&&zr(),e.role!==void 0){let t;try{t=cn()}catch(b){p({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await he(async b=>(await Me(b),t===void 0?void 0:await sn(b,t,"release")));l=await he(async b=>await an(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
|
|
8
|
+
`)}else{const t=await he(async o=>(await Me(o),await on(o)));for(const o of t.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
|
|
9
9
|
`);for(const o of t.invalid)process.stderr.write(`[crtrd] package file is not a document: ${o.path}: ${o.error}
|
|
10
10
|
`);for(const o of t.quarantined)process.stderr.write(`[crtrd] plugin "${o.name}" has a damaged ${o.file} (${o.reason}); ${o.movedTo!==void 0?`moved to ${o.movedTo}`:"left in place and skipped"}
|
|
11
11
|
`);for(const o of t.kinds.refused)process.stderr.write(`[crtrd] plugin "${o.plugin}" kind ${o.kind} not registered: ${o.message}
|
|
12
12
|
`);for(const o of t.kinds.invalid)process.stderr.write(`[crtrd] plugin "${o.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${o.error}
|
|
13
|
-
`)}if(P=await
|
|
14
|
-
`)}}catch(n){await
|
|
13
|
+
`)}if(P=await qt(),Wt(P),e.role===void 0&&(m=await Ur(),m!==null)){if(Wr(m.id),await yn(m.id),process.platform==="darwin"){const{readConfig:t,updateConfig:o}=await import("../core/config.js");if(t("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",Pe=>{Pe.paths??={},Pe.paths.user_files??=b()})}}u=await qr(),u.joinedFrom!==null&&await We(u.person),await dr(),r=await Jr()}if(process.platform==="linux"&&R(D)&&(Ir(),await A({operation:"users.sync",users:await Rr()})),d){await _t(g.token);const t=await fn();Object.values(t).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(t)}
|
|
14
|
+
`)}}catch(n){await N.close();try{if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}await ue()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}let T=!0,Z,z=Promise.resolve(),ee=!1,U,re,te,ne,C;const q=new Set;let oe=!1,ge=!1,E,L,ie,W=!1,J,G,O,F,B,ae,se,ce,le;const Ze=ct();let I,y={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",er=null;function rr(){return y.phase==="ready"?null:{phase:y.phase,message:y.message,blockerPaths:y.blockerPaths}}s(rr,"startupBlock");function k(n){q.add(n),n.finally(()=>{q.delete(n)}).catch(()=>{})}s(k,"registerDetached");const ye={acceptsDetachedWork:s(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await ln(ye,Ue);async function tr(){try{T=!1,tn.close(),re?.(),re=void 0,te?.(),S?.(),te=void 0,ne?.(),ne=void 0,ce?.(),ce=void 0,await N.close(),U!==void 0&&(clearInterval(U),U=void 0),O!==void 0&&(clearInterval(O),O=void 0),F!==void 0&&(clearInterval(F),F=void 0),le?.(),le=void 0;let n;do n=z,await n;while(n!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(d&&await In(C),await C.exitsSettled(),C.dispose()),ie!==void 0&&await ie.close(),L!==void 0&&!W&&(W=!0,await L.close()),ae?.(),ae=void 0,se?.(),se=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if(G!==void 0){const a=G;G=void 0,await a.close()}if(J!==void 0){const a=J;J=void 0,await a.close()}if(oe||(Qe(process.pid),oe=!0),oe&&!ge){if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}ge=!0,await ue()}}finally{Ht(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(tr,"cleanupAttempt");const K=1e3;let Se=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return Se?{graceMs:K}:(Se=!0,_.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{or()},K),{graceMs:K})}s(nr,"requestHandover");async function or(){try{await x()}catch(n){const a=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
15
15
|
${a}
|
|
16
|
-
`),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await
|
|
17
|
-
`),process.exit(1)}process.exit(0)}s(
|
|
16
|
+
`),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await jt();const n=await zt({waitForJoinLock:!0});_.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
|
|
17
|
+
`),process.exit(1)}process.exit(0)}s(or,"performHandover");function x(){if(E!==void 0)return E;const n=tr();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function ir(){y={phase:"initializing",message:Yn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:Kn}))}s(ir,"drainApi");async function _e(n){try{n==="SIGTERM"&&e.role==="api"&&await ir(),await x(),await en({claimed:s(async()=>{try{return d&&await Vt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
|
|
18
18
|
${w}
|
|
19
|
-
`),process.exit(1)}}s(
|
|
19
|
+
`),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){x().catch(()=>{})}s(Re,"onExit");async function V(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(V,"enqueue");async function Y(){!T||ee||(Ze.check()&&I&&(p({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),ee=!0,await V(async()=>{if(ee=!1,!!T)try{f||await Zt({log:c}),await Wn(Date.now(),ye)}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(Y,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(y.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(y.phase!=="prepared"&&y.phase!=="recovering")throw{status:409,code:"not_prepared",message:y.message};const n=y.phase==="prepared";try{return await de(),y={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await gn({dryRun:n.dryRun});if(n.dryRun||a.pending||y.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return y={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await de(),y={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(sr,"repairMigrations");async function cr(){Z=e.intervalMs??st;const n=g.token;C=new pn({epoch:n,enqueue:V}),Ft(C),y={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Z}})});const a=P;_.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Hr(a);if(_.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=at()}catch{return}t!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&jr(),!j(e.role)){y={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await it(),await tt(),await nt(Date.now()),await ot(Date.now())}),e.role===void 0&&await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ut(St);t.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await fe();for(const o of await $e())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Ae(o.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Mt();for(const t of un){const o=await t.apply();o.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(et()),I){const t=s(()=>{k(I().catch(()=>{})),k(pr().then(o=>B?.observe(o)).then(()=>{},o=>{p({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Zr().then(({completion:o})=>o).catch(o=>{p({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),O=setInterval(t,Ge*1e3),O.unref(),le=mr({joined:!0,register:k})}await V(async()=>{await mn(),await dn()}),U=setInterval(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},Z),re=await Nt(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))}),te=await N.subscribe(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),ne=await N.subscribe(t=>{V(()=>_.fresh(()=>Jn(t)))},{kinds:["execution_exit"]}),await Y(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>p({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>p({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(cr,"completeStartup");function de(){return er??=cr().catch(n=>{throw y={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(de,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),hn(),m!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:m.id,source:m.source}}),l!==null&&!l.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...r}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),M(e.role)?J=await Sr():_r(yr());const n=g.token;Bt({epoch:n,requestHandover:nr,registerDetached:k,startupBlock:rr,admitStartup:ar,repairMigrations:sr}),Ve(),L=M(e.role)?Nr({tcp:e.tcp}):Vn(e),await L.ready;const a=gr()??me("user").document_port;if(M(e.role)){const t=Or(a,Fr());try{await t.ready,ie=t}catch(o){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=me("user").runtime;if(w?.issuer&&(I=Xr(w.issuer,k),w.unsandboxed===!0&&(B=fr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Yr().catch(o=>{p({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),F=setInterval(t,Ge*1e3),F.unref()}if(M(e.role)&&(ae=await Kr()),j(e.role)&&(se=Qr()),ce=await Vr({serves:M(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),M(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(G=await Br(w,async()=>await rt(w.issuer.replace(/\/$/,"")),I),await G.ready),e.role===void 0)try{await wn()}catch(t){if($=null,t instanceof vn)return y={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(Er(),await Pr("app:terminal"));try{e.prepare?y={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await de(),y={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Xn,"runDaemon");var Zi=Xn;export{Kn as API_DRAIN_GRACE_MS,ta as brokerCommandDeclaresCanvasHome,ve as brokerCommandEpoch,Zi as default,Jn as exitedNodePass,j as roleRunsLanes,M as roleServesRequests,Xn as runDaemon,Wn as superviseTick,In as teardownFleet};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _=Object.defineProperty;var c=(
|
|
1
|
+
var _=Object.defineProperty;var c=(r,n)=>_(r,"name",{value:n,configurable:!0});import{chmodSync as M,existsSync as S,mkdirSync as h,unlinkSync as g,writeFileSync as I,rmSync as v}from"node:fs";import{createServer as k}from"node:http";import{dirname as E}from"node:path";import{apiSocketPath as T}from"../core/canvas/paths.js";import{bindDaemonEventSource as R}from"../core/events/source.js";import{emitEvent as l}from"../core/events/emit.js";import{createMachineExecutor as x,stopAllBrokers as P}from"../core/runtime/runner/machine/executor.js";import{machineWorktreeHandlers as C}from"../core/worktree-machine.js";import{readPersonCredential as F}from"../core/directory/person-credential.js";import{socketDir as G}from"../core/layout.js";import{isDaemonRunning as b,pidfilePath as u,readPidfile as N}from"./pidfile.js";import{cancelMachineCron as D,runMachineCron as O,stopOrphanedMachineCrons as U}from"./cron/machine-exec.js";import{startMachineLink as Y}from"./machine-link/client.js";import{deleteMoveRecord as w,readMachineConfig as A,readMachineCredential as y,readMoveRecord as H,writeMoveRecord as z}from"./machine-link/config.js";import{notifyMoveFinished as j}from"./machine-link/move-notify.js";function B(r,n){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:r,signed_in:n,startup_phase:r?"ready":"recovering"}}c(B,"machineHealth");async function de(){const r=A();if(r===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const n=F()!==void 0;if(n&&y(),b())throw new Error("a crtrd is already running for this home");R(),n||(await P(),await U(),l({level:"info",event:"daemon.machine.signed_out",fields:{environment:r.environmentId}})),h(G(),{recursive:!0,mode:493});const s=T();S(s)&&g(s);let e;const o=k((a,d)=>{const p=(a.method??"GET")==="GET"&&(a.url??"/").split("?")[0]==="/healthz";d.writeHead(p?200:404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify(p?B(e?.connected()===!0,n):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((a,d)=>{o.once("error",d),o.listen(s,()=>{o.off("error",d),M(s,384),a()})}),h(E(u()),{recursive:!0}),I(u(),String(process.pid),"utf8");let i;await W(r.runId,n,()=>i!==void 0);const t=x({apiUrl:r.apiUrl,environmentId:r.environmentId,onExit:c(a=>e?.reportExit(a),"onExit")});e=n?Y({apiUrl:r.apiUrl,environmentId:r.environmentId,credential:y,handlers:{start:t.start,wake:t.wake,stop:t.stop,status:t.status,"status.all":t["status.all"],delete:t.delete,viewer:t.viewer,"cron.run":O,"cron.cancel":D,...C}}):void 0,l({level:"info",event:"daemon.machine.started",fields:{environment:r.environmentId}});const f=c(()=>i??=(async()=>{e?.stop(),await new Promise(a=>{o.close(()=>a()),o.closeAllConnections()}),N()===process.pid&&(v(s,{force:!0}),v(u(),{force:!0})),process.off("SIGINT",m),process.off("SIGTERM",m)})(),"teardown"),m=c(()=>{f().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",m),process.on("SIGTERM",m),f}c(de,"runMachineDaemon");const J=5e3,L=3e5;async function W(r,n,s){let e;try{e=H()}catch(i){l({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(e===void 0||e.state==="running"||e.runId!==r)return;if(e.notified||e.notify===null){w();return}if(e.state==="committed"&&(e={...e,state:"activated"},z(e)),!n)return;const o=e;(async()=>{let i=J;for(;;){try{await j(o),w();return}catch(t){l({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:o.notify??"",error:t.message}})}if(await new Promise(t=>{setTimeout(t,i).unref()}),s())return;i=Math.min(i*2,L)}})()}c(W,"settleFinishedMove");export{B as machineHealth,de as runMachineDaemon};
|
|
@@ -28,6 +28,15 @@ export interface MachineLinkOptions {
|
|
|
28
28
|
export interface MachineLink {
|
|
29
29
|
stop(): void;
|
|
30
30
|
connected(): boolean;
|
|
31
|
+
/** Tell the control plane a broker exited. Sent now when the link is open, else when it next opens: the cloud's timed status check
|
|
32
|
+
* also finds the exit, so a report lost with this process costs only the delay. */
|
|
33
|
+
reportExit(exit: BrokerExit): void;
|
|
34
|
+
}
|
|
35
|
+
export interface BrokerExit {
|
|
36
|
+
execution: string;
|
|
37
|
+
node: string;
|
|
38
|
+
code: number | null;
|
|
39
|
+
signal: string | null;
|
|
31
40
|
}
|
|
32
41
|
export interface ViewSink {
|
|
33
42
|
readonly bufferedAmount: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var B=Object.defineProperty;var o=(t,l)=>B(t,"name",{value:l,configurable:!0});import{WebSocket as v}from"ws";import{emitEvent as x}from"../../core/events/emit.js";import{connectViewSocket as W}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as K,LINK_MAX_PAYLOAD_BYTES as P,parseFrame as U}from"./frames.js";const R=1e3,F=6e4,Y=64*1024,X=4*1024*1024,D=1024*1024,J=8*1024*1024,$=75e3;function q(t){const l=[];let c=0;const f=new Set,y=o(()=>{for(;l.length>0&&t.open()&&t.bufferedAmount<Y;){const i=l.shift();c-=i.length,t.send(i,y)}if(c<D&&f.size>0){for(const i of f)i.resume();f.clear()}},"pump");return{push(i,a){t.open()&&(l.push(i),c+=i.length,a!==void 0&&c>X&&(a.pause(),f.add(a)),y())},forget(i){f.delete(i)}}}o(q,"createViewQueue");function z(t,l){const c=new URL(`/v1/machines/${encodeURIComponent(l)}/link`,t);return c.protocol=c.protocol==="https:"?"wss:":c.protocol==="http:"?"ws:":c.protocol,c.toString()}o(z,"linkUrl");function ee(t){const l=t.backoffMinMs??R,c=t.backoffMaxMs??F,f=t.openView??W,y=t.silenceMs??$;let i=!1,a,h=l,g;const b=200,p=[],A=o(()=>{const d=a;for(;p.length>0&&d?.readyState===v.OPEN;)d.send(JSON.stringify({type:"exit",...p.shift()}))},"flushExits"),O=o((d,r)=>{x({level:"error",event:d,fields:{environment:t.environmentId},error:r})},"fault");let S;const M=o(()=>{if(i)return;if(S!==void 0){if(t.credential()===S){g=setTimeout(M,h),h=Math.min(h*2,c);return}S=void 0}const d=t.credential(),r=new v(z(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${d}`},maxPayload:P});a=r;const u=new Map,m=new Map,k=o(e=>{r.readyState===v.OPEN&&r.send(JSON.stringify(e))},"send"),I=q({get bufferedAmount(){return r.bufferedAmount},open:o(()=>r.readyState===v.OPEN,"open"),send:o((e,n)=>r.send(e,n),"send")}),_=o((e,n)=>I.push(JSON.stringify(e),n),"sendView"),L=o(async e=>{const n=t.handlers[e.op];if(n===void 0){k({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const s=new AbortController,E=o(()=>s.abort(new Error("the machine link closed")),"onClose");r.once("close",E);try{k({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,s.signal)??null})}catch(T){k({type:"result",call_id:e.call_id,ok:!1,error:T instanceof Error?T.message:String(T)})}finally{r.off("close",E)}},"runCall"),C=o(e=>{const n=f(e.node);u.set(e.channel,n),n.once("connect",()=>_({type:"view.ready",channel:e.channel})),n.on("data",s=>_({type:"view.data",channel:e.channel,bytes:s.toString("base64")},n)),n.once("error",s=>{I.forget(n),u.delete(e.channel)&&_({type:"view.close",channel:e.channel,error:s.message})}),n.once("close",()=>{I.forget(n),u.delete(e.channel)&&_({type:"view.close",channel:e.channel})})},"openChannel"),V=o((e,n)=>{const s=u.get(e);if(s===void 0||s.write(n))return;const E=(m.get(e)??0)+n.length;if(E>J){u.delete(e),m.delete(e),s.destroy(),_({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}m.has(e)||s.once("drain",()=>m.delete(e)),m.set(e,E)},"writeToChannel");let w;const N=o(()=>{w!==void 0&&clearTimeout(w),w=setTimeout(()=>{x({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),r.terminate()},y)},"heard");r.on("open",()=>{h=l,N(),A()}),r.on("ping",N),r.on("message",e=>{N();const n=U(e);if(n!==null)try{switch(n.type){case"call":L(n);return;case"view.open":C(n);return;case"view.data":V(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const s=u.get(n.channel);u.delete(n.channel),s?.destroy();return}default:return}}catch(s){O("daemon.machine_link.frame_failed",s)}}),r.on("error",e=>O("daemon.machine_link.client_error",e)),r.on("close",e=>{w!==void 0&&clearTimeout(w);for(const n of u.values())n.destroy();u.clear(),a===r&&(a=void 0),!i&&(e===K&&(x({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),S=d),g=setTimeout(M,h),h=Math.min(h*2,c))})},"connect");return M(),{stop(){i=!0,g!==void 0&&clearTimeout(g),a?.close()},connected:o(()=>a?.readyState===v.OPEN,"connected"),reportExit(d){p.push(d),p.length>b&&p.shift(),A()}}}o(ee,"startMachineLink");export{F as LINK_BACKOFF_MAX_MS,R as LINK_BACKOFF_MIN_MS,$ as LINK_SILENCE_MS,J as VIEW_WRITE_LIMIT_BYTES,q as createViewQueue,z as linkUrl,ee as startMachineLink};
|
|
@@ -19,6 +19,14 @@ export type MachineFrame =
|
|
|
19
19
|
ok: false;
|
|
20
20
|
error: string;
|
|
21
21
|
}
|
|
22
|
+
/** Mac → holder: a broker this machine spawned exited (the cloud's `Fleet.onChildExit`). */
|
|
23
|
+
| {
|
|
24
|
+
type: 'exit';
|
|
25
|
+
execution: string;
|
|
26
|
+
node: string;
|
|
27
|
+
code: number | null;
|
|
28
|
+
signal: string | null;
|
|
29
|
+
}
|
|
22
30
|
/** holder → Mac: open a viewer channel to `node`'s view.sock. */
|
|
23
31
|
| {
|
|
24
32
|
type: 'view.open';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var o=Object.defineProperty;var l=(
|
|
1
|
+
var o=Object.defineProperty;var l=(n,t)=>o(n,"name",{value:t,configurable:!0});const f=33554432,i=4001,p=4003,s=l(n=>n===null||typeof n=="number","nullableNumber");function y(n){const t=Array.isArray(n)?Buffer.concat(n):Buffer.isBuffer(n)?n:Buffer.from(new Uint8Array(n));try{const e=JSON.parse(t.toString("utf8"));if(typeof e!="object"||e===null)return null;const r=l((...u)=>u.every(c=>typeof e[c]=="string"),"strings");switch(e.type){case"call":return r("call_id","op")?e:null;case"result":return r("call_id")&&(e.ok===!0||e.ok===!1&&r("error"))?e:null;case"exit":return r("execution","node")&&s(e.code)&&(e.signal===null||typeof e.signal=="string")?e:null;case"view.open":return r("channel","node")?e:null;case"view.ready":case"view.close":return r("channel")?e:null;case"view.data":return r("channel","bytes")?e:null;default:return null}}catch{return null}}l(y,"parseFrame");export{p as CLOSE_REVOKED,i as CLOSE_SUPERSEDED,f as LINK_MAX_PAYLOAD_BYTES,y as parseFrame};
|
|
@@ -46,6 +46,17 @@ export declare class HeldLink extends EventEmitter {
|
|
|
46
46
|
private onMessage;
|
|
47
47
|
private teardown;
|
|
48
48
|
}
|
|
49
|
+
/** A broker exit the Mac reported: what `Fleet.onChildExit` does for a local child. Only a live machine execution of this node whose profile
|
|
50
|
+
* runs in this link's environment is ended, so a machine cannot end another machine's executions. The lane processes hear
|
|
51
|
+
* `execution_exit:<node>` and run the node-lifecycle pass for that node at once. The execution of a node held by an import is left to the
|
|
52
|
+
* import, and a broker exiting because a stop was requested on it (the stopper decides the row's next state, or the next tick does)
|
|
53
|
+
* ends its execution without a signal. */
|
|
54
|
+
export declare function recordMachineBrokerExit(environmentId: string, exit: {
|
|
55
|
+
execution: string;
|
|
56
|
+
node: string;
|
|
57
|
+
code: number | null;
|
|
58
|
+
signal: string | null;
|
|
59
|
+
}): Promise<boolean>;
|
|
49
60
|
/** A viewer channel to one node's view.sock on the Mac, as the relay's broker-side link. */
|
|
50
61
|
export declare class MachineViewLink extends EventEmitter implements BrokerViewLink {
|
|
51
62
|
private readonly link;
|