@north-light/cli 0.3.728 → 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 +1 @@
1
- var c=Object.defineProperty;var a=(t,e)=>c(t,"name",{value:e,configurable:!0});import{clearFinalReportIfMatches as l,getFinalReport as f,getNode as u,updateNode as p}from"../canvas/index.js";import{subscribersOf as w}from"../canvas/tree.js";import{InputError as o}from"../io.js";import{transition as m}from"./lifecycle.js";import{noticeChangedWhileDone as h}from"./ledger.js";async function s(t){return await f(t)}a(s,"currentFinalReport");function d(t,e){throw new o({error:"node_finalized",message:`${t} already submitted its canonical final result (\`crtr canvas read ${t}/${e}\`) \u2014 reviving it now would hand it a mandate it can never finish, since a second \`push final\` always errors against an already-latched node.`,next:`Re-run this exact command with --reopen to clear ${t}'s spent latch and re-task it in place.`})}a(d,"throwNodeFinalized");function g(t){throw new o({error:"not_finalized",message:`${t} is not finalized \u2014 --reopen has nothing to clear.`,next:"Drop --reopen."})}a(g,"throwNotFinalized");async function R(t){const e=await s(t);e!==null&&d(t,e)}a(R,"assertNotFinalized");async function y(t){const e=await s(t);return e===null&&g(t),e}a(y,"assertFinalizedForReopen");async function x(t,e){if(!await l(t,e))throw new o({error:"reopen_latch_changed",message:`${t}'s finalization latch changed since it was last inspected \u2014 a concurrent --reopen (or a fresh push final) already moved it, so clearing it now would risk erasing a newer canonical result.`,next:"Re-run this exact command \u2014 it will re-inspect the current state before acting."})}a(x,"commitReopen");async function F(t,e){return t==null?!1:(await w(e)).some(i=>i.node_id===t)}a(F,"isManagerOf");async function _(t,e,i){const r=await s(t);await F(i,t)||await p(t,{lifecycle:"resident"});const n=await u(t);return n!==null&&(n.status==="done"||n.status==="canceled"||n.status==="dead")&&(n.status==="done"&&n.last_settled_at!=null&&await h(t,n.last_settled_at),await m(t,"revive")),r!==null&&await x(t,e??r),r}a(_,"commitReopenResident");async function D(t,e,i){if(e){const r=await y(t);await _(t,r,i);return}await R(t)}a(D,"assertReopenGate");export{y as assertFinalizedForReopen,R as assertNotFinalized,D as assertReopenGate,x as commitReopen,_ as commitReopenResident};
1
+ var f=Object.defineProperty;var a=(t,e)=>f(t,"name",{value:e,configurable:!0});import{clearFinalReportIfMatches as u,getFinalReport as p,getNode as l,updateNode as w}from"../canvas/index.js";import{subscribersOf as m}from"../canvas/tree.js";import{InputError as s}from"../io.js";import{transition as h}from"./lifecycle.js";import{assertCheckoutNotRemoved as d}from"./revive.js";import{noticeChangedWhileDone as g}from"./ledger.js";async function c(t){return await p(t)}a(c,"currentFinalReport");function R(t,e){throw new s({error:"node_finalized",message:`${t} already submitted its canonical final result (\`crtr canvas read ${t}/${e}\`) \u2014 reviving it now would hand it a mandate it can never finish, since a second \`push final\` always errors against an already-latched node.`,next:`Re-run this exact command with --reopen to clear ${t}'s spent latch and re-task it in place.`})}a(R,"throwNodeFinalized");function y(t){throw new s({error:"not_finalized",message:`${t} is not finalized \u2014 --reopen has nothing to clear.`,next:"Drop --reopen."})}a(y,"throwNotFinalized");async function x(t){const e=await c(t);e!==null&&R(t,e)}a(x,"assertNotFinalized");async function F(t){const e=await c(t);return e===null&&y(t),e}a(F,"assertFinalizedForReopen");async function _(t,e){if(!await u(t,e))throw new s({error:"reopen_latch_changed",message:`${t}'s finalization latch changed since it was last inspected \u2014 a concurrent --reopen (or a fresh push final) already moved it, so clearing it now would risk erasing a newer canonical result.`,next:"Re-run this exact command \u2014 it will re-inspect the current state before acting."})}a(_,"commitReopen");async function v(t,e){return t==null?!1:(await m(e)).some(i=>i.node_id===t)}a(v,"isManagerOf");async function z(t,e,i){const r=await l(t);r!==null&&d(t,r);const o=await c(t);await v(i,t)||await w(t,{lifecycle:"resident"});const n=await l(t);return n!==null&&(n.status==="done"||n.status==="canceled"||n.status==="dead")&&(n.status==="done"&&n.last_settled_at!=null&&await g(t,n.last_settled_at),await h(t,"revive")),o!==null&&await _(t,e??o),o}a(z,"commitReopenResident");async function O(t,e,i){if(e){const r=await F(t);await z(t,r,i);return}await x(t)}a(O,"assertReopenGate");export{F as assertFinalizedForReopen,x as assertNotFinalized,O as assertReopenGate,_ as commitReopen,z as commitReopenResident};
@@ -111,7 +111,8 @@ export declare function assertRecordedCwdExists(nodeId: string, meta: NodeMeta):
111
111
  blaxelEnvironment: string | null;
112
112
  remoteMachine: boolean;
113
113
  }>;
114
- /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
114
+ /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them; its cwd now names the shared repository
115
+ * root, so a launch would edit the base checkout. Refuse on any host, before a caller changes state. */
115
116
  export declare function assertCheckoutNotRemoved(nodeId: string, meta: NodeMeta): void;
116
117
  /** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
117
118
  export declare function runNodeStartHooks(nodeId: string, meta: NodeMeta, isBirth: boolean): Promise<void>;
@@ -1,3 +1,3 @@
1
- var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as F,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as A,endLiveExecution as me,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as O}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as x,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function dr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}s(dr,"sessionHasConversation");async function mr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||H(i)}s(mr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await mr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await O(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const m=!k&&await n.reserveSlot(e);let o=null;if(m){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!m||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await me(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function pi(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(pi,"assertCheckoutNotRemoved");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await F(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(m&&(typeof o!="string"||!fe(o)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=m&&typeof o=="string";if(w&&!await re(o))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await F(e,{cycles:r.cycles});const S=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,S,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),$=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await dr(p.resumeSessionPath)?(await x(e))?.trim():void 0,T=$!==void 0&&$!=="",se=w||D||T,M=r.cycle_pending===!0||B;await F(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const ce=(await d().header(await d().fork(N,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)l=y(r,{...p,prompt:$}),h=C(),await V(l,r);else if(v)l=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await x(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await O(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,l,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await O(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
1
+ var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as U}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as K}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as A,beginExecution as he,ExecutionAlreadyLive as me,recordExecutionPid as pe,abortExecution as O,endLiveExecution as de,unbindSession as W,recordLaunch as ve,setFrozen as _e,clearFrozen as P,fullName as ye}from"../canvas/index.js";import{emitEvent as J}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as B,transition as E}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as x}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as S,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as D}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function mr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await p().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof K)return{};throw n}}s(mr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await p().header(r),!0}catch(i){if(i instanceof K)return!1;throw i}}s(re,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await p().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||U(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await mr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function hi(e){const r=await S(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(hi,"hasFreshGroundState");async function mi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(mi,"reviveNode");async function pi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(pi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);(i||!(t.lifecycle==="resident"&&B(t)))&&await gr(e,t),ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&B(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await E(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&B(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await n.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(D().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:D().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await Rr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(e,{reason:"frozen"}),J({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!U(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new x({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function kr(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"))throw new x({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(kr,"assertCheckoutNotRemoved");async function gr(e,r){try{kr(e,r)}catch(i){throw(r.status==="active"||r.status==="idle")&&(await E(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:i.message}}}),await P(e)),i}}s(gr,"refuseRemovedCheckout");async function br(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(br,"runNodeStartHooks");async function Rr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await A(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await W(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new x({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=d&&typeof o=="string";if(w&&!await re(o))throw new x({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=D();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof me)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await A(e,{cycles:r.cycles});const $=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,m=w?{}:await vr(e,r,$,!u),g=m.resumeSessionPath!==void 0,T=g&&m.newCycle===!0,v=g&&!T,M=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),C=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(m.resumeSessionPath)?(await S(e))?.trim():void 0,L=C!==void 0&&C!=="",se=w||M||L,z=r.cycle_pending===!0||T;await A(e,{cycle_pending:z}),r.cycle_pending=z,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await W(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const N=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await S(e),F=_(o);if(F===null)throw new Error(`invalid fork source ${o}`);const ce=(await p().header(await p().fork(F,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=N()),await qe(e,(await Ze(o))?.node_id??null)}else if(L)l=y(r,{...m,prompt:C}),h=N(),await V(l,r);else if(v)l=y(r,{...m,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(M){const a=(await S(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=N(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...m,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await E(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const H=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await br(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const G=await Fe(e,l,r.cwd);await Ge(f,G);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:G,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await E(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
2
2
 
3
- It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await A(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await de(f,e,b.pid)==="shutdown")throw await A(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(c){throw c instanceof Y&&c.sent||(await A(f,{reason:"launch_failed"}),await Be(f,c).catch(S=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:S})})),c}}s(gr,"launchRevive");export{pi as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await O(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await P(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:H.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await O(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await P(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:H.explanation,outcome:"launched"}}catch(c){throw c instanceof Y&&c.sent||(await O(f,{reason:"launch_failed"}),await Be(f,c).catch($=>{J({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:$})})),c}}s(Rr,"launchRevive");export{kr as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,pi as decideAttachRevive,hi as hasFreshGroundState,mr as resumeArgs,mi as reviveNode,br as runNodeStartHooks};
@@ -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,2 +1,2 @@
1
- var ce=Object.defineProperty;var u=(t,e)=>ce(t,"name",{value:e,configurable:!0});import{randomBytes as ue}from"node:crypto";import{claimNodeMail as le,acknowledgeNodeMail as fe}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as me}from"../../../core/feed/inbox.js";import{enqueueNodeMail as D,cancelPendingNodeMail as pe}from"../../../core/feed/messages.js";import{assertCheckoutNotRemoved as ye,assertRecordedCwdExists as he,reviveNode as L}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as U}from"../../../core/runtime/broker-request.js";import{isBrokerLive as q}from"../../../core/runtime/model-swap.js";import{deliverLive as we,interruptLive as be}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as ge}from"../../../core/profiles/manifest.js";import{getNode as C,withFreshTerminalGuard as ve}from"../../../core/canvas/canvas.js";import{getById as G,nodeObject as F,ownerForGrantee as _e}from"../../../core/graph/objects.js";import{recordActedOn as ke}from"../../../core/graph/edges.js";import{recordWatch as H}from"../../../core/graph/watches.js";import{publish as V}from"../../../core/graph/events.js";import{readerFor as K}from"../reader.js";import{canRead as Se}from"../../../core/graph/access.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as Q}from"../../../core/canvas/structured-requests.js";import{consumeDeadlineOnWake as X}from"../../../core/feed/messages.js";import{assertNotFinalized as M,assertFinalizedForReopen as Ne,commitReopenResident as E}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as $e}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as je}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as P,formatSituationalProse as Ae}from"../../../core/runtime/situational-context.js";import{formatDataCard as Y}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as Oe}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as qe}from"../../park-pending.js";import{wantsExecution as Ce}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as xe}from"../../../core/runtime/revive.js";import{CrtrError as Re,notFound as x,usage as d}from"../../../core/errors.js";import{isStartRefusal as Fe}from"../../../core/runtime/start-check.js";import{emitEvent as Me}from"../../../core/events/emit.js";import{assertScope as Ee}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Pe}from"../../../api/index.js";import{describeObject as Ie,stubOf as Te}from"../../../core/peer/stubs.js";import{machineNameOf as Z}from"../../../core/peer/names.js";import{callerNode as Be,callerStub as ze,forwardVerb as ee,relayError as te,remoteStub as Je,unknownError as re,withMachine as ne}from"../../peer/forward.js";import{ownerOnly as We}from"../router.js";import{personId as De}from"../../../core/canvas/person.js";const Le=["critical","urgent","normal","deferred"];function oe(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} must be an object { kind, facts?, body? }`);const a=t,n=a.kind;if(typeof n!="string"||n.trim()==="")throw d(`${e}.kind is required`);if(!n.includes(":"))throw d(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=a.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw d(`${e}.facts must be an object of string or number values`);const c={};for(const[l,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw d(`${e}.facts.${l} must be a string or number`);c[l]=m}r.facts=c}const i=a.body;if(i!==void 0){if(typeof i!="string")throw d(`${e}.body must be a string`);r.body=i}return r}u(oe,"parseCardRequest");function ae(t,e){try{return Y(t.kind,t.facts??{},t.body??"")}catch(a){throw d(`${e}: ${a instanceof Error?a.message:String(a)}`)}}u(ae,"renderCard");function Ue(t){if(typeof t!="object"||t===null)throw d("a message requires a JSON body { body, tier?, fresh? }");const e=t,a=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,i=e.output_schema;if(i!=null&&typeof i!="string")throw d("output_schema must be a JSON schema string");const c=typeof a=="string"&&a.trim()!=="",l=typeof o=="string"&&o.trim()!=="",m=typeof i=="string"&&i.trim()!=="",v=e.situational_card,S=e.context_cards,b=v===void 0?void 0:oe(v,"situational_card");if(S!==void 0&&!Array.isArray(S))throw d("context_cards must be an array of { kind, facts?, body? }");const p=S?.map(($,N)=>oe($,`context_cards[${N}]`));if(b!==void 0&&typeof o=="string"&&o!=="")throw d("situational_card and situational_context are mutually exclusive");const w=b!==void 0||p!==void 0&&p.length>0;if(!n&&!c&&!l&&!m&&!w)throw d("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw d("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!Le.includes(r))throw d(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const f={body:typeof a=="string"?a:""};r!==void 0&&(f.tier=r),n&&(f.fresh=!0),e.reopen===!0&&(f.reopen=!0),typeof o=="string"&&(f.situational_context=o),b!==void 0&&(f.situational_card=b),p!==void 0&&(f.context_cards=p),typeof i=="string"&&(f.output_schema=i),typeof e.from=="string"&&(f.from=e.from);const y=e.delivery;if(y!==void 0&&y!=="interactive")throw d(`invalid delivery: ${String(y)} (expected interactive)`);if(y==="interactive"){if(n||f.situational_context!==void 0||f.output_schema!==void 0)throw d("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!c)throw d("interactive delivery requires a non-empty body");if(f.tier==="deferred")throw d("interactive delivery cannot be deferred");f.delivery="interactive"}return f}u(Ue,"parseSendBody");function Ge(t){let e;try{e=JSON.parse(t)}catch{throw d("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw d("output_schema must be a JSON schema object");return e}u(Ge,"parseSchema");function He(t){return t.split(`
2
- `)[0].slice(0,120)}u(He,"label");function ie(t,e){return e===null?"":Y("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(ie,"previousFinalReportCard");async function Ve(t,e,a){if(a!==null&&a!=="human"&&(await G(t,a))?.type==="node"){const o=await F(t,a);return{actor:o,senderNode:o}}if(a==="human")return{actor:await _e(t,De()),senderNode:null};const n=await K(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Ve,"messageActor");async function se(t,e,a,n,r,o){const i=await F(t,a),{actor:c,senderNode:l}=await Ve(t,e,n),m=r===null?{}:{pointer:r};await ke(t,c,i),l!==null&&l.id!==i.id&&await H(t,l,i,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),await V(t,{event:"messaged",object:i,actor:c,attrs:{},...m}),l!==null&&await V(t,{event:"sent",object:l,actor:l,attrs:{to:i.id},...m})}u(se,"recordMessage");function Ke(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ke,"deferredNoNaturalCycle");async function Qe(t){if(!await xe(t))throw new Pe(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Qe,"assertRecoverableForFresh");function Xe(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof Re?{error:t.code,message:t.message,message_id:e}:Fe(t)?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(Xe,"wakeFailure");async function Ye(t,e){const a=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof a=="object"&&a!==null&&delete a.from;const n=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:a});if(n.kind==="local")return null;if(n.kind==="unknown")throw re(e,n.unreachable);if(n.status>=400)throw te(n.status,n.body);return await k(async r=>{const o=await Be(r,t);if(o===null)return;const i=n.body?.object,c=await Je(r,e,"node",n.machine.id,i);await H(r,o,c,"message",{endsOn:"final"})}),{status:n.status,body:ne(n.body,n.machine)}}u(Ye,"forwardMessage");async function Ze(t){const e=await et(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const a=await k(async n=>{const r=await F(n,t.params.id);return await Se(n,await K(n,t),r)?await Ie(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:a}}}u(Ze,"handleMessage");async function et(t){const e=t.params.id,a=await Ye(t,e);if(a!==null)return a;const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=Ue(t.body),o=r.tier??"normal",i=ge(n.profile_id);r.reopen&&ye(e,n),r.reopen&&!i&&!q(n)&&await he(e,n);const c=t.principal.class==="forwarded"?await k(async s=>(await ze(s,t))?.id??null):r.from??null;if(c!==null){const s=await C(c);s!==null&&Ee(s,"crtr:act")}const l=c===null?null:await k(async s=>{const h=await G(s,c);return h===null?null:(await Te(s,h))?.home_machine??null}),m=l===null?void 0:`${c} on ${Z(l)}`,v=t.principal.class==="broker"?t.principal.node:null,S=l===null?{}:{from_machine:Z(l)},b=r.body.trim()!=="",p=r.situational_card!==void 0?ae(r.situational_card,"situational_card"):r.situational_context!==void 0?Ae(r.situational_context.trim()):"",w=p!=="",f=(r.context_cards??[]).map((s,h)=>ae(s,`context_cards[${h}]`)),y=r.output_schema!==void 0&&r.output_schema.trim()!==""?Ge(r.output_schema):null;y!==null&&await je(y);let $=!1;const N=u(async s=>{if(!(y===null||$)){if(await Q(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});await $e(e,"oneoff",y,s),$=!0}},"ensureSchema");if(r.fresh){const s=r.reopen?await Ne(e):null;r.reopen||await M(e),await Qe(e),await N(),w&&await P(e,p),r.reopen&&await E(e,s,v);const h=await L(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:h.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&await M(e);let T=!1,_="";if(r.delivery==="interactive"&&r.reopen&&(_=ie(e,await E(e,void 0,v)),T=!0),r.delivery==="interactive"&&await N(),r.delivery==="interactive"&&!i&&!n.run_id&&q(n))try{return w&&await P(e,p),await we(e,r.body,{cards:[..._===""?[]:[_],...w?[p]:[],...f],origin:c==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...c===null?{}:{from:c},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),await k(async h=>await se(h,t,e,c,null,!1)),await X(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(s){if(!(s instanceof U))throw s}const B=u(async()=>{r.reopen||await M(e);const s=ue(16).toString("hex"),h=u(async O=>await se(O,t,e,c,s,y!==null),"withinEnqueue");await N(s),w&&await P(e,p),r.reopen&&!T&&(_=ie(e,await E(e,void 0,v)));const R=[..._===""?[]:[_],...f],W=R.length>0?{cards:R}:{};if(b||y!==null){const O=b?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${(await Q(e))?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:He(O),bodyJson:{body:O,...S,...w?{situational:!0}:{},...W}})}return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:w?"(ambient context updated)":"(context delivered)",bodyJson:{...w?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),g=await u(async()=>{if(o==="deferred"){const s=await ve(e,Oe,B);if(s.kind==="missing")throw x(`unknown node: ${e}`,{received:e});if(s.kind==="terminal")throw Ke(e,s.status);return s.result}return await B()},"deliver")();g.urgency!=="deferred"&&await k(async()=>qe(e));const j=await C(e);if(j===null)throw x(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&await X(e);let z=!1,J=!1,A;if((r.reopen||j.lifecycle==="terminal"||!await Ce(j))&&g.urgency!=="deferred"&&!i&&!q(j))try{const s=await L(e,{resume:!0,capacity:"freeze"});z=s.launch!==void 0,J=s.outcome==="frozen"}catch(s){A=Xe(s,g.messageId),Me({level:"error",event:"message.wake_failed",node_id:e,error:s,fields:{message_id:g.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:z,...J?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:g.createdAt,...g.urgency===o?{}:{delivered_tier:g.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(et,"handleMessageHere");async function tt(t){const e=t.params.id,a=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(a.kind==="unknown")throw re(e,a.unreachable);if(a.kind==="remote"){if(a.status>=400)throw te(a.status,a.body);return{status:a.status,body:ne(a.body,a.machine)}}const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=await pe(e,{senderNodeId:"human",kind:"message"});let o=!1;if(q(n))try{o=await be(e)!=="idle"}catch(c){if(!(c instanceof U))throw c}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(tt,"handleInterrupt");function de(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw d("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw d("execution_id is required");return e}u(de,"mailBody");async function rt(t){const e=de(t),a=e.channel;if(a!=="wake"&&a!=="passive"&&a!=="deferred_run")throw d("channel must be wake, passive, or deferred_run");const n=await le(t.params.id,e.execution_id,a);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...me(o),seq:o.message.seq}}))}}}u(rt,"handleMailClaim");async function nt(t){const e=de(t);if(!Array.isArray(e.deliveries))throw d("deliveries must be an array");const a=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw d("each delivery must be an object");const i=o;if(typeof i.delivery_id!="string"||i.delivery_id==="")throw d("delivery_id is required");if(!Number.isSafeInteger(i.attempts)||i.attempts<1)throw d("attempts must be a positive integer");if(i.disposition!=="acknowledged"&&i.disposition!=="released")throw d("disposition must be acknowledged or released");return{delivery_id:i.delivery_id,attempts:i.attempts,disposition:i.disposition}}),n=await fe(t.params.id,e.execution_id,a.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(nt,"handleMailAcknowledge");const Ht=We([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:nt}]),Vt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ze},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:tt}];export{Ht as brokerMailRoutes,Ze as handleMessage,Vt as messageRoutes};
1
+ var ue=Object.defineProperty;var u=(t,e)=>ue(t,"name",{value:e,configurable:!0});import{randomBytes as le}from"node:crypto";import{claimNodeMail as fe,acknowledgeNodeMail as me}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as pe}from"../../../core/feed/inbox.js";import{enqueueNodeMail as D,cancelPendingNodeMail as ye}from"../../../core/feed/messages.js";import{assertCheckoutNotRemoved as L,assertRecordedCwdExists as he,reviveNode as U}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as G}from"../../../core/runtime/broker-request.js";import{isBrokerLive as q}from"../../../core/runtime/model-swap.js";import{deliverLive as we,interruptLive as be}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as ge}from"../../../core/profiles/manifest.js";import{getNode as C,withFreshTerminalGuard as ve}from"../../../core/canvas/canvas.js";import{getById as H,nodeObject as F,ownerForGrantee as _e}from"../../../core/graph/objects.js";import{recordActedOn as ke}from"../../../core/graph/edges.js";import{recordWatch as V}from"../../../core/graph/watches.js";import{publish as K}from"../../../core/graph/events.js";import{readerFor as Q}from"../reader.js";import{canRead as Se}from"../../../core/graph/access.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as X}from"../../../core/canvas/structured-requests.js";import{consumeDeadlineOnWake as Y}from"../../../core/feed/messages.js";import{assertNotFinalized as M,assertFinalizedForReopen as Ne,commitReopenResident as E}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as $e}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as je}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as P,formatSituationalProse as Ae}from"../../../core/runtime/situational-context.js";import{formatDataCard as Z}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as Oe}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as qe}from"../../park-pending.js";import{wantsExecution as Ce}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as xe}from"../../../core/runtime/revive.js";import{CrtrError as Re,notFound as x,usage as d}from"../../../core/errors.js";import{isStartRefusal as Fe}from"../../../core/runtime/start-check.js";import{emitEvent as Me}from"../../../core/events/emit.js";import{assertScope as Ee}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Pe}from"../../../api/index.js";import{describeObject as Ie,stubOf as Te}from"../../../core/peer/stubs.js";import{machineNameOf as ee}from"../../../core/peer/names.js";import{callerNode as Be,callerStub as ze,forwardVerb as te,relayError as re,remoteStub as Je,unknownError as ne,withMachine as oe}from"../../peer/forward.js";import{ownerOnly as We}from"../router.js";import{personId as De}from"../../../core/canvas/person.js";const Le=["critical","urgent","normal","deferred"];function ae(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} must be an object { kind, facts?, body? }`);const a=t,n=a.kind;if(typeof n!="string"||n.trim()==="")throw d(`${e}.kind is required`);if(!n.includes(":"))throw d(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=a.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw d(`${e}.facts must be an object of string or number values`);const c={};for(const[l,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw d(`${e}.facts.${l} must be a string or number`);c[l]=m}r.facts=c}const i=a.body;if(i!==void 0){if(typeof i!="string")throw d(`${e}.body must be a string`);r.body=i}return r}u(ae,"parseCardRequest");function ie(t,e){try{return Z(t.kind,t.facts??{},t.body??"")}catch(a){throw d(`${e}: ${a instanceof Error?a.message:String(a)}`)}}u(ie,"renderCard");function Ue(t){if(typeof t!="object"||t===null)throw d("a message requires a JSON body { body, tier?, fresh? }");const e=t,a=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,i=e.output_schema;if(i!=null&&typeof i!="string")throw d("output_schema must be a JSON schema string");const c=typeof a=="string"&&a.trim()!=="",l=typeof o=="string"&&o.trim()!=="",m=typeof i=="string"&&i.trim()!=="",v=e.situational_card,S=e.context_cards,b=v===void 0?void 0:ae(v,"situational_card");if(S!==void 0&&!Array.isArray(S))throw d("context_cards must be an array of { kind, facts?, body? }");const p=S?.map(($,N)=>ae($,`context_cards[${N}]`));if(b!==void 0&&typeof o=="string"&&o!=="")throw d("situational_card and situational_context are mutually exclusive");const w=b!==void 0||p!==void 0&&p.length>0;if(!n&&!c&&!l&&!m&&!w)throw d("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw d("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!Le.includes(r))throw d(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const f={body:typeof a=="string"?a:""};r!==void 0&&(f.tier=r),n&&(f.fresh=!0),e.reopen===!0&&(f.reopen=!0),typeof o=="string"&&(f.situational_context=o),b!==void 0&&(f.situational_card=b),p!==void 0&&(f.context_cards=p),typeof i=="string"&&(f.output_schema=i),typeof e.from=="string"&&(f.from=e.from);const y=e.delivery;if(y!==void 0&&y!=="interactive")throw d(`invalid delivery: ${String(y)} (expected interactive)`);if(y==="interactive"){if(n||f.situational_context!==void 0||f.output_schema!==void 0)throw d("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!c)throw d("interactive delivery requires a non-empty body");if(f.tier==="deferred")throw d("interactive delivery cannot be deferred");f.delivery="interactive"}return f}u(Ue,"parseSendBody");function Ge(t){let e;try{e=JSON.parse(t)}catch{throw d("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw d("output_schema must be a JSON schema object");return e}u(Ge,"parseSchema");function He(t){return t.split(`
2
+ `)[0].slice(0,120)}u(He,"label");function se(t,e){return e===null?"":Z("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(se,"previousFinalReportCard");async function Ve(t,e,a){if(a!==null&&a!=="human"&&(await H(t,a))?.type==="node"){const o=await F(t,a);return{actor:o,senderNode:o}}if(a==="human")return{actor:await _e(t,De()),senderNode:null};const n=await Q(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Ve,"messageActor");async function de(t,e,a,n,r,o){const i=await F(t,a),{actor:c,senderNode:l}=await Ve(t,e,n),m=r===null?{}:{pointer:r};await ke(t,c,i),l!==null&&l.id!==i.id&&await V(t,l,i,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),await K(t,{event:"messaged",object:i,actor:c,attrs:{},...m}),l!==null&&await K(t,{event:"sent",object:l,actor:l,attrs:{to:i.id},...m})}u(de,"recordMessage");function Ke(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ke,"deferredNoNaturalCycle");async function Qe(t){if(!await xe(t))throw new Pe(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Qe,"assertRecoverableForFresh");function Xe(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof Re?{error:t.code,message:t.message,message_id:e}:Fe(t)?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(Xe,"wakeFailure");async function Ye(t,e){const a=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof a=="object"&&a!==null&&delete a.from;const n=await te(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:a});if(n.kind==="local")return null;if(n.kind==="unknown")throw ne(e,n.unreachable);if(n.status>=400)throw re(n.status,n.body);return await k(async r=>{const o=await Be(r,t);if(o===null)return;const i=n.body?.object,c=await Je(r,e,"node",n.machine.id,i);await V(r,o,c,"message",{endsOn:"final"})}),{status:n.status,body:oe(n.body,n.machine)}}u(Ye,"forwardMessage");async function Ze(t){const e=await et(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const a=await k(async n=>{const r=await F(n,t.params.id);return await Se(n,await Q(n,t),r)?await Ie(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:a}}}u(Ze,"handleMessage");async function et(t){const e=t.params.id,a=await Ye(t,e);if(a!==null)return a;const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=Ue(t.body),o=r.tier??"normal",i=ge(n.profile_id);r.reopen&&L(e,n),r.reopen&&!i&&!q(n)&&await he(e,n);const c=t.principal.class==="forwarded"?await k(async s=>(await ze(s,t))?.id??null):r.from??null;if(c!==null){const s=await C(c);s!==null&&Ee(s,"crtr:act")}const l=c===null?null:await k(async s=>{const h=await H(s,c);return h===null?null:(await Te(s,h))?.home_machine??null}),m=l===null?void 0:`${c} on ${ee(l)}`,v=t.principal.class==="broker"?t.principal.node:null,S=l===null?{}:{from_machine:ee(l)},b=r.body.trim()!=="",p=r.situational_card!==void 0?ie(r.situational_card,"situational_card"):r.situational_context!==void 0?Ae(r.situational_context.trim()):"",w=p!=="",f=(r.context_cards??[]).map((s,h)=>ie(s,`context_cards[${h}]`)),y=r.output_schema!==void 0&&r.output_schema.trim()!==""?Ge(r.output_schema):null;y!==null&&await je(y);let $=!1;const N=u(async s=>{if(!(y===null||$)){if(await X(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});await $e(e,"oneoff",y,s),$=!0}},"ensureSchema");if(r.fresh){L(e,n);const s=r.reopen?await Ne(e):null;r.reopen||await M(e),await Qe(e),await N(),w&&await P(e,p),r.reopen&&await E(e,s,v);const h=await U(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:h.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&await M(e);let T=!1,_="";if(r.delivery==="interactive"&&r.reopen&&(_=se(e,await E(e,void 0,v)),T=!0),r.delivery==="interactive"&&await N(),r.delivery==="interactive"&&!i&&!n.run_id&&q(n))try{return w&&await P(e,p),await we(e,r.body,{cards:[..._===""?[]:[_],...w?[p]:[],...f],origin:c==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...c===null?{}:{from:c},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),await k(async h=>await de(h,t,e,c,null,!1)),await Y(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(s){if(!(s instanceof G))throw s}const B=u(async()=>{r.reopen||await M(e);const s=le(16).toString("hex"),h=u(async O=>await de(O,t,e,c,s,y!==null),"withinEnqueue");await N(s),w&&await P(e,p),r.reopen&&!T&&(_=se(e,await E(e,void 0,v)));const R=[..._===""?[]:[_],...f],W=R.length>0?{cards:R}:{};if(b||y!==null){const O=b?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${(await X(e))?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:He(O),bodyJson:{body:O,...S,...w?{situational:!0}:{},...W}})}return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:w?"(ambient context updated)":"(context delivered)",bodyJson:{...w?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),g=await u(async()=>{if(o==="deferred"){const s=await ve(e,Oe,B);if(s.kind==="missing")throw x(`unknown node: ${e}`,{received:e});if(s.kind==="terminal")throw Ke(e,s.status);return s.result}return await B()},"deliver")();g.urgency!=="deferred"&&await k(async()=>qe(e));const j=await C(e);if(j===null)throw x(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&await Y(e);let z=!1,J=!1,A;if((r.reopen||j.lifecycle==="terminal"||!await Ce(j))&&g.urgency!=="deferred"&&!i&&!q(j))try{const s=await U(e,{resume:!0,capacity:"freeze"});z=s.launch!==void 0,J=s.outcome==="frozen"}catch(s){A=Xe(s,g.messageId),Me({level:"error",event:"message.wake_failed",node_id:e,error:s,fields:{message_id:g.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:z,...J?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:g.createdAt,...g.urgency===o?{}:{delivered_tier:g.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(et,"handleMessageHere");async function tt(t){const e=t.params.id,a=await te(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(a.kind==="unknown")throw ne(e,a.unreachable);if(a.kind==="remote"){if(a.status>=400)throw re(a.status,a.body);return{status:a.status,body:oe(a.body,a.machine)}}const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=await ye(e,{senderNodeId:"human",kind:"message"});let o=!1;if(q(n))try{o=await be(e)!=="idle"}catch(c){if(!(c instanceof G))throw c}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(tt,"handleInterrupt");function ce(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw d("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw d("execution_id is required");return e}u(ce,"mailBody");async function rt(t){const e=ce(t),a=e.channel;if(a!=="wake"&&a!=="passive"&&a!=="deferred_run")throw d("channel must be wake, passive, or deferred_run");const n=await fe(t.params.id,e.execution_id,a);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...pe(o),seq:o.message.seq}}))}}}u(rt,"handleMailClaim");async function nt(t){const e=ce(t);if(!Array.isArray(e.deliveries))throw d("deliveries must be an array");const a=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw d("each delivery must be an object");const i=o;if(typeof i.delivery_id!="string"||i.delivery_id==="")throw d("delivery_id is required");if(!Number.isSafeInteger(i.attempts)||i.attempts<1)throw d("attempts must be a positive integer");if(i.disposition!=="acknowledged"&&i.disposition!=="released")throw d("disposition must be acknowledged or released");return{delivery_id:i.delivery_id,attempts:i.attempts,disposition:i.disposition}}),n=await me(t.params.id,e.execution_id,a.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(nt,"handleMailAcknowledge");const Ht=We([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:nt}]),Vt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ze},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:tt}];export{Ht as brokerMailRoutes,Ze as handleMessage,Vt as messageRoutes};