@north-light/cli 0.3.708 → 0.3.709

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.
Files changed (118) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/crons.d.ts +3 -0
  4. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  5. package/dist/clients/attach/chrome/roster.js +6 -6
  6. package/dist/clients/attach/chrome/status-line.d.ts +1 -1
  7. package/dist/clients/attach/chrome/status-line.js +1 -1
  8. package/dist/clients/attach/input/capabilities.js +1 -1
  9. package/dist/clients/attach/input/controller.d.ts +4 -0
  10. package/dist/clients/attach/input/controller.js +3 -3
  11. package/dist/clients/attach/overlays/graph.d.ts +3 -2
  12. package/dist/clients/attach/overlays/graph.js +1 -1
  13. package/dist/clients/attach/render/chat-view.d.ts +2 -0
  14. package/dist/clients/attach/render/chat-view.js +1 -1
  15. package/dist/clients/attach/render/doc-links.d.ts +1 -1
  16. package/dist/clients/attach/session/chrome-refresh.js +1 -1
  17. package/dist/clients/attach/session/connection.d.ts +10 -9
  18. package/dist/clients/attach/session/connection.js +1 -1
  19. package/dist/clients/attach/session/context.d.ts +1 -1
  20. package/dist/clients/attach/session/document-links.d.ts +1 -1
  21. package/dist/clients/attach/session/document-links.js +1 -1
  22. package/dist/clients/attach/session/identity.d.ts +2 -0
  23. package/dist/clients/attach/session/identity.js +1 -1
  24. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  25. package/dist/clients/attach/session/input-wiring.js +1 -1
  26. package/dist/clients/attach/session/keys.d.ts +2 -0
  27. package/dist/clients/attach/session/keys.js +1 -1
  28. package/dist/clients/attach/session/pane-tag.d.ts +3 -1
  29. package/dist/clients/attach/session/pane-tag.js +1 -1
  30. package/dist/clients/attach/session/reconnect.js +1 -1
  31. package/dist/clients/attach/session/teardown.d.ts +2 -2
  32. package/dist/clients/attach/session/teardown.js +9 -7
  33. package/dist/clients/attach/viewer.d.ts +7 -5
  34. package/dist/clients/attach/viewer.js +540 -538
  35. package/dist/commands/node/wait.js +2 -6
  36. package/dist/core/broker-client/client.d.ts +6 -3
  37. package/dist/core/broker-client/client.js +1 -1
  38. package/dist/core/canvas/crons.d.ts +11 -1
  39. package/dist/core/canvas/crons.js +14 -14
  40. package/dist/core/canvas/executions.js +1 -1
  41. package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
  42. package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
  43. package/dist/core/canvas/schema-version.d.ts +1 -1
  44. package/dist/core/canvas/schema-version.js +1 -1
  45. package/dist/core/command.js +5 -5
  46. package/dist/core/feed/messages.d.ts +5 -0
  47. package/dist/core/feed/messages.js +5 -5
  48. package/dist/core/runtime/bearings.js +4 -4
  49. package/dist/core/runtime/boot-root.js +4 -4
  50. package/dist/core/runtime/lifecycle.js +2 -2
  51. package/dist/core/runtime/revive.js +2 -2
  52. package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
  53. package/dist/core/runtime/runner/blaxel/client.js +1 -1
  54. package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
  55. package/dist/core/runtime/runner/blaxel/runner.js +3 -3
  56. package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
  57. package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
  58. package/dist/core/runtime/runner/types.d.ts +19 -3
  59. package/dist/daemon/api/bridge.d.ts +5 -0
  60. package/dist/daemon/api/bridge.js +3 -3
  61. package/dist/daemon/api/handlers/crons.d.ts +2 -0
  62. package/dist/daemon/api/handlers/crons.js +1 -1
  63. package/dist/daemon/api/handlers/nodes.js +1 -1
  64. package/dist/daemon/api/operations.js +1 -1
  65. package/dist/daemon/cron/ended.d.ts +3 -0
  66. package/dist/daemon/cron/ended.js +2 -2
  67. package/dist/daemon/cron/lease-recovery.js +1 -1
  68. package/dist/daemon/cron/machine-fire.d.ts +9 -2
  69. package/dist/daemon/cron/machine-fire.js +1 -1
  70. package/dist/daemon/cron/passes.js +1 -1
  71. package/dist/daemon/cron-run.js +2 -2
  72. package/dist/daemon/machine-link/client.js +1 -1
  73. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  74. package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
  75. package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
  76. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  77. package/package.json +3 -3
  78. package/packages/crouter-api/dist/api/contract.js +1 -1
  79. package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
  80. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
  81. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
  82. package/packages/crouter-api/dist/clients/attach/input/capabilities.js +2 -1
  83. package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
  84. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
  85. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
  86. package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
  87. package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
  88. package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
  89. package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
  90. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
  91. package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
  92. package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
  93. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
  94. package/packages/crouter-api/dist/clients/attach/session/teardown.js +7 -4
  95. package/packages/crouter-api/dist/clients/attach/viewer.js +77 -30
  96. package/packages/crouter-api/dist/commands/node/wait.js +2 -10
  97. package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
  98. package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
  99. package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
  100. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  101. package/packages/crouter-api/dist/core/command.js +3 -0
  102. package/packages/crouter-api/dist/core/feed/messages.js +15 -0
  103. package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
  104. package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
  105. package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
  106. package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
  107. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
  108. package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
  109. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  110. package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
  111. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
  112. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  113. package/packages/crouter-api/package.json +1 -1
  114. package/packages/crouter-identity/package.json +1 -1
  115. package/packages/crouter-plugin/package.json +3 -3
  116. package/runtime.lock.json +14 -14
  117. package/dist/core/runtime/starting-screen.d.ts +0 -12
  118. package/dist/core/runtime/starting-screen.js +0 -9
@@ -1,7 +1,7 @@
1
- var x=Object.defineProperty;var p=(e,o)=>x(e,"name",{value:o,configurable:!0});import{inTmux as b,currentTmux as w}from"./placement-tmux.js";import{selectProfileForCwd as g}from"../profiles/select.js";import{cliClient as c}from"../../commands/api-client.js";import{mark as s}from"../timing.js";import{handle as T}from"../io.js";import{loadedPersonSettings as k}from"../../commands/person-settings.js";import{showStartingScreen as C}from"./starting-screen.js";import{printComeBackNote as l}from"./come-back-note.js";function h(e,o){const i=e.kind;return{...i!==void 0?{kind:i}:{},mode:"base",prompt:e.prompt,profile:o,cwd:e.cwd,...e.name!==void 0?{name:e.name}:i!==void 0?{name:i}:{},root:!0,start:!0,prefer_warm:!0}}p(h,"rootCreateRequest");async function R(e){if(!b()){const t=process.stderr.isTTY?r=>`\x1B[1;33m${r}\x1B[0m`:r=>r;process.stderr.write(`
1
+ var l=Object.defineProperty;var c=(e,i)=>l(e,"name",{value:i,configurable:!0});import{inTmux as x,currentTmux as p}from"./placement-tmux.js";import{selectProfileForCwd as _}from"../profiles/select.js";import{cliClient as a}from"../../commands/api-client.js";import{mark as d}from"../timing.js";import{handle as h}from"../io.js";import{loadedPersonSettings as b}from"../../commands/person-settings.js";import{printComeBackNote as u}from"./come-back-note.js";function w(e,i){const o=e.kind;return{...o!==void 0?{kind:o}:{},mode:"base",prompt:e.prompt,profile:i,cwd:e.cwd,...e.name!==void 0?{name:e.name}:o!==void 0?{name:o}:{},root:!0,start:!0,prefer_warm:!0}}c(w,"rootCreateRequest");async function P(e){if(!x()){const t=process.stderr.isTTY?r=>`\x1B[1;33m${r}\x1B[0m`:r=>r;process.stderr.write(`
2
2
  ${t("crtr must be started from inside a tmux session.")}
3
3
  ${t("Start tmux first, e.g. tmux new -s work \u2014 then run crtr there.")}
4
4
 
5
- `),process.exit(1)}s("boot_root.start");const o=e.selectedProfileId??await g(e.cwd,e.profile,e.pickProfile??!1,!1);if(s("boot_root.profile_resolved"),!process.stdout.isTTY){const t=await c().createNode(h(e,o)),r=w();r!==null&&await c().registerFocus({node_id:t.node_id,pane:r.pane,session:r.session,window:r.window}).catch(()=>{}),process.stdout.write(`crtr surface attach is an interactive terminal viewer \u2014 run it in a tmux pane (a TTY), not a pipe. Node: ${t.node_id}
6
- `),await l(t.node_id,0),process.exit(0)}const{buildBannerInfo:i}=await import("../../clients/attach/session/banner.js"),{hint:$,..._}=i({cwd:e.cwd,profile_id:o}),a=C(_);s("boot_root.starting_painted");const f=import("../../clients/attach/viewer.js");f.catch(()=>{});let m;try{m=await c().createNode(h(e,o))}catch(t){throw a.stop(),t}const n=m.node_id;a.setNode(n),s("boot_root.node_created",{node:n});const d=w();d!==null&&c().registerFocus({node_id:n,pane:d.pane,session:d.session,window:d.window}).catch(()=>{});let u=0;try{const{runAttach:t}=await f;s("boot_root.viewer_attach"),await t(n,!1,void 0,!0,{node:m,settings:k(),initialWhip:e.initialWhip??(e.prompt!==void 0&&e.prompt!=="")},()=>a.stop())}catch(t){a.stop(),process.stderr.write(`crtr: the agent ${n} is still running; reopen it with crtr -r ${n}
7
- `),T(t),process.exit(typeof process.exitCode=="number"?process.exitCode:1)}await l(n,u),process.exit(u)}p(R,"bootRoot");export{R as bootRoot,h as rootCreateRequest};
5
+ `),process.exit(1)}d("boot_root.start");const i=e.selectedProfileId??await _(e.cwd,e.profile,e.pickProfile??!1,!1);if(d("boot_root.profile_resolved"),!process.stdout.isTTY){const t=await a().createNode(w(e,i)),r=p();r!==null&&await a().registerFocus({node_id:t.node_id,pane:r.pane,session:r.session,window:r.window}).catch(()=>{}),process.stdout.write(`crtr surface attach is an interactive terminal viewer \u2014 run it in a tmux pane (a TTY), not a pipe. Node: ${t.node_id}
6
+ `),await u(t.node_id,0),process.exit(0)}const o=a().createNode(w(e,i));o.catch(()=>{});const f=import("../../clients/attach/viewer.js");f.catch(()=>{}),d("boot_root.create_started");const s=p();o.then(t=>{d("boot_root.node_created",{node:t.node_id}),s!==null&&a().registerFocus({node_id:t.node_id,pane:s.pane,session:s.session,window:s.window}).catch(()=>{})},()=>{});let m=0,n;try{const{runAttach:t}=await f;d("boot_root.viewer_attach"),await t({cwd:e.cwd,profile_id:i,created:o.then(r=>(n=r.node_id,r)),settings:b(),initialWhip:e.initialWhip??(e.prompt!==void 0&&e.prompt!=="")},!1)}catch(t){n!==void 0&&process.stderr.write(`crtr: the agent ${n} is still running; reopen it with crtr -r ${n}
7
+ `),h(t),process.exit(typeof process.exitCode=="number"?process.exitCode:1)}n===void 0&&process.exit(typeof process.exitCode=="number"?process.exitCode:1),await u(n,m),process.exit(m)}c(P,"bootRoot");export{P as bootRoot,w as rootCreateRequest};
@@ -1,2 +1,2 @@
1
- var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{getNode as y,cancelCronsOnWake as B,transitionStatusIntent as D}from"../canvas/index.js";import{closeSync as J,constants as N,existsSync as j,fstatSync as F,readSync as P}from"node:fs";import{join as E}from"node:path";import{BROKER_RELEASED_MARKER as $,BROKER_RELAY_GENERATION as M,nodeRunDir as x}from"../canvas/paths.js";import{openBeneath as T,writeFileBeneath as W,isAbsentOrRefused as q}from"../spaces/open-beneath.js";import{emitEvent as C}from"../events/emit.js";import{composeNodeOutcomeDocument as K}from"./outcome-document.js";import{afterCommit as Y,withCanvasWrite as G}from"../canvas/db.js";import{nodeObject as z}from"../graph/objects.js";import{endMessageSubscriptions as V}from"../graph/watches.js";import{settleNodeObjectWaits as v}from"../canvas/waits.js";import{runStructuredRequestEffects as H,settlePendingStructuredRequestForNodeIn as I}from"../canvas/structured-requests.js";const p="*",Q={finish:"finished",park:"parked",cancel:"stranded",crash:"crashed","refresh-launch":null,revive:null},u=["active","idle"],U={finish:{status:"done",intent:"done",from:u},park:{status:"done",intent:"parked",from:u},cancel:{status:"canceled",intent:null,from:p},crash:{status:"dead",from:u},yield:{intent:"refresh",from:u},release:{status:"idle",intent:"idle-release",from:[...u,"done"]},"refresh-launch":{status:"active",intent:"refresh",from:p},revive:{status:"active",intent:null,from:p}};function X(t,e){const r=t.split(`
2
- `)[0]??"";let n=0,l="";for(const c of r){const s=Buffer.byteLength(c,"utf8");if(n+s>e)break;n+=s,l+=c}return l}o(X,"firstLineAtMost");function Z(t){if(t===void 0)return null;const e=t.message===void 0?void 0:X(t.message,500),r={...t,...e===void 0?{}:{message:e}},n=JSON.stringify(r);return Buffer.byteLength(n,"utf8")<=4*1024?n:JSON.stringify({schema:"crtr.node-outcome-detail/v1",truncated:!0,...e===void 0?{}:{message:e}})}o(Z,"detailJson");function ee(t,e){let r,n;return e==="finished"||e==="declined"?(r="done",n="done"):e==="parked"?(r="done",n="parked"):e==="closed"||e==="retired"||e==="stranded"||e==="deadline_exceeded"?(r="canceled",n=null):(r="dead",n=null),{...t,status:r,intent:n,terminal_reason:e}}o(ee,"nodeAtOutcome");async function Oe(t,e,r){const n=U[e],l=Object.prototype.hasOwnProperty.call(n,"status"),c=Object.prototype.hasOwnProperty.call(n,"intent"),s=r?.reason??Q[e],d={};l&&(d.status=n.status),c&&(d.intent=n.intent??null),s!==void 0&&(d.terminal_reason=s);const f=e==="finish"||e==="park"||e==="cancel"||e==="crash",_=f?new Date().toISOString():null,h=s,k=Z(r?.outcome?.detail),S=f?s==="deadline_exceeded"?{intended:"expired",failureReason:"node_deadline_exceeded",failureDetail:r?.outcome?.detail??null}:{intended:"failed",failureReason:s,failureDetail:r?.outcome?.detail??null}:null,w=await G(async i=>{const a=f?await y(t):null,O=f&&a?.kind!=="human",g=O&&a?.run_id!=null&&s!=="parked"&&a.outcome_at!==null&&(u.includes(a.status)||a.outcome_reason==="parked");let R;O&&a!==null&&(a.outcome_at===null||g)&&(R=JSON.stringify(await K({node:ee(a,h),outcome:{kind:"failure",reason:h,at:_,revision:(a.outcome_revision??0)+1,detailJson:k}})));const m=await D(t,d,{fromStatuses:n.from===p?void 0:n.from,requireNoFinalReport:e==="cancel",...O?{outcome:{kind:"failure",reason:h,detailJson:k,at:_,...g?{supersede:!0}:{},...R===void 0?{}:{documentJson:R}}}:{}});f&&m>0&&(await V(i,await z(i,t),"done"),await v(i,t));const A=m===1&&S!==null?await I(i,t,S):null;if(m===1&&(e==="release"||e==="park"||e==="finish"||e==="cancel")){const b=te(t);Y(()=>ne(t,b))}return{changes:m,settlement:A}});if(w.changes===0){const i=await y(t);if(i===null)throw new Error(`transition: unknown node ${t}`);if(e==="cancel"&&i.final_report!==null&&i.final_report!==void 0)return i;throw new Error(`illegal lifecycle transition: '${e}' from status='${i.status}' (node ${t})`)}return w.settlement?.changed&&H(w.settlement.row),(e==="finish"||e==="park"||e==="cancel")&&await B(t),await y(t)}o(Oe,"transition");function te(t){const e=x(t);let r;try{r=T(e,E(e,M),N.O_RDONLY|N.O_NOFOLLOW)}catch(n){if(q(n))return null;throw n}try{if(!F(r).isFile())return null;const n=Buffer.alloc(37),l=P(r,n,0,n.length,0),c=n.toString("utf8",0,l);return l===36&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(c)?c:null}finally{J(r)}}o(te,"brokerRelayGeneration");function ne(t,e){const r=x(t);if(!(e===null||!j(r)))try{W(r,E(r,$),e,{atomic:!0})}catch(n){C({level:"warn",event:"node.lifecycle.release_marker_failed",node_id:t,error:n})}}o(ne,"recordBrokerRelease");function re(t){return t.status==="done"&&t.intent==="parked"}o(re,"isParked");function Re(t){return re(t)&&t.lifecycle==="resident"&&t.final_report==null&&t.deleting_at==null}o(Re,"isParkedResident");function ye(t){return t?.intent==="idle-release"}o(ye,"hasIdleReleaseIntent");export{te as brokerRelayGeneration,ye as hasIdleReleaseIntent,re as isParked,Re as isParkedResident,ne as recordBrokerRelease,Oe as transition};
1
+ var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{getNode as y,cancelCronsOnWake as B,transitionStatusIntent as D}from"../canvas/index.js";import{closeSync as J,constants as N,existsSync as j,fstatSync as F,readSync as P}from"node:fs";import{join as E}from"node:path";import{BROKER_RELEASED_MARKER as $,BROKER_RELAY_GENERATION as M,nodeRunDir as x}from"../canvas/paths.js";import{openBeneath as T,writeFileBeneath as W,isAbsentOrRefused as q}from"../spaces/open-beneath.js";import{emitEvent as C}from"../events/emit.js";import{deleteSandboxOfEndedNode as K}from"./runner/delete-sandboxes.js";import{composeNodeOutcomeDocument as Y}from"./outcome-document.js";import{afterCommit as G,withCanvasWrite as z}from"../canvas/db.js";import{nodeObject as V}from"../graph/objects.js";import{endMessageSubscriptions as H}from"../graph/watches.js";import{settleNodeObjectWaits as Q}from"../canvas/waits.js";import{runStructuredRequestEffects as U,settlePendingStructuredRequestForNodeIn as X}from"../canvas/structured-requests.js";const p="*",Z={finish:"finished",park:"parked",cancel:"stranded",crash:"crashed","refresh-launch":null,revive:null},u=["active","idle"],I={finish:{status:"done",intent:"done",from:u},park:{status:"done",intent:"parked",from:u},cancel:{status:"canceled",intent:null,from:p},crash:{status:"dead",from:u},yield:{intent:"refresh",from:u},release:{status:"idle",intent:"idle-release",from:[...u,"done"]},"refresh-launch":{status:"active",intent:"refresh",from:p},revive:{status:"active",intent:null,from:p}};function v(t,e){const r=t.split(`
2
+ `)[0]??"";let n=0,l="";for(const c of r){const s=Buffer.byteLength(c,"utf8");if(n+s>e)break;n+=s,l+=c}return l}o(v,"firstLineAtMost");function ee(t){if(t===void 0)return null;const e=t.message===void 0?void 0:v(t.message,500),r={...t,...e===void 0?{}:{message:e}},n=JSON.stringify(r);return Buffer.byteLength(n,"utf8")<=4*1024?n:JSON.stringify({schema:"crtr.node-outcome-detail/v1",truncated:!0,...e===void 0?{}:{message:e}})}o(ee,"detailJson");function te(t,e){let r,n;return e==="finished"||e==="declined"?(r="done",n="done"):e==="parked"?(r="done",n="parked"):e==="closed"||e==="retired"||e==="stranded"||e==="deadline_exceeded"?(r="canceled",n=null):(r="dead",n=null),{...t,status:r,intent:n,terminal_reason:e}}o(te,"nodeAtOutcome");async function ye(t,e,r){const n=I[e],l=Object.prototype.hasOwnProperty.call(n,"status"),c=Object.prototype.hasOwnProperty.call(n,"intent"),s=r?.reason??Z[e],d={};l&&(d.status=n.status),c&&(d.intent=n.intent??null),s!==void 0&&(d.terminal_reason=s);const f=e==="finish"||e==="park"||e==="cancel"||e==="crash",_=f?new Date().toISOString():null,h=s,k=ee(r?.outcome?.detail),S=f?s==="deadline_exceeded"?{intended:"expired",failureReason:"node_deadline_exceeded",failureDetail:r?.outcome?.detail??null}:{intended:"failed",failureReason:s,failureDetail:r?.outcome?.detail??null}:null,O=await z(async i=>{const a=f?await y(t):null,w=f&&a?.kind!=="human",g=w&&a?.run_id!=null&&s!=="parked"&&a.outcome_at!==null&&(u.includes(a.status)||a.outcome_reason==="parked");let R;w&&a!==null&&(a.outcome_at===null||g)&&(R=JSON.stringify(await Y({node:te(a,h),outcome:{kind:"failure",reason:h,at:_,revision:(a.outcome_revision??0)+1,detailJson:k}})));const m=await D(t,d,{fromStatuses:n.from===p?void 0:n.from,requireNoFinalReport:e==="cancel",...w?{outcome:{kind:"failure",reason:h,detailJson:k,at:_,...g?{supersede:!0}:{},...R===void 0?{}:{documentJson:R}}}:{}});f&&m>0&&(await H(i,await V(i,t),"done"),await Q(i,t));const A=m===1&&S!==null?await X(i,t,S):null;if(m===1&&(e==="release"||e==="park"||e==="finish"||e==="cancel")){const b=ne(t);G(()=>re(t,b))}return{changes:m,settlement:A}});if(O.changes===0){const i=await y(t);if(i===null)throw new Error(`transition: unknown node ${t}`);if(e==="cancel"&&i.final_report!==null&&i.final_report!==void 0)return i;throw new Error(`illegal lifecycle transition: '${e}' from status='${i.status}' (node ${t})`)}return O.settlement?.changed&&U(O.settlement.row),(e==="finish"||e==="park"||e==="cancel")&&await B(t),(e==="finish"||e==="cancel"||e==="crash")&&K(t),await y(t)}o(ye,"transition");function ne(t){const e=x(t);let r;try{r=T(e,E(e,M),N.O_RDONLY|N.O_NOFOLLOW)}catch(n){if(q(n))return null;throw n}try{if(!F(r).isFile())return null;const n=Buffer.alloc(37),l=P(r,n,0,n.length,0),c=n.toString("utf8",0,l);return l===36&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(c)?c:null}finally{J(r)}}o(ne,"brokerRelayGeneration");function re(t,e){const r=x(t);if(!(e===null||!j(r)))try{W(r,E(r,$),e,{atomic:!0})}catch(n){C({level:"warn",event:"node.lifecycle.release_marker_failed",node_id:t,error:n})}}o(re,"recordBrokerRelease");function ie(t){return t.status==="done"&&t.intent==="parked"}o(ie,"isParked");function _e(t){return ie(t)&&t.lifecycle==="resident"&&t.final_report==null&&t.deleting_at==null}o(_e,"isParkedResident");function ke(t){return t?.intent==="idle-release"}o(ke,"hasIdleReleaseIntent");export{ne as brokerRelayGeneration,ke as hasIdleReleaseIntent,ie as isParked,_e as isParkedResident,re as recordBrokerRelease,ye as transition};
@@ -1,3 +1,3 @@
1
- var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as $,beginExecution as me,ExecutionAlreadyLive as de,recordExecutionPid as pe,abortExecution as F,endLiveExecution as he,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as xe,readGoal as x,readYieldMessage as Ee,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as $e,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as 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 mr}from"../command-hooks/transport/exec-lifecycle.js";async function dr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await p().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(dr,"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 G)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 hr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||H(i)}s(hr,"sessionCwdExists");async function vr(e,r,i,t){const a=r.pi_session_file;if(!a||!await re(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await hr(a)?{}:await dr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await Ee(e)===null&&!await xe(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function mi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(mi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const a=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const h=!k&&await a.reserveSlot(e);let o=null;if(h){try{o=await Je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!h||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await a.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 a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{a.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await he(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({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");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await mr(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}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await yr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const h=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(h&&(typeof o!="string"||!fe(o)))throw new O({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=h&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:a?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof de)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const E=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await vr(e,r,E,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(d.resumeSessionPath)?(await x(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await $(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const le=(await p().header(await p().fork(N,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await x(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await ee(e)}else{const n=await Re(r,f);c=y(r,{...d,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=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)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},m!==null&&(c.env[Ne]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const n=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Y)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
1
+ var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as $,beginExecution as me,ExecutionAlreadyLive as he,recordExecutionPid as pe,abortExecution as F,endLiveExecution as de,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as $e,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as 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 mr}from"../command-hooks/transport/exec-lifecycle.js";async function hr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await p().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(hr,"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 G)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"||H(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const a=r.pi_session_file;if(!a||!await re(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(a)?{}:await hr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function mi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(mi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const a=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await a.isClaimed(e))return await a.has(e)&&await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await a.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.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(P().automaticReviveCap,await a.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 a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{a.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"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({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");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await mr(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}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await yr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await $(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new O({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 O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:a?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof he)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await $(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,h=w?{}:await vr(e,r,x,!u),g=h.resumeSessionPath!==void 0,B=g&&h.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(h.resumeSessionPath)?(await E(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await $(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const le=(await p().header(await p().fork(N,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...h,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...h,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await ee(e)}else{const n=await Re(r,f);c=y(r,{...h,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=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)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},m!==null&&(c.env[Ne]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const n=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof Y)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.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 F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),$e.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(E=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:E})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,mi as decideAttachRevive,fi as hasFreshGroundState,dr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),$e.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,mi as decideAttachRevive,fi as hasFreshGroundState,hr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
@@ -5,6 +5,8 @@ export interface BlaxelConfig {
5
5
  /** Defaults to `https://api.blaxel.ai/v0`. */
6
6
  controlUrl?: string;
7
7
  fetch?: typeof fetch;
8
+ /** How long `createSandbox` waits for a sandbox being deleted to free its name. Default 60 s. */
9
+ deletingWaitMs?: number;
8
10
  }
9
11
  /** `BLAXEL_API_KEY`, `BLAXEL_WORKSPACE`, `BLAXEL_REGION` (H-1 names). Throws when one is missing. */
10
12
  export declare function blaxelConfigFromEnv(env?: NodeJS.ProcessEnv): BlaxelConfig;
@@ -32,6 +34,8 @@ export interface SandboxInfo {
32
34
  /** `RUNNING`, `STANDBY` (frozen), ...; reading it does not wake the sandbox. */
33
35
  state: string | null;
34
36
  status: string | null;
37
+ /** `spec.runtime.image`: an adopted sandbox keeps the image it was created with. */
38
+ image: string | null;
35
39
  }
36
40
  export type ProcessStatus = 'running' | 'completed' | 'failed' | 'killed' | 'stopped';
37
41
  export interface SandboxProcess {
@@ -1 +1 @@
1
- var $=Object.defineProperty;var p=(s,c)=>$(s,"name",{value:c,configurable:!0});function A(s=process.env){const c=p(n=>{const d=s[n];if(!d)throw new Error(`${n} is required for the Blaxel runner`);return d},"need");return{apiKey:c("BLAXEL_API_KEY"),workspace:c("BLAXEL_WORKSPACE"),region:c("BLAXEL_REGION")}}p(A,"blaxelConfigFromEnv");class w extends Error{static{p(this,"BlaxelApiError")}status;code;constructor(c,n,d){super(d),this.status=c,this.code=n,this.name="BlaxelApiError"}}const g=p(s=>s instanceof w&&s.status===404&&s.code==="WORKLOAD_UNAVAILABLE","isWorkloadUnavailable");function E(s){const c=s.metadata.url;if(!c)throw new Error(`Blaxel sandbox ${s.metadata.name} has no url`);return{name:s.metadata.name,url:c,state:s.state??null,status:s.status??null}}p(E,"toInfo");function y(s,c){const n=s??{},d=typeof n.error=="object"&&n.error!==null?n.error:{},i=typeof d.code=="string"?d.code:typeof n.code=="string"?n.code:null,l=[d.message,n.message,n.error].find(e=>typeof e=="string")??c.slice(0,300);return{code:i,message:l}}p(y,"errorFields");function T(s){const c=s.fetch??fetch,n=s.controlUrl??"https://api.blaxel.ai/v0",d=p(()=>({authorization:`Bearer ${s.apiKey}`,"x-blaxel-workspace":s.workspace,"content-type":"application/json"}),"headers");async function i(e,t,a,r=[]){const o=await c(e,{method:t,headers:d(),...a===void 0?{}:{body:JSON.stringify(a)}}),u=await o.text();let f=null;if(u!=="")try{f=JSON.parse(u)}catch{f={raw:u}}if(!o.ok){const{code:x,message:m}=y(f,u);if(o.status===404&&x==="WORKLOAD_UNAVAILABLE"||!r.includes(o.status))throw new w(o.status,x,`Blaxel ${t} ${e} failed (${o.status}): ${m}`)}return{status:o.status,json:f}}p(i,"call");const l=encodeURIComponent;return{config:s,async createSandbox(e){const t=[...e.ports??[]].map(u=>({name:u.name,target:u.target,protocol:"HTTP"})),a={metadata:{name:e.name},spec:{runtime:{image:e.image,memory:e.memoryMb,...t.length>0?{ports:t}:{}},region:s.region}},{status:r,json:o}=await i(`${n}/sandboxes`,"POST",a,[409]);if(r===409){const u=await this.getSandbox(e.name);if(u===null)throw new Error(`Blaxel sandbox ${e.name} reported as existing but cannot be read`);return{...u,created:!1}}return{...E(o),created:!0}},async getSandbox(e){const{status:t,json:a}=await i(`${n}/sandboxes/${l(e)}`,"GET",void 0,[404]);if(t===404)return null;const r=a;return r.status==="DELETING"||r.status==="TERMINATED"?null:E(r)},async deleteSandbox(e){await i(`${n}/sandboxes/${l(e)}`,"DELETE",void 0,[404])},async startProcess(e,t){const{json:a}=await i(`${e.url}/process`,"POST",t);return a},async getProcess(e,t){const{status:a,json:r}=await i(`${e.url}/process/${l(t)}`,"GET",void 0,[404]);return a===404?null:r},async stopProcess(e,t){await i(`${e.url}/process/${l(t)}`,"DELETE",void 0,[404])},async killProcess(e,t){await i(`${e.url}/process/${l(t)}/kill`,"DELETE",void 0,[404])},async exec(e,t,a,r,o){return await this.startProcess(e,{name:t,command:a,waitForCompletion:!0,timeout:r,...o?{env:o}:{}})},async putFile(e,t,a,r="0644"){await i(`${e.url}/filesystem/${t.replace(/^\/+/,"").split("/").map(l).join("/")}`,"PUT",{content:a,permissions:r})},async ensurePreview(e,t,a){const{json:r}=await i(`${n}/sandboxes/${l(e)}/previews`,"POST",{metadata:{name:t},spec:{port:a,public:!1}},[409]),o=r?.spec?.url;if(o)return o;const f=(await i(`${n}/sandboxes/${l(e)}/previews`,"GET")).json.find(x=>x.metadata.name===t);if(!f)throw new Error(`Blaxel preview ${t} of ${e} not found`);return f.spec.url},async createPreviewToken(e,t,a){const{json:r}=await i(`${n}/sandboxes/${l(e)}/previews/${l(t)}/tokens`,"POST",{spec:{expiresAt:a.toISOString()}}),o=r.spec;return{token:o.token,expiresAt:o.expiresAt}}}}p(T,"createBlaxelClient");export{w as BlaxelApiError,A as blaxelConfigFromEnv,T as createBlaxelClient,g as isWorkloadUnavailable};
1
+ var $=Object.defineProperty;var p=(t,i)=>$(t,"name",{value:i,configurable:!0});function b(t=process.env){const i=p(a=>{const u=t[a];if(!u)throw new Error(`${a} is required for the Blaxel runner`);return u},"need");return{apiKey:i("BLAXEL_API_KEY"),workspace:i("BLAXEL_WORKSPACE"),region:i("BLAXEL_REGION")}}p(b,"blaxelConfigFromEnv");class w extends Error{static{p(this,"BlaxelApiError")}status;code;constructor(i,a,u){super(u),this.status=i,this.code=a,this.name="BlaxelApiError"}}const A=p(t=>t instanceof w&&t.status===404&&t.code==="WORKLOAD_UNAVAILABLE","isWorkloadUnavailable");function x(t){const i=t.metadata.url;if(!i)throw new Error(`Blaxel sandbox ${t.metadata.name} has no url`);return{name:t.metadata.name,url:i,state:t.state??null,status:t.status??null,image:t.spec?.runtime?.image??null}}p(x,"toInfo");function y(t,i){const a=t??{},u=typeof a.error=="object"&&a.error!==null?a.error:{},c=typeof u.code=="string"?u.code:typeof a.code=="string"?a.code:null,l=[u.message,a.message,a.error].find(e=>typeof e=="string")??i.slice(0,300);return{code:c,message:l}}p(y,"errorFields");function T(t){const i=t.fetch??fetch,a=t.controlUrl??"https://api.blaxel.ai/v0",u=p(()=>({authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"}),"headers");async function c(e,s,o,r=[]){const n=await i(e,{method:s,headers:u(),...o===void 0?{}:{body:JSON.stringify(o)}}),f=await n.text();let d=null;if(f!=="")try{d=JSON.parse(f)}catch{d={raw:f}}if(!n.ok){const{code:m,message:E}=y(d,f);if(n.status===404&&m==="WORKLOAD_UNAVAILABLE"||!r.includes(n.status))throw new w(n.status,m,`Blaxel ${s} ${e} failed (${n.status}): ${E}`)}return{status:n.status,json:d}}p(c,"call");const l=encodeURIComponent;return{config:t,async createSandbox(e){const s=[...e.ports??[]].map(n=>({name:n.name,target:n.target,protocol:"HTTP"})),o={metadata:{name:e.name},spec:{runtime:{image:e.image,memory:e.memoryMb,...s.length>0?{ports:s}:{}},region:t.region,lifecycle:{expirationPolicies:[{type:"ttl-idle",value:"7d",action:"delete"}]}}},r=Date.now()+(t.deletingWaitMs??6e4);for(;;){const{status:n,json:f}=await c(`${a}/sandboxes`,"POST",o,[409]);if(n!==409)return{...x(f),created:!0};const d=await this.getSandbox(e.name);if(d!==null)return{...d,created:!1};if(Date.now()>=r)throw new Error(`Blaxel sandbox ${e.name} is still being deleted; its name did not free in time`);await new Promise(m=>setTimeout(m,1e3))}},async getSandbox(e){const{status:s,json:o}=await c(`${a}/sandboxes/${l(e)}`,"GET",void 0,[404]);if(s===404)return null;const r=o;return r.status==="DELETING"||r.status==="TERMINATED"?null:x(r)},async deleteSandbox(e){await c(`${a}/sandboxes/${l(e)}`,"DELETE",void 0,[404])},async startProcess(e,s){const{json:o}=await c(`${e.url}/process`,"POST",s);return o},async getProcess(e,s){const{status:o,json:r}=await c(`${e.url}/process/${l(s)}`,"GET",void 0,[404]);return o===404?null:r},async stopProcess(e,s){await c(`${e.url}/process/${l(s)}`,"DELETE",void 0,[404])},async killProcess(e,s){await c(`${e.url}/process/${l(s)}/kill`,"DELETE",void 0,[404])},async exec(e,s,o,r,n){return await this.startProcess(e,{name:s,command:o,waitForCompletion:!0,timeout:r,...n?{env:n}:{}})},async putFile(e,s,o,r="0644"){await c(`${e.url}/filesystem/${s.replace(/^\/+/,"").split("/").map(l).join("/")}`,"PUT",{content:o,permissions:r})},async ensurePreview(e,s,o){const{json:r}=await c(`${a}/sandboxes/${l(e)}/previews`,"POST",{metadata:{name:s},spec:{port:o,public:!1}},[409]),n=r?.spec?.url;if(n)return n;const d=(await c(`${a}/sandboxes/${l(e)}/previews`,"GET")).json.find(m=>m.metadata.name===s);if(!d)throw new Error(`Blaxel preview ${s} of ${e} not found`);return d.spec.url},async createPreviewToken(e,s,o){const{json:r}=await c(`${a}/sandboxes/${l(e)}/previews/${l(s)}/tokens`,"POST",{spec:{expiresAt:o.toISOString()}}),n=r.spec;return{token:n.token,expiresAt:n.expiresAt}}}}p(T,"createBlaxelClient");export{w as BlaxelApiError,b as blaxelConfigFromEnv,T as createBlaxelClient,A as isWorkloadUnavailable};
@@ -9,7 +9,8 @@ export declare const EXIT_NO_BROKER = 3;
9
9
  /** A failing start script prints a last line `crtr-sandbox-start: failed <reason>`; `status` reports the reason. */
10
10
  export declare const FAILURE_LINE: RegExp;
11
11
  export declare const brokerProcessName: (executionId: string) => string;
12
- export declare const sandboxNameFor: (execution: RunnerExecution) => string;
12
+ export declare const sandboxNameFor: (nodeId: string) => string;
13
+ export declare const cronProcessName: (runId: string) => string;
13
14
  /** What `start` needs from the control plane beyond the execution: the environment's image and size, the release object, the secrets. */
14
15
  export interface BlaxelLaunchContext {
15
16
  /** `environments.image_ref` for a recipe environment, else the release's own image (release-image.ts) when it was published with one, else `blaxel/base-image:latest`. */
@@ -30,8 +31,6 @@ export interface BlaxelRunnerDeps {
30
31
  mintToken?(input: RunnerStartInput): Promise<string>;
31
32
  /** The bootstrap script text passed as the process command (`scripts/sandbox-bootstrap.sh`). */
32
33
  bootstrap(): string;
33
- /** Sandbox names that belong to a node, for `delete`. Default: one per execution of the node (`sandboxNameFor`). */
34
- sandboxNamesForNode?(nodeId: string): Promise<string[]>;
35
34
  /** Seconds `stop` waits after SIGTERM before the kill. */
36
35
  stopGraceS?: number;
37
36
  }
@@ -1,3 +1,3 @@
1
- var $=Object.defineProperty;var i=(n,a)=>$(n,"name",{value:a,configurable:!0});import{openDb as k}from"../../../canvas/db.js";import{mintExecutionToken as S}from"../../../canvas/node-tokens.js";import{BlaxelApiError as T,isWorkloadUnavailable as m}from"./client.js";const f=4180,w="view",I="node /opt/crtr/current/scripts/sandbox-start.mjs --wake",y=3,C=/^crtr-sandbox-start: failed (\S+)/m,h=2e3,p=i(n=>`broker-${n}`,"brokerProcessName"),d=i(n=>n.sandboxName??`${n.nodeId}-${n.attempt}`,"sandboxNameFor");async function A(n){const a=await(await k()).prepare("SELECT execution_id, attempt, sandbox_name FROM executions WHERE node_id = ? AND runner = 'blaxel'").all(n);return[...new Set(a.map(c=>d({executionId:c.execution_id,nodeId:n,attempt:Number(c.attempt),sandboxName:c.sandbox_name})))]}i(A,"defaultSandboxNames");function N(n){const a=`${n.logs}
2
- ${n.stderr}
3
- ${n.stdout}`,c=(n.stderr||n.logs||n.stdout||"").trim().slice(-h);return{state:"failed",reason:C.exec(a)?.[1]??"start_failed",code:n.exitCode,...c===""?{}:{output:c}}}i(N,"failureOf");function L(n){const{client:a}=n,c=(n.stopGraceS??10)*1e3,E=new Map;async function u(t){return await a.getSandbox(d(t))}i(u,"sandboxOf");async function g(t,r){if(!/^[A-Za-z0-9_-]+$/.test(r))throw new Error(`execution id ${JSON.stringify(r)} is not safe to name in a command`);const e=Math.max(1,Math.ceil(c/1e3)),o=`p='[b]roker-cli\\.js .*--epoch ${r}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${e*5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;return(await a.exec(t,`stop-${r}-${Date.now()}`,o,e+20)).exitCode===0}return i(g,"brokerGone"),{kind:"blaxel",async start(t){const r=await n.launchContext(t),e=d(t),o=await a.createSandbox({name:e,image:r.image,memoryMb:r.memoryMb,ports:[{name:w,target:f}]}),s=p(t.executionId);if((await a.getProcess(o,s))?.status==="running")return{pid:null,exited:null};await a.ensurePreview(e,w,f);const x=await(n.mintToken??(b=>S(b.executionId,b.nodeId)))(t),R={...r.secrets,CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t.executionId,CRTR_NODE_TOKEN:x,CRTR_RELEASE:t.release,CRTR_RELEASE_URL:r.releaseUrl,CRTR_RELEASE_SHA256:r.releaseSha256};return await a.startProcess(o,{name:s,command:n.bootstrap(),env:R,waitForCompletion:!1}),{pid:null,exited:null}},async wake(t){const r=await u(t);if(r===null)return"no_broker";try{const e=await a.exec(r,`wake-${t.executionId}-${Date.now()}`,`${I} ${t.executionId}`,30);if(e.exitCode===0)return"signalled";if(e.exitCode===y)return"no_broker";throw new Error(`wake of ${t.executionId} failed (exit ${e.exitCode}): ${(e.stderr||e.logs).slice(0,300)}`)}catch(e){if(m(e))return"no_broker";throw e}},async stop(t,r){try{const e=await u(t);if(e===null)return{confirmed:!0};const o=p(t.executionId),s=i(async()=>(await a.getProcess(e,o))?.status==="running","running");if(await s()){await a.stopProcess(e,o);const l=Date.now()+c;for(;Date.now()<l&&await s();)await new Promise(x=>setTimeout(x,250));if(await s()&&await a.killProcess(e,o),await s())return{confirmed:!1}}return{confirmed:await g(e,t.executionId)}}catch(e){return m(e)?{confirmed:!0}:{confirmed:!1,error:e instanceof Error?e:new Error(String(e))}}},async status(t,r){try{const e=await u(t);if(e===null)return{state:"gone"};if(r?.idle===!0)return{state:"running",pid:null};const o=await a.getProcess(e,p(t.executionId));return o===null?{state:"gone"}:o.status==="running"?{state:"running",pid:null}:o.status==="failed"||o.status==="completed"&&o.exitCode!==0?N(o):{state:"gone"}}catch(e){return m(e)?{state:"gone"}:{state:"unknown",error:e instanceof Error?e.message:String(e)}}},async delete(t){for(const r of await(n.sandboxNamesForNode??A)(t))await a.deleteSandbox(r)},async deleteExecution(t){await a.deleteSandbox(d(t))},async viewerAddress(t){const r=d(t),e=E.get(r);if(e&&e.expiresAt-Date.now()>5*6e4)return _(e.url,e.token);const o=await a.ensurePreview(r,w,f),s=new Date(Date.now()+60*6e4),{token:l}=await a.createPreviewToken(r,w,s);return E.set(r,{url:o,token:l,expiresAt:s.getTime()}),_(o,l)},async sandboxState(t){return(await u(t))?.state??null}}}i(L,"createBlaxelRunner");function _(n,a){return{kind:"wss",url:`${n.replace(/^https:/,"wss:")}/view`,headers:{"x-blaxel-preview-token":a}}}i(_,"viewer");export{f as BROKER_VIEW_PORT,T as BlaxelApiError,y as EXIT_NO_BROKER,C as FAILURE_LINE,I as WAKE_COMMAND,p as brokerProcessName,L as createBlaxelRunner,d as sandboxNameFor};
1
+ var h=Object.defineProperty;var c=(a,n)=>h(a,"name",{value:n,configurable:!0});import{mintExecutionToken as S}from"../../../canvas/node-tokens.js";import{BlaxelApiError as P,isWorkloadUnavailable as R}from"./client.js";const b=4180,p="view",T="node /opt/crtr/current/scripts/sandbox-start.mjs --wake",O=3,I=/^crtr-sandbox-start: failed (\S+)/m,A=2e3,E=c(a=>`broker-${a}`,"brokerProcessName"),l=c(a=>a,"sandboxNameFor"),_=c(a=>`cron-${a}`,"cronProcessName"),y=2e3,$="crtr",N="/opt/crtr/current/bin";function v(a){const n=`${a.logs}
2
+ ${a.stderr}
3
+ ${a.stdout}`,u=(a.stderr||a.logs||a.stdout||"").trim().slice(-A);return{state:"failed",reason:I.exec(n)?.[1]??"start_failed",code:a.exitCode,...u===""?{}:{output:u}}}c(v,"failureOf");function U(a){const{client:n}=a,u=(a.stopGraceS??10)*1e3,f=new Map;async function x(t){return await n.getSandbox(l(t.nodeId))}c(x,"sandboxOf");async function k(t,r){if(!/^[A-Za-z0-9_-]+$/.test(r))throw new Error(`execution id ${JSON.stringify(r)} is not safe to name in a command`);const e=Math.max(1,Math.ceil(u/1e3)),o=`p='[b]roker-cli\\.js .*--epoch ${r}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${e*5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;return(await n.exec(t,`stop-${r}-${Date.now()}`,o,e+20)).exitCode===0}return c(k,"brokerGone"),{kind:"blaxel",async start(t){const r=await a.launchContext(t),e=l(t.nodeId),o={name:e,image:r.image,memoryMb:r.memoryMb,ports:[{name:p,target:b}]};let i=await n.createSandbox(o);i.image!==r.image&&(await n.deleteSandbox(e),f.delete(e),i=await n.createSandbox(o));const d=E(t.executionId);if((await n.getProcess(i,d))?.status==="running")return{pid:null,exited:null};await n.ensurePreview(e,p,b);const g=await(a.mintToken??(m=>S(m.executionId,m.nodeId)))(t),w={...r.secrets,CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t.executionId,CRTR_NODE_TOKEN:g,CRTR_RELEASE:t.release,CRTR_RELEASE_URL:r.releaseUrl,CRTR_RELEASE_SHA256:r.releaseSha256};return await n.startProcess(i,{name:d,command:a.bootstrap(),env:w,waitForCompletion:!1}),{pid:null,exited:null}},async wake(t){const r=await x(t);if(r===null)return"no_broker";try{const e=await n.exec(r,`wake-${t.executionId}-${Date.now()}`,`${T} ${t.executionId}`,30);if(e.exitCode===0)return"signalled";if(e.exitCode===O)return"no_broker";throw new Error(`wake of ${t.executionId} failed (exit ${e.exitCode}): ${(e.stderr||e.logs).slice(0,300)}`)}catch(e){if(R(e))return"no_broker";throw e}},async stop(t,r){try{const e=await x(t);if(e===null)return{confirmed:!0};const o=E(t.executionId),i=c(async()=>(await n.getProcess(e,o))?.status==="running","running");if(await i()){await n.stopProcess(e,o);const d=Date.now()+u;for(;Date.now()<d&&await i();)await new Promise(s=>setTimeout(s,250));if(await i()&&await n.killProcess(e,o),await i())return{confirmed:!1}}return{confirmed:await k(e,t.executionId)}}catch(e){return R(e)?{confirmed:!0}:{confirmed:!1,error:e instanceof Error?e:new Error(String(e))}}},async status(t,r){try{const e=await x(t);if(e===null)return{state:"gone"};if(r?.idle===!0)return{state:"running",pid:null};const o=await n.getProcess(e,E(t.executionId));return o===null?{state:"gone"}:o.status==="running"?{state:"running",pid:null}:o.status==="failed"||o.status==="completed"&&o.exitCode!==0?v(o):{state:"gone"}}catch(e){return R(e)?{state:"gone"}:{state:"unknown",error:e instanceof Error?e.message:String(e)}}},async delete(t){await n.deleteSandbox(l(t)),f.delete(l(t))},async viewerAddress(t){const r=l(t.nodeId),e=f.get(r);if(e&&e.expiresAt-Date.now()>5*6e4)return C(e.url,e.token);const o=await n.ensurePreview(r,p,b),i=new Date(Date.now()+60*6e4),{token:d}=await n.createPreviewToken(r,p,i);return f.set(r,{url:o,token:d,expiresAt:i.getTime()}),C(o,d)},async cronRun(t,r){const e=await n.getSandbox(l(t));if(e===null)throw new Error(`node ${t} has no sandbox, so the cron cannot run; the scheduler never starts a node to get one`);const o=_(r.runId),i=`exec nsenter -S "$(id -u ${$})" -G "$(id -g ${$})" bash -c "$CRTR_CRON_COMMAND"`,d={...r.env,CRTR_CRON_COMMAND:r.command,PATH:`${N}:/usr/local/bin:/usr/bin:/bin`};let s=await n.getProcess(e,o)??await n.startProcess(e,{name:o,command:i,workingDir:r.cwd,env:d,waitForCompletion:!1});const g=r.startedAtMs+r.timeoutS*1e3;for(;s.status==="running";){if(Date.now()>=g)return await n.killProcess(e,o),{exitCode:null,timedOut:!0,stdout:s.stdout,stderr:s.stderr};await new Promise(m=>setTimeout(m,y));let w;try{w=await n.getProcess(e,o)}catch{continue}if(w===null)return{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} is gone from the sandbox, so its outcome is unknown`};s=w}return s.status==="completed"||s.status==="failed"?{exitCode:s.exitCode,timedOut:!1,stdout:s.stdout,stderr:s.stderr}:{exitCode:null,timedOut:!1,stdout:s.stdout,stderr:s.stderr,error:`process ${o} was ${s.status} from outside the run`}},async cronCancel(t,r){const e=await n.getSandbox(l(t));e!==null&&await n.killProcess(e,_(r))},async sandboxState(t){return(await x(t))?.state??null}}}c(U,"createBlaxelRunner");function C(a,n){return{kind:"wss",url:`${a.replace(/^https:/,"wss:")}/view`,headers:{"x-blaxel-preview-token":n}}}c(C,"viewer");export{b as BROKER_VIEW_PORT,P as BlaxelApiError,O as EXIT_NO_BROKER,I as FAILURE_LINE,T as WAKE_COMMAND,E as brokerProcessName,U as createBlaxelRunner,_ as cronProcessName,l as sandboxNameFor};
@@ -1,3 +1,8 @@
1
1
  /** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
2
2
  * those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
3
3
  export declare function deleteNodeSandboxes(nodeIds: readonly string[]): Promise<string[]>;
4
+ /** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
5
+ * (its fires run there). Called after each of those ends; a failure is left to the sandbox's idle expiry. A parked node is not ended:
6
+ * wake mail reopens it in the same sandbox. The check and the DELETE run holding the node row's lock, which `beginExecution` also
7
+ * takes, so no new execution can start in the sandbox between them. */
8
+ export declare function deleteSandboxOfEndedNode(nodeId: string): void;
@@ -1 +1,6 @@
1
- var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});import{openDb as c}from"../../canvas/db.js";import{emitEvent as d}from"../../events/emit.js";async function u(e){if(e.length===0)return[];const t=e.map(()=>"?").join(","),a=await(await c()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${t})`).all(...e),r=[];for(const{node_id:o}of a)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(o)}catch(i){r.push(o),d({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:o,error:i})}return r}n(u,"deleteNodeSandboxes");export{u as deleteNodeSandboxes};
1
+ var c=Object.defineProperty;var o=(e,n)=>c(e,"name",{value:n,configurable:!0});import{afterCommit as E,openDb as l,withCanvasWrite as s}from"../../canvas/db.js";import{emitEvent as i}from"../../events/emit.js";async function S(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),a=await(await l()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${n})`).all(...e),d=[];for(const{node_id:t}of a)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(t)}catch(r){d.push(t),i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:t,error:r})}return d}o(S,"deleteNodeSandboxes");function _(e){E(()=>{s(async n=>{await n.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
2
+ AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
3
+ AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
4
+ AND NOT EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited')
5
+ AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
6
+ FOR UPDATE OF n`).get(e)!==void 0&&await(await import("./index.js")).runnerForExecution("blaxel").delete(e)}).catch(n=>{i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:e,error:n})})})}o(_,"deleteSandboxOfEndedNode");export{S as deleteNodeSandboxes,_ as deleteSandboxOfEndedNode};
@@ -3,7 +3,7 @@ export type RunnerKind = 'process' | 'blaxel' | 'machine';
3
3
  export interface RunnerExecution {
4
4
  executionId: string;
5
5
  nodeId: string;
6
- /** `executions.attempt`, the sandbox name suffix. */
6
+ /** `executions.attempt`. */
7
7
  attempt: number;
8
8
  /** `executions.sandbox_name`, null for the process runner. */
9
9
  sandboxName: string | null;
@@ -101,10 +101,26 @@ export interface Runner {
101
101
  status(execution: RunnerExecution, options?: RunnerStatusOptions): Promise<RunnerStatus>;
102
102
  /** Remove everything the runner holds for the node: the run dir (process) or the sandbox (Blaxel). */
103
103
  delete(nodeId: string): Promise<void>;
104
- /** Remove only what one failed execution created (the Blaxel sandbox `<node id>-<attempt>`), where each attempt has its own. */
105
- deleteExecution?(execution: RunnerExecution): Promise<void>;
106
104
  /** Where a viewer reaches this execution's broker. */
107
105
  viewerAddress(execution: RunnerExecution): Promise<RunnerViewerAddress>;
106
+ /** Blaxel only: run a cron fire's command to completion in the node's sandbox, as process `cron-<run id>`. A repeat for the same run id
107
+ * reads that process instead of starting another. Throws when the node has no sandbox. `error` says why there is no exit code. */
108
+ cronRun?(nodeId: string, run: {
109
+ runId: string;
110
+ command: string;
111
+ cwd: string;
112
+ env: Record<string, string>;
113
+ timeoutS: number;
114
+ startedAtMs: number;
115
+ }): Promise<{
116
+ exitCode: number | null;
117
+ timedOut: boolean;
118
+ stdout: string;
119
+ stderr: string;
120
+ error?: string;
121
+ }>;
122
+ /** Blaxel only: kill the process of that run id; no sandbox or no process is not an error. */
123
+ cronCancel?(nodeId: string, runId: string): Promise<void>;
108
124
  }
109
125
  /** The runner for an environment kind: `machine` → process, `blaxel` → Blaxel. */
110
126
  export type RunnerForKind = (kind: 'machine' | 'blaxel') => Runner;
@@ -15,6 +15,11 @@ export declare const REMOTE_ATTACH_HEARTBEAT_MS = 25000;
15
15
  * quiet attach is a normal close the remote peer re-attaches from, and real work
16
16
  * is anchored by its own keep-alive, not by this ping.
17
17
  *
18
+ * A broker on a machine (`address.kind === 'machine'`, a Mac) is the exception:
19
+ * there is no sandbox to suspend, and the network route closes a silent
20
+ * connection about 125s after the last ping, which disconnects an idle viewer.
21
+ * Its heartbeat never goes quiet and pings for as long as the viewer is attached.
22
+ *
18
23
  * The clock starts when the attach OPENS, not at its first relayed frame: a
19
24
  * never-relaying attach still gets pings until this window elapses. The welcome
20
25
  * frame lands in milliseconds, so this only pads the tail of the very first
@@ -1,8 +1,8 @@
1
- var se=Object.defineProperty;var a=(r,e)=>se(r,"name",{value:e,configurable:!0});import{WebSocketServer as le}from"ws";import{general as fe}from"../../core/errors.js";import{toErrorBody as ue}from"./map.js";import{isSafeNodeId as K,viewSocketPath as de}from"../../core/canvas/paths.js";import{getNode as Q}from"../../core/canvas/index.js";import{requestPersonId as me,runAsPerson as he}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as we,CLIENT_READ_CAPS as pe,FrameDecoder as ye,FrameOverflowError as _e}from"../../core/runtime/broker-protocol.js";import{emitEvent as M}from"../../core/events/emit.js";import{addStepTiming as ke}from"../../core/step-timings.js";import{markAt as ve,timedSpan as F,withLoggedStepTimings as ge}from"../../core/logged-step-timings.js";import{classify as W}from"../../core/fault-classifier.js";import{clearFault as R,markNodeRead as be,recordFault as D}from"../../core/canvas/recovery.js";import{decideAttachRevive as Ae}from"../../core/runtime/revive.js";import{connectViewSocket as Se,connectWssView as Ee,probeViewSocket as xe,waitForBrokerViewSocket as Me,waitForWssView as G}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as Re,recordExecutionAwake as $e}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as Be}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as Ce}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as Te}from"../../core/spaces/open-beneath.js";import{openMachineView as Oe,waitForMachineView as X}from"../machine-link/forward.js";import{attachViewer as Y,detachViewer as Ve,holdViewerForRedial as Ne,presentViewer as Pe}from"./viewer-presence.js";const Z=3e4,Fe=new le({noServer:!0,maxPayload:we.maxLineBytes}),We=25e3,De=6e4;function Ue(r,e=We,i=De){let n=!0,c=!1,m=Date.now();const p=a(()=>{n=!0},"acknowledge"),u=a(()=>{c||(c=!0,clearInterval(b),r.off("pong",p))},"stop");r.on("pong",p);const b=setInterval(()=>{if(Date.now()-m>i){n=!0;return}if(!n){u(),r.terminate();return}n=!1;try{r.ping()}catch{u(),r.terminate()}},e);return b.unref(),{stop:u,noteActivity:a(()=>{m=Date.now()},"noteActivity")}}a(Ue,"startRemoteAttachHeartbeat");function U(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}a(U,"clampReason");function g(r,e,i,n,c){ke("refused_status",e);const m=JSON.stringify({error:{code:n,message:c,origin:"runtime"}}),p=`HTTP/1.1 ${e} ${i}\r
1
+ var fe=Object.defineProperty;var i=(r,e)=>fe(r,"name",{value:e,configurable:!0});import{WebSocketServer as ue}from"ws";import{general as de}from"../../core/errors.js";import{toErrorBody as me}from"./map.js";import{isSafeNodeId as K,viewSocketPath as he}from"../../core/canvas/paths.js";import{getNode as Q}from"../../core/canvas/index.js";import{requestPersonId as we,runAsPerson as pe}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as ye,CLIENT_READ_CAPS as _e,FrameDecoder as ke,FrameOverflowError as ve}from"../../core/runtime/broker-protocol.js";import{emitEvent as M}from"../../core/events/emit.js";import{addStepTiming as ge}from"../../core/step-timings.js";import{markAt as be,timedSpan as F,withLoggedStepTimings as Ae}from"../../core/logged-step-timings.js";import{classify as W}from"../../core/fault-classifier.js";import{clearFault as R,markNodeRead as Se,recordFault as D}from"../../core/canvas/recovery.js";import{decideAttachRevive as Ee}from"../../core/runtime/revive.js";import{connectViewSocket as xe,connectWssView as Me,probeViewSocket as Re,waitForBrokerViewSocket as $e,waitForWssView as G}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as Be,recordExecutionAwake as Ce}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as Te}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as Oe}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as Ve}from"../../core/spaces/open-beneath.js";import{openMachineView as Ne,waitForMachineView as X}from"../machine-link/forward.js";import{attachViewer as Y,detachViewer as Pe,holdViewerForRedial as Fe,presentViewer as We}from"./viewer-presence.js";const Z=3e4,De=new ue({noServer:!0,maxPayload:ye.maxLineBytes}),I=25e3,ee=6e4;function Ue(r,e=I,a=ee){let n=!0,c=!1,m=Date.now();const p=i(()=>{n=!0},"acknowledge"),u=i(()=>{c||(c=!0,clearInterval(b),r.off("pong",p))},"stop");r.on("pong",p);const b=setInterval(()=>{if(Date.now()-m>a){n=!0;return}if(!n){u(),r.terminate();return}n=!1;try{r.ping()}catch{u(),r.terminate()}},e);return b.unref(),{stop:u,noteActivity:i(()=>{m=Date.now()},"noteActivity")}}i(Ue,"startRemoteAttachHeartbeat");function U(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}i(U,"clampReason");function g(r,e,a,n,c){ge("refused_status",e);const m=JSON.stringify({error:{code:n,message:c,origin:"runtime"}}),p=`HTTP/1.1 ${e} ${a}\r
2
2
  content-type: application/json; charset=utf-8\r
3
3
  content-length: ${Buffer.byteLength(m)}\r
4
4
  connection: close\r
5
5
  \r
6
- `+m;try{r.end(p)}catch{try{r.destroy()}catch{}}}a(g,"refuseUpgrade");function I(r,e){const{status:i,body:n}=ue(e);g(r,i,"Refused",n.error.code,n.error.message)}a(I,"refuseWithError");function He(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const i=r.headers["x-crtr-attach-revive"];return(Array.isArray(i)?i[0]:i)==="0"}a(He,"reviveOptedOut");function Le(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}a(Le,"wakeParkedRequested");function ee(r){return r===1e3||r===1001||r===1005}a(ee,"isCleanViewerClose");function _(r,e,i){i.catch(n=>M({level:"error",event:e,node_id:r,error:n}))}a(_,"detach");async function re(r){const e=await Re(r);return e===null||e.runner==="process"?{kind:"unix",path:de(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Be(e.executionId,Date.now()),await $e(e.executionId)),Ce(e.runner).viewerAddress(e))}a(re,"brokerViewAddress");function ze(r,e){return e.kind==="machine"?Oe(e.environmentId,r):e.kind==="wss"?Ee(e.url,e.headers):Se(r)}a(ze,"connectBrokerView");function Je(r,e,i){return e.kind==="wss"?G(e.url,e.headers,void 0,i):xe(r,i)}a(Je,"probeBrokerView");async function je(r,e,i,n,c){const m=[];let p=a(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>p(t)),!K(e)){c?.destroy();try{r.close(1008,U(`invalid node id: ${e}`))}catch{}return}if(await Q(e)===null){c?.destroy();try{r.close(1011,U(`no node ${e}`))}catch{}return}const u=performance.now();await R(e,{link:"viewer\u2194crtrd"});const b=performance.now(),o=c??ze(e,i),f=a(()=>Math.round((performance.now()-b)*10)/10,"sinceOpen"),h=a((t,s={})=>{M({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:i.kind,channel:o.channel??"",since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10,...s}})},"bridgeMark");c===void 0&&h("channel_opened");const A=new ye(pe);let k=!1,$=!1,B,H=!1,L=!1,S,z=!1,T="controller",J=Promise.resolve(),C=!1;const O=[];let V=!1,N=!1,j=!1,x=0;const q=a(()=>{c===void 0&&h("channel_connected"),H=!0,!k&&C&&_(e,"daemon.bridge.presence_failed",Y(e,r)),_(e,"daemon.bridge.connect_failed",R(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",q);const y=a((t,s,l=!1)=>{if(!k){if(k=!0,_(e,"daemon.bridge.presence_failed",l?Ne(e,r):Ve(e,r)),B?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,U(s))}catch{}}},"teardown");B=Ue(r);const te=a(async t=>{B?.noteActivity();let s;const l=performance.now();try{s=A.push(t)}catch(w){const E=w instanceof _e?`broker sent an oversized frame (${w.message})`:`failed to decode a broker frame for ${e}`;y(1009,E);return}!N&&s.some(w=>w?.type==="welcome")&&(N=!0,x=performance.now(),h("welcome_decoded",{decode_ms:Math.round((x-l)*10)/10,chunk_bytes:t.length,since_hello_ms:S===void 0?-1:Math.round((x-S)*10)/10})),O.push(...s),V||await ne()},"onData"),ne=a(async()=>{V=!0;try{for(;O.length>0&&!k;){const t=O.splice(0),s=N&&!j&&t.some(d=>d?.type==="welcome"),l=performance.now();let w;try{w=await n(T),s&&(j=!0,h("welcome_authorized",{auth_ms:Math.round((performance.now()-l)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}catch(d){M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),y(1011,"revoked");return}if(k)return;if(!w){y(1008,"revoked");return}let E=!1;for(const d of t){if(r.readyState!==r.OPEN)continue;const v=d?.type==="welcome",P=performance.now();r.send(JSON.stringify(d)),v&&(E=!0,h("welcome_forwarded",{send_ms:Math.round((performance.now()-P)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}if(C&&E)try{await Pe(e,r)&&await be(e)}catch(d){M({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{V=!1}},"drainOutbound");o.on("data",t=>_(e,"daemon.bridge.data_failed",te(t)));const oe=a(async t=>{const s=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const l=W("relay\u2194broker",t);await D(e,{link:"relay\u2194broker",op:"bridge socket",kind:l.kind,retry:{disposition:"manual"},message:t.message})}finally{y(1011,s,!0)}},"onSocketError");o.on("error",t=>_(e,"daemon.bridge.socket_error_failed",oe(t)));const ae=a(async t=>{if(!(k||t))try{await R(e,{link:"relay\u2194broker"})}finally{y(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>_(e,"daemon.bridge.socket_close_failed",ae(t)));const ie=a(async(t,s)=>{const l=s.toString("utf8");if(k){ee(t)&&await R(e,{link:"viewer\u2194crtrd"});return}try{if(ee(t))await R(e,{link:"viewer\u2194crtrd"});else if(!$){$=!0;const w=W("viewer\u2194crtrd",{code:t,reason:l});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:w.kind,retry:{disposition:"auto"},message:l||`remote attach closed (${t})`})}}finally{y(t,l||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,s)=>_(e,"daemon.bridge.ws_close_failed",ie(t,s)));const ce=a(async()=>{try{if(!$){$=!0;const t=W("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{y(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>_(e,"daemon.bridge.ws_error_failed",ce())),p=a(t=>{if(k||o.destroyed)return;B?.noteActivity();const l=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!L)try{const v=JSON.parse(l);v?.type==="hello"&&(h("hello_received"),S=performance.now(),L=!0,T=v.role==="observer"?"observer":"controller",C=v.attends!==!1,C&&H&&_(e,"daemon.bridge.presence_failed",Y(e,r)))}catch{}const w=l.endsWith(`
6
+ `+m;try{r.end(p)}catch{try{r.destroy()}catch{}}}i(g,"refuseUpgrade");function re(r,e){const{status:a,body:n}=me(e);g(r,a,"Refused",n.error.code,n.error.message)}i(re,"refuseWithError");function He(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(He,"reviveOptedOut");function Le(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Le,"wakeParkedRequested");function te(r){return r===1e3||r===1001||r===1005}i(te,"isCleanViewerClose");function _(r,e,a){a.catch(n=>M({level:"error",event:e,node_id:r,error:n}))}i(_,"detach");async function ne(r){const e=await Be(r);return e===null||e.runner==="process"?{kind:"unix",path:he(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Te(e.executionId,Date.now()),await Ce(e.executionId)),Oe(e.runner).viewerAddress(e))}i(ne,"brokerViewAddress");function ze(r,e){return e.kind==="machine"?Ne(e.environmentId,r):e.kind==="wss"?Me(e.url,e.headers):xe(r)}i(ze,"connectBrokerView");function Je(r,e,a){return e.kind==="wss"?G(e.url,e.headers,void 0,a):Re(r,a)}i(Je,"probeBrokerView");async function je(r,e,a,n,c){const m=[];let p=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>p(t)),!K(e)){c?.destroy();try{r.close(1008,U(`invalid node id: ${e}`))}catch{}return}if(await Q(e)===null){c?.destroy();try{r.close(1011,U(`no node ${e}`))}catch{}return}const u=performance.now();await R(e,{link:"viewer\u2194crtrd"});const b=performance.now(),o=c??ze(e,a),f=i(()=>Math.round((performance.now()-b)*10)/10,"sinceOpen"),h=i((t,s={})=>{M({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:a.kind,channel:o.channel??"",since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10,...s}})},"bridgeMark");c===void 0&&h("channel_opened");const A=new ke(_e);let k=!1,$=!1,B,H=!1,L=!1,S,z=!1,T="controller",J=Promise.resolve(),C=!1;const O=[];let V=!1,N=!1,j=!1,x=0;const q=i(()=>{c===void 0&&h("channel_connected"),H=!0,!k&&C&&_(e,"daemon.bridge.presence_failed",Y(e,r)),_(e,"daemon.bridge.connect_failed",R(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",q);const y=i((t,s,l=!1)=>{if(!k){if(k=!0,_(e,"daemon.bridge.presence_failed",l?Fe(e,r):Pe(e,r)),B?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,U(s))}catch{}}},"teardown");B=Ue(r,I,a.kind==="machine"?1/0:ee);const oe=i(async t=>{B?.noteActivity();let s;const l=performance.now();try{s=A.push(t)}catch(w){const E=w instanceof ve?`broker sent an oversized frame (${w.message})`:`failed to decode a broker frame for ${e}`;y(1009,E);return}!N&&s.some(w=>w?.type==="welcome")&&(N=!0,x=performance.now(),h("welcome_decoded",{decode_ms:Math.round((x-l)*10)/10,chunk_bytes:t.length,since_hello_ms:S===void 0?-1:Math.round((x-S)*10)/10})),O.push(...s),V||await ie()},"onData"),ie=i(async()=>{V=!0;try{for(;O.length>0&&!k;){const t=O.splice(0),s=N&&!j&&t.some(d=>d?.type==="welcome"),l=performance.now();let w;try{w=await n(T),s&&(j=!0,h("welcome_authorized",{auth_ms:Math.round((performance.now()-l)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}catch(d){M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),y(1011,"revoked");return}if(k)return;if(!w){y(1008,"revoked");return}let E=!1;for(const d of t){if(r.readyState!==r.OPEN)continue;const v=d?.type==="welcome",P=performance.now();r.send(JSON.stringify(d)),v&&(E=!0,h("welcome_forwarded",{send_ms:Math.round((performance.now()-P)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}if(C&&E)try{await We(e,r)&&await Se(e)}catch(d){M({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{V=!1}},"drainOutbound");o.on("data",t=>_(e,"daemon.bridge.data_failed",oe(t)));const ae=i(async t=>{const s=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const l=W("relay\u2194broker",t);await D(e,{link:"relay\u2194broker",op:"bridge socket",kind:l.kind,retry:{disposition:"manual"},message:t.message})}finally{y(1011,s,!0)}},"onSocketError");o.on("error",t=>_(e,"daemon.bridge.socket_error_failed",ae(t)));const ce=i(async t=>{if(!(k||t))try{await R(e,{link:"relay\u2194broker"})}finally{y(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>_(e,"daemon.bridge.socket_close_failed",ce(t)));const se=i(async(t,s)=>{const l=s.toString("utf8");if(k){te(t)&&await R(e,{link:"viewer\u2194crtrd"});return}try{if(te(t))await R(e,{link:"viewer\u2194crtrd"});else if(!$){$=!0;const w=W("viewer\u2194crtrd",{code:t,reason:l});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:w.kind,retry:{disposition:"auto"},message:l||`remote attach closed (${t})`})}}finally{y(t,l||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,s)=>_(e,"daemon.bridge.ws_close_failed",se(t,s)));const le=i(async()=>{try{if(!$){$=!0;const t=W("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{y(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>_(e,"daemon.bridge.ws_error_failed",le())),p=i(t=>{if(k||o.destroyed)return;B?.noteActivity();const l=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!L)try{const v=JSON.parse(l);v?.type==="hello"&&(h("hello_received"),S=performance.now(),L=!0,T=v.role==="observer"?"observer":"controller",C=v.attends!==!1,C&&H&&_(e,"daemon.bridge.presence_failed",Y(e,r)))}catch{}const w=l.endsWith(`
7
7
  `)?l:l+`
8
- `,E=a(()=>{try{o.write(w)}catch{}},"write"),d=S===void 0?!1:z===!1;d&&(z=!0),J=J.then(async()=>{if(k)return;const v=performance.now(),P=await n(T);d&&h("hello_authorized",{auth_ms:Math.round((performance.now()-v)*10)/10,since_hello_ms:Math.round((performance.now()-S)*10)/10}),P?(E(),d&&h("hello_written",{since_hello_ms:Math.round((performance.now()-S)*10)/10})):y(1008,"revoked")}).catch(v=>{M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:v}),y(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))p(t);c!==void 0&&(c.destroyed?y(1011,`no running broker for ${e}`,!0):q())}a(je,"bridgeConnection");async function hr(r,e,i,n,c){await ge("attach_upgrade",{node:n},r,()=>qe(r,e,i,n,c))}a(hr,"handleAttachUpgrade");async function qe(r,e,i,n,c){const m=me(),p=m===void 0?c:o=>he(m,()=>c(o));e.on("error",()=>{});let u,b=!1;try{if(!K(n)){g(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await F("admission",async()=>await Q(n)===null)){g(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(He(r)){o=await re(n);let f;if(o.kind==="machine"?(u=await X(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Je(n,o,o.kind==="wss"?Z:250),!f){g(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const A=await F("revive_decision",async()=>await Ae(n,{resume:!0,capacity:"refuse"},Le(r)));if(A.parked){g(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=A.result.launch?.exited}catch(A){I(e,A);return}if(o=await F("address_lookup",async()=>await re(n)),o.kind==="machine"&&(u=await X(o.environmentId,n,f,Z)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await G(o.url,o.headers,f):await Me(n,f))){o.kind==="machine"?I(e,fe(`the broker for ${n} on its machine did not accept a viewer after revive`)):g(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;ve("upgrading"),Fe.handleUpgrade(r,e,i,f=>{b=!0,_(n,"daemon.bridge.connection_failed",je(f,n,o,p,u).catch(h=>{throw u?.destroy(),h}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Te(o)){g(e,400,"Bad Request","invalid_request",f);return}g(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{b||u?.destroy()}}a(qe,"attachUpgrade");export{We as REMOTE_ATTACH_HEARTBEAT_MS,De as REMOTE_ATTACH_QUIET_MS,hr as handleAttachUpgrade,ee as isCleanViewerClose,g as refuseUpgrade,Ue as startRemoteAttachHeartbeat};
8
+ `,E=i(()=>{try{o.write(w)}catch{}},"write"),d=S===void 0?!1:z===!1;d&&(z=!0),J=J.then(async()=>{if(k)return;const v=performance.now(),P=await n(T);d&&h("hello_authorized",{auth_ms:Math.round((performance.now()-v)*10)/10,since_hello_ms:Math.round((performance.now()-S)*10)/10}),P?(E(),d&&h("hello_written",{since_hello_ms:Math.round((performance.now()-S)*10)/10})):y(1008,"revoked")}).catch(v=>{M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:v}),y(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))p(t);c!==void 0&&(c.destroyed?y(1011,`no running broker for ${e}`,!0):q())}i(je,"bridgeConnection");async function hr(r,e,a,n,c){await Ae("attach_upgrade",{node:n},r,()=>qe(r,e,a,n,c))}i(hr,"handleAttachUpgrade");async function qe(r,e,a,n,c){const m=we(),p=m===void 0?c:o=>pe(m,()=>c(o));e.on("error",()=>{});let u,b=!1;try{if(!K(n)){g(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await F("admission",async()=>await Q(n)===null)){g(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(He(r)){o=await ne(n);let f;if(o.kind==="machine"?(u=await X(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Je(n,o,o.kind==="wss"?Z:250),!f){g(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const A=await F("revive_decision",async()=>await Ee(n,{resume:!0,capacity:"refuse"},Le(r)));if(A.parked){g(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=A.result.launch?.exited}catch(A){re(e,A);return}if(o=await F("address_lookup",async()=>await ne(n)),o.kind==="machine"&&(u=await X(o.environmentId,n,f,Z)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await G(o.url,o.headers,f):await $e(n,f))){o.kind==="machine"?re(e,de(`the broker for ${n} on its machine did not accept a viewer after revive`)):g(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;be("upgrading"),De.handleUpgrade(r,e,a,f=>{b=!0,_(n,"daemon.bridge.connection_failed",je(f,n,o,p,u).catch(h=>{throw u?.destroy(),h}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Ve(o)){g(e,400,"Bad Request","invalid_request",f);return}g(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{b||u?.destroy()}}i(qe,"attachUpgrade");export{I as REMOTE_ATTACH_HEARTBEAT_MS,ee as REMOTE_ATTACH_QUIET_MS,hr as handleAttachUpgrade,te as isCleanViewerClose,g as refuseUpgrade,Ue as startRemoteAttachHeartbeat};
@@ -1,2 +1,4 @@
1
1
  import { type RouteTable } from '../router.js';
2
+ /** How long a hosted cron armed without an expiry lasts. */
3
+ export declare const HOSTED_CRON_DEFAULT_EXPIRY_MS: number;
2
4
  export declare const cronRoutes: RouteTable;
@@ -1 +1 @@
1
- var tn=Object.defineProperty;var t=(e,n)=>tn(e,"name",{value:n,configurable:!0});import{randomUUID as an}from"node:crypto";import{relative as sn,resolve as H,sep as M}from"node:path";import{ApiError as a}from"../../../api/errors.js";import{armCron as ln,parseCronSink as cn,getCron as v,listCrons as A,listCronRuns as Z,pokeHeldCrons as un,setCronState as Y}from"../../../core/canvas/crons.js";import{getNode as f}from"../../../core/canvas/canvas.js";import{appSpace as dn,cronFolder as pn}from"../../../core/layout.js";import{appProcessesSandboxed as fn,cwdIsMounted as wn}from"../../../core/spaces/process.js";import{activeGrant as _n,activeGrantForApp as hn,grantFor as mn}from"../../../core/grants/mirror.js";import{callerTerminalGrant as gn}from"../../../core/grants/terminal.js";import{assertScope as K}from"../../../core/scopes.js";import{InputError as l}from"../../../core/io.js";import{nextSlotAfter as yn}from"../../../core/wake.js";import{executeCron as bn,markSelfCanceledCronRun as kn}from"../../cron-run.js";import{toCronDTO as S,toCronRunDTO as Q}from"../map.js";import{appOf as R,assertCeiling as vn,canReadNode as Sn}from"../router.js";import{checkCronBirth as $n,checkCronFire as On,cronRefusalError as Cn}from"../../cron/authority.js";import{endCron as In}from"../../cron/ended.js";import{requireUsableProfile as qn}from"./profiles.js";import{lookupProfile as Nn}from"../../../core/profiles/manifest.js";import{filterAsync as Tn,mapAsync as jn}from"../../../core/async-array.js";import{personId as Pn}from"../../../core/canvas/person.js";import{openDb as En}from"../../../core/canvas/db.js";function U(e,n){const r=e[n];if(typeof r!="string"||r.trim()==="")throw new l({error:"missing_field",message:`cron arm request requires a non-empty "${n}"`,field:n,next:`Send a non-empty string "${n}".`});return r}t(U,"requireString");function C(e,n,r,o){if(e==null)return o;if(typeof e=="string"&&r.includes(e))return e;throw new l({error:`bad_${n}`,message:`"${String(e)}" is not a valid ${n}`,field:n,next:`Use one of: ${r.join(", ")}.`})}t(C,"requireEnum");async function An(e){if(e==="human")return JSON.stringify({human:!0});if(e.startsWith("node:")){const n=e.slice(5).trim();if(n==="")throw new l({error:"bad_sink",message:"node sink requires a node id",field:"sink",next:'Use sink "node:<node-id>".'});if(await f(n)===null)throw new l({error:"sink_node_not_found",message:`sink node ${n} does not exist on the canvas`,field:"sink",next:"Name a live node id, or use spawn:<kind> for a delivery that outlives any one node."});return JSON.stringify({node:n})}if(e.startsWith("spawn:")){const n=e.slice(6).trim();if(n==="")throw new l({error:"bad_sink",message:"spawn sink requires a node kind",field:"sink",next:'Use sink "spawn:<kind>" (e.g. spawn:general).'});return JSON.stringify({spawn:n})}throw new l({error:"bad_sink",message:`"${e}" is not a valid sink`,field:"sink",next:"Use node:<node-id>, spawn:<kind>, or human."})}t(An,"parseSinkSpec");const Rn=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/;function V(e,n){if(!Rn.test(e)||Number.isNaN(Date.parse(e)))throw new l({error:`bad_${n}`,message:`"${e}" is not a UTC ISO instant`,field:n,next:'Send a resolved UTC instant like "2026-06-07T09:00:00.000Z" (the client resolves the time grammar).'});return e}t(V,"requireUtcIso");function Un(e){try{yn(e,new Date)}catch(n){throw new l({error:"bad_recur",message:`recur is not advanceable: ${n instanceof Error?n.message:String(n)}`,field:"recur",next:'Send recur JSON the daemon can advance: {"every":"6h"} or {"cron":"0 9 * * *","tz":"America/New_York"}.'})}return e}t(Un,"requireRecur");function Jn(e){let n;try{n=JSON.parse(e)}catch{throw new l({error:"bad_env_json",message:"env_json is not valid JSON",field:"env_json",next:'Send a JSON object of string values, e.g. {"API_BASE":"https://x"}.'})}if(typeof n!="object"||n===null||Array.isArray(n))throw new l({error:"bad_env_json",message:"env_json must be a JSON object",field:"env_json",next:'Send a JSON object of string values, e.g. {"API_BASE":"https://x"}.'});for(const[r,o]of Object.entries(n))if(typeof o!="string")throw new l({error:"bad_env_json",message:`env_json value for "${r}" is not a string`,field:"env_json",next:"Every env value must be a string."});return e}t(Jn,"requireEnvJson");function J(e){const n=e.query.get("profile");return n!==null&&n.trim()!==""?n.trim():null}t(J,"callerProfile");function X(e,n){return n===null||e.scope==="global"||e.profile===n}t(X,"inScope");function nn(e){return e.principal.class==="person"?null:R(e.principal)}t(nn,"callerApp");function I(e){return e.principal.class==="person"?e.principal.sub??null:null}t(I,"bearerPerson");async function en(e,n){return(await(await En()).prepare("SELECT person FROM profiles WHERE id = ?").get(e))?.person===n}t(en,"profileBelongsTo");async function W(e,n){const r=I(e);if(r!==null)return n.profile!==null&&await en(n.profile,r);if(!await Sn(e.principal,n.grantee))return!1;const o=e.principal,i=o.class==="broker"?await f(o.node):o.class==="cron"?{run_id:o.origin_run,isolated:o.isolated}:o.class==="forwarded"&&o.actor.kind==="app"?{run_id:o.actor.place.run,isolated:o.actor.place.isolated}:null;return!(i!==null&&(i.isolated||n.isolated)&&i.run_id!==n.origin_run_id)}t(W,"visibleTo");function Wn(e){return typeof e.anchor_node=="string"&&e.anchor_node!==""?e.anchor_node:null}t(Wn,"anchorNodeOf");async function Dn(e,n,r,o,i,u){const p=typeof e.cwd=="string"&&e.cwd.trim()!==""?H(e.cwd):null;if(!fn()){if(p===null)throw new l({error:"missing_field",message:'cron arm request requires a non-empty "cwd"',field:"cwd",next:'Send a non-empty string "cwd".'});return p}const g=o!==null&&await f(o)!==null?o:void 0,c=t(async T=>await wn(n,T,g,i,void 0,u),"reaches");if(p!==null&&await c(p))return p;const s=dn(n).files;if(p!==null&&e.cwd_is_default!==!0)throw new a(400,"invalid_request",`cwd ${p} is not inside a directory this app's cron runs can see, so every run would fail to start; use a directory under ${s}`,{cwd:p,default:s},void 0,{param:"cwd"});const w=r===null?null:(await f(r))?.cwd??null;return w!==null&&await c(w)?w:s}t(Dn,"resolveArmedCwd");async function Bn(e,n,r){const o=e.principal;if(o.class==="person"){const s=await gn();return{sub:s?.sub??o.sub??Pn(),grant_id:s?.id??null,scopes:null,origin_run_id:null}}if(o.class==="app"){const s=await hn(n);if(s===null)throw new a(401,"grant_revoked",`no active grant for ${n}`);const w=e.ceiling??o.scopes;return{sub:s.sub,grant_id:s.id,scopes:w===null?null:[...w],origin_run_id:null}}if(o.class==="cron"){const s=await On({grantee:o.app,sub:o.sub,grant_id:o.grant,scopes:o.scopes});if(!s.allowed)throw new a(s.reason==="scope_missing"?403:401,s.reason==="scope_missing"?"scope_missing":"grant_revoked",s.message);return{sub:o.sub,grant_id:o.grant,scopes:o.scopes===null?null:[...o.scopes],origin_run_id:o.origin_run,armed_from_exec:o.from_exec}}if(o.class!=="broker")throw new a(401,"unauthorized","this caller cannot arm a cron");const i=r??await f(o.node),u=i?.grant_id??o.grant,p=i?.sub??o.sub,g=u!=null?await _n(u):await mn(n,p);if(g===null)throw new a(401,"grant_revoked","the node grant is not active");const c=i?.scopes??o.scopes;return{sub:g.sub,grant_id:g.id,scopes:c===null?null:[...c],origin_run_id:i?.run_id??o.run}}t(Bn,"armPrincipal");async function zn(e){const n=e.body??{},r=U(n,"name"),o=U(n,"command"),i=V(U(n,"fire_at"),"fire_at"),u=typeof n.recur=="string"&&n.recur!==""?Un(n.recur):null,p=typeof n.expires_at=="string"&&n.expires_at!==""?V(n.expires_at,"expires_at"):null,g=typeof n.env_json=="string"&&n.env_json!==""?Jn(n.env_json):null,c=typeof n.sink=="string"&&n.sink.trim()!==""?n.sink.trim():null,s=C(n.on_output,"on_output",["silent","on-failure","always","on-change"],c?.startsWith("node:")?"on-change":"on-failure"),w=C(n.overlap,"overlap",["skip","queue","replace"],"skip"),T=C(n.tier,"tier",["normal","urgent","critical"],"normal"),B=s==="always"||s==="on-change";if(B&&c===null)throw new l({error:"sink_required",message:`on_output "${s}" delivers stdout every qualifying run \u2014 it needs a sink`,field:"sink",next:"Pass sink node:<node-id> (a living node's inbox), spawn:<kind> (birth a fresh node per delivery), or human (the humanloop inbox)."});if(!B&&c!==null)throw new l({error:"sink_unused",message:`on_output "${s}" never delivers stdout \u2014 a sink would be dead config`,field:"sink",next:'Drop the sink, or use on_output "always"/"on-change" if delivery is the point.'});const rn=c!==null?await An(c):"{}",z=I(e);if(z!==null)for(const d of[c?.startsWith("node:")?c.slice(5).trim():null,typeof n.created_by=="string"?n.created_by:null,typeof n.anchor_node=="string"?n.anchor_node:null]){const L=d===null||d===""?null:await f(d);if(L!==null&&L.sub!==z)throw new a(404,"not_found","node not found")}if(c?.startsWith("spawn:")&&(vn(e.ceiling,"crtr:act"),e.principal.class==="cron")){const d=await $n({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,from_exec:e.principal.from_exec},{kind:c.slice(6)});if(!d.allowed)throw Cn(d)}const b=R(e.principal)??"app:terminal",k=e.principal.class==="broker"?e.principal.node:e.principal.class==="cron"?null:typeof n.created_by=="string"&&n.created_by!==""?n.created_by:null;if(e.principal.class==="broker"&&n.created_by!=null&&n.created_by!==k)throw new a(403,"permission_error","a broker may only arm a cron as its own node");const y=k===null?null:await f(k);if(y!==null){if(y.grantee!==b)throw new l({error:"creator_app_mismatch",message:"creator node belongs to another app",field:"created_by",next:"Use a node of the calling app."});K(y,"crtr:schedule"),c?.startsWith("spawn:")&&K(y,"crtr:act")}if(n.isolated!==void 0&&typeof n.isolated!="boolean")throw new a(400,"invalid_request","isolated must be a boolean");if(y?.isolated&&n.isolated===!1)throw new a(403,"isolated_run","a cron created by an isolated node cannot escape isolation");const F=y?.isolated===!0||e.principal.class==="cron"&&e.principal.isolated;if(F&&n.isolated===!1)throw new a(403,"isolated_run","a cron created by an isolated caller cannot escape isolation");const j=F||n.isolated===!0,_=await Bn(e,b,y),P=an(),$=j?pn(b,P):null;if($!==null&&n.cwd_is_default!==!0){const d=sn($,typeof n.cwd=="string"&&n.cwd.trim()!==""?H(n.cwd):$);if(d===".."||d.startsWith(`..${M}`)||d.startsWith(M))throw new a(400,"invalid_request","an isolated cron must run in its own cron folder",{param:"cwd"})}const on=$??await Dn(n,b,k,Wn(n),j,{sub:_.sub,grantId:_.grant_id,scopes:_.scopes}),h=typeof n.anchor_node=="string"&&n.anchor_node!==""?n.anchor_node:null;if(h!==null&&await f(h)!==null&&(await f(h)).grantee!==b)throw new l({error:"anchor_app_mismatch",message:"anchor node belongs to another app",field:"anchor_node",next:"Use an anchor of the calling app."});if(h!==null&&await f(h)===null)throw new l({error:"anchor_not_found",message:`anchor node ${h} does not exist on the canvas`,field:"anchor_node",next:"Name a live node id, or drop the anchor \u2014 an unanchored cron outlives every node."});const G=n.cancel_on_wake===!0;if(G&&h===null)throw new l({error:"cancel_on_wake_needs_anchor",message:"cancel_on_wake couples the cron to a node's dormancy \u2014 it requires an anchor node",field:"anchor_node",next:"Pass anchor_node with the node whose wake should cancel this cron."});const O=n.run_timeout_s??300;if(typeof O!="number"||!Number.isInteger(O)||O<=0)throw new l({error:"bad_run_timeout",message:`run_timeout_s must be a positive integer (got ${String(n.run_timeout_s)})`,field:"run_timeout_s",next:"Send the timeout in whole seconds, e.g. 300."});const E=I(e),m=typeof n.profile!="string"||n.profile===""?null:E===null?(await qn(e,n.profile)).profileId:(()=>{const d=Nn(n.profile);if(d.kind!=="resolved")throw new a(404,"not_found","profile not found");return d.entry.profileId})();if(E!==null&&(m===null||!await en(m,E)))throw new a(m===null?400:404,m===null?"invalid_request":"not_found",m===null?"a person's cron names the profile it belongs to":"profile not found",void 0,void 0,{param:"profile"});const x=C(n.scope,"scope",["profile","global"],m!==null?"profile":"global");if(x==="profile"&&m===null)throw new l({error:"scope_needs_profile",message:'scope "profile" names the profile the cron lists and cancels within \u2014 it requires a profile',field:"profile",next:'Send a profile, or use scope "global" for a canvas-home-wide cron.'});return await ln({cron_id:P,name:r,created_by:k,grantee:b,sub:_.sub,grant_id:_.grant_id,scopes:_.scopes,origin_run_id:_.origin_run_id,armed_from_exec:_.armed_from_exec===!0,isolated:j,command:o,fire_at:i,recur:u,tz:typeof n.tz=="string"?n.tz:null,expires_at:p,anchor_node:h,cancel_on_wake:G,cwd:on,env_json:g,profile:m,scope:x,run_timeout_s:O,overlap:w,on_output:s,sink:rn,tier:T}),{status:201,body:S(await v(P),null)}}t(zn,"handleArm");async function Fn(e){const n=J(e),r=e.query.get("created_by");if(r==="")throw new a(400,"invalid_request","created_by must be nonempty when present");const o=await Tn((n===null?await A({all:!0}):[...await A({profile:n}),...await A({global:!0})].sort((i,u)=>i.fire_at<u.fire_at?-1:i.fire_at>u.fire_at?1:0)).filter(i=>r===null||i.created_by===r),async i=>await W(e,i));return{status:200,body:await jn(o,async i=>S(i,await D(i)))}}t(Fn,"handleList");async function D(e){return(await Z(e.cron_id))[0]??null}t(D,"lastRunOf");async function q(e){const n=e.params.cronId,r=await v(n);if(r===null||!await W(e,r))throw new a(404,"cron_not_found",`no cron ${n}`);if(!X(r,J(e)))throw new a(404,"cron_not_found",`no cron ${n} in this profile \u2014 it is scoped to another profile`);return r}t(q,"requireCron");function N(e,n){const r=nn(e);if(r!==null&&n.grantee!==r)throw new a(403,"other_app_run",`cron ${n.cron_id} belongs to another app`);return n}t(N,"requireOwnCron");async function Gn(e){const n=await q(e),r=await Z(n.cron_id);return{status:200,body:{cron:S(n,r[0]??null),runs:r.map(Q)}}}t(Gn,"handleShow");async function xn(e){const n=N(e,await q(e));await Y(n.cron_id,"paused");const r=await v(n.cron_id);return{status:200,body:S(r,await D(r))}}t(xn,"handlePause");async function Ln(e){const n=N(e,await q(e));await Y(n.cron_id,"active");const r=await v(n.cron_id);return{status:200,body:S(r,await D(r))}}t(Ln,"handleResume");async function Hn(e){const n=N(e,await q(e));if(n.run_state==="running")throw new a(409,"cron_running",`cron ${n.cron_id} has a run in flight \u2014 wait for it to settle`);const r=await bn(n,{outOfBand:!0});if(r===null)throw new a(409,"cron_running",`cron ${n.cron_id} was claimed by a concurrent run \u2014 check \`cron show\` for its result`);return{status:200,body:Q(r)}}t(Hn,"handleRun");async function Mn(e){if(I(e)!==null)throw new a(403,"permission_error","a person's sign-in does not poke the whole control plane's crons");const n=new Date().toISOString();return{status:200,body:{unparked:await un(n,nn(e)),at:n}}}t(Mn,"handlePoke");function Zn(e,n){const r=e.principal;if(r.class==="cron")return r.kind==="exec"?{kind:"canceled",by:r.app}:r.cron===n.cron_id?null:{kind:"canceled",by:`cron ${r.cron}`};if(r.class==="broker"){const i=cn(n.sink);return i?.kind==="node"&&i.node===r.node?null:{kind:"canceled",by:`node ${r.node}`}}const o=R(r);return{kind:"canceled",by:o===null||o==="app:terminal"?"the person":o}}t(Zn,"cancelNotice");async function Yn(e){const n=e.params.cronId,r=await v(n);if(r!==null&&!await W(e,r))throw new a(404,"cron_not_found",`no cron ${n}`);if(r!==null&&!X(r,J(e)))throw new a(404,"cron_not_found",`no cron ${n} in this profile \u2014 it is scoped to another profile`);r!==null&&N(e,r);const o=e.query.get("run_id"),i=e.principal.class==="cron"?e.principal.kind==="cron"&&o===e.principal.execution&&n===e.principal.cron:!0,u=o!==null&&i&&kn(n,o);return r!==null&&await In(r,u?null:Zn(e,r),{preserveRunningProcess:u}),{status:204}}t(Yn,"handleCancel");const ye=[{method:"POST",pattern:"/v1/crons",scope:"crtr:schedule",handler:zn},{method:"GET",pattern:"/v1/crons",handler:Fn},{method:"GET",pattern:"/v1/crons/:cronId",handler:Gn},{method:"POST",pattern:"/v1/crons/:cronId/pause",scope:"crtr:schedule",handler:xn},{method:"POST",pattern:"/v1/crons/:cronId/resume",scope:"crtr:schedule",handler:Ln},{method:"POST",pattern:"/v1/crons/poke",scope:"crtr:schedule",handler:Mn},{method:"POST",pattern:"/v1/crons/:cronId/run",scope:"crtr:schedule",handler:Hn},{method:"DELETE",pattern:"/v1/crons/:cronId",scope:"crtr:schedule",handler:Yn}];export{ye as cronRoutes};
1
+ var dn=Object.defineProperty;var t=(e,n)=>dn(e,"name",{value:n,configurable:!0});import{randomUUID as un}from"node:crypto";import{relative as pn,resolve as Y,sep as Z}from"node:path";import{ApiError as s}from"../../../api/errors.js";import{armCron as fn,parseCronSink as wn,getCron as v,listCrons as x,listCronRuns as X,pokeHeldCrons as _n,setCronState as K}from"../../../core/canvas/crons.js";import{getNode as f}from"../../../core/canvas/canvas.js";import{appSpace as hn,cronFolder as mn}from"../../../core/layout.js";import{appProcessesSandboxed as gn,cwdIsMounted as yn}from"../../../core/spaces/process.js";import{activeGrant as bn,activeGrantForApp as kn,grantFor as vn}from"../../../core/grants/mirror.js";import{callerTerminalGrant as Sn}from"../../../core/grants/terminal.js";import{assertScope as Q}from"../../../core/scopes.js";import{InputError as l}from"../../../core/io.js";import{nextSlotAfter as On}from"../../../core/wake.js";import{executeCron as In,markSelfCanceledCronRun as $n}from"../../cron-run.js";import{toCronDTO as S,toCronRunDTO as V}from"../map.js";import{appOf as J,assertCeiling as Cn,canReadNode as qn}from"../router.js";import{checkCronBirth as En,checkCronFire as Nn,cronRefusalError as An}from"../../cron/authority.js";import{endCron as Tn}from"../../cron/ended.js";import{requireUsableProfile as Pn}from"./profiles.js";import{lookupProfile as jn}from"../../../core/profiles/manifest.js";import{filterAsync as Dn,mapAsync as Rn}from"../../../core/async-array.js";import{personId as Un}from"../../../core/canvas/person.js";import{openDb as xn}from"../../../core/canvas/db.js";import{blaxelEnvironmentOf as Jn}from"../../../core/runtime/blaxel-environment.js";const Wn=1440*6e4,Bn="# node deadline: the scheduler sends its message to the anchor node";function $(e,n){const r=e[n];if(typeof r!="string"||r.trim()==="")throw new l({error:"missing_field",message:`cron arm request requires a non-empty "${n}"`,field:n,next:`Send a non-empty string "${n}".`});return r}t($,"requireString");function C(e,n,r,o){if(e==null)return o;if(typeof e=="string"&&r.includes(e))return e;throw new l({error:`bad_${n}`,message:`"${String(e)}" is not a valid ${n}`,field:n,next:`Use one of: ${r.join(", ")}.`})}t(C,"requireEnum");async function Fn(e){if(e==="human")return JSON.stringify({human:!0});if(e.startsWith("node:")){const n=e.slice(5).trim();if(n==="")throw new l({error:"bad_sink",message:"node sink requires a node id",field:"sink",next:'Use sink "node:<node-id>".'});if(await f(n)===null)throw new l({error:"sink_node_not_found",message:`sink node ${n} does not exist on the canvas`,field:"sink",next:"Name a live node id, or use spawn:<kind> for a delivery that outlives any one node."});return JSON.stringify({node:n})}if(e.startsWith("spawn:")){const n=e.slice(6).trim();if(n==="")throw new l({error:"bad_sink",message:"spawn sink requires a node kind",field:"sink",next:'Use sink "spawn:<kind>" (e.g. spawn:general).'});return JSON.stringify({spawn:n})}throw new l({error:"bad_sink",message:`"${e}" is not a valid sink`,field:"sink",next:"Use node:<node-id>, spawn:<kind>, or human."})}t(Fn,"parseSinkSpec");const zn=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/;function nn(e,n){if(!zn.test(e)||Number.isNaN(Date.parse(e)))throw new l({error:`bad_${n}`,message:`"${e}" is not a UTC ISO instant`,field:n,next:'Send a resolved UTC instant like "2026-06-07T09:00:00.000Z" (the client resolves the time grammar).'});return e}t(nn,"requireUtcIso");function Gn(e){try{On(e,new Date)}catch(n){throw new l({error:"bad_recur",message:`recur is not advanceable: ${n instanceof Error?n.message:String(n)}`,field:"recur",next:'Send recur JSON the daemon can advance: {"every":"6h"} or {"cron":"0 9 * * *","tz":"America/New_York"}.'})}return e}t(Gn,"requireRecur");function Ln(e){let n;try{n=JSON.parse(e)}catch{throw new l({error:"bad_env_json",message:"env_json is not valid JSON",field:"env_json",next:'Send a JSON object of string values, e.g. {"API_BASE":"https://x"}.'})}if(typeof n!="object"||n===null||Array.isArray(n))throw new l({error:"bad_env_json",message:"env_json must be a JSON object",field:"env_json",next:'Send a JSON object of string values, e.g. {"API_BASE":"https://x"}.'});for(const[r,o]of Object.entries(n))if(typeof o!="string")throw new l({error:"bad_env_json",message:`env_json value for "${r}" is not a string`,field:"env_json",next:"Every env value must be a string."});return e}t(Ln,"requireEnvJson");function W(e){const n=e.query.get("profile");return n!==null&&n.trim()!==""?n.trim():null}t(W,"callerProfile");function en(e,n){return n===null||e.scope==="global"||e.profile===n}t(en,"inScope");function rn(e){return e.principal.class==="person"?null:J(e.principal)}t(rn,"callerApp");function q(e){return e.principal.class==="person"?e.principal.sub??null:null}t(q,"bearerPerson");async function on(e,n){return(await(await xn()).prepare("SELECT person FROM profiles WHERE id = ?").get(e))?.person===n}t(on,"profileBelongsTo");async function B(e,n){const r=q(e);if(r!==null)return n.profile!==null&&await on(n.profile,r);if(!await qn(e.principal,n.grantee))return!1;const o=e.principal,i=o.class==="broker"?await f(o.node):o.class==="cron"?{run_id:o.origin_run,isolated:o.isolated}:o.class==="forwarded"&&o.actor.kind==="app"?{run_id:o.actor.place.run,isolated:o.actor.place.isolated}:null;return!(i!==null&&(i.isolated||n.isolated)&&i.run_id!==n.origin_run_id)}t(B,"visibleTo");function Mn(e){return typeof e.anchor_node=="string"&&e.anchor_node!==""?e.anchor_node:null}t(Mn,"anchorNodeOf");async function Hn(e,n,r,o,i,c){const u=typeof e.cwd=="string"&&e.cwd.trim()!==""?Y(e.cwd):null;if(!gn()){if(u===null)throw new l({error:"missing_field",message:'cron arm request requires a non-empty "cwd"',field:"cwd",next:'Send a non-empty string "cwd".'});return u}const m=o!==null&&await f(o)!==null?o:void 0,g=t(async A=>await yn(n,A,m,i,void 0,c),"reaches");if(u!==null&&await g(u))return u;const a=hn(n).files;if(u!==null&&e.cwd_is_default!==!0)throw new s(400,"invalid_request",`cwd ${u} is not inside a directory this app's cron runs can see, so every run would fail to start; use a directory under ${a}`,{cwd:u,default:a},void 0,{param:"cwd"});const p=r===null?null:(await f(r))?.cwd??null;return p!==null&&await g(p)?p:a}t(Hn,"resolveArmedCwd");async function Yn(e,n,r){const o=e.principal;if(o.class==="person"){const a=await Sn();return{sub:a?.sub??o.sub??Un(),grant_id:a?.id??null,scopes:null,origin_run_id:null}}if(o.class==="app"){const a=await kn(n);if(a===null)throw new s(401,"grant_revoked",`no active grant for ${n}`);const p=e.ceiling??o.scopes;return{sub:a.sub,grant_id:a.id,scopes:p===null?null:[...p],origin_run_id:null}}if(o.class==="cron"){const a=await Nn({grantee:o.app,sub:o.sub,grant_id:o.grant,scopes:o.scopes});if(!a.allowed)throw new s(a.reason==="scope_missing"?403:401,a.reason==="scope_missing"?"scope_missing":"grant_revoked",a.message);return{sub:o.sub,grant_id:o.grant,scopes:o.scopes===null?null:[...o.scopes],origin_run_id:o.origin_run,armed_from_exec:o.from_exec}}if(o.class!=="broker")throw new s(401,"unauthorized","this caller cannot arm a cron");const i=r??await f(o.node),c=i?.grant_id??o.grant,u=i?.sub??o.sub,m=c!=null?await bn(c):await vn(n,u);if(m===null)throw new s(401,"grant_revoked","the node grant is not active");const g=i?.scopes??o.scopes;return{sub:m.sub,grant_id:m.id,scopes:g===null?null:[...g],origin_run_id:i?.run_id??o.run}}t(Yn,"armPrincipal");async function Zn(e){const n=e.body??{},r=$(n,"name"),o=typeof n.deadline_body=="string"&&n.deadline_body.trim()!==""?n.deadline_body:null,i=o!==null?Bn:$(n,"command"),c=nn($(n,"fire_at"),"fire_at"),u=typeof n.recur=="string"&&n.recur!==""?Gn(n.recur):null,m=typeof n.expires_at=="string"&&n.expires_at!==""?nn(n.expires_at,"expires_at"):null,g=typeof n.env_json=="string"&&n.env_json!==""?Ln(n.env_json):null,a=typeof n.sink=="string"&&n.sink.trim()!==""?n.sink.trim():null,p=C(n.on_output,"on_output",["silent","on-failure","always","on-change"],a?.startsWith("node:")?"on-change":"on-failure"),A=C(n.overlap,"overlap",["skip","queue","replace"],"skip"),tn=C(n.tier,"tier",["normal","urgent","critical"],"normal"),z=p==="always"||p==="on-change";if(z&&a===null)throw new l({error:"sink_required",message:`on_output "${p}" delivers stdout every qualifying run \u2014 it needs a sink`,field:"sink",next:"Pass sink node:<node-id> (a living node's inbox), spawn:<kind> (birth a fresh node per delivery), or human (the humanloop inbox)."});if(!z&&a!==null)throw new l({error:"sink_unused",message:`on_output "${p}" never delivers stdout \u2014 a sink would be dead config`,field:"sink",next:'Drop the sink, or use on_output "always"/"on-change" if delivery is the point.'});const an=a!==null?await Fn(a):"{}",G=q(e);if(G!==null)for(const d of[a?.startsWith("node:")?a.slice(5).trim():null,typeof n.created_by=="string"?n.created_by:null,typeof n.anchor_node=="string"?n.anchor_node:null]){const H=d===null||d===""?null:await f(d);if(H!==null&&H.sub!==G)throw new s(404,"not_found","node not found")}if(a?.startsWith("spawn:")&&(Cn(e.ceiling,"crtr:act"),e.principal.class==="cron")){const d=await En({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,from_exec:e.principal.from_exec},{kind:a.slice(6)});if(!d.allowed)throw An(d)}const b=J(e.principal)??"app:terminal",k=e.principal.class==="broker"?e.principal.node:e.principal.class==="cron"?null:typeof n.created_by=="string"&&n.created_by!==""?n.created_by:null;if(e.principal.class==="broker"&&n.created_by!=null&&n.created_by!==k)throw new s(403,"permission_error","a broker may only arm a cron as its own node");const y=k===null?null:await f(k);if(y!==null){if(y.grantee!==b)throw new l({error:"creator_app_mismatch",message:"creator node belongs to another app",field:"created_by",next:"Use a node of the calling app."});Q(y,"crtr:schedule"),a?.startsWith("spawn:")&&Q(y,"crtr:act")}if(n.isolated!==void 0&&typeof n.isolated!="boolean")throw new s(400,"invalid_request","isolated must be a boolean");if(y?.isolated&&n.isolated===!1)throw new s(403,"isolated_run","a cron created by an isolated node cannot escape isolation");const L=y?.isolated===!0||e.principal.class==="cron"&&e.principal.isolated;if(L&&n.isolated===!1)throw new s(403,"isolated_run","a cron created by an isolated caller cannot escape isolation");const T=L||n.isolated===!0,_=await Yn(e,b,y),P=un(),O=T?mn(b,P):null;if(O!==null&&n.cwd_is_default!==!0){const d=pn(O,typeof n.cwd=="string"&&n.cwd.trim()!==""?Y(n.cwd):O);if(d===".."||d.startsWith(`..${Z}`)||d.startsWith(Z))throw new s(400,"invalid_request","an isolated cron must run in its own cron folder",{param:"cwd"})}const j=q(e),w=typeof n.profile!="string"||n.profile===""?null:j===null?(await Pn(e,n.profile)).profileId:(()=>{const d=jn(n.profile);if(d.kind!=="resolved")throw new s(404,"not_found","profile not found");return d.entry.profileId})();if(j!==null&&(w===null||!await on(w,j)))throw new s(w===null?400:404,w===null?"invalid_request":"not_found",w===null?"a person's cron names the profile it belongs to":"profile not found",void 0,void 0,{param:"profile"});const M=C(n.scope,"scope",["profile","global"],w!==null?"profile":"global");if(M==="profile"&&w===null)throw new l({error:"scope_needs_profile",message:'scope "profile" names the profile the cron lists and cancels within \u2014 it requires a profile',field:"profile",next:'Send a profile, or use scope "global" for a canvas-home-wide cron.'});const D=await Jn(w)!==null,sn=m??(D?new Date(Date.now()+Wn).toISOString():null),R=Mn(n);if(D&&R===null)throw new l({error:"anchor_required",message:"a cron of a hosted profile runs in its anchor node's sandbox, so it needs an anchor node",field:"anchor_node",next:"Anchor it to a node (`--anchor <node-id>` or `--anchor-self`)."});const ln=typeof n.cwd=="string"&&n.cwd.trim()!==""&&n.cwd_is_default!==!0?n.cwd:null,cn=O??(D?ln??(await f(R))?.cwd??$(n,"cwd"):await Hn(n,b,k,R,T,{sub:_.sub,grantId:_.grant_id,scopes:_.scopes})),h=typeof n.anchor_node=="string"&&n.anchor_node!==""?n.anchor_node:null;if(h!==null&&await f(h)!==null&&(await f(h)).grantee!==b)throw new l({error:"anchor_app_mismatch",message:"anchor node belongs to another app",field:"anchor_node",next:"Use an anchor of the calling app."});if(h!==null&&await f(h)===null)throw new l({error:"anchor_not_found",message:`anchor node ${h} does not exist on the canvas`,field:"anchor_node",next:"Name a live node id, or drop the anchor \u2014 an unanchored cron outlives every node."});const U=n.cancel_on_wake===!0;if(U&&h===null)throw new l({error:"cancel_on_wake_needs_anchor",message:"cancel_on_wake couples the cron to a node's dormancy \u2014 it requires an anchor node",field:"anchor_node",next:"Pass anchor_node with the node whose wake should cancel this cron."});if(o!==null&&!U)throw new l({error:"deadline_needs_cancel_on_wake",message:"a deadline body is sent to the anchor only until it wakes \u2014 it requires cancel_on_wake",field:"cancel_on_wake",next:"Pass cancel_on_wake with the anchor node."});const I=n.run_timeout_s??300;if(typeof I!="number"||!Number.isInteger(I)||I<=0)throw new l({error:"bad_run_timeout",message:`run_timeout_s must be a positive integer (got ${String(n.run_timeout_s)})`,field:"run_timeout_s",next:"Send the timeout in whole seconds, e.g. 300."});return await fn({cron_id:P,name:r,created_by:k,grantee:b,sub:_.sub,grant_id:_.grant_id,scopes:_.scopes,origin_run_id:_.origin_run_id,armed_from_exec:_.armed_from_exec===!0,isolated:T,command:i,fire_at:c,recur:u,tz:typeof n.tz=="string"?n.tz:null,expires_at:sn,anchor_node:h,cancel_on_wake:U,deadline_body:o,cwd:cn,env_json:g,profile:w,scope:M,run_timeout_s:I,overlap:A,on_output:p,sink:an,tier:tn}),{status:201,body:S(await v(P),null)}}t(Zn,"handleArm");async function Xn(e){const n=W(e),r=e.query.get("created_by");if(r==="")throw new s(400,"invalid_request","created_by must be nonempty when present");const o=await Dn((n===null?await x({all:!0}):[...await x({profile:n}),...await x({global:!0})].sort((i,c)=>i.fire_at<c.fire_at?-1:i.fire_at>c.fire_at?1:0)).filter(i=>r===null||i.created_by===r),async i=>await B(e,i));return{status:200,body:await Rn(o,async i=>S(i,await F(i)))}}t(Xn,"handleList");async function F(e){return(await X(e.cron_id))[0]??null}t(F,"lastRunOf");async function E(e){const n=e.params.cronId,r=await v(n);if(r===null||!await B(e,r))throw new s(404,"cron_not_found",`no cron ${n}`);if(!en(r,W(e)))throw new s(404,"cron_not_found",`no cron ${n} in this profile \u2014 it is scoped to another profile`);return r}t(E,"requireCron");function N(e,n){const r=rn(e);if(r!==null&&n.grantee!==r)throw new s(403,"other_app_run",`cron ${n.cron_id} belongs to another app`);return n}t(N,"requireOwnCron");async function Kn(e){const n=await E(e),r=await X(n.cron_id);return{status:200,body:{cron:S(n,r[0]??null),runs:r.map(V)}}}t(Kn,"handleShow");async function Qn(e){const n=N(e,await E(e));await K(n.cron_id,"paused");const r=await v(n.cron_id);return{status:200,body:S(r,await F(r))}}t(Qn,"handlePause");async function Vn(e){const n=N(e,await E(e));await K(n.cron_id,"active");const r=await v(n.cron_id);return{status:200,body:S(r,await F(r))}}t(Vn,"handleResume");async function ne(e){const n=N(e,await E(e));if(n.run_state==="running")throw new s(409,"cron_running",`cron ${n.cron_id} has a run in flight \u2014 wait for it to settle`);if(n.deadline_body!==null)throw new s(409,"invalid_request",`cron ${n.cron_id} is a node deadline; it runs no command`);const r=await In(n,{outOfBand:!0});if(r===null)throw new s(409,"cron_running",`cron ${n.cron_id} was claimed by a concurrent run \u2014 check \`cron show\` for its result`);return{status:200,body:V(r)}}t(ne,"handleRun");async function ee(e){if(q(e)!==null)throw new s(403,"permission_error","a person's sign-in does not poke the whole control plane's crons");const n=new Date().toISOString();return{status:200,body:{unparked:await _n(n,rn(e)),at:n}}}t(ee,"handlePoke");function re(e,n){const r=e.principal;if(r.class==="cron")return r.kind==="exec"?{kind:"canceled",by:r.app}:r.cron===n.cron_id?null:{kind:"canceled",by:`cron ${r.cron}`};if(r.class==="broker"){const i=wn(n.sink);return i?.kind==="node"&&i.node===r.node?null:{kind:"canceled",by:`node ${r.node}`}}const o=J(r);return{kind:"canceled",by:o===null||o==="app:terminal"?"the person":o}}t(re,"cancelNotice");async function oe(e){const n=e.params.cronId,r=await v(n);if(r!==null&&!await B(e,r))throw new s(404,"cron_not_found",`no cron ${n}`);if(r!==null&&!en(r,W(e)))throw new s(404,"cron_not_found",`no cron ${n} in this profile \u2014 it is scoped to another profile`);r!==null&&N(e,r);const o=e.query.get("run_id"),i=e.principal.class==="cron"?e.principal.kind==="cron"&&o===e.principal.execution&&n===e.principal.cron:!0,c=o!==null&&i&&$n(n,o);return r!==null&&await Tn(r,c?null:re(e,r),{preserveRunningProcess:c}),{status:204}}t(oe,"handleCancel");const qe=[{method:"POST",pattern:"/v1/crons",scope:"crtr:schedule",handler:Zn},{method:"GET",pattern:"/v1/crons",handler:Xn},{method:"GET",pattern:"/v1/crons/:cronId",handler:Kn},{method:"POST",pattern:"/v1/crons/:cronId/pause",scope:"crtr:schedule",handler:Qn},{method:"POST",pattern:"/v1/crons/:cronId/resume",scope:"crtr:schedule",handler:Vn},{method:"POST",pattern:"/v1/crons/poke",scope:"crtr:schedule",handler:ee},{method:"POST",pattern:"/v1/crons/:cronId/run",scope:"crtr:schedule",handler:ne},{method:"DELETE",pattern:"/v1/crons/:cronId",scope:"crtr:schedule",handler:oe}];export{Wn as HOSTED_CRON_DEFAULT_EXPIRY_MS,qe as cronRoutes};