@north-light/cli 0.3.729 → 0.3.730

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as P}from"./pid.js";import{existsSync as U,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&U(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!P(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function T(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(T,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",L="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await T(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(L,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===L}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await T(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,T as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
1
+ var D=Object.defineProperty;var a=(e,t)=>D(e,"name",{value:t,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as U}from"./pid.js";import{existsSync as P,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i),await n.prepare("UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL").run(e);const p=g(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&P(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!U(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function L(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(L,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",T="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await L(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===T}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await L(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,L as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
@@ -0,0 +1,3 @@
1
+ -- 033-node-sandbox-deleted.sql — when the retention pass deleted a finished node's Blaxel sandbox while keeping its rows, so the pass
2
+ -- does not delete it again every sweep. A new execution clears it. Added column only.
3
+ ALTER TABLE nodes ADD COLUMN IF NOT EXISTS sandbox_deleted_at text;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 32;
4
+ export declare const CANVAS_SCHEMA_VERSION = 33;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=32;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=33;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1,8 +1,19 @@
1
+ /** A launch that has not reached `running` in this long never will: its row no longer keeps the node's sandbox. */
2
+ export declare const STALE_LAUNCH_MS: number;
1
3
  /** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
2
4
  * those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
3
5
  export declare function deleteNodeSandboxes(nodeIds: readonly string[]): Promise<string[]>;
4
6
  /** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
5
- * (its fires run there). Called after each of those ends; a failure is left to the sandbox's idle expiry. A parked node is not ended:
6
- * wake mail reopens it in the same sandbox. The check and the DELETE run holding the node row's lock, which `beginExecution` also
7
- * takes, so no new execution can start in the sandbox between them. */
7
+ * (its fires run there). Called after each of those ends; a failure is left to the retention pass. A parked node is not ended:
8
+ * wake mail reopens it in the same sandbox. A launch stuck in `launching` past {@link STALE_LAUNCH_MS} does not hold the sandbox.
9
+ * The check and the DELETE run holding the node row's lock, which `beginExecution` also takes, so no new execution can start in
10
+ * the sandbox between them. */
8
11
  export declare function deleteSandboxOfEndedNode(nodeId: string): void;
12
+ /** Delete the sandbox of every finished, canceled, dead or parked node quiet for `quietMs`, keeping its rows; app runs included.
13
+ * `quiet` decides the activity test ({@link lastActivityMs} reads disk too); `held` excludes nodes retention must not touch.
14
+ * Each node is marked `sandbox_deleted_at` so later passes skip it until a new execution clears the mark. Returns the deleted count. */
15
+ export declare function deleteQuietNodeSandboxes(opts: {
16
+ quiet: (nodeId: string) => Promise<boolean>;
17
+ held: (nodeId: string) => Promise<boolean>;
18
+ now?: number;
19
+ }): Promise<number>;
@@ -1,6 +1,14 @@
1
- var c=Object.defineProperty;var o=(e,n)=>c(e,"name",{value:n,configurable:!0});import{afterCommit as E,openDb as l,withCanvasWrite as s}from"../../canvas/db.js";import{emitEvent as i}from"../../events/emit.js";async function S(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),a=await(await l()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${n})`).all(...e),d=[];for(const{node_id:t}of a)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(t)}catch(r){d.push(t),i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:t,error:r})}return d}o(S,"deleteNodeSandboxes");function _(e){E(()=>{s(async n=>{await n.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
1
+ var u=Object.defineProperty;var o=(e,n)=>u(e,"name",{value:n,configurable:!0});import{afterCommit as S,openDb as l,withCanvasWrite as s}from"../../canvas/db.js";import{emitEvent as i}from"../../events/emit.js";const N=60*6e4,c=`EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id
2
+ AND (x.state = 'running' OR (x.state = 'launching' AND x.started_at > ?)))`;function _(e=Date.now()){return new Date(e-N).toISOString()}o(_,"staleLaunchCutoff");async function O(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),d=await(await l()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${n})`).all(...e),a=[];for(const{node_id:t}of d)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(t)}catch(r){a.push(t),i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:t,error:r})}return a}o(O,"deleteNodeSandboxes");function f(e){S(()=>{s(async n=>{await n.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
2
3
  AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
3
4
  AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
4
- AND NOT EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited')
5
+ AND NOT ${c}
5
6
  AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
6
- FOR UPDATE OF n`).get(e)!==void 0&&await(await import("./index.js")).runnerForExecution("blaxel").delete(e)}).catch(n=>{i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:e,error:n})})})}o(_,"deleteSandboxOfEndedNode");export{S as deleteNodeSandboxes,_ as deleteSandboxOfEndedNode};
7
+ FOR UPDATE OF n`).get(e,_())!==void 0&&(await(await import("./index.js")).runnerForExecution("blaxel").delete(e),await n.prepare("UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?").run(new Date().toISOString(),e))}).catch(n=>{i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:e,error:n})})})}o(f,"deleteSandboxOfEndedNode");async function w(e){const n=_(e.now),d=await(await l()).prepare(`SELECT n.node_id FROM nodes n WHERE n.status IN ('done', 'canceled', 'dead')
8
+ AND n.sandbox_deleted_at IS NULL
9
+ AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
10
+ AND NOT ${c}
11
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)`).all(n);let a=0;for(const{node_id:t}of d)if(!(!await e.quiet(t)||await e.held(t)))try{await s(async E=>await E.prepare(`SELECT 1 AS ok FROM nodes n WHERE n.node_id = ? AND n.status IN ('done', 'canceled', 'dead')
12
+ AND n.sandbox_deleted_at IS NULL AND NOT ${c}
13
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
14
+ FOR UPDATE OF n`).get(t,n)===void 0?!1:(await(await import("./index.js")).runnerForExecution("blaxel").delete(t),await E.prepare("UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?").run(new Date().toISOString(),t),!0))&&a++}catch(r){i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:t,error:r})}return a}o(w,"deleteQuietNodeSandboxes");export{N as STALE_LAUNCH_MS,O as deleteNodeSandboxes,w as deleteQuietNodeSandboxes,f as deleteSandboxOfEndedNode};
@@ -1 +1 @@
1
- var S=Object.defineProperty;var f=(_,e)=>S(_,"name",{value:e,configurable:!0});import{rm as R}from"node:fs/promises";import{closeFocusRow as I,getFocusById as A,listFocuses as N,listNodes as T}from"../../core/canvas/index.js";import{pruneExpiredIdempotencyKeys as P}from"../../core/runs/operations.js";import{getNode as C,lastActivityMs as p,listTerminalPlacementResidue as D,pruneExpiredCreateRequests as F,pruneNodes as x}from"../../core/canvas/canvas.js";import{lastContextStripMs as M,stripContextDir as L}from"../../core/canvas/context-strip.js";import{isAppRun as W}from"../../core/canvas/app-run.js";import{isSafeNodeId as d}from"../../core/canvas/paths.js";import{emitEvent as a}from"../../core/events/emit.js";import{operationIdContext as s}from"../../core/events/operation-id.js";import{listLivePanesAsync as b,tearDownNode as G}from"../../core/runtime/placement.js";import{reapStaleSpares as V}from"../../core/runtime/warm-pool.js";import{GroveInstanceSweepReconciler as k}from"./grove-instance-sweep.js";import{ManagedWorktreeSweepReconciler as O}from"./managed-worktree-sweep.js";import{compactRunEvents as q}from"../../core/runs/events.js";import{archiveExpiredRunEvents as U}from"../../core/events/run-event-chunks.js";import{blobStore as H}from"../../core/blobs/index.js";import{runThrottledLane as c}from"./throttled-lane.js";import{openDb as w}from"../../core/canvas/db.js";import{touchMachineEnvironment as Y}from"../../core/environments.js";import{retentionHold as y}from"./live-obligation.js";import{pruneMemoryReads as z}from"../../core/canvas/memory-reads.js";import{existsSync as K}from"node:fs";import{launcherRequest as $}from"../../launcher/client.js";import{LAUNCHER_SOCKET as B}from"../../launcher/spec.js";import{cachePassDue as Q}from"../../launcher/limits/policy.js";const X=10*6e4,l=60*1e3,g=60*1e3,h=5*6e4,Z=2,j=1440*6e4,J=2e3,ee=6e4;class Te{static{f(this,"StorageMaintenanceReconciler")}focusGcInFlight=!1;lastCachePassAt=null;cachePassInFlight=!1;worktreeSweep=new O;groveInstanceSweep=new k;async run(e,r){await this.reapDeadResidue(e,r.held),this.scheduleFocusGc(r),await this.gcWarmPool(e),await this.touchEnvironment(e),await this.gcCreateRequests(e),await this.gcViewerAttachments(e);try{await c("run-event-maintenance","",e,J,ee,async t=>{await U(await H(),e);const n=await q(e,t.state===null?0:Number(t.state));await t.save(String(n.cursor))})}catch(t){console.warn(`run event maintenance failed: ${String(t)}`)}await c("memory-read-prune","",e,60*6e4,10*6e4,async()=>{try{await z(e)}catch(t){console.warn(`memory-read log prune failed: ${String(t)}`)}}),await c("storage-analyze","",e,1440*6e4,10*6e4,async()=>{await(await w()).exec("ANALYZE")}),await this.sweepRetention(e,r),this.scheduleCachePass(e,r),this.scheduleContextStrip(e,r),this.worktreeSweep.run(e,r),this.groveInstanceSweep.run(e,r)}scheduleCachePass(e,r){this.cachePassInFlight||!Q(this.lastCachePassAt,e)||process.platform!=="linux"||!K(B)||r.lifecycle.acceptsDetachedWork()&&(this.lastCachePassAt=e,this.cachePassInFlight=!0,r.lifecycle.registerDetached($({operation:"cache.purge"}).then(()=>{}).catch(t=>{s.fresh(()=>{a({level:"warn",event:"app.cache.pass_failed",error:t})})}).then(()=>{this.cachePassInFlight=!1})))}msSinceTerminalActivity(e,r){const t=p(e);return t===0?Number.POSITIVE_INFINITY:r-t}async sweepRetention(e,r){r.lifecycle.acceptsDetachedWork()&&await c("retention-sweep","",e,h,h,()=>s.fresh(async()=>{try{const t=await x({ttlDays:Z,held:await y(r.fleet),removeDirs:f(n=>{r.lifecycle.registerDetached(Promise.all(n.map(o=>R(o,{recursive:!0,force:!0}))).then(()=>{}).catch(o=>{s.fresh(()=>{a({level:"error",event:"canvas.retention.failed",error:o})})}))},"removeDirs")});t.pruned.length>0&&a({level:"info",event:"canvas.retention.pruned",outcome:"succeeded",fields:{pruned_count:t.pruned.length}})}catch(t){a({level:"error",event:"canvas.retention.failed",error:t})}}))}scheduleContextStrip(e,r){r.lifecycle.acceptsDetachedWork()&&r.lifecycle.registerDetached(c("context-strip","",e,h,10*6e4,()=>this.stripFinishedContexts(e,r)).then(()=>{},t=>{a({level:"error",event:"canvas.context_strip.failed",error:t})}))}async stripFinishedContexts(e,r){const t=await y(r.fleet),n=f(async i=>i!==null&&["done","canceled","dead"].includes(i.status)&&(i.pi_pid??null)===null&&(i.frozen_at??null)===null&&!W(i)&&p(i)<e-j&&!await t(i.node_id),"eligible");let o=0,m=0;try{for(const i of await T({status:["done","canceled","dead"]})){if(!d(i.node_id)||!await n(i))continue;const v=await M(i.node_id);if(v!==null&&v>=p(i)||!await n(await C(i.node_id)))continue;let u;try{u=await L(i.node_id)}catch(E){s.fresh(()=>{a({level:"warn",event:"canvas.context_strip.node_failed",error:E,fields:{node_id:i.node_id}})});continue}u.removed.length>0&&(o+=1,m+=u.bytes)}}catch(i){s.fresh(()=>{a({level:"error",event:"canvas.context_strip.failed",error:i})})}o>0&&s.fresh(()=>{a({level:"info",event:"canvas.context_strip.completed",outcome:"succeeded",fields:{node_count:o,bytes:m}})})}async reapDeadResidue(e,r){let t;try{t=await D()}catch(n){s.fresh(()=>{a({level:"error",event:"residue.reap_scan.failed",error:n})});return}for(const n of t)if(!r.has(n.node_id)){try{if(this.msSinceTerminalActivity(n,e)<X)continue}catch(o){s.fresh(()=>{a({level:"error",event:"residue.reap.failed",...d(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})});continue}await s.fresh(async()=>{try{a({level:"info",event:"residue.reaped",...d(n.node_id)?{node_id:n.node_id}:{},fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}}),await G(n.node_id)}catch(o){a({level:"error",event:"residue.reap.failed",...d(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})}})}}scheduleFocusGc(e){if(this.focusGcInFlight||!e.lifecycle.acceptsDetachedWork())return;this.focusGcInFlight=!0;const r=this.gcStaleFocuses().finally(()=>{this.focusGcInFlight=!1});e.lifecycle.registerDetached(r)}async gcStaleFocuses(){let e;try{e=await N()}catch(t){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:t})});return}if(e.length===0)return;let r;try{r=await b()}catch(t){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:t})});return}if(r!==null)for(const t of e){if(t.pane===null||r.has(t.pane))continue;if(!await s.fresh(async()=>{try{return(await A(t.focus_id))?.pane!==t.pane||(a({level:"info",event:"focus.gc.removed",...d(t.node_id)?{node_id:t.node_id}:{},fields:{focus_id:t.focus_id,focus_node_id:t.node_id,pane:t.pane}}),await I(t.focus_id)),!0}catch(o){return a({level:"error",event:"focus.gc.failed",error:o}),!1}}))return}}async gcCreateRequests(e){await c("create-request-gc","",e,g,g,()=>s.fresh(async()=>{const r=await F(e),t=await P(e);t>0&&a({level:"info",event:"canvas.idempotency_keys.reaped",outcome:"succeeded",fields:{reaped_count:t}}),r>0&&a({level:"info",event:"canvas.create_requests.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async gcViewerAttachments(e){await c("viewer-attachment-gc","",e,l,l,()=>s.fresh(async()=>{const r=Number((await(await w()).prepare("DELETE FROM viewer_attachments WHERE expires_at <= ?").run(new Date(e).toISOString())).changes);r>0&&a({level:"info",event:"viewer_attachments.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async touchEnvironment(e){await c("environment-touch","",e,l,l,()=>s.fresh(async()=>{try{await Y(new Date(e).toISOString())}catch(r){a({level:"warn",event:"environment.touch.failed",error:r})}}))}async gcWarmPool(e){await c("warm-pool-gc","",e,l,l,()=>s.fresh(async()=>{const r=await V();r.length>0&&a({level:"info",event:"warm_pool.spares_reaped",outcome:"succeeded",fields:{reaped_count:r.length}})}))}}export{j as CONTEXT_STRIP_GRACE_MS,X as DEAD_REAP_GRACE_MS,h as RETENTION_SWEEP_INTERVAL_MS,Z as RETENTION_TTL_DAYS,Te as StorageMaintenanceReconciler};
1
+ var I=Object.defineProperty;var p=(w,e)=>I(w,"name",{value:e,configurable:!0});import{rm as A}from"node:fs/promises";import{closeFocusRow as N,getFocusById as T,listFocuses as P,listNodes as C}from"../../core/canvas/index.js";import{pruneExpiredIdempotencyKeys as D}from"../../core/runs/operations.js";import{getNode as y,lastActivityMs as h,listTerminalPlacementResidue as x,pruneExpiredCreateRequests as F,pruneNodes as M}from"../../core/canvas/canvas.js";import{lastContextStripMs as b,stripContextDir as L}from"../../core/canvas/context-strip.js";import{isAppRun as W}from"../../core/canvas/app-run.js";import{isSafeNodeId as l}from"../../core/canvas/paths.js";import{emitEvent as a}from"../../core/events/emit.js";import{operationIdContext as s}from"../../core/events/operation-id.js";import{listLivePanesAsync as G,tearDownNode as V}from"../../core/runtime/placement.js";import{reapStaleSpares as k}from"../../core/runtime/warm-pool.js";import{GroveInstanceSweepReconciler as q}from"./grove-instance-sweep.js";import{ManagedWorktreeSweepReconciler as O}from"./managed-worktree-sweep.js";import{compactRunEvents as U}from"../../core/runs/events.js";import{archiveExpiredRunEvents as H}from"../../core/events/run-event-chunks.js";import{blobStore as Y}from"../../core/blobs/index.js";import{runThrottledLane as d}from"./throttled-lane.js";import{openDb as g}from"../../core/canvas/db.js";import{touchMachineEnvironment as z}from"../../core/environments.js";import{retentionHold as m}from"./live-obligation.js";import{deleteQuietNodeSandboxes as B}from"../../core/runtime/runner/delete-sandboxes.js";import{pruneMemoryReads as K}from"../../core/canvas/memory-reads.js";import{existsSync as Q}from"node:fs";import{launcherRequest as $}from"../../launcher/client.js";import{LAUNCHER_SOCKET as X}from"../../launcher/spec.js";import{cachePassDue as Z}from"../../launcher/limits/policy.js";const j=10*6e4,u=60*1e3,E=60*1e3,v=5*6e4,S=2,J=1440*6e4,ee=2e3,te=6e4;class Ce{static{p(this,"StorageMaintenanceReconciler")}focusGcInFlight=!1;lastCachePassAt=null;cachePassInFlight=!1;worktreeSweep=new O;groveInstanceSweep=new q;async run(e,t){await this.reapDeadResidue(e,t.held),this.scheduleFocusGc(t),await this.gcWarmPool(e),await this.touchEnvironment(e),await this.gcCreateRequests(e),await this.gcViewerAttachments(e);try{await d("run-event-maintenance","",e,ee,te,async r=>{await H(await Y(),e);const n=await U(e,r.state===null?0:Number(r.state));await r.save(String(n.cursor))})}catch(r){console.warn(`run event maintenance failed: ${String(r)}`)}await d("memory-read-prune","",e,60*6e4,10*6e4,async()=>{try{await K(e)}catch(r){console.warn(`memory-read log prune failed: ${String(r)}`)}}),await d("storage-analyze","",e,1440*6e4,10*6e4,async()=>{await(await g()).exec("ANALYZE")}),await this.sweepRetention(e,t),this.scheduleCachePass(e,t),this.scheduleContextStrip(e,t),this.worktreeSweep.run(e,t),this.groveInstanceSweep.run(e,t)}scheduleCachePass(e,t){this.cachePassInFlight||!Z(this.lastCachePassAt,e)||process.platform!=="linux"||!Q(X)||t.lifecycle.acceptsDetachedWork()&&(this.lastCachePassAt=e,this.cachePassInFlight=!0,t.lifecycle.registerDetached($({operation:"cache.purge"}).then(()=>{}).catch(r=>{s.fresh(()=>{a({level:"warn",event:"app.cache.pass_failed",error:r})})}).then(()=>{this.cachePassInFlight=!1})))}msSinceTerminalActivity(e,t){const r=h(e);return r===0?Number.POSITIVE_INFINITY:t-r}async sweepRetention(e,t){t.lifecycle.acceptsDetachedWork()&&await d("retention-sweep","",e,v,v,()=>s.fresh(async()=>{try{const r=await M({ttlDays:S,held:await m(t.fleet),removeDirs:p(i=>{t.lifecycle.registerDetached(Promise.all(i.map(c=>A(c,{recursive:!0,force:!0}))).then(()=>{}).catch(c=>{s.fresh(()=>{a({level:"error",event:"canvas.retention.failed",error:c})})}))},"removeDirs")});r.pruned.length>0&&a({level:"info",event:"canvas.retention.pruned",outcome:"succeeded",fields:{pruned_count:r.pruned.length}});const n=await m(t.fleet),o=e-S*24*60*6e4,f=await B({now:e,held:n,quiet:p(async i=>{const c=await y(i);return c!==null&&h(c)<o},"quiet")});f>0&&a({level:"info",event:"canvas.retention.sandboxes_deleted",outcome:"succeeded",fields:{deleted_count:f}})}catch(r){a({level:"error",event:"canvas.retention.failed",error:r})}}))}scheduleContextStrip(e,t){t.lifecycle.acceptsDetachedWork()&&t.lifecycle.registerDetached(d("context-strip","",e,v,10*6e4,()=>this.stripFinishedContexts(e,t)).then(()=>{},r=>{a({level:"error",event:"canvas.context_strip.failed",error:r})}))}async stripFinishedContexts(e,t){const r=await m(t.fleet),n=p(async i=>i!==null&&["done","canceled","dead"].includes(i.status)&&(i.pi_pid??null)===null&&(i.frozen_at??null)===null&&!W(i)&&h(i)<e-J&&!await r(i.node_id),"eligible");let o=0,f=0;try{for(const i of await C({status:["done","canceled","dead"]})){if(!l(i.node_id)||!await n(i))continue;const c=await b(i.node_id);if(c!==null&&c>=h(i)||!await n(await y(i.node_id)))continue;let _;try{_=await L(i.node_id)}catch(R){s.fresh(()=>{a({level:"warn",event:"canvas.context_strip.node_failed",error:R,fields:{node_id:i.node_id}})});continue}_.removed.length>0&&(o+=1,f+=_.bytes)}}catch(i){s.fresh(()=>{a({level:"error",event:"canvas.context_strip.failed",error:i})})}o>0&&s.fresh(()=>{a({level:"info",event:"canvas.context_strip.completed",outcome:"succeeded",fields:{node_count:o,bytes:f}})})}async reapDeadResidue(e,t){let r;try{r=await x()}catch(n){s.fresh(()=>{a({level:"error",event:"residue.reap_scan.failed",error:n})});return}for(const n of r)if(!t.has(n.node_id)){try{if(this.msSinceTerminalActivity(n,e)<j)continue}catch(o){s.fresh(()=>{a({level:"error",event:"residue.reap.failed",...l(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})});continue}await s.fresh(async()=>{try{a({level:"info",event:"residue.reaped",...l(n.node_id)?{node_id:n.node_id}:{},fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}}),await V(n.node_id)}catch(o){a({level:"error",event:"residue.reap.failed",...l(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})}})}}scheduleFocusGc(e){if(this.focusGcInFlight||!e.lifecycle.acceptsDetachedWork())return;this.focusGcInFlight=!0;const t=this.gcStaleFocuses().finally(()=>{this.focusGcInFlight=!1});e.lifecycle.registerDetached(t)}async gcStaleFocuses(){let e;try{e=await P()}catch(r){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:r})});return}if(e.length===0)return;let t;try{t=await G()}catch(r){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:r})});return}if(t!==null)for(const r of e){if(r.pane===null||t.has(r.pane))continue;if(!await s.fresh(async()=>{try{return(await T(r.focus_id))?.pane!==r.pane||(a({level:"info",event:"focus.gc.removed",...l(r.node_id)?{node_id:r.node_id}:{},fields:{focus_id:r.focus_id,focus_node_id:r.node_id,pane:r.pane}}),await N(r.focus_id)),!0}catch(o){return a({level:"error",event:"focus.gc.failed",error:o}),!1}}))return}}async gcCreateRequests(e){await d("create-request-gc","",e,E,E,()=>s.fresh(async()=>{const t=await F(e),r=await D(e);r>0&&a({level:"info",event:"canvas.idempotency_keys.reaped",outcome:"succeeded",fields:{reaped_count:r}}),t>0&&a({level:"info",event:"canvas.create_requests.reaped",outcome:"succeeded",fields:{reaped_count:t}})}))}async gcViewerAttachments(e){await d("viewer-attachment-gc","",e,u,u,()=>s.fresh(async()=>{const t=Number((await(await g()).prepare("DELETE FROM viewer_attachments WHERE expires_at <= ?").run(new Date(e).toISOString())).changes);t>0&&a({level:"info",event:"viewer_attachments.reaped",outcome:"succeeded",fields:{reaped_count:t}})}))}async touchEnvironment(e){await d("environment-touch","",e,u,u,()=>s.fresh(async()=>{try{await z(new Date(e).toISOString())}catch(t){a({level:"warn",event:"environment.touch.failed",error:t})}}))}async gcWarmPool(e){await d("warm-pool-gc","",e,u,u,()=>s.fresh(async()=>{const t=await k();t.length>0&&a({level:"info",event:"warm_pool.spares_reaped",outcome:"succeeded",fields:{reaped_count:t.length}})}))}}export{J as CONTEXT_STRIP_GRACE_MS,j as DEAD_REAP_GRACE_MS,v as RETENTION_SWEEP_INTERVAL_MS,S as RETENTION_TTL_DAYS,Ce as StorageMaintenanceReconciler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.729",
3
+ "version": "0.3.730",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.729",
162
- "@north-light/plugin": "0.3.729",
161
+ "@north-light/identity": "0.3.730",
162
+ "@north-light/plugin": "0.3.730",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -88,6 +88,7 @@ export async function beginExecution(nodeId, input) {
88
88
  if (superseded.changes > 0)
89
89
  await clearPendingParkIn(db, nodeId);
90
90
  await revokeNodeTokens(db, 'node_id', nodeId, at);
91
+ await db.prepare('UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL').run(nodeId);
91
92
  const executionId = randomUUID();
92
93
  const attempt = input.attempt ?? Number((await db.prepare('SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?').get(nodeId)).next);
93
94
  await db.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)")
@@ -6,7 +6,7 @@
6
6
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
7
7
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
8
8
  * one below the live database's `schema_min_reader`. */
9
- export const CANVAS_SCHEMA_VERSION = 32;
9
+ export const CANVAS_SCHEMA_VERSION = 33;
10
10
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
11
11
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
12
12
  * it is put in a `search_path` connection option. */
@@ -3,6 +3,15 @@
3
3
  // on the Blaxel runner deletes the sandbox). Every path that deletes node rows calls this first.
4
4
  import { afterCommit, openDb, withCanvasWrite } from '../../canvas/db.js';
5
5
  import { emitEvent } from '../../events/emit.js';
6
+ /** A launch that has not reached `running` in this long never will: its row no longer keeps the node's sandbox. */
7
+ export const STALE_LAUNCH_MS = 60 * 60_000;
8
+ /** SQL true when node `n` has an execution that still holds its sandbox: a running one, or a launch younger than {@link STALE_LAUNCH_MS}.
9
+ * Binds one parameter, the stale-launch cutoff as an ISO time. */
10
+ const OPEN_EXECUTION = `EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id
11
+ AND (x.state = 'running' OR (x.state = 'launching' AND x.started_at > ?)))`;
12
+ function staleLaunchCutoff(now = Date.now()) {
13
+ return new Date(now - STALE_LAUNCH_MS).toISOString();
14
+ }
6
15
  /** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
7
16
  * those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
8
17
  export async function deleteNodeSandboxes(nodeIds) {
@@ -23,18 +32,57 @@ export async function deleteNodeSandboxes(nodeIds) {
23
32
  return failed;
24
33
  }
25
34
  /** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
26
- * (its fires run there). Called after each of those ends; a failure is left to the sandbox's idle expiry. A parked node is not ended:
27
- * wake mail reopens it in the same sandbox. The check and the DELETE run holding the node row's lock, which `beginExecution` also
28
- * takes, so no new execution can start in the sandbox between them. */
35
+ * (its fires run there). Called after each of those ends; a failure is left to the retention pass. A parked node is not ended:
36
+ * wake mail reopens it in the same sandbox. A launch stuck in `launching` past {@link STALE_LAUNCH_MS} does not hold the sandbox.
37
+ * The check and the DELETE run holding the node row's lock, which `beginExecution` also takes, so no new execution can start in
38
+ * the sandbox between them. */
29
39
  export function deleteSandboxOfEndedNode(nodeId) {
30
40
  afterCommit(() => void withCanvasWrite(async (db) => {
31
41
  const ended = await db.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
32
42
  AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
33
43
  AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
34
- AND NOT EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited')
44
+ AND NOT ${OPEN_EXECUTION}
35
45
  AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
36
- FOR UPDATE OF n`).get(nodeId);
37
- if (ended !== undefined)
38
- await (await import('./index.js')).runnerForExecution('blaxel').delete(nodeId);
46
+ FOR UPDATE OF n`).get(nodeId, staleLaunchCutoff());
47
+ if (ended === undefined)
48
+ return;
49
+ await (await import('./index.js')).runnerForExecution('blaxel').delete(nodeId);
50
+ await db.prepare('UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?').run(new Date().toISOString(), nodeId);
39
51
  }).catch((error) => { emitEvent({ level: 'error', event: 'canvas.node_sandbox.delete_failed', node_id: nodeId, error }); }));
40
52
  }
53
+ /** Delete the sandbox of every finished, canceled, dead or parked node quiet for `quietMs`, keeping its rows; app runs included.
54
+ * `quiet` decides the activity test ({@link lastActivityMs} reads disk too); `held` excludes nodes retention must not touch.
55
+ * Each node is marked `sandbox_deleted_at` so later passes skip it until a new execution clears the mark. Returns the deleted count. */
56
+ export async function deleteQuietNodeSandboxes(opts) {
57
+ const cutoff = staleLaunchCutoff(opts.now);
58
+ const candidates = await (await openDb()).prepare(`SELECT n.node_id FROM nodes n WHERE n.status IN ('done', 'canceled', 'dead')
59
+ AND n.sandbox_deleted_at IS NULL
60
+ AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
61
+ AND NOT ${OPEN_EXECUTION}
62
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)`).all(cutoff);
63
+ let deleted = 0;
64
+ for (const { node_id } of candidates) {
65
+ if (!await opts.quiet(node_id) || await opts.held(node_id))
66
+ continue;
67
+ try {
68
+ const done = await withCanvasWrite(async (db) => {
69
+ // Re-check under the node lock `beginExecution` takes, so no execution starts in the sandbox while it is deleted.
70
+ const still = await db.prepare(`SELECT 1 AS ok FROM nodes n WHERE n.node_id = ? AND n.status IN ('done', 'canceled', 'dead')
71
+ AND n.sandbox_deleted_at IS NULL AND NOT ${OPEN_EXECUTION}
72
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
73
+ FOR UPDATE OF n`).get(node_id, cutoff);
74
+ if (still === undefined)
75
+ return false;
76
+ await (await import('./index.js')).runnerForExecution('blaxel').delete(node_id);
77
+ await db.prepare('UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?').run(new Date().toISOString(), node_id);
78
+ return true;
79
+ });
80
+ if (done)
81
+ deleted++;
82
+ }
83
+ catch (error) {
84
+ emitEvent({ level: 'error', event: 'canvas.node_sandbox.delete_failed', node_id, error });
85
+ }
86
+ }
87
+ return deleted;
88
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.729",
3
+ "version": "0.3.730",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.729",
3
+ "version": "0.3.730",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.729",
3
+ "version": "0.3.730",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.729",
31
- "@north-light/identity": "0.3.729"
30
+ "@north-light/api": "0.3.730",
31
+ "@north-light/identity": "0.3.730"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.729",
3
+ "version": "0.3.730",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.729",
9
+ "version": "0.3.730",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.729",
32
- "@north-light/plugin": "0.3.729",
31
+ "@north-light/identity": "0.3.730",
32
+ "@north-light/plugin": "0.3.730",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.729",
11905
+ "version": "0.3.730",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.729",
11910
+ "version": "0.3.730",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.729",
11915
+ "version": "0.3.730",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.729",
11923
+ "version": "0.3.730",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.729",
11927
- "@north-light/identity": "0.3.729"
11926
+ "@north-light/api": "0.3.730",
11927
+ "@north-light/identity": "0.3.730"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.729",
11932
+ "version": "0.3.730",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.729",
11936
- "@north-light/identity": "0.3.729",
11937
- "@north-light/plugin": "0.3.729",
11935
+ "@north-light/api": "0.3.730",
11936
+ "@north-light/identity": "0.3.730",
11937
+ "@north-light/plugin": "0.3.730",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {