@north-light/cli 0.3.762 → 0.3.764
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/clients/attach/viewer.js +480 -480
- package/dist/core/canvas/executions.d.ts +2 -1
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/directory/person-credential.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/daemon/api/app-listener.js +12 -12
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/canvas/executions.js +4 -3
- package/packages/crouter-api/dist/core/directory/person-credential.js +25 -8
- package/packages/crouter-api/dist/core/runtime/revive.js +6 -3
- package/packages/crouter-api/dist/core/runtime/spawn.js +27 -9
- package/packages/crouter-api/dist/daemon/api/operations.js +4 -4
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -93,7 +93,8 @@ export declare function hasRunningRemoteExecution(nodeId: string): Promise<boole
|
|
|
93
93
|
export declare function hasLaunchingExecution(nodeId: string, epoch: string): Promise<boolean>;
|
|
94
94
|
/** Node ids with a live process-runner execution begun by this daemon epoch. */
|
|
95
95
|
export declare function liveProcessExecutionNodeIds(epoch: string): Promise<Set<string>>;
|
|
96
|
-
/** Every node with a live (not exited) execution row, whichever process
|
|
96
|
+
/** Every node with a live (not exited) process-runner execution row, whichever daemon process holds it. A Blaxel sandbox or a
|
|
97
|
+
* machine's broker uses no capacity on this host, so the broker cap does not count it. */
|
|
97
98
|
export declare function liveExecutionNodeIds(): Promise<Set<string>>;
|
|
98
99
|
export declare const PROFILE_PAUSE_STOP_REASON = "profile_pause";
|
|
99
100
|
/** Marks the node's live execution as stopped by a profile pause, so the exit it causes is not read as a crash. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var L=Object.defineProperty;var a=(e,t)=>L(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as p}from"./db.js";import{capturePidIdentities as g,captureLivenessSnapshot as R,recordedPidLiveness as y}from"./pid.js";import{existsSync as C,readFileSync as O}from"node:fs";import{LAUNCHER_SOCKET as P}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as m}from"../runtime/runner/delete-sandboxes.js";function u(){return new Date().toISOString()}a(u,"now");function A(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(A,"hydrate");async function X(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:A(t)}a(X,"liveExecutionForNode");class U 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 W 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 H=7340001;async function Y(e,t){return await p(async n=>{const i=u();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(${H})`).get();const s=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(s>=t.cap)throw new U(t.cap,s)}const c=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(s=>s.runner!=="process"||t.daemonEpoch!==null&&s.daemon_epoch===t.daemonEpoch&&(s.state==="launching"||y(s.pid,s.process_identity,R())!=="dead"));if(c!==void 0)throw new W(e,c.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 d=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(d,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),d})}a(Y,"beginExecution");async function j(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(j,"setExecutionLaunchJson");async function J(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(u(),e);return Number(t.changes)===1}a(J,"recordExecutionIdle");async function G(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(u(),e)}a(G,"recordExecutionAwake");async function V(e,t,n){const i=g([n])?.get(n)??null;return await p(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,u(),e,t)).changes>0)return"recorded";const c=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(c?.pid===n)return"recorded";if(process.platform==="linux"&&C(P)&&c?.pid!=null){const S=R(),d=[c.pid];for(let E=0;E<d.length;E++)d.push(...S?.childrenOf.get(d[E])??[]);if(d.includes(n))return"recorded";for(const E of d)try{const s=O(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(s)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(V,"recordExecutionPid");async function F(e,t){return await p(async n=>{const i=u(),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),m(o.node_id)),o!==void 0})}a(F,"endExecution");async function z(e,t){return await p(async n=>{const i=u(),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(z,"endLaunchingExecution");async function Q(e,t){return await F(e,t)}a(Q,"abortExecution");async function Z(e,t){return await p(async n=>{const i=u(),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),m(e)),Number(o.changes)===1})}a(Z,"endLiveExecution");async function ee(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(u(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ee,"requestExecutionStop");async function te(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(A)}a(te,"executionsWithStopRequestedBefore");async function w(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:A(t)}a(w,"latestExecutionForNode");async function ne(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(ne,"hasRunningRemoteExecution");async function ae(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(ae,"hasLaunchingExecution");async function ie(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(ie,"liveProcessExecutionNodeIds");async function oe(){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(oe,"liveExecutionNodeIds");const N="profile_pause",T="profile_pause_absorbed";async function re(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(u(),N,e)}a(re,"markProfilePauseStop");async function se(e){return(await w(e))?.stopReason===N}a(se,"hasProfilePauseStop");async function ce(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,N);return Number(t.changes)>0}a(ce,"absorbProfilePauseStop");function ue(e){return e.stopReason===T}a(ue,"hasAbsorbedProfilePauseStop");const f="exited:";async function de(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(de,"recordExecutionExit");function Ee(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(Ee,"hasObservedExit");async function pe(e){const t=await w(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]=n.slice(f.length).split(":");return{code:_===""?null:Number(_),signal:c===""?null:c}}a(pe,"takeObservedExit");export{W as ExecutionAlreadyLive,U as ExecutionCapReached,N as PROFILE_PAUSE_STOP_REASON,Q as abortExecution,ce as absorbProfilePauseStop,Y as beginExecution,F as endExecution,z as endLaunchingExecution,Z as endLiveExecution,te as executionsWithStopRequestedBefore,ue as hasAbsorbedProfilePauseStop,ae as hasLaunchingExecution,Ee as hasObservedExit,se as hasProfilePauseStop,ne as hasRunningRemoteExecution,w as latestExecutionForNode,X as liveExecutionForNode,oe as liveExecutionNodeIds,ie as liveProcessExecutionNodeIds,re as markProfilePauseStop,G as recordExecutionAwake,de as recordExecutionExit,J as recordExecutionIdle,V as recordExecutionPid,ee as requestExecutionStop,j as setExecutionLaunchJson,pe as takeObservedExit};
|
|
1
|
+
var L=Object.defineProperty;var a=(e,t)=>L(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as i,withCanvasWrite as p}from"./db.js";import{capturePidIdentities as g,captureLivenessSnapshot as R,recordedPidLiveness as y}from"./pid.js";import{existsSync as C,readFileSync as O}from"node:fs";import{LAUNCHER_SOCKET as P}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as m}from"../runtime/runner/delete-sandboxes.js";function u(){return new Date().toISOString()}a(u,"now");function A(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(A,"hydrate");async function X(e){const t=await(await i()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:A(t)}a(X,"liveExecutionForNode");class U 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 W 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 H=7340001;async function Y(e,t){return await p(async n=>{const r=u();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(${H})`).get();const s=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND runner = 'process' AND node_id != ?").get(e)).n);if(s>=t.cap)throw new U(t.cap,s)}const c=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(s=>s.runner!=="process"||t.daemonEpoch!==null&&s.daemon_epoch===t.daemonEpoch&&(s.state==="launching"||y(s.pid,s.process_identity,R())!=="dead"));if(c!==void 0)throw new W(e,c.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(r,r,e)).changes>0&&await l(n,e),await x(n,"node_id",e,r),await n.prepare("UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL").run(e);const d=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(d,e,t.daemonEpoch,r,t.runner??"process",E,t.release??null,t.launchJson??null),d})}a(Y,"beginExecution");async function j(e,t){const n=await(await i()).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(j,"setExecutionLaunchJson");async function J(e){const t=await(await i()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(u(),e);return Number(t.changes)===1}a(J,"recordExecutionIdle");async function G(e){await(await i()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(u(),e)}a(G,"recordExecutionAwake");async function V(e,t,n){const r=g([n])?.get(n)??null;return await p(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,r,u(),e,t)).changes>0)return"recorded";const c=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(c?.pid===n)return"recorded";if(process.platform==="linux"&&C(P)&&c?.pid!=null){const S=R(),d=[c.pid];for(let E=0;E<d.length;E++)d.push(...S?.childrenOf.get(d[E])??[]);if(d.includes(n))return"recorded";for(const E of d)try{const s=O(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(s)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(V,"recordExecutionPid");async function F(e,t){return await p(async n=>{const r=u(),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(r,r,t.reason,e);return await x(n,"broker_process_id",e,r),o!==void 0&&(await l(n,o.node_id),m(o.node_id)),o!==void 0})}a(F,"endExecution");async function z(e,t){return await p(async n=>{const r=u(),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(r,r,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,r),await l(n,o.node_id),!0)})}a(z,"endLaunchingExecution");async function Q(e,t){return await F(e,t)}a(Q,"abortExecution");async function Z(e,t){return await p(async n=>{const r=u(),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(r,r,t.reason,e);return await x(n,"node_id",e,r),Number(o.changes)>0&&(await l(n,e),m(e)),Number(o.changes)===1})}a(Z,"endLiveExecution");async function ee(e,t){const n=await(await i()).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(u(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ee,"requestExecutionStop");async function te(e){return(await(await i()).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(A)}a(te,"executionsWithStopRequestedBefore");async function w(e){const t=await(await i()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:A(t)}a(w,"latestExecutionForNode");async function ne(e){return await(await i()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(ne,"hasRunningRemoteExecution");async function ae(e,t){return await(await i()).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(ae,"hasLaunchingExecution");async function re(e){const t=await(await i()).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(re,"liveProcessExecutionNodeIds");async function oe(){const e=await(await i()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process'").all();return new Set(e.map(t=>t.node_id))}a(oe,"liveExecutionNodeIds");const N="profile_pause",T="profile_pause_absorbed";async function ie(e){await(await i()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(u(),N,e)}a(ie,"markProfilePauseStop");async function se(e){return(await w(e))?.stopReason===N}a(se,"hasProfilePauseStop");async function ce(e){const t=await(await i()).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,N);return Number(t.changes)>0}a(ce,"absorbProfilePauseStop");function ue(e){return e.stopReason===T}a(ue,"hasAbsorbedProfilePauseStop");const f="exited:";async function de(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await i()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(de,"recordExecutionExit");function Ee(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(Ee,"hasObservedExit");async function pe(e){const t=await w(e),n=t?.exitReason;if(t===null||n==null)return;const r=n==="out_of_memory";if(!r&&!n.startsWith(f))return;const o=await(await i()).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(r)return{code:null,signal:null,oomKilled:!0};const[_,c]=n.slice(f.length).split(":");return{code:_===""?null:Number(_),signal:c===""?null:c}}a(pe,"takeObservedExit");export{W as ExecutionAlreadyLive,U as ExecutionCapReached,N as PROFILE_PAUSE_STOP_REASON,Q as abortExecution,ce as absorbProfilePauseStop,Y as beginExecution,F as endExecution,z as endLaunchingExecution,Z as endLiveExecution,te as executionsWithStopRequestedBefore,ue as hasAbsorbedProfilePauseStop,ae as hasLaunchingExecution,Ee as hasObservedExit,se as hasProfilePauseStop,ne as hasRunningRemoteExecution,w as latestExecutionForNode,X as liveExecutionForNode,oe as liveExecutionNodeIds,re as liveProcessExecutionNodeIds,ie as markProfilePauseStop,G as recordExecutionAwake,de as recordExecutionExit,J as recordExecutionIdle,V as recordExecutionPid,ee as requestExecutionStop,j as setExecutionLaunchJson,pe as takeObservedExit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var M=Object.defineProperty;var s=(e,n)=>M(e,"name",{value:n,configurable:!0});import{createHash as N,randomBytes as R}from"node:crypto";import{renameSync as z,rmSync as b}from"node:fs";import{hostname as F}from"node:os";import{join as y}from"node:path";import{CrtrError as G,general as f}from"../errors.js";import{atomicWriteJson as A,readJsonOrNull as B}from"../fs-utils.js";import{withExclusiveDirectoryLockAsync as D}from"../exclusive-lock.js";import{secretsDir as h}from"../layout.js";import{ExitCode as L}from"../../types.js";import{northlightUnreachable as H}from"./reach.js";const k=s(()=>y(h(),"person-credential"),"personCredentialPath"),w=s(()=>y(h(),"person-bearer.json"),"personBearerPath"),I=s(()=>y(h(),"person-credential.pending"),"pendingPath"),T=s(()=>y(h(),"person-bearer.lock"),"refreshLockPath"),K=3e4,V=s(e=>N("sha256").update(e).digest("hex"),"sha256Hex"),l=s(e=>e.replace(/\/+$/,""),"trimUrl"),v=s(e=>new G("not_signed_in",e,L.USAGE,{next:"Run `crtr sys signin`, then retry."}),"notSignedIn");function m(){const e=B(k());if(!(e===null||typeof e.secret!="string"||typeof e.directoryUrl!="string"))return{directoryUrl:e.directoryUrl,secret:e.secret}}s(m,"readPersonCredential");function p(e,n){const r=e!==null&&typeof e=="object"?e:{},t=r.error;if(t!==null&&typeof t=="object"){const i=t;return{code:String(i.code??"error"),message:String(i.message??`HTTP ${n}`)}}return typeof t=="string"?{code:t,message:String(r.error_description??r.message??t)}:{code:"error",message:`the directory answered HTTP ${n}`}}s(p,"errorOf");async function g(e,n,r,t){let i;try{i=await fetch(`${l(e)}${n}`,{method:"POST",headers:{"content-type":"application/json",...t===void 0?{}:{authorization:`Bearer ${t}`}},body:JSON.stringify(r),signal:AbortSignal.timeout(3e4)})}catch(d){throw H(d,e)}const o=await i.text();let a={};try{a=o===""?{}:JSON.parse(o)}catch{}return{status:i.status,body:a}}s(g,"call");const _=s((e,n)=>{const r=p(n,e);throw f(`the directory refused: ${r.message}`,{code:r.code})},"refuse");async function W(e,n,r={}){const t=l(e),i=r.sleep??(c=>new Promise(u=>setTimeout(u,c))),o=`nld_${R(32).toString("base64url")}`,a=await g(t,"/v1/developer/logins",{credential_hash:V(o),name:F().slice(0,64),platform:process.platform==="darwin"||process.platform==="win32"?process.platform:"linux",sdk_version:"crtr",kind:"crtr"});a.status!==200&&a.status!==201&&_(a.status,a.body);const d=a.body;n({verificationUri:d.verification_uri,userCode:d.user_code,complete:d.verification_uri_complete});let P=Math.max(1,d.interval)*1e3;const J=Date.now()+d.expires_in*1e3;for(;;){if(Date.now()>J)throw f("the sign-in code expired before it was allowed: run `crtr sys signin` again",{code:"expired_token"});await i(P);const c=await g(t,"/v1/developer/logins/poll",{device_code:d.device_code});if(c.status===200){const x=c.body,$=await S(t,o),E=await r.accept?.({account:x.account,bearer:$.access_token});if(E!==void 0)throw await C(t,o),E;return A(I(),{directoryUrl:t,secret:o},{mode:384}),z(I(),k()),U(t,$),{account:x.account.display,credentialId:x.credential_id}}const u=p(c.body,c.status).code;if(!(c.status===400&&u==="authorization_pending")){if(c.status===400&&u==="slow_down"){P+=5e3;continue}if(c.status===400&&u==="access_denied")throw f("the sign-in was declined in the browser",{code:u});if(c.status===400&&u==="expired_token")throw f("the sign-in code expired before it was allowed: run `crtr sys signin` again",{code:u});_(c.status,c.body)}}}s(W,"signIn");const j=new Set(["credential_revoked","credential_expired","credential_unknown"]);async function S(e,n,r=!1){const t=await g(e,"/v1/developer/token",{},n);if(t.status===401&&j.has(p(t.body,401).code))throw r&&b(w(),{force:!0}),v(`the sign-in on this computer is no longer valid (${p(t.body,401).code})`);t.status!==200&&_(t.status,t.body);const i=t.body;if(typeof i.access_token!="string"||typeof i.expires_in!="number")throw f("the directory answered without a bearer token");const o=i.account;return{access_token:i.access_token,expires_in:i.expires_in,...typeof o?.id=="string"&&typeof o.display=="string"?{account:{id:o.id,display:o.display}}:{}}}s(S,"exchange");function U(e,n){A(w(),{directoryUrl:e,access_token:n.access_token,expires_at_ms:Date.now()+n.expires_in*1e3},{mode:384})}s(U,"writeBearer");async function O(e){const n=m();if(n===void 0)throw v("this computer is not signed in");const r=l(e??n.directoryUrl),t=s(()=>{const o=B(w());return o!==null&&o.directoryUrl===r&&typeof o.access_token=="string"&&o.expires_at_ms-Date.now()>K?o.access_token:void 0},"fresh"),i=t();return i!==void 0?i:D(T(),async()=>{const o=t();if(o!==void 0)return o;const a=await S(r,n.secret,!0);return U(r,a),a.access_token},{timeoutMs:4e4})}s(O,"personBearer");function ce(e,n){return async(r,t)=>{const i=new Headers(t?.headers);i.set("authorization",`Bearer ${await O(e)}`);try{return await fetch(r,{...t,headers:i})}catch(o){throw t?.signal?.aborted===!0?o:H(o,n)}}}s(ce,"northlightFetch");async function ae(e){const n=m();if(n===void 0)throw v("this computer is not signed in");const r=l(e??n.directoryUrl),t=await D(T(),async()=>{const i=await S(r,n.secret,!0);return U(r,i),i},{timeoutMs:4e4});if(t.account===void 0)throw f("the directory's token answer names no account");return t.account}s(ae,"personAccount");async function de(e){const n=await O(e);let r;try{r=JSON.parse(Buffer.from(n.split(".")[1]??"","base64url").toString("utf8")).aud}catch{r=void 0}const t=Array.isArray(r)?r[0]:r;if(typeof t!="string"||!/^https?:\/\//.test(t))throw f("the directory's sign-in token names no control plane (no http(s) `aud`)");return l(t)}s(de,"controlPlaneUrl");async function C(e,n){const r=await g(e,"/v1/developer/token/revoke",{},n);return r.status===200?!0:r.status===401&&j.has(p(r.body,401).code)?!1:_(r.status,r.body)}s(C,"revoke");function q(){b(k(),{force:!0}),b(w(),{force:!0})}s(q,"forgetSignIn");async function ue(){const e=m();if(e===void 0)return{signedOut:!1,revoked:!1};const n=await C(e.directoryUrl,e.secret);return q(),{signedOut:!0,revoked:n}}s(ue,"signOut");async function fe(e,n){return m()===void 0&&await W(e,n),O(e)}s(fe,"ensureSignedIn");export{de as controlPlaneUrl,fe as ensureSignedIn,q as forgetSignIn,ce as northlightFetch,v as notSignedIn,ae as personAccount,O as personBearer,w as personBearerPath,k as personCredentialPath,m as readPersonCredential,W as signIn,ue as signOut};
|
|
@@ -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 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}
|
|
1
|
+
var ue=Object.defineProperty;var o=(e,r)=>ue(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as fe}from"./unsandboxed.js";import{existsSync as W}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as J}from"../conversation-store/index.js";import{isAbsolute as we}from"node:path";import{findNodeBySessionFile as he,getNode as b,updateNode as A,beginExecution as me,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as O,endLiveExecution as ve,unbindSession as j,recordLaunch as _e,setFrozen as ye,clearFrozen as P,fullName as ke}from"../canvas/index.js";import{emitEvent as V}from"../events/emit.js";import{consumeDeadlineOnWake as ge}from"../feed/messages.js";import{isParked as B,transition as R}from"./lifecycle.js";import{publishNotice as be}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as Re,drainBearings as Ee,hasRetainedReports as xe,readGoal as x,readYieldMessage as Se,RUNTIME_RESTART_CONTINUATION as $e}from"./kickoff.js";import{readRoadmap as X}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as Y}from"../runs/initial-input.js";import{headlessBrokerHost as Fe,brokerLaunchJson as Ae}from"./host.js";import{isCloudRole as Oe}from"../canvas/person.js";import{asNodePerson as Pe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Be}from"./runner/process.js";import{runnerForEnvironment as q}from"./runner/index.js";import{MachineOfflineError as Q}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as D}from"./blaxel-environment.js";import{recordLaunchFailure as De}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Z,remoteMachineEnvironmentOf as I,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 ee,brokerCapReached as re,brokerThresholdsForDaemon as T}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 ie,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 lr}from"../canvas/paths.js";import{contextDir as cr,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 d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof J)return{};throw n}}o(mr,"resumeArgs");async function te(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof J)return!1;throw i}}o(te,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}o(pr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||W(i)}o(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await te(n))return{};const u=await he(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await mr(r,i)}o(vr,"resumableSessionArgs");async function _r(e){return await X(e)===null&&await Se(e)===null&&!await xe(e)}o(_r,"isUnstartedBirth");async function hi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await X(e);return i!==null&&i.trim()!==""}o(hi,"hasFreshGroundState");async function mi(e,r){const i=await ne(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}o(mi,"reviveNode");async function pi(e,r,i){return ne(e,{...r,viewerAttach:!0},i)}o(pi,"decideAttachRevive");async function ne(e,r,i){const t=Oe()?await b(e):null;return t===null?await ae(e,r,i):await Pe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ae(e,r,i))}o(ne,"decideRevive");async function ae(e,r,i){let t=await b(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await b(e)??t,t.run_id&&(await b(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),fe(t.grantee);const n=ee(),u=await D(t.profile_id??null)!==null||await I(t.profile_id??null)!==null,M=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 D(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await R(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(M){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await oe(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const m=await Ue();if(m&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const f=!m&&(u||await n.reserveSlot(e));let s=null;if(f&&!u){try{s=await Je(e)}catch(S){throw n.releaseReservation(e),S}s.verdict!=="admitted"&&n.releaseReservation(e)}if(s?.verdict==="too_small")throw We(s);if(!f||s?.verdict==="denied"){if(r.capacity==="refuse")throw s?.verdict==="denied"?Ke(s):re(T().automaticReviveCap,await n.occupancy());return await oe(e,t,m?{reason:"drain"}:s?.verdict==="denied"?{reason:"app_memory",free_bytes:s.free_bytes,needed_bytes:s.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:T().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)}}o(ae,"decideReviveAsCaller");async function oe(e,r,i){r.frozen_at==null&&(await ye(e,new Date().toISOString()),await ve(e,{reason:"frozen"}),V({level:"info",event:"broker.frozen",node_id:e,fields:i}))}o(oe,"freezeForWait");async function yr(e,r){const i=await D(r.profile_id??null),t=await I(r.profile_id??null)!==null;if(!(i!==null||t)&&!W(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}}o(yr,"assertRecordedCwdExists");function kr(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}.`})}o(kr,"assertCheckoutNotRemoved");async function gr(e,r){try{kr(e,r)}catch(i){throw(r.status==="active"||r.status==="idle")&&(await R(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:i.message}}}),await P(e)),i}}o(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 cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}o(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 j(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,f=r.fork_source_file;if(m&&(typeof f!="string"||!we(f)))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 s=m&&typeof f=="string";if(s&&!await te(f))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${f}`,next:`Restore ${f}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:S}=T();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const se=t!==null?q("blaxel"):n?q("machine"):Be;let w;try{w=await me(e,{daemonEpoch:ee().epoch(),...u?{}:{cap:S},...t!==null?{runner:"blaxel",release:Z()}:n?{runner:"machine",release:Z()}:{}})}catch(l){if(l instanceof ze)throw re(l.cap,l.live);if(l instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await A(e,{cycles:r.cycles});const $=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=s?{}:await vr(e,r,$,!u),k=p.resumeSessionPath!==void 0,L=k&&p.newCycle===!0,v=k&&!L,z=!k&&(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(p.resumeSessionPath)?(await x(e))?.trim():void 0,H=C!==void 0&&C!=="",le=s||z||H,G=r.cycle_pending===!0||L;await A(e,{cycle_pending:G}),r.cycle_pending=G,!s&&!k&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await j(e),r.pi_session_id=null,r.pi_session_file=null);let c,h=null;const N=o(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(s){const a=await x(e),F=_(f);if(F===null)throw new Error(`invalid fork source ${f}`);const ce=(await d().header(await d().fork(F,e))).path;c=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=N()),await qe(e,(await Ze(f))?.node_id??null)}else if(H)c=y(r,{...p,prompt:C}),h=N(),await Y(c,r);else if(v)c=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:$e}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(z){const a=(await x(e))?.trim();c=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=N(),await Y(c,r)),await ie(e)}else{const a=await Ee(r,w);c=y(r,{...p,prompt:await Re(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(c.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 ie(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(c.env[Ne]=Ce(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await R(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const U=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ge(e),await ur(e,r.grantee),await br(e,r,le),c.env={...c.env,CRTR_EXECUTION_ID:w};const K=await Ae(e,c,r.cwd);await Ge(w,K);let g;try{const a=await He(e);if(g=await se.start({executionId:w,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:K,cwd:r.cwd,resuming:v}),!u&&g.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Q)throw a;try{await R(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await be(e,"notice.crash",`Child crashed \u2014 ${ke(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 O(
|
|
3
|
+
It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await O(w,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await _e(e,new Date().toISOString()),u)return await P(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:U.explanation,outcome:"launched"};if(await de(w,e,g.pid)==="shutdown")throw await O(w,{reason:"superseded"}),Fe.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:g,faultExplanation:U.explanation,outcome:"launched"}}catch(l){throw l instanceof Q&&l.sent||(await O(w,{reason:"launch_failed"}),await De(w,l).catch($=>{V({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:$})})),l}}o(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,3 +1,3 @@
|
|
|
1
|
-
var Se=Object.defineProperty;var c=(e,r)=>Se(e,"name",{value:r,configurable:!0});import{accessSync as Ce,constants as Ee,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Pe}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as U}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as _,fullName as we,jobDir as dn,recordExecutionPid as sn,abortExecution as L,setFrozen as V}from"../canvas/index.js";import{contextDir as J,nodeAgentDir as Y}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as X,conversationStore as D}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Q}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as I}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Z,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Sn}from"../canvas/person.js";import{recordLaunch as Cn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as q,timedStep as A}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Pn,unregisteredConcreteModel as Tn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}from"./start-check.js";function R(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}c(R,"launchFailureOutcome");async function qn(e,r,o){try{return await Z.launch(e,r,o)}catch(t){try{await I(e,"crash",{reason:"launch_failed",outcome:R(t)})}catch{}const a=t.message;throw U(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}c(qn,"launchBrokerOrCrash");function Gn(e){return _n({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}c(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:s}=r.status;return{text:`exited (code ${a??"null"}, signal ${s??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:s,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}c(Vn,"notReadyDescription");async function Jn(e,r){try{await I(e,"crash",{reason:"launch_failed",outcome:R(r)})}catch{}try{Z.teardown(e)}catch{}}c(Jn,"crashAndTearDown");async function Yn(e){const r=(await D().list()).map(({conversation_id:a,path:s})=>({id:a,path:s})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}c(Yn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=X(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await D().header(t)).path}const o=await _(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=X(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await D().header(a)).path}return await Yn(r)}c(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await _(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}c(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Pn(e.model,r,e.modelExact===!0)}c(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await zn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:s,...d}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...d,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}c(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Tn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}c(ve,"assertLaunchModelRegistered");function Zn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}c(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(e);o!==null&&q("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))q(`mac_${t}`,a)}c(er,"recordStartCallTimings");async function nr(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:s}=await import("../../daemon/api/handlers/broker-ops.js");if(await Dn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Q().automaticReviveCap,runner:"machine",release:he()})}catch(l){return l instanceof ue?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),"failed")}let w;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const l=await vn(e.node_id,o,e.cwd);await En(d,l);const b=d;q("execution_setup",performance.now()-t);const[N,m]=await A("warm_and_bundle",async()=>await Promise.allSettled([A("warm_repos",async()=>await bn(await gn(),e.node_id)),A("start_bundle",async()=>{const x=e.sub??await Sn();return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:x,launchJson:l,runner:"machine"})})]));if(N.status==="rejected")throw N.reason;if(m.status==="rejected")throw m.reason;const B=m.value;w=await A("render_transaction",()=>yn(async x=>{const S=await s(e.node_id),f=await xn(x,b,e.node_id,new Date().toISOString());return await On(r,"start",{executionId:b,nodeId:e.node_id,attempt:1,release:he(),launchJson:l,cwd:e.cwd,resuming:!1,nodeToken:f,bundle:B,start:S})},{timingName:"render_tx"}))}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),await L(d,{reason:"launch_failed"}),"failed"}let y;try{y=await In(r,"start",w)}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),l instanceof Mn||l instanceof Fn&&l.sent?"uncertain":(await L(d,{reason:"launch_failed"}),"failed")}try{await er(w,y)}catch(l){v({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:l})}try{await A("record_launch",()=>Cn(e.node_id,new Date().toISOString()))}catch(l){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:l})}return"started"}c(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),s=e.root===!0,d=Zn(e.parent,a.nodeId??null,s),w=e.mode??"base",y=e.rootLifecycle??(s?"resident":"terminal"),l=s&&y==="resident",b=d===null?null:await _(d),N=e.creator===void 0||e.creator===null?null:await _(e.creator);e.nodeId!==void 0&&await Pe(e.nodeId);const m=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,B=m===void 0?null:await De(m),x=await Un([b,N,B],async p=>p?.isolated===!0||p?.run_id!=null&&(await _(p.run_id))?.isolated===!0);if(x&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=x||e.isolated===!0;if(S&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let f=S||e.worktree===!0?e.nodeId??await le():e.nodeId,M=S?e.run!==void 0&&s&&!x?e.cwd:Re(Me(e.run?.grantee??b?.grantee??"app:terminal").nodes,f):e.cwd;const h=await Qn(e.profile,d,M),W=S?null:await je(h,e.worktreeCwd??M);W!==null&&(M=W,f??=await le());const P=e.worktree===!0||W!==null,ne=e.run?.grant_id??b?.grant_id??null,T=e.run??N??b??B,re=await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:h,app:T?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:M,profileId:h}),await Xn({grantee:T?.grantee??"app:terminal",sub:T?.sub,grant_id:T?.grant_id,profile_id:h});const te=B?.node_id??null;let C,j=M;const z=P&&await ze(h)?await He(h,W??e.worktreeCwd??e.cwd,f,e.worktreeBase):void 0,H=P&&z===void 0?await Ge(h):null;try{P&&z===void 0&&(C=H!==null?await Xe(H,e.worktreeCwd??e.cwd,f,e.worktreeBase):await Ke(e.worktreeCwd??e.cwd,f,e.worktreeBase),j=C.path);const p=P?await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:j,profileId:h,app:T?.grantee??"app:terminal"})).launch,ne,e.model):re;z!==void 0&&(p.worktree=z),P&&await ve(_e(p),{cwd:j,profileId:h});const n=await Fe({kind:e.kind,mode:w,lifecycle:y,cwd:j,name:e.name??e.kind,description:e.description,parent:s?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:s?d??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:m,modelOverride:e.model===void 0?void 0:p.model,...C!==void 0?{managedWorktree:C}:{},...f!==void 0?{nodeId:f}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:p});if(o?.(n.node_id),e.forkFrom!==void 0)try{await jn(n.node_id,te??null)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const G=e.prompt!=="",ye=`${G&&e.wakeOrigin!==void 0?`${nn(e.wakeOrigin)}
|
|
1
|
+
var Ce=Object.defineProperty;var l=(e,r)=>Ce(e,"name",{value:r,configurable:!0});import{accessSync as Ee,constants as $e,existsSync as Oe}from"node:fs";import{isAbsolute as Ie,resolve as Re,join as Me}from"node:path";import{appSpace as Fe}from"../layout.js";import{ApiError as le}from"../../api/errors.js";import{spawnNode as De,forkSourceNode as Ne,currentNodeContext as Be,rootOfSpine as Pe,newNodeId as ce,preflightNodeId as Te}from"./nodes.js";import{resolveProfileOperand as Le}from"../profiles/manifest.js";import{selectProfileForCwd as Ae,selectProfileForCwdReadOnly as ze}from"../profiles/select.js";import{buildLaunchSpecAsync as ue,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as He,sandboxWorktreeRequest as Ke}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ue,rollbackManagedWorktreeAsync as Xe}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as qe,rollbackManagedWorktreeOnMachine as Ge,worktreeMachineOf as Ve}from"../worktree-machine.js";import{usage as v,brokerLaunchFailed as q}from"../errors.js";import{InputError as Je}from"../io.js";import{isCloudRole as Ye}from"../canvas/person-state.js";import{writeGoal as Qe}from"./kickoff.js";import{appendSituationalContext as Ze,formatSituationalProse as en}from"./situational-context.js";import{ensureRoadmap as nn}from"./roadmap.js";import{buildWakeBearings as rn}from"./bearings.js";import{encodeKickoffOrigin as tn,KICKOFF_ORIGIN_ENV as on}from"./stamp/protocol.js";import{carryInitialInput as an}from"../runs/initial-input.js";import{ExecutionCapReached as dn,beginExecution as fe,crtrHome as sn,getNode as w,fullName as we,jobDir as ln,recordExecutionPid as cn,abortExecution as z,setFrozen as Y}from"../canvas/index.js";import{contextDir as Q,nodeAgentDir as Z}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as un}from"../spaces/open-beneath.js";import{conversationIdFromPath as G,conversationStore as R}from"../conversation-store/index.js";import{appMemoryTooSmall as fn,boundFleet as me,brokerThresholdsForDaemon as he}from"./fleet.js";import{admitBrokerMemory as wn}from"./memory-admission.js";import{emitEvent as k}from"../events/emit.js";import{remoteEnvironmentOf as mn}from"./blaxel-environment.js";import{openViewerWindow as hn,focusOf as pn,windowOfPane as _n}from"./placement.js";import{awaitBrokerViewSocket as kn}from"./view-socket.js";import{readLogSnapshot as vn}from"../events/read.js";import{transition as M}from"./lifecycle.js";import{beginBootFaultAttempt as gn}from"../canvas/recovery.js";import{headlessBrokerHost as ee,brokerLaunchJson as yn}from"./host.js";import{openDb as bn,withCanvasWrite as xn}from"../canvas/db.js";import{warmNodeRepos as Sn}from"../graph/reader.js";import{mintNodeToken as Cn}from"../canvas/node-tokens.js";import{personIdAsync as En}from"../canvas/person.js";import{recordLaunch as $n}from"../canvas/canvas.js";import{setExecutionLaunchJson as On}from"../canvas/executions.js";import{acceptedRelease as pe,remoteMachineEnvironmentOf as In}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as Rn,awaitMachineCall as Mn,callTimes as Fn}from"./runner/machine/call.js";import{addStepTiming as V,timedStep as W}from"../step-timings.js";import{MachineLostError as Dn,MachineOfflineError as Nn}from"./runner/machine/ops.js";import{isDrained as Bn}from"../../daemon/drain.js";import{ensureDaemon as Pn}from"../../daemon/manage.js";import{readConfig as Tn}from"../config.js";import{modelRequestFromConfig as Ln,unregisteredConcreteModel as An,unroutableConcreteModel as zn}from"../model-routes.js";import{openModelRegistry as Wn}from"./model-registry.js";import{MODEL_SPEC_NEXT as jn}from"./model-selection.js";import{forkNodeLedger as Hn}from"./ledger.js";import{appRungForGrant as Kn}from"../llm/app-rungs.js";import{APP_FAMILY as ne}from"../model-routes.js";import{discoverLifecycleHookRegistry as Un}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Xn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as qn}from"../async-array.js";import{checkStart as Gn}from"./start-check.js";function F(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(F,"launchFailureOutcome");async function Vn(e,r,t){try{return await ee.launch(e,r,t)}catch(o){try{await M(e,"crash",{reason:"launch_failed",outcome:F(o)})}catch{}const a=o.message;throw q(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}l(Vn,"launchBrokerOrCrash");function Jn(e){return vn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(t=>t.kind==="event"&&t.envelope.event.startsWith("broker.startup.")&&t.envelope.event!=="broker.startup.warning"?[t.envelope.event.slice(15)]:[]).at(-1)??null}l(Jn,"lastStartupStep");function Yn(e,r){const t=Jn(e),o=t===null?"it had logged no startup step":`the last startup step it logged was \`${t}\``;if(r.reason==="exited"){const{code:a,signal:d}=r.status;return{text:`exited (code ${a??"null"}, signal ${d??"null"}) before binding its view socket; ${o}`,fields:{reason:"exited",code:a,signal:d,last_startup_step:t}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${o}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:t}}}l(Yn,"notReadyDescription");async function Qn(e,r){try{await M(e,"crash",{reason:"launch_failed",outcome:F(r)})}catch{}try{ee.teardown(e)}catch{}}l(Qn,"crashAndTearDown");async function Zn(e){const r=await R().header(e).then(d=>d.path,()=>null);if(r!==null)return r;const t=(await R().list()).map(({conversation_id:d,path:s})=>({id:d,path:s})),o=t.filter(d=>d.id===e),a=o.length>0?o:t.filter(d=>d.id.startsWith(e));if(a.length===0)throw v(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(a.length>1)throw v(`--fork-from '${e}': ambiguous \u2014 ${a.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return a[0].path}l(Zn,"resolveSessionUuid");async function _e(e){const r=e.trim();if(r==="")throw v("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const o=G(Ie(r)?r:Re(process.cwd(),r));if(o===null)throw v(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await R().header(o)).path}const t=await w(r);if(t!==null){const o=t.pi_session_file;if(o==null||o==="")throw v(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=G(o);if(a===null)throw v(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await R().header(a)).path}return await Zn(r)}l(_e,"resolveForkSource");async function er(e,r,t,o={}){return e===null?null:e!==void 0&&e!==""?Le(e).profileId:r!==null?(await w(r))?.profile_id??null:o.readOnlySelection===!0?ze(t):Ae(t)}l(er,"resolveProfileId");function ke(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Ln(e.model,r,e.modelExact===!0)}l(ke,"requestFromLaunch");async function ve(e,r,t){const o=t??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await Kn(r,o,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:d,...s}=e.env??{};return{...e,model:a.model,modelIntent:{family:ne,strength:a.strength},modelExact:void 0,env:{...s,CRTR_MODEL_INTENT:`${ne}/${a.strength}`}}}l(ve,"appPaidLaunch");async function ge(e,r,t){if(e===void 0||e.kind==="logical"&&e.family!==ne)return;const o=await An(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,t??await Wn(),r);if(o!==void 0)throw v(`model '${o.request.spec}' is not registered in this daemon.`,{received:o.request.spec,next:jn});const a=await zn(e,r);if(a!==void 0)throw v(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(ge,"assertLaunchModelRegistered");function nr(e,r,t){const o=e??r??null;if(!t&&o===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return o}l(nr,"resolveSpawner");async function rr(e,r){const t=await Fn(e);t!==null&&V("start_enqueue_to_answer",t.finishedAt-t.createdAt);for(const[o,a]of Object.entries(r?.timings??{}))V(`mac_${o}`,a)}l(rr,"recordStartCallTimings");async function tr(e,r,t){const o=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:d}=await import("../../daemon/api/handlers/broker-ops.js");if(await Bn())return"full";let s;try{s=await fe(e.node_id,{daemonEpoch:me().epoch(),runner:"machine",release:pe()})}catch(c){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),"failed"}let m;try{t.env={...t.env,CRTR_EXECUTION_ID:s};const c=await yn(e.node_id,t,e.cwd);await On(s,c);const b=s;V("execution_setup",performance.now()-o);const[P,h]=await W("warm_and_bundle",async()=>await Promise.allSettled([W("warm_repos",async()=>await Sn(await bn(),e.node_id)),W("start_bundle",async()=>{const x=e.sub??await En();return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:x,launchJson:c,runner:"machine"})})]));if(P.status==="rejected")throw P.reason;if(h.status==="rejected")throw h.reason;const T=h.value;m=await W("render_transaction",()=>xn(async x=>{const S=await d(e.node_id),f=await Cn(x,b,e.node_id,new Date().toISOString());return await Rn(r,"start",{executionId:b,nodeId:e.node_id,attempt:1,release:pe(),launchJson:c,cwd:e.cwd,resuming:!1,nodeToken:f,bundle:T,start:S})},{timingName:"render_tx"}))}catch(c){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),await z(s,{reason:"launch_failed"}),"failed"}let y;try{y=await Mn(r,"start",m)}catch(c){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:c}),c instanceof Dn||c instanceof Nn&&c.sent?"uncertain":(await z(s,{reason:"launch_failed"}),"failed")}try{await rr(m,y)}catch(c){k({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:c})}try{await W("record_launch",()=>$n(e.node_id,new Date().toISOString()))}catch(c){k({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:c})}return"started"}l(tr,"startOnMachine");async function ye(e,r,t){const o=performance.now();try{Pn()}catch{}const a=Be(),d=e.root===!0,s=nr(e.parent,a.nodeId??null,d),m=e.mode??"base",y=e.rootLifecycle??(d?"resident":"terminal"),c=d&&y==="resident",b=s===null?null:await w(s),P=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Te(e.nodeId);const h=e.forkFrom!==void 0?await _e(e.forkFrom):void 0,T=h===void 0?null:await Ne(h),x=await qn([b,P,T],async _=>_?.isolated===!0||_?.run_id!=null&&(await w(_.run_id))?.isolated===!0);if(x&&e.isolated===!1)throw new le(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=x||e.isolated===!0;if(S&&e.worktree===!0)throw new le(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let f=S||e.worktree===!0?e.nodeId??await ce():e.nodeId,D=S?e.run!==void 0&&d&&!x?e.cwd:Me(Fe(e.run?.grantee??b?.grantee??"app:terminal").nodes,f):e.cwd;const p=await er(e.profile,s,D),j=S?null:await je(p,e.worktreeCwd??D);j!==null&&(D=j,f??=await ce());const L=e.worktree===!0||j!==null,re=e.run?.grant_id??b?.grant_id??null,A=e.run??P??b??T,te=await ve((await ue(e.kind,m,{lifecycle:y,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:D,profileId:p,app:A?.grantee??"app:terminal"})).launch,re,e.model);await ge(ke(te),{cwd:D,profileId:p}),await Gn({grantee:A?.grantee??"app:terminal",sub:A?.sub,grant_id:A?.grant_id,profile_id:p});const oe=T?.node_id??null;let C,H=D;const K=L&&await He(p)?await Ke(p,j??e.worktreeCwd??e.cwd,f,e.worktreeBase):void 0,U=L&&K===void 0?await Ve(p):null;try{L&&K===void 0&&(C=U!==null?await qe(U,e.worktreeCwd??e.cwd,f,e.worktreeBase):await Ue(e.worktreeCwd??e.cwd,f,e.worktreeBase),H=C.path);const _=L?await ve((await ue(e.kind,m,{lifecycle:y,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:H,profileId:p,app:A?.grantee??"app:terminal"})).launch,re,e.model):te;K!==void 0&&(_.worktree=K),L&&await ge(ke(_),{cwd:H,profileId:p});const n=await De({kind:e.kind,mode:m,lifecycle:y,cwd:H,name:e.name??e.kind,description:e.description,parent:d?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:oe,spawnedBy:d?s??void 0:void 0,profile_id:p,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:h,modelOverride:e.model===void 0?void 0:_.model,...C!==void 0?{managedWorktree:C}:{},...f!==void 0?{nodeId:f}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:_});if(t?.(n.node_id),e.forkFrom!==void 0)try{await Hn(n.node_id,oe??null)}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}if(await Qe(n.node_id,e.prompt),e.situationalContext!==void 0&&await Ze(n.node_id,en(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}const J=e.prompt!=="",be=`${J&&e.wakeOrigin!==void 0?`${rn(e.wakeOrigin)}
|
|
2
2
|
|
|
3
|
-
`:""}${e.prompt}`;
|
|
3
|
+
`:""}${e.prompt}`;m==="orchestrator"&&await nn(n.node_id,{goal:e.prompt.trim()}),await or(n);let ie;if(h!==void 0)try{const i=G(h);if(i===null)throw new Error(`invalid fork source ${h}`);const u=await R().fork(i,n.node_id);ie=(await R().header(u)).path}catch(i){throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}const g=We(n,{prompt:be,resumeSessionPath:ie});if(g.env={...g.env,CRTR_SUBTREE:await Pe(n.node_id)},J){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[on]=tn(i),await an(g,n)}const E=me();if(await mn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await In(n.profile_id??null):null;if(u!==null){V("birth",performance.now()-o);const B=await tr(n,u,g);if(B==="started"||B==="uncertain")return{node:n,frozen:!1,window:null,session:null}}let O=!1;if(u===null)try{const{reviveNode:B}=await import("./revive.js");O=(await B(n.node_id,{resume:!0,capacity:"freeze",recovery:!0})).outcome!=="frozen"}catch(B){k({level:"warn",event:"broker.create_start_failed",node_id:n.node_id,error:B})}const I=await w(n.node_id);return O?{node:I,frozen:!1,window:null,session:null}:I.frozen_at!=null||I.status!=="active"&&I.status!=="idle"?{node:I,frozen:I.frozen_at!=null,window:null,session:null}:(await Y(n.node_id,i),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...I,frozen_at:i},frozen:!0,window:null,session:null})}if(Ye()&&!Oe(n.cwd))throw new Je({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ae=await E.reserveSlot(n.node_id),$=ae?await wn(n.node_id):null;if($?.verdict==="too_small"){E.releaseReservation(n.node_id);const i=fn($);throw await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),i}if(!ae||$?.verdict==="denied")return $?.verdict==="denied"&&E.releaseReservation(n.node_id),await Y(n.node_id,new Date().toISOString()),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:$?.verdict==="denied"?{reason:"app_memory",free_bytes:$.free_bytes,needed_bytes:$.needed_bytes}:{reason:"broker_cap",live_count:await E.occupancy(),hard_cap:he().automaticReviveCap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null};const xe=await gn(n.node_id),{automaticReviveCap:Se}=he();let N;try{N=await fe(n.node_id,{daemonEpoch:E.epoch(),cap:Se})}catch(i){if(!(i instanceof dn))throw i;return E.releaseReservation(n.node_id),await Y(n.node_id,new Date().toISOString()),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null}}g.env={...g.env,CRTR_EXECUTION_ID:N};let X;try{X=await Vn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await z(N,{reason:"launch_failed"}),i}finally{E.releaseReservation(n.node_id)}if(X.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await z(N,{reason:"launch_failed"}),await M(n.node_id,"crash",{reason:"launch_failed",outcome:F(i)}),q(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await cn(N,n.node_id,X.pid)==="shutdown")throw await z(N,{reason:"superseded"}),ee.teardown(n.node_id),q(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(c&&e.readiness==="await"){const i=await kn(n.node_id,X.exited);if(!i.ready){const u=Yn(n.node_id,i);k({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const O=await xe.explanation();throw await Qn(n.node_id,new Error(O??u.text)),q(O!==null?`the root broker ${n.node_id} could not start \u2014 ${O}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,O!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let de=null,se=null;if(!d&&s!==null&&Tn("user").auto_open_child_viewers)try{const i=await pn(s);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await hn(n.node_id,i.session??"",{name:we(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:J});u!==null&&u.pane!==null&&u.pane!==""&&(se=u.session,de=_n(u.pane))}}catch{}return{node:await w(n.node_id),frozen:!1,window:de,session:se}}catch(_){throw C!==void 0&&f!==void 0&&await w(f)===null&&(U!==null?await Ge(U,C):await Xe(C)),_}}l(ye,"spawnChildPrepared");async function ft(e){return ye(e)}l(ft,"spawnChild");async function or(e){const r=Un(e.cwd,e.profile_id).plans.get("node:start")??[];await Xn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await Z(e.node_id),contextDir:await Q(e.node_id),jobDir:ln(e.node_id)},runtime:{isBirth:!0,canvasHome:sn(),profile:e.profile_id??null}})}l(or,"invokeBirthLifecycleHooks");const ir=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function wt(e,r,t){const o=await w(e);if(o===null)throw v(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await _e(e),d=await Q(e);try{await R().header(G(a)),Ee(d,$e.R_OK)}catch(s){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${s.message}`)}return ye({kind:o.kind,mode:"base",cwd:o.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...t===void 0?{}:{actor:t},profile:o.profile_id,model:o.model_override??void 0,...r===void 0?{}:{scopes:r}},async s=>{const m=await Q(s);un(await Z(e),d,await Z(s),m,ir)})}l(wt,"forkNode");export{ve as appPaidLaunch,ge as assertLaunchModelRegistered,wt as forkNode,or as invokeBirthLifecycleHooks,_e as resolveForkSource,er as resolveProfileId,nr as resolveSpawner,ft as spawnChild,ye as spawnChildPrepared};
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var ee=Object.defineProperty;var i=(e,n)=>ee(e,"name",{value:n,configurable:!0});import{AsyncResource as te}from"node:async_hooks";import{randomUUID as ne}from"node:crypto";import{createServer as re}from"node:http";import{Router as z,causedByOf as ae}from"./router.js";import{toErrorBody as oe}from"./map.js";import{
|
|
1
|
+
var ee=Object.defineProperty;var i=(e,n)=>ee(e,"name",{value:n,configurable:!0});import{AsyncResource as te}from"node:async_hooks";import{randomUUID as ne}from"node:crypto";import{createServer as re}from"node:http";import{Router as z,causedByOf as ae}from"./router.js";import{toErrorBody as oe}from"./map.js";import{appEnvironmentRoutes as ie}from"./handlers/app-environments.js";import{objectRoutes as se}from"./handlers/objects.js";import{customObjectRoutes as ue}from"./handlers/custom-objects.js";import{checkRoutes as de}from"./handlers/check.js";import{chargeRoutes as ce}from"./handlers/charges.js";import{docRoutes as le}from"./handlers/docs.js";import{relationRoutes as me}from"./handlers/relations.js";import{schemaRoutes as fe}from"./handlers/schemas.js";import{OPERATIONS as pe}from"./operations.js";import{runtimeReadiness as he}from"../readiness.js";import{errorCodes as G}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as we,RUNTIME_VERSION_HEADER as ye,minimumRuntimeRefusal as _e}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ge,CONTRACT_LEVEL as Y,REQUIRED_CONTRACT_HEADER as ve,contractRefusal as Re}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as Oe,parseTraceparent as be}from"../../shared/traceparent.js";import{AppPrincipalResolver as Ee,grantIdOf as L}from"./principal.js";import{isDaemonRoute as Ae,runtimeOwner as Se,servePeer as F}from"../peer/ingress.js";import{applySyncNotice as Te}from"./sync-notice.js";import{ownMachineId as Ne}from"../../core/peer/directory.js";import{handleRunOperation as Ce,integer as Ie}from"./handlers/runs.js";import{runAnthropicMessages as Pe}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as ke,parseLlmRequest as Me,runLlm as He}from"../../core/llm/run.js";import{parseUsageMonth as De,usageFor as Be}from"../../core/ledger/index.js";import{capFields as xe}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as Q,MODEL_CONTEXT_BODY_MAX_BYTES as W}from"../../core/llm/body-limits.js";import{RunError as m,cloudPersonScope as je,runIsRunning as Je}from"../../core/runs/operations.js";import{requireRun as U}from"./router.js";import{deferHead as Le}from"./deferred-head.js";import{readRunEvents as q,registerGrantStream as Ue,subscribeRunEvents as Xe}from"../../core/runs/events.js";import{activeGrant as K,payerOfGrant as $e}from"../../core/grants/mirror.js";async function Ve(e){if(await $e(e)==="app")throw new m(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Ve,"appPaidGone");import{releaseGrantWaiters as ze}from"../../core/grants/watch.js";import{emitEvent as Ge}from"../../core/events/emit.js";import{runNotices as Ye}from"../run-notices.js";import{handleRuntimeSignIn as Fe,isRuntimeSignInPath as Qe}from"./key-signin.js";import{listAppProfiles as We}from"./handlers/app-profiles.js";import{handleTransferOperation as qe,TRANSFER_OPERATIONS as Ke}from"./handlers/transfer.js";import{handleQuestionOperation as Ze,QUESTION_OPERATIONS as et}from"./handlers/questions.js";import{removeVendorAccount as tt,vendorStatus as nt}from"./handlers/vendor-status.js";import{handleMemoryOperation as rt,MEMORY_OPERATIONS as at}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as ot,handleExec as it}from"./handlers/exec.js";import{abortOnClose as X,callerFromApp as st,handleProviderOperation as ut,PROVIDER_OPERATIONS as dt,providerFailure as ct}from"./handlers/providers.js";function lt(e){return Object.prototype.hasOwnProperty.call(G,e)?G[e]:void 0}i(lt,"fixedRow");function mt(e){const n=lt(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(mt,"errorType");function ft(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(ft,"appDetails");function x(e,n,o){const c=ft(e.details);return{error:{code:e.code,message:e.message,...c===void 0?{}:{details:c},type:mt(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...xe(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(x,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function pt(e,n,o,c,d){const y=n instanceof m?n:new m(500,"server_failure","runtime request failed");if(n instanceof m||console.error("[app-listener]",`trace_id=${c}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
|
|
2
2
|
data: ${JSON.stringify(x(y,o,d))}
|
|
3
3
|
|
|
4
|
-
`);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(
|
|
4
|
+
`);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(pt,"fail");function $(e){return Array.isArray(e)?e[0]:e}i($,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function Z(e,n=Q){const o=[];let c=0;for await(const d of e){if(c+=d.length,c>n)throw new m(400,"invalid_request","request body too large");o.push(d)}return Buffer.concat(o)}i(Z,"rawBodyOf");async function I(e,n=Q){const o=await Z(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new m(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function ht(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new m(400,"invalid_request","invalid cursor","after");return Ie(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(ht,"cursor");function wt(e){return`id: ${e.sequence_number}
|
|
5
5
|
event: ${e.type}
|
|
6
6
|
data: ${JSON.stringify(e)}
|
|
7
7
|
|
|
8
|
-
`}i(
|
|
8
|
+
`}i(wt,"frame");const yt=6e4;async function _t(e,n,o,c,d,y,S,O={},r){await U(c,o);let t=await q(o,d);if(d>t.latest_sequence)throw new m(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new m(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":S==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),S==="sse"?n.write(`: connected
|
|
9
9
|
|
|
10
|
-
`):n.flushHeaders();let p=d;const _=await
|
|
11
|
-
data: ${JSON.stringify(x(
|
|
10
|
+
`):n.flushHeaders();let p=d;const _=await Ye().streamOpened(o);let v=!1,T=!1,N=!1,b;const h=new Promise(f=>{b=f}),R=i(()=>{v||(v=!0,_(p).catch(f=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],f)),clearInterval(B),clearInterval(M),C(),u(),n.off("close",R),n.off("drain",a),n.end(),b())},"end"),a=i(()=>{N=!1,E()},"onDrain"),H=i(f=>{v||n.write(S==="sse"?`event: error
|
|
11
|
+
data: ${JSON.stringify(x(f,y,o))}
|
|
12
12
|
|
|
13
|
-
`:`${JSON.stringify({type:"error",...x(
|
|
14
|
-
`),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await U(c,o),t=await q(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new
|
|
15
|
-
`),p=
|
|
13
|
+
`:`${JSON.stringify({type:"error",...x(f,y,o)})}
|
|
14
|
+
`),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await U(c,o),t=await q(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new m(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const f of t.events){if(N)break;N=!n.write(S==="sse"?wt(f):`${JSON.stringify(f)}
|
|
15
|
+
`),p=f.sequence_number}}catch(f){H(f instanceof m?f:new m(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new m(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in c||c.grant===null||await K(c.grant)!==null,"grantActive"),C=await Xe(o,te.bind(E)),u="class"in c||c.grant===null?()=>{}:Ue(c.grant,P),B=setInterval(()=>{!v&&!N&&S==="sse"&&n.write(`: keepalive
|
|
16
16
|
|
|
17
|
-
`)},15e3),s=O.idleMs??
|
|
17
|
+
`)},15e3),s=O.idleMs??yt,w=O.isRunning??Je;let l=Date.now(),A=p;const k=i(async()=>{if(v||S!=="sse")return;const f=Date.now();let V=!0;try{V=await w(o)}catch{}if(!v){if(V||p!==A){l=f,A=p;return}f-l<s||N||(n.write(`event: idle
|
|
18
18
|
data: {}
|
|
19
19
|
|
|
20
|
-
`),R())}},"checkIdle"),M=setInterval(()=>{k().catch(
|
|
20
|
+
`),R())}},"checkIdle"),M=setInterval(()=>{k().catch(f=>Ge({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},O.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await E(),h}i(_t,"streamRunEvents");function gt(e,n,o,c={}){const d=new z,y=new Map;for(const r of pe.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const S=new z().registerAll(se).registerAll(ue).registerAll(le).registerAll(fe).registerAll(me).registerAll(de).registerAll(ce).registerAll(ie);return i((r,t,p)=>(async()=>{Le(r,t,c.deferHead);const _=ne();t.setHeader("Request-Id",_);const v=be($(r.headers.traceparent))??Oe();t.setHeader(ye,J()),t.setHeader(ge,Y);let T;try{const N=$(r.headers[we.toLowerCase()]),b=_e(N,J())??Re($(r.headers[ve.toLowerCase()]),Y,{legacyMinimum:N,runtimeVersion:J()});if(b!==null)throw b.status===400?new m(400,b.code,b.message,b.param):new m(426,b.code,b.message,void 0,b.details);const h=new URL(r.url??"/","http://runtime.local");if(Qe(h.pathname)){await Fe(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?y.get(R.handler):void 0,H=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let E,P;if(p!==void 0)E=p;else if(!H&&r.headers.authorization!==void 0)try{E=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Se,self:Ne,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(E?.chain[0]?.sub.startsWith("runtime:")){await F(r,t,D,E);return}if(E===void 0&&a===void 0&&await Ae(r.method??"GET",h.pathname)){await F(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),w=await he({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,w.ready?200:503,w);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new m(503,"runtime_starting","runtime_starting");if(!R||!a)throw new m(404,"not_found","unknown operation");T=R.params.run_id;const C=ae(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Te(await e.verifySyncNotice(r.headers.authorization),o,_),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await nt());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await tt(await I(r)));return}if(E===void 0)throw P??new m(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(E,a.scope);if(t.setHeader("Request-Id",_),T&&await U(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=S.match(a.method,h.pathname);if(!s)throw new m(404,"not_found","unknown operation");const w={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let l;try{l=await s.handler(w)}catch(A){const{status:k,body:M}=oe(A);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,A),new m(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(l.rawBody!==void 0||l.status===204||l.body===void 0){t.writeHead(l.status,l.headers??{}),t.end(l.rawBody);return}t.writeHead(l.status,{"Content-Type":"application/json; charset=utf-8",...l.headers??{}}),t.end(JSON.stringify(l.body));return}if(a.stream){await _t(r,t,T,u,ht(r,h.searchParams),_,"sse",c.stream,v);return}if(a.name==="llm"){const s=Me(await I(r,W)),w=new AbortController,l=i(()=>w.abort(),"abort");t.on("close",l);try{const A=await He(s,w.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
|
|
21
21
|
|
|
22
|
-
`)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},
|
|
22
|
+
`)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},ke(await K(L(u))??await Ve(L(u))),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
|
|
23
23
|
|
|
24
|
-
`)):g(t,200,A.completion)}finally{t.off("close",l)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=X(t);try{await
|
|
24
|
+
`)):g(t,200,A.completion)}finally{t.off("close",l)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=X(t);try{await Pe(await Z(r,W),r.headers,s,{grant:L(u),sub:u.sub,grantee:u.grantee,request:_,...C===void 0?{}:{causedBy:C}},t)}finally{w()}return}if(a.name==="exec"){const{signal:s,release:w}=X(t);try{g(t,200,await it(u,await I(r,ot),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await Be(u.grantee,De(h.searchParams.get("month")),je(u.sub)));return}if(a.name==="profile.list"){g(t,200,await We(u));return}if(et.has(a.name)){const s=await Ze(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(dt.has(a.name)){const{signal:s,release:w}=X(t);try{const l=await ut(a.name,st(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:_,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,l.status,l.body)}catch(l){const A=ct(l,_,!0);t.writeHead(A.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...A.headers}),t.end(JSON.stringify(A.body))}finally{w()}return}if(at.has(a.name)){const s=await rt(a.name,{class:"app",app:u.grantee,sub:u.sub,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(Ke.has(a.name)){const s=await qe(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Ce(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,B.status,B.body)}catch(N){pt(t,N,_,v,T)}})(),"handle")}i(gt,"createAppRequestHandler");async function pn(e,n,o,c={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<0||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const y=new Ee(e.issuer,e.audience,o,e.jwksUrl),S=gt(y,n,o,c),O=re((t,p)=>{S(t,p)});return{ready:new Promise((t,p)=>{O.once("error",p),O.listen(d.port,d.address,()=>{O.off("error",p),t()})}),port:i(()=>O.address().port,"port"),close:i(async()=>{y.close(),ze(),O.closeAllConnections(),await new Promise((t,p)=>O.close(_=>_?p(_):t()))},"close")}}i(pn,"createAppListener");export{yt as RUN_STREAM_IDLE_MS,pn as createAppListener,gt as createAppRequestHandler,ht as cursor,_t as streamRunEvents};
|