@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,3 @@
1
- var p=Object.defineProperty;var o=(e,n)=>p(e,"name",{value:n,configurable:!0});import{envNodeId as m,envProfileId as g}from"../../shared/env.js";import{defineBranch as y,defineLeaf as u}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{requireScope as _}from"../../core/errors.js";import{parseWhen as b}from"../../core/wake.js";import{cliClient as h,getNodeOrNull as x,rethrowAsCliError as f}from"../api-client.js";import{shellQuote as v}from"../surface/node/placement.js";function k(){const e=m();if(e===void 0||e==="")throw new i({error:"no_node",message:"no node to anchor a deadline cron (CRTR_NODE_ID unset)",next:"Run from inside a node."});return e}o(k,"armerId");function I(e,n){return n!==void 0&&n.trim()!==""?{tz:n,now:e}:{now:e}}o(I,"parseOpts");function T(e){const n={wake_in_past:'Pick a future instant \u2014 a positive duration ("5m","2h") or an ISO time later than now.',bad_when:'Use a duration ("5m","1h30m"), a zoned ISO ("2026-06-07T09:00:00Z"), or a bare ISO ("2026-06-07T09:00").',bad_cadence:'Use a duration ("6h"), a 5-field cron ("0 9 * * *"), or an @alias ("@daily").',unknown_zone:'Pass --tz with an IANA zone name (e.g. "America/New_York").',cadence_too_fast:'Use a cadence of at least 60s (e.g. "1m","5m","1h").'};throw new i({error:e.code,message:e.message,received:e.received,next:n[e.code]??"Fix the time value and retry."})}o(T,"throwTimeError");function $(e,n){const t=new Date(e).getTime()-n.getTime();if(!Number.isFinite(t)||t<=0)return"";const r=Math.round(t/6e4);if(r<60)return` (~${r}m)`;const a=Math.round(t/36e5);return a<48?` (~${a}h)`:` (~${Math.round(t/864e5)}d)`}o($,"etaHint");function D(e,n){let t="CRTR_DEADLINE",r=0;const a=new Set(e.split(`
2
- `));for(;a.has(t);)t=`CRTR_DEADLINE_${++r}`;return`crtr cron cancel "$CRTR_CRON_ID"
3
- crtr node message send --to ${v(n)} --tier urgent <<'${t}'
4
- ${e}
5
- ${t}`}o(D,"deadlineHeredoc");const R=u({name:"deadline",description:"race this node\u2019s next wake against one urgent deadline cron",whenToUse:"you are waiting on an event nothing can push for, so a self-scheduled deadline must settle the wait",help:{name:"node wait deadline",summary:"arm one cancel-on-wake deadline cron for this node",params:[{kind:"stdin",name:"body",required:!0,constraint:"Policy delivered urgently to this node if the deadline fires first."},{kind:"flag",name:"until",type:"string",required:!0,constraint:"Future duration, zoned ISO timestamp, or bare ISO timestamp interpreted in --tz or host-local time."},{kind:"flag",name:"tz",type:"string",required:!1,constraint:"IANA timezone for a bare ISO --until value."}],output:[{name:"id",type:"string",required:!0,constraint:"The armed cron id."},{name:"name",type:"string",required:!0,constraint:"The cron label."},{name:"fires_at",type:"string",required:!0,constraint:"Absolute UTC deadline."},{name:"guidance",type:"string",required:!0,constraint:"How to inspect the cron and dorm."}],outputKind:"object",effects:["Arms one anchored cancel-on-wake cron. Any wake of this node cancels it; otherwise it urgently sends the body to this node at the deadline.","Re-arming replaces this node\u2019s pending deadline rather than stacking a second."]},run:o(async e=>{_("crtr:schedule","crtr node wait deadline");const n=k(),t=typeof e.body=="string"?e.body.trim():"";if(t==="")throw new i({error:"empty_body",message:"a deadline body is required",field:"body",next:"Pass the timeout policy on stdin."});const r=typeof e.until=="string"?e.until.trim():"";if(r==="")throw new i({error:"missing_until",message:"--until is required",field:"until",next:"Pass a future duration or timestamp."});const a=typeof e.tz=="string"&&e.tz.trim()!==""?e.tz:void 0,c=new Date,s=b(r,I(c,a));"error"in s&&T(s.error);const l=g(),d=await h().armCron({name:`deadline:${n}`,command:D(t,n),fire_at:s.fireAt,recur:null,tz:a??null,created_by:n,cwd:process.cwd(),profile:l!==void 0&&l!==""?l:null,scope:"profile",on_output:"on-failure",sink:null,tier:"normal",expires_at:null,anchor_node:n,cancel_on_wake:!0,run_timeout_s:300,overlap:"skip"}).catch(f),w=`Deadline cron armed for ${d.fire_at}${$(d.fire_at,c)}. End your turn to dorm; any earlier wake cancels it. Inspect pending schedules with \`crtr cron list\`.`;return{id:d.cron_id,name:d.name,fires_at:d.fire_at,guidance:w}},"run"),render:o(e=>`Deadline cron armed \u2014 ${e.name} (${e.id}), fires ${e.fires_at}.
1
+ var p=Object.defineProperty;var r=(e,n)=>p(e,"name",{value:n,configurable:!0});import{envNodeId as m,envProfileId as y}from"../../shared/env.js";import{defineBranch as g,defineLeaf as u}from"../../core/command.js";import{InputError as a}from"../../core/io.js";import{requireScope as _}from"../../core/errors.js";import{parseWhen as b}from"../../core/wake.js";import{cliClient as h,getNodeOrNull as x,rethrowAsCliError as f}from"../api-client.js";function v(){const e=m();if(e===void 0||e==="")throw new a({error:"no_node",message:"no node to anchor a deadline cron (CRTR_NODE_ID unset)",next:"Run from inside a node."});return e}r(v,"armerId");function k(e,n){return n!==void 0&&n.trim()!==""?{tz:n,now:e}:{now:e}}r(k,"parseOpts");function I(e){const n={wake_in_past:'Pick a future instant \u2014 a positive duration ("5m","2h") or an ISO time later than now.',bad_when:'Use a duration ("5m","1h30m"), a zoned ISO ("2026-06-07T09:00:00Z"), or a bare ISO ("2026-06-07T09:00").',bad_cadence:'Use a duration ("6h"), a 5-field cron ("0 9 * * *"), or an @alias ("@daily").',unknown_zone:'Pass --tz with an IANA zone name (e.g. "America/New_York").',cadence_too_fast:'Use a cadence of at least 60s (e.g. "1m","5m","1h").'};throw new a({error:e.code,message:e.message,received:e.received,next:n[e.code]??"Fix the time value and retry."})}r(I,"throwTimeError");function T(e,n){const t=new Date(e).getTime()-n.getTime();if(!Number.isFinite(t)||t<=0)return"";const o=Math.round(t/6e4);if(o<60)return` (~${o}m)`;const i=Math.round(t/36e5);return i<48?` (~${i}h)`:` (~${Math.round(t/864e5)}d)`}r(T,"etaHint");const q=u({name:"deadline",description:"race this node\u2019s next wake against one urgent deadline cron",whenToUse:"you are waiting on an event nothing can push for, so a self-scheduled deadline must settle the wait",help:{name:"node wait deadline",summary:"arm one cancel-on-wake deadline cron for this node",params:[{kind:"stdin",name:"body",required:!0,constraint:"Policy delivered urgently to this node if the deadline fires first."},{kind:"flag",name:"until",type:"string",required:!0,constraint:"Future duration, zoned ISO timestamp, or bare ISO timestamp interpreted in --tz or host-local time."},{kind:"flag",name:"tz",type:"string",required:!1,constraint:"IANA timezone for a bare ISO --until value."}],output:[{name:"id",type:"string",required:!0,constraint:"The armed cron id."},{name:"name",type:"string",required:!0,constraint:"The cron label."},{name:"fires_at",type:"string",required:!0,constraint:"Absolute UTC deadline."},{name:"guidance",type:"string",required:!0,constraint:"How to inspect the cron and dorm."}],outputKind:"object",effects:["Arms one anchored cancel-on-wake cron. Any wake of this node cancels it; otherwise it urgently sends the body to this node at the deadline.","Re-arming replaces this node\u2019s pending deadline rather than stacking a second."]},run:r(async e=>{_("crtr:schedule","crtr node wait deadline");const n=v(),t=typeof e.body=="string"?e.body.trim():"";if(t==="")throw new a({error:"empty_body",message:"a deadline body is required",field:"body",next:"Pass the timeout policy on stdin."});const o=typeof e.until=="string"?e.until.trim():"";if(o==="")throw new a({error:"missing_until",message:"--until is required",field:"until",next:"Pass a future duration or timestamp."});const i=typeof e.tz=="string"&&e.tz.trim()!==""?e.tz:void 0,c=new Date,s=b(o,k(c,i));"error"in s&&I(s.error);const l=y(),d=await h().armCron({name:`deadline:${n}`,command:"",deadline_body:t,fire_at:s.fireAt,recur:null,tz:i??null,created_by:n,cwd:process.cwd(),profile:l!==void 0&&l!==""?l:null,scope:"profile",on_output:"on-failure",sink:null,tier:"normal",expires_at:null,anchor_node:n,cancel_on_wake:!0,run_timeout_s:300,overlap:"skip"}).catch(f),w=`Deadline cron armed for ${d.fire_at}${T(d.fire_at,c)}. End your turn to dorm; any earlier wake cancels it. Inspect pending schedules with \`crtr cron list\`.`;return{id:d.cron_id,name:d.name,fires_at:d.fire_at,guidance:w}},"run"),render:r(e=>`Deadline cron armed \u2014 ${e.name} (${e.id}), fires ${e.fires_at}.
6
2
 
7
- ${e.guidance}`,"render")}),N=u({name:"controller",description:"wait durably for a named controller message",whenToUse:"you are a terminal node blocked on one specific live parent or controller and have no managed-child subscription whose report will wake you",help:{name:"node wait controller",summary:"declare that your next stop may dorm only until one live controller delivers an inbox message",params:[{kind:"positional",name:"controller",type:"string",required:!0,constraint:"Live node id expected to send the message. It may be your parent or another named controller, but cannot be yourself."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The terminal node that declared the wait."}],outputKind:"object",effects:["Durably records the controller on this node. The stop guard permits dormancy only while that controller remains active or idle; its next inbox delivery clears the record before the delivery wakes this node."]},run:o(async e=>{const n=m();if(n===void 0||n==="")throw new i({error:"no_node",message:"no node to wait (CRTR_NODE_ID unset)",next:"Run from inside the terminal node that is blocked."});const t=await x(n);if(t===null)throw new i({error:"not_found",message:`no node: ${n}`,next:"Run from a live canvas node."});if(t.lifecycle!=="terminal")throw new i({error:"resident_node",message:`node ${n} is resident and may already dorm on its inbox`,next:"Use this only from a terminal node that needs the stop guard to recognize a controller dependency."});const r=String(e.controller).trim();if(r===n)throw new i({error:"self_controller",message:"a node cannot wait for its own message",field:"controller",next:"Name the parent or external controller expected to send the message."});return await h().waitNode(n,{controller:r}).catch(a=>f(a)),{node_id:n}},"run"),render:o(()=>"Waiting for the controller. End your turn to dorm; its next message wakes you and clears this wait.","render")}),P=y({name:"wait",description:"declare a durable controller or deadline wait",whenToUse:"a terminal node must dorm for one named controller, or race its inbox against a self-scheduled deadline",help:{name:"node wait",summary:"declare durable wait state; choose the event that settles it",model:"Both waits belong to the calling terminal node and settle on one future event. A controller wait records an existing node as the wake source; a deadline wait arms an urgent one-shot cron that races any earlier inbox delivery and is canceled when that delivery wins."},children:[N,R]});export{P as nodeWaitBranch};
3
+ ${e.guidance}`,"render")}),z=u({name:"controller",description:"wait durably for a named controller message",whenToUse:"you are a terminal node blocked on one specific live parent or controller and have no managed-child subscription whose report will wake you",help:{name:"node wait controller",summary:"declare that your next stop may dorm only until one live controller delivers an inbox message",params:[{kind:"positional",name:"controller",type:"string",required:!0,constraint:"Live node id expected to send the message. It may be your parent or another named controller, but cannot be yourself."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The terminal node that declared the wait."}],outputKind:"object",effects:["Durably records the controller on this node. The stop guard permits dormancy only while that controller remains active or idle; its next inbox delivery clears the record before the delivery wakes this node."]},run:r(async e=>{const n=m();if(n===void 0||n==="")throw new a({error:"no_node",message:"no node to wait (CRTR_NODE_ID unset)",next:"Run from inside the terminal node that is blocked."});const t=await x(n);if(t===null)throw new a({error:"not_found",message:`no node: ${n}`,next:"Run from a live canvas node."});if(t.lifecycle!=="terminal")throw new a({error:"resident_node",message:`node ${n} is resident and may already dorm on its inbox`,next:"Use this only from a terminal node that needs the stop guard to recognize a controller dependency."});const o=String(e.controller).trim();if(o===n)throw new a({error:"self_controller",message:"a node cannot wait for its own message",field:"controller",next:"Name the parent or external controller expected to send the message."});return await h().waitNode(n,{controller:o}).catch(i=>f(i)),{node_id:n}},"run"),render:r(()=>"Waiting for the controller. End your turn to dorm; its next message wakes you and clears this wait.","render")}),U=g({name:"wait",description:"declare a durable controller or deadline wait",whenToUse:"a terminal node must dorm for one named controller, or race its inbox against a self-scheduled deadline",help:{name:"node wait",summary:"declare durable wait state; choose the event that settles it",model:"Both waits belong to the calling terminal node and settle on one future event. A controller wait records an existing node as the wake source; a deadline wait arms an urgent one-shot cron that races any earlier inbox delivery and is canceled when that delivery wins."},children:[z,q]});export{U as nodeWaitBranch};
@@ -39,8 +39,7 @@ export interface BrokerClient {
39
39
  off(event: 'close', listener: () => void): this;
40
40
  }
41
41
  export declare class BrokerClient extends EventEmitter {
42
- private readonly nodeId;
43
- private readonly transport;
42
+ private transport;
44
43
  private closeEmitted;
45
44
  /** Tracks live connect↔close state so {@link request} can fail fast on a
46
45
  * dead/absent connection rather than parking a promise the reply will
@@ -56,7 +55,11 @@ export declare class BrokerClient extends EventEmitter {
56
55
  * Resolved by the matching `data` frame / rejected by the matching `error`
57
56
  * frame in {@link onFrame}, the request's timeout, or transport teardown. */
58
57
  private pending;
59
- constructor(nodeId: string, options?: BrokerClientOptions);
58
+ /** `nodeId` is undefined only for a viewer whose node is still being created: it holds no transport until {@link bindTransport}, so
59
+ * every send is a no-op and every request rejects until then. */
60
+ constructor(nodeId: string | undefined, options?: BrokerClientOptions);
61
+ /** Wire the transport once the node it reaches is known. */
62
+ bindTransport(transport: Transport): void;
60
63
  /** Issue a correlated read-op and resolve with the broker's `data` reply (or
61
64
  * reject on the correlated `error`, a timeout, or transport teardown). Mints
62
65
  * the `id`, sends `{...frame, id}`, and parks a resolver consumed by
@@ -1 +1 @@
1
- var c=Object.defineProperty;var i=(n,t)=>c(n,"name",{value:t,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as k}from"./transport.js";import{SocketTransport as x}from"./transport-socket.js";import{RelayTransport as w}from"./transport-relay.js";const d=1e4;function f(n){return n===null||n.status==="done"&&n.final_report!=null}i(f,"reconnectShouldGiveUp");class g extends l{static{i(this,"BrokerClient")}nodeId;transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(t,e={}){super(),this.nodeId=t,this.transport=e.transport??new a(t),this.transport.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),this.transport.on("frame",r=>this.onFrame(r)),this.transport.on("error",r=>{this.lastTransportError=r.message,this.emitError(r)}),this.transport.on("close",()=>this.onClose())}request(t){const e=p();return new Promise((r,o)=>{if(!this.connected){o(new Error(`cannot issue '${t.type}': no live broker connection`));return}const s=setTimeout(()=>{this.pending.delete(e),o(new Error(`request '${t.type}' timed out after ${d}ms`))},d);typeof s.unref=="function"&&s.unref(),this.pending.set(e,{resolve:r,reject:o,timer:s}),this.send({...t,id:e})})}rejectAllPending(t){for(const{reject:e,timer:r}of this.pending.values())clearTimeout(r),e(new Error(t));this.pending.clear()}connect(){this.transport.connect()}redial(t){return this.transport.redial(t)}send(t){this.transport.send(t)}close(){this.transport.destroy()}onFrame(t){if(t.type==="data"){const e=typeof t.id=="string"?this.pending.get(t.id):void 0;e&&(this.pending.delete(t.id),clearTimeout(e.timer),e.resolve(t));return}if(t.type==="error"&&typeof t.id=="string"&&this.pending.has(t.id)){const e=this.pending.get(t.id);this.pending.delete(t.id),clearTimeout(e.timer),e.reject(new Error(t.message||`request failed: ${t.code}`));return}this.emit("frame",t)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(t){this.listenerCount("error")>0&&this.emit("error",t)}}export{g as BrokerClient,k as BrokerUnavailableError,w as RelayTransport,x as SocketTransport,f as reconnectShouldGiveUp};
1
+ var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as w}from"./transport.js";import{SocketTransport as v}from"./transport-socket.js";import{RelayTransport as U}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(new Error(e.message||`request failed: ${e.code}`));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,w as BrokerUnavailableError,U as RelayTransport,v as SocketTransport,E as reconnectShouldGiveUp};
@@ -41,6 +41,11 @@ export interface Cron {
41
41
  expires_at: string | null;
42
42
  anchor_node: string | null;
43
43
  cancel_on_wake: boolean;
44
+ /** A node deadline (`crtr node wait deadline`): the message the cron lane sends the anchor, urgently, when the row falls
45
+ * due. Such a row runs no command. Null for every other cron. */
46
+ deadline_body: string | null;
47
+ /** How many times the cron has fired (a hosted cron ends after HOSTED_CRON_MAX_FIRES). */
48
+ fires: number;
44
49
  cwd: string;
45
50
  env_json: string | null;
46
51
  profile: string | null;
@@ -102,6 +107,7 @@ export interface ArmCronSpec {
102
107
  expires_at: string | null;
103
108
  anchor_node: string | null;
104
109
  cancel_on_wake: boolean;
110
+ deadline_body?: string | null;
105
111
  cwd: string;
106
112
  env_json: string | null;
107
113
  profile: string | null;
@@ -194,6 +200,10 @@ export declare function deleteCronsForProfile(profileId: string, anchorNodeIds:
194
200
  export declare function cronIdsForProfileDetach(profileId: string): Promise<string[]>;
195
201
  /** Preserve matching crons while removing their deleted profile dependency. */
196
202
  export declare function globalizeCronsForProfile(profileId: string): Promise<string[]>;
203
+ /** A hosted cron ends after this many fires; no flag raises it (NL-1110). */
204
+ export declare const HOSTED_CRON_MAX_FIRES = 64;
205
+ /** Idle crons that have used all `max` fires; the due pass ends them whether paused or not (NL-1110). */
206
+ export declare function cappedIdleCrons(max: number): Promise<Cron[]>;
197
207
  /** DELETE one cron by id — one-shot consumption after its run settles.
198
208
  * Returns whether a live row was removed, so a consumer racing an explicit
199
209
  * cancel can no-op instead of double-settling. */
@@ -243,7 +253,7 @@ export declare function dueClockCrons(nowIso: string): Promise<Cron[]>;
243
253
  *
244
254
  * `outOfBand` stamps the lease as a `cron run` (manual verification) so the
245
255
  * overlap pass leaves it alone — see `dueOverlapCrons`. */
246
- export declare function acquireCronRunLease(cron_id: string, leaseOwner: string, startedAtIso: string, outOfBand: boolean, executionId?: string | null): Promise<boolean>;
256
+ export declare function acquireCronRunLease(cron_id: string, leaseOwner: string, startedAtIso: string, outOfBand: boolean, executionId?: string | null, maxFires?: number | null): Promise<boolean>;
247
257
  /** Attach the launcher's pid only to the run that claimed this lease. */
248
258
  export declare function attachCronRunPid(cron_id: string, leaseOwner: string, startedAtIso: string, pid: number): Promise<boolean>;
249
259
  /** What a settling run does with the row's `held` state, applied in the SAME
@@ -1,8 +1,8 @@
1
- var w=Object.defineProperty;var a=(n,r)=>w(n,"name",{value:r,configurable:!0});import{withCanvasWrite as c,openDb as i}from"./db.js";import{capturePidIdentities as l,identitiesMatch as R,killProcessGroup as m}from"./pid.js";import{isProfilePaused as D}from"../profiles/manifest.js";import{stopAppProcess as S}from"../spaces/process.js";import{emitEvent as N}from"../events/emit.js";import{personId as p}from"./person.js";const h=20;function O(n){if(typeof n!="string")return null;try{const r=JSON.parse(n);return Array.isArray(r)?r.filter(e=>typeof e=="string"):null}catch{return null}}a(O,"scopesFrom");function s(n){return{cron_id:n.cron_id,name:n.name,created_by:n.created_by??null,grantee:n.grantee,sub:n.sub??p(),grant_id:n.grant_id??null,scopes:O(n.scopes_json),origin_run_id:n.origin_run_id??null,run_execution_id:n.run_execution_id??null,armed_from_exec:Number(n.armed_from_exec??0)!==0,isolated:Number(n.isolated)!==0,command:n.command,fire_at:n.fire_at,recur:n.recur??null,tz:n.tz??null,expires_at:n.expires_at??null,anchor_node:n.anchor_node??null,cancel_on_wake:Number(n.cancel_on_wake)!==0,cwd:n.cwd,env_json:n.env_json??null,profile:n.profile??null,scope:n.scope,run_timeout_s:Number(n.run_timeout_s),overlap:n.overlap,on_output:n.on_output,sink:n.sink,tier:n.tier,last_output_hash:n.last_output_hash??null,held:Number(n.held)!==0,last_poke_at:n.last_poke_at??null,state:n.state,run_state:n.run_state,run_pid:n.run_pid??null,run_pid_identity:n.run_pid_identity??null,run_started_at:n.run_started_at??null,run_lease_owner:n.run_lease_owner??null,run_out_of_band:Number(n.run_out_of_band)!==0,created:n.created,updated:n.updated}}a(s,"cronFrom");function E(n){try{const r=JSON.parse(n);if(typeof r.node=="string")return{kind:"node",node:r.node};if(typeof r.spawn=="string")return{kind:"spawn",spawn:r.spawn};if(r.human===!0)return{kind:"human"}}catch{}return null}a(E,"parseCronSink");function F(n){const r=E(n);if(r===null)return null;switch(r.kind){case"node":return`node:${r.node}`;case"spawn":return`spawn:${r.spawn}`;case"human":return"human"}}a(F,"cronSinkDisplay");async function T(n,r="SIGTERM"){if(!d(n))return!1;if(process.platform!=="linux")return m(n.run_pid,r),!0;try{return await S(n.run_pid,r,n.anchor_node??void 0),!0}catch(e){if(!d(n))return!1;throw e}}a(T,"stopLeasedCronRun");function _(n,r="SIGTERM"){return d(n)?(T(n,r).catch(e=>{N({level:"error",event:"cron.run.stop_failed",error:e,fields:{cron_id:n.cron_id,pid:n.run_pid}})}),!0):!1}a(_,"killLeasedCronRun");function d(n){const r=n.run_pid;if(r==null||n.run_pid_identity==null)return!1;const e=l([r]);if(e===null)return!1;const t=e.get(r);return t===void 0?!1:R(t,n.run_pid_identity)}a(d,"verifyLeasedCronRun");async function I(n){return await c(async r=>{const e=[];if(n.cancel_on_wake&&n.anchor_node!==null){await r.prepare("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(n.anchor_node);const t=(await r.prepare("SELECT * FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1").all(n.anchor_node)).map(s);for(const o of t)o.run_state==="running"&&_(o),await r.prepare("DELETE FROM crons WHERE cron_id = ?").run(o.cron_id),e.push(o.cron_id)}return await L(r,n),{cron_id:n.cron_id,replaced:e}})}a(I,"armCron");async function L(n,r){const e=new Date().toISOString();await n.prepare(`INSERT INTO crons (
1
+ var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{withCanvasWrite as c,openDb as i}from"./db.js";import{capturePidIdentities as p,identitiesMatch as N,killProcessGroup as S}from"./pid.js";import{stopAppProcess as h}from"../spaces/process.js";import{emitEvent as O}from"../events/emit.js";import{personId as E}from"./person.js";import{deleteSandboxOfEndedNode as f}from"../runtime/runner/delete-sandboxes.js";const T=20;function y(n){if(typeof n!="string")return null;try{const e=JSON.parse(n);return Array.isArray(e)?e.filter(r=>typeof r=="string"):null}catch{return null}}a(y,"scopesFrom");function s(n){return{cron_id:n.cron_id,name:n.name,created_by:n.created_by??null,grantee:n.grantee,sub:n.sub??E(),grant_id:n.grant_id??null,scopes:y(n.scopes_json),origin_run_id:n.origin_run_id??null,run_execution_id:n.run_execution_id??null,armed_from_exec:Number(n.armed_from_exec??0)!==0,isolated:Number(n.isolated)!==0,command:n.command,fire_at:n.fire_at,recur:n.recur??null,tz:n.tz??null,expires_at:n.expires_at??null,anchor_node:n.anchor_node??null,cancel_on_wake:Number(n.cancel_on_wake)!==0,deadline_body:n.deadline_body??null,fires:Number(n.fires??0),cwd:n.cwd,env_json:n.env_json??null,profile:n.profile??null,scope:n.scope,run_timeout_s:Number(n.run_timeout_s),overlap:n.overlap,on_output:n.on_output,sink:n.sink,tier:n.tier,last_output_hash:n.last_output_hash??null,held:Number(n.held)!==0,last_poke_at:n.last_poke_at??null,state:n.state,run_state:n.run_state,run_pid:n.run_pid??null,run_pid_identity:n.run_pid_identity??null,run_started_at:n.run_started_at??null,run_lease_owner:n.run_lease_owner??null,run_out_of_band:Number(n.run_out_of_band)!==0,created:n.created,updated:n.updated}}a(s,"cronFrom");function w(n){try{const e=JSON.parse(n);if(typeof e.node=="string")return{kind:"node",node:e.node};if(typeof e.spawn=="string")return{kind:"spawn",spawn:e.spawn};if(e.human===!0)return{kind:"human"}}catch{}return null}a(w,"parseCronSink");function M(n){const e=w(n);if(e===null)return null;switch(e.kind){case"node":return`node:${e.node}`;case"spawn":return`spawn:${e.spawn}`;case"human":return"human"}}a(M,"cronSinkDisplay");async function L(n,e="SIGTERM"){if(!l(n))return!1;if(process.platform!=="linux")return S(n.run_pid,e),!0;try{return await h(n.run_pid,e,n.anchor_node??void 0),!0}catch(r){if(!l(n))return!1;throw r}}a(L,"stopLeasedCronRun");function d(n,e="SIGTERM"){return l(n)?(L(n,e).catch(r=>{O({level:"error",event:"cron.run.stop_failed",error:r,fields:{cron_id:n.cron_id,pid:n.run_pid}})}),!0):!1}a(d,"killLeasedCronRun");function l(n){const e=n.run_pid;if(e==null||n.run_pid_identity==null)return!1;const r=p([e]);if(r===null)return!1;const t=r.get(e);return t===void 0?!1:N(t,n.run_pid_identity)}a(l,"verifyLeasedCronRun");async function U(n){return await c(async e=>{const r=[];if(n.cancel_on_wake&&n.anchor_node!==null){await e.prepare("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(n.anchor_node);const t=(await e.prepare("SELECT * FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1").all(n.anchor_node)).map(s);for(const o of t)o.run_state==="running"&&d(o),await e.prepare("DELETE FROM crons WHERE cron_id = ?").run(o.cron_id),r.push(o.cron_id)}return await C(e,n),{cron_id:n.cron_id,replaced:r}})}a(U,"armCron");async function C(n,e){const r=new Date().toISOString();await n.prepare(`INSERT INTO crons (
2
2
  cron_id, name, created_by, grantee, sub, grant_id, scopes_json, origin_run_id, isolated, command, fire_at, recur, tz, expires_at,
3
3
  anchor_node, cancel_on_wake, cwd, env_json, profile, scope,
4
- run_timeout_s, overlap, on_output, sink, tier, created, updated, armed_from_exec
5
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(r.cron_id,r.name,r.created_by,r.grantee??"app:terminal",r.sub??p(),r.grant_id??null,r.scopes==null?null:JSON.stringify(r.scopes),r.origin_run_id??null,r.isolated?1:0,r.command,r.fire_at,r.recur,r.tz,r.expires_at,r.anchor_node,r.cancel_on_wake?1:0,r.cwd,r.env_json,r.profile,r.scope,r.run_timeout_s,r.overlap,r.on_output,r.sink,r.tier,e,e,r.armed_from_exec?1:0)}a(L,"insertCron");async function U(n){const r=await(await i()).prepare("SELECT * FROM crons WHERE cron_id = ?").get(n);return r===void 0?null:s(r)}a(U,"getCron");async function M(n){const r=await i();let e;return"profile"in n?e=await r.prepare("SELECT * FROM crons WHERE scope = 'profile' AND profile = ? ORDER BY fire_at").all(n.profile):"global"in n?e=await r.prepare("SELECT * FROM crons WHERE scope = 'global' ORDER BY fire_at").all():e=await r.prepare("SELECT * FROM crons ORDER BY fire_at").all(),e.map(s)}a(M,"listCrons");async function v(n,r){return await c(async e=>{const t=await e.prepare("SELECT * FROM crons WHERE cron_id = ?").get(n);if(t===void 0)return!1;const o=s(t);return o.run_state==="running"&&r?.preserveRunningProcess!==!0&&_(o),await e.prepare("DELETE FROM crons WHERE cron_id = ?").run(n),!0})}a(v,"cancelCron");function f(n,r){const e=[...new Set(r)];return e.length===0?{sql:"profile = ?",params:[n]}:{sql:`profile = ? OR anchor_node IN (${e.map(()=>"?").join(",")})`,params:[n,...e]}}a(f,"profileCronWhere");async function P(n,r){const e=f(n,r);return(await(await i()).prepareUncached(`SELECT cron_id FROM crons WHERE ${e.sql} ORDER BY created, cron_id`).all(...e.params)).map(({cron_id:t})=>t)}a(P,"cronIdsForProfileDeletion");async function b(n,r){return await c(async e=>{const t=f(n,r),o=(await e.prepareUncached(`SELECT * FROM crons WHERE ${t.sql} ORDER BY created, cron_id`).all(...t.params)).map(s);for(const u of o)u.run_state==="running"&&_(u);return await e.prepareUncached(`DELETE FROM crons WHERE ${t.sql}`).run(...t.params),o.map(({cron_id:u})=>u)})}a(b,"deleteCronsForProfile");async function B(n){return(await(await i()).prepare("SELECT cron_id FROM crons WHERE profile = ? ORDER BY created, cron_id").all(n)).map(({cron_id:r})=>r)}a(B,"cronIdsForProfileDetach");async function Y(n){return await c(async r=>{const e=(await r.prepare("SELECT cron_id FROM crons WHERE profile = ? ORDER BY created, cron_id").all(n)).map(({cron_id:t})=>t);return e.length>0&&await r.prepare("UPDATE crons SET profile = NULL, scope = 'global', updated = ? WHERE profile = ?").run(new Date().toISOString(),n),e})}a(Y,"globalizeCronsForProfile");async function $(n){return(await(await i()).prepare("DELETE FROM crons WHERE cron_id = ?").run(n)).changes>0}a($,"consumeCron");async function j(n,r){return(await(await i()).prepare("UPDATE crons SET state = ?, updated = ? WHERE cron_id = ?").run(r,new Date().toISOString(),n)).changes>0}a(j,"setCronState");async function q(n,r){await(await i()).prepare("UPDATE crons SET last_output_hash = ?, updated = ? WHERE cron_id = ?").run(r,new Date().toISOString(),n)}a(q,"setCronLastOutputHash");async function z(n){const r=await(await i()).prepare(`SELECT anchor_node, cancel_on_wake, sink
4
+ run_timeout_s, overlap, on_output, sink, tier, created, updated, armed_from_exec, deadline_body
5
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.cron_id,e.name,e.created_by,e.grantee??"app:terminal",e.sub??E(),e.grant_id??null,e.scopes==null?null:JSON.stringify(e.scopes),e.origin_run_id??null,e.isolated?1:0,e.command,e.fire_at,e.recur,e.tz,e.expires_at,e.anchor_node,e.cancel_on_wake?1:0,e.cwd,e.env_json,e.profile,e.scope,e.run_timeout_s,e.overlap,e.on_output,e.sink,e.tier,r,r,e.armed_from_exec?1:0,e.deadline_body??null)}a(C,"insertCron");async function b(n){const e=await(await i()).prepare("SELECT * FROM crons WHERE cron_id = ?").get(n);return e===void 0?null:s(e)}a(b,"getCron");async function v(n){const e=await i();let r;return"profile"in n?r=await e.prepare("SELECT * FROM crons WHERE scope = 'profile' AND profile = ? ORDER BY fire_at").all(n.profile):"global"in n?r=await e.prepare("SELECT * FROM crons WHERE scope = 'global' ORDER BY fire_at").all():r=await e.prepare("SELECT * FROM crons ORDER BY fire_at").all(),r.map(s)}a(v,"listCrons");async function P(n,e){return await c(async r=>{const t=await r.prepare("SELECT * FROM crons WHERE cron_id = ?").get(n);if(t===void 0)return!1;const o=s(t);return o.run_state==="running"&&e?.preserveRunningProcess!==!0&&d(o),await r.prepare("DELETE FROM crons WHERE cron_id = ?").run(n),o.anchor_node!==null&&f(o.anchor_node),!0})}a(P,"cancelCron");function R(n,e){const r=[...new Set(e)];return r.length===0?{sql:"profile = ?",params:[n]}:{sql:`profile = ? OR anchor_node IN (${r.map(()=>"?").join(",")})`,params:[n,...r]}}a(R,"profileCronWhere");async function B(n,e){const r=R(n,e);return(await(await i()).prepareUncached(`SELECT cron_id FROM crons WHERE ${r.sql} ORDER BY created, cron_id`).all(...r.params)).map(({cron_id:t})=>t)}a(B,"cronIdsForProfileDeletion");async function Y(n,e){return await c(async r=>{const t=R(n,e),o=(await r.prepareUncached(`SELECT * FROM crons WHERE ${t.sql} ORDER BY created, cron_id`).all(...t.params)).map(s);for(const u of o)u.run_state==="running"&&d(u);return await r.prepareUncached(`DELETE FROM crons WHERE ${t.sql}`).run(...t.params),o.map(({cron_id:u})=>u)})}a(Y,"deleteCronsForProfile");async function $(n){return(await(await i()).prepare("SELECT cron_id FROM crons WHERE profile = ? ORDER BY created, cron_id").all(n)).map(({cron_id:e})=>e)}a($,"cronIdsForProfileDetach");async function j(n){return await c(async e=>{const r=(await e.prepare("SELECT cron_id FROM crons WHERE profile = ? ORDER BY created, cron_id").all(n)).map(({cron_id:t})=>t);return r.length>0&&await e.prepare("UPDATE crons SET profile = NULL, scope = 'global', updated = ? WHERE profile = ?").run(new Date().toISOString(),n),r})}a(j,"globalizeCronsForProfile");const q=64;async function z(n){return(await(await i()).prepare("SELECT * FROM crons WHERE fires >= ? AND run_state = 'idle' ORDER BY cron_id").all(n)).map(s)}a(z,"cappedIdleCrons");async function G(n){const e=await(await i()).prepare("DELETE FROM crons WHERE cron_id = ? RETURNING anchor_node").get(n);return e!==void 0&&e.anchor_node!==null&&f(e.anchor_node),e!==void 0}a(G,"consumeCron");async function J(n,e){return(await(await i()).prepare("UPDATE crons SET state = ?, updated = ? WHERE cron_id = ?").run(e,new Date().toISOString(),n)).changes>0}a(J,"setCronState");async function V(n,e){await(await i()).prepare("UPDATE crons SET last_output_hash = ?, updated = ? WHERE cron_id = ?").run(e,new Date().toISOString(),n)}a(V,"setCronLastOutputHash");async function X(n){const e=await(await i()).prepare(`SELECT anchor_node, cancel_on_wake, sink
6
6
  FROM crons
7
7
  WHERE (anchor_node = ? AND cancel_on_wake = 1 AND state = 'active')
8
8
  OR (
@@ -11,28 +11,28 @@ var w=Object.defineProperty;var a=(n,r)=>w(n,"name",{value:r,configurable:!0});i
11
11
  run_state = 'running'
12
12
  OR (run_state = 'idle' AND state = 'active' AND (expires_at IS NULL OR expires_at > ?))
13
13
  )
14
- )`).all(n,new Date().toISOString());for(const e of r){if(e.anchor_node===n&&Number(e.cancel_on_wake)!==0)return!0;const t=E(e.sink);if(t?.kind==="node"&&t.node===n)return!0}return!1}a(z,"hasPendingCronWake");async function G(n){return await c(async r=>{const e=(await r.prepare("SELECT * FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1").all(n)).map(s);for(const t of e)t.run_state==="running"&&_(t),await r.prepare("DELETE FROM crons WHERE cron_id = ?").run(t.cron_id);return e})}a(G,"cancelCronsOnWake");async function J(n,r){await(await i()).prepare("UPDATE crons SET fire_at = ?, updated = ? WHERE cron_id = ?").run(r,new Date().toISOString(),n)}a(J,"advanceCron");async function V(n){return(await(await i()).prepare(`SELECT * FROM crons
14
+ )`).all(n,new Date().toISOString());for(const r of e){if(r.anchor_node===n&&Number(r.cancel_on_wake)!==0)return!0;const t=w(r.sink);if(t?.kind==="node"&&t.node===n)return!0}return!1}a(X,"hasPendingCronWake");async function K(n){return await c(async e=>{const r=(await e.prepare("SELECT * FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1").all(n)).map(s);for(const t of r)t.run_state==="running"&&d(t),await e.prepare("DELETE FROM crons WHERE cron_id = ?").run(t.cron_id);return r})}a(K,"cancelCronsOnWake");async function Q(n,e){await(await i()).prepare("UPDATE crons SET fire_at = ?, updated = ? WHERE cron_id = ?").run(e,new Date().toISOString(),n)}a(Q,"advanceCron");async function Z(n){return(await(await i()).prepare(`SELECT * FROM crons
15
15
  WHERE state = 'active' AND run_state = 'idle' AND fire_at <= ?
16
- ORDER BY fire_at, created, cron_id`).all(n)).map(s).filter(r=>!D(r.profile))}a(V,"dueClockCrons");async function K(n,r,e,t,o=null){const u=await(await i()).prepare(`UPDATE crons
16
+ ORDER BY fire_at, created, cron_id`).all(n)).map(s)}a(Z,"dueClockCrons");async function nn(n,e,r,t,o=null,u=null){const _=u!==null,m=await(await i()).prepare(`UPDATE crons
17
17
  SET run_state = 'running', run_started_at = ?, run_pid = NULL, run_pid_identity = NULL,
18
- run_lease_owner = ?, run_out_of_band = ?, run_execution_id = ?, updated = ?
19
- WHERE cron_id = ? AND run_state = 'idle'`).run(e,r,t?1:0,o,new Date().toISOString(),n);return Number(u.changes)>0}a(K,"acquireCronRunLease");async function Q(n,r,e,t){const o=l([t])?.get(t)??null,u=await(await i()).prepare(`UPDATE crons SET run_pid = ?, run_pid_identity = ?, updated = ?
18
+ run_lease_owner = ?, run_out_of_band = ?, run_execution_id = ?, updated = ?${_?", fires = fires + 1":""}
19
+ WHERE cron_id = ? AND run_state = 'idle'${_?" AND fires < ?":""}`).run(r,e,t?1:0,o,new Date().toISOString(),n,..._?[u]:[]);return Number(m.changes)>0}a(nn,"acquireCronRunLease");async function en(n,e,r,t){const o=p([t])?.get(t)??null,u=await(await i()).prepare(`UPDATE crons SET run_pid = ?, run_pid_identity = ?, updated = ?
20
20
  WHERE cron_id = ? AND run_state = 'running' AND run_lease_owner = ?
21
- AND run_started_at = ? AND run_pid IS NULL`).run(t,o,new Date().toISOString(),n,r,e);return Number(u.changes)>0}a(Q,"attachCronRunPid");async function X(n,r,e){let t="";const o=[];e!==void 0&&(e.kind==="clear"?t=", held = 0":e.kind==="park"?(t=e.fireAt!==void 0?", held = 1, fire_at = ?":", held = 1",e.fireAt!==void 0&&o.push(e.fireAt)):(t=", held = 0, fire_at = ?",o.push(e.nowIso))),await(await i()).prepareUncached(`UPDATE crons
21
+ AND run_started_at = ? AND run_pid IS NULL`).run(t,o,new Date().toISOString(),n,e,r);return Number(u.changes)>0}a(en,"attachCronRunPid");async function rn(n,e,r){let t="";const o=[];r!==void 0&&(r.kind==="clear"?t=", held = 0":r.kind==="park"?(t=r.fireAt!==void 0?", held = 1, fire_at = ?":", held = 1",r.fireAt!==void 0&&o.push(r.fireAt)):(t=", held = 0, fire_at = ?",o.push(r.nowIso))),await(await i()).prepareUncached(`UPDATE crons
22
22
  SET run_state = 'idle', run_started_at = NULL, run_pid = NULL, run_pid_identity = NULL,
23
23
  run_lease_owner = NULL, run_out_of_band = 0, run_execution_id = NULL, updated = ?${t}
24
- WHERE cron_id = ? AND run_execution_id = ?`).run(new Date().toISOString(),...o,n,r)}a(X,"releaseCronRunLease");async function Z(n,r){const e=await(await i()).prepare(`UPDATE crons SET run_execution_id = ?, updated = ?
24
+ WHERE cron_id = ? AND run_execution_id = ?`).run(new Date().toISOString(),...o,n,e)}a(rn,"releaseCronRunLease");async function tn(n,e){const r=await(await i()).prepare(`UPDATE crons SET run_execution_id = ?, updated = ?
25
25
  WHERE cron_id = ? AND run_state = 'running' AND run_execution_id IS NULL
26
- AND run_started_at IS NOT DISTINCT FROM ? AND run_lease_owner IS NOT DISTINCT FROM ?`).run(r,new Date().toISOString(),n.cron_id,n.run_started_at,n.run_lease_owner);return Number(e.changes)>0}a(Z,"adoptCronRunId");async function nn(n,r=null){return await c(async e=>{const t=r===null?"":" AND grantee = ?",o=r===null?[]:[r];await e.prepareUncached(`UPDATE crons SET last_poke_at = ? WHERE 1 = 1${t}`).run(n,...o);const u=await e.prepareUncached(`UPDATE crons SET fire_at = ?, held = 0, updated = ? WHERE held = 1 AND state = 'active' AND run_state = 'idle'${t}`).run(n,n,...o);return Number(u.changes)})}a(nn,"pokeHeldCrons");async function rn(n){return(await(await i()).prepare(`SELECT * FROM crons
26
+ AND run_started_at IS NOT DISTINCT FROM ? AND run_lease_owner IS NOT DISTINCT FROM ?`).run(e,new Date().toISOString(),n.cron_id,n.run_started_at,n.run_lease_owner);return Number(r.changes)>0}a(tn,"adoptCronRunId");async function an(n,e=null){return await c(async r=>{const t=e===null?"":" AND grantee = ?",o=e===null?[]:[e];await r.prepareUncached(`UPDATE crons SET last_poke_at = ? WHERE 1 = 1${t}`).run(n,...o);const u=await r.prepareUncached(`UPDATE crons SET fire_at = ?, held = 0, updated = ? WHERE held = 1 AND state = 'active' AND run_state = 'idle'${t}`).run(n,n,...o);return Number(u.changes)})}a(an,"pokeHeldCrons");async function on(n){return(await(await i()).prepare(`SELECT * FROM crons
27
27
  WHERE state = 'active' AND run_state = 'running' AND run_out_of_band = 0
28
28
  AND recur IS NOT NULL AND fire_at <= ?
29
- ORDER BY fire_at, created, cron_id`).all(n)).map(s)}a(rn,"dueOverlapCrons");async function en(n){return(await(await i()).prepare(`SELECT * FROM crons
29
+ ORDER BY fire_at, created, cron_id`).all(n)).map(s)}a(on,"dueOverlapCrons");async function un(n){return(await(await i()).prepare(`SELECT * FROM crons
30
30
  WHERE expires_at IS NOT NULL AND expires_at <= ? AND run_state = 'idle'
31
- ORDER BY expires_at`).all(n)).map(s)}a(en,"expiredIdleCrons");async function tn(n){return(await(await i()).prepare("SELECT * FROM cron_runs WHERE cron_id = ? ORDER BY started DESC, run_id DESC").all(n)).map(r=>({run_id:r.run_id,cron_id:r.cron_id,started:r.started,finished:r.finished,duration_ms:Number(r.duration_ms),exit_code:r.exit_code??null,stdout_head:r.stdout_head??null,stderr_head:r.stderr_head??null,delivered:r.delivered??null}))}a(tn,"listCronRuns");async function an(){return(await(await i()).prepare("SELECT * FROM crons WHERE run_state = 'running'").all()).map(s)}a(an,"runningCrons");async function y(n,r){return await n.prepare("SELECT 1 FROM crons WHERE cron_id = ?").get(r.cron_id)===void 0?!1:(await n.prepare(`INSERT INTO cron_runs (
31
+ ORDER BY expires_at`).all(n)).map(s)}a(un,"expiredIdleCrons");async function sn(n){return(await(await i()).prepare("SELECT * FROM cron_runs WHERE cron_id = ? ORDER BY started DESC, run_id DESC").all(n)).map(e=>({run_id:e.run_id,cron_id:e.cron_id,started:e.started,finished:e.finished,duration_ms:Number(e.duration_ms),exit_code:e.exit_code??null,stdout_head:e.stdout_head??null,stderr_head:e.stderr_head??null,delivered:e.delivered??null}))}a(sn,"listCronRuns");async function cn(){return(await(await i()).prepare("SELECT * FROM crons WHERE run_state = 'running'").all()).map(s)}a(cn,"runningCrons");async function g(n,e){return await n.prepare("SELECT 1 FROM crons WHERE cron_id = ?").get(e.cron_id)===void 0?!1:(await n.prepare(`INSERT INTO cron_runs (
32
32
  run_id, cron_id, started, finished, duration_ms, exit_code,
33
33
  stdout_head, stderr_head, delivered
34
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(r.run_id,r.cron_id,r.started,r.finished,r.duration_ms,r.exit_code,r.stdout_head,r.stderr_head,r.delivered),await n.prepare(`DELETE FROM cron_runs
34
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.run_id,e.cron_id,e.started,e.finished,e.duration_ms,e.exit_code,e.stdout_head,e.stderr_head,e.delivered),await n.prepare(`DELETE FROM cron_runs
35
35
  WHERE cron_id = ? AND run_id NOT IN (
36
36
  SELECT run_id FROM cron_runs WHERE cron_id = ?
37
37
  ORDER BY started DESC, run_id DESC LIMIT ?
38
- )`).run(r.cron_id,r.cron_id,h),!0)}a(y,"recordCronRunLocked");async function on(n){return await c(async r=>await y(r,n))}a(on,"recordCronRun");export{h as CRON_RUN_RING,K as acquireCronRunLease,Z as adoptCronRunId,J as advanceCron,I as armCron,Q as attachCronRunPid,v as cancelCron,G as cancelCronsOnWake,$ as consumeCron,P as cronIdsForProfileDeletion,B as cronIdsForProfileDetach,F as cronSinkDisplay,b as deleteCronsForProfile,V as dueClockCrons,rn as dueOverlapCrons,en as expiredIdleCrons,U as getCron,Y as globalizeCronsForProfile,z as hasPendingCronWake,_ as killLeasedCronRun,tn as listCronRuns,M as listCrons,E as parseCronSink,nn as pokeHeldCrons,on as recordCronRun,y as recordCronRunLocked,X as releaseCronRunLease,an as runningCrons,q as setCronLastOutputHash,j as setCronState,T as stopLeasedCronRun,d as verifyLeasedCronRun};
38
+ )`).run(e.cron_id,e.cron_id,T),!0)}a(g,"recordCronRunLocked");async function dn(n){return await c(async e=>await g(e,n))}a(dn,"recordCronRun");export{T as CRON_RUN_RING,q as HOSTED_CRON_MAX_FIRES,nn as acquireCronRunLease,tn as adoptCronRunId,Q as advanceCron,U as armCron,en as attachCronRunPid,P as cancelCron,K as cancelCronsOnWake,z as cappedIdleCrons,G as consumeCron,B as cronIdsForProfileDeletion,$ as cronIdsForProfileDetach,M as cronSinkDisplay,Y as deleteCronsForProfile,Z as dueClockCrons,on as dueOverlapCrons,un as expiredIdleCrons,b as getCron,j as globalizeCronsForProfile,X as hasPendingCronWake,d as killLeasedCronRun,sn as listCronRuns,v as listCrons,w as parseCronSink,an as pokeHeldCrons,dn as recordCronRun,g as recordCronRunLocked,rn as releaseCronRunLease,cn as runningCrons,V as setCronLastOutputHash,J as setCronState,L as stopLeasedCronRun,l as verifyLeasedCronRun};
@@ -1 +1 @@
1
- var T=Object.defineProperty;var a=(e,t)=>T(e,"name",{value:t,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as m,captureLivenessSnapshot as L,identitiesMatch as D,isBootScopedIdentity as y,isLegacyTicksIdentity as C}from"./pid.js";import{existsSync as O,readFileSync as P}from"node:fs";import{LAUNCHER_SOCKET as U}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,sandboxName:e.sandbox_name??null,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function X(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(X,"liveExecutionForNode");class W extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class H extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const b=7340001;async function Y(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${b})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new W(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.state==="launching"?u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch:u.runner!=="process");if(s!==void 0)throw new H(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=g(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, sandbox_name, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",t.sandboxName??null,E,t.release??null,t.launchJson??null),p})}a(Y,"beginExecution");async function j(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(j,"setExecutionLaunchJson");async function J(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(J,"recordExecutionIdle");async function G(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(G,"recordExecutionAwake");async function V(e,t,n){const i=m([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&O(U)&&s?.pid!=null){const h=L(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...h?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=P(`/proc/${E}/status`,"utf8"),S=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(S.length>1&&S.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(V,"recordExecutionPid");async function F(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&await l(n,o.node_id),o!==void 0})}a(F,"endExecution");async function z(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(z,"endLaunchingExecution");async function Q(e,t){return await F(e,t)}a(Q,"abortExecution");async function Z(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&await l(n,e),Number(o.changes)===1})}a(Z,"endLiveExecution");async function ee(e=t=>m([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!C(c.process_identity))continue;const s=e(c.pid);s===void 0||!y(s)||!D(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ee,"migrateLegacyExecutionIdentities");async function te(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(te,"requestExecutionStop");async function ne(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(ne,"executionsWithStopRequestedBefore");async function R(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(R,"latestExecutionForNode");async function ae(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(ae,"hasRunningRemoteExecution");async function ie(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(ie,"hasLaunchingExecution");async function oe(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(oe,"liveProcessExecutionNodeIds");async function re(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(re,"liveExecutionNodeIds");const A="profile_pause",w="profile_pause_absorbed";async function se(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(se,"markProfilePauseStop");async function ce(e){return(await R(e))?.stopReason===A}a(ce,"hasProfilePauseStop");async function ue(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(w,e,A);return Number(t.changes)>0}a(ue,"absorbProfilePauseStop");function de(e){return e.stopReason===w}a(de,"hasAbsorbedProfilePauseStop");const f="exited:";async function pe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(pe,"recordExecutionExit");function Ee(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(Ee,"hasObservedExit");async function _e(e){const t=await R(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(_e,"takeObservedExit");export{H as ExecutionAlreadyLive,W as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,Q as abortExecution,ue as absorbProfilePauseStop,Y as beginExecution,F as endExecution,z as endLaunchingExecution,Z as endLiveExecution,ne as executionsWithStopRequestedBefore,de as hasAbsorbedProfilePauseStop,ie as hasLaunchingExecution,Ee as hasObservedExit,ce as hasProfilePauseStop,ae as hasRunningRemoteExecution,R as latestExecutionForNode,X as liveExecutionForNode,re as liveExecutionNodeIds,oe as liveProcessExecutionNodeIds,se as markProfilePauseStop,ee as migrateLegacyExecutionIdentities,G as recordExecutionAwake,pe as recordExecutionExit,J as recordExecutionIdle,V as recordExecutionPid,te as requestExecutionStop,j as setExecutionLaunchJson,_e as takeObservedExit};
1
+ var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as L}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as m,captureLivenessSnapshot as D,identitiesMatch as y,isBootScopedIdentity as O,isLegacyTicksIdentity as C}from"./pid.js";import{existsSync as P,readFileSync as U}from"node:fs";import{LAUNCHER_SOCKET as W}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as R}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,sandboxName:e.sandbox_name??null,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function j(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(j,"liveExecutionForNode");class H extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const F=7340001;async function J(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${F})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new H(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.state==="launching"?u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch:u.runner!=="process");if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=L(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, sandbox_name, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",t.sandboxName??null,E,t.release??null,t.launchJson??null),p})}a(J,"beginExecution");async function G(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(G,"setExecutionLaunchJson");async function V(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(V,"recordExecutionIdle");async function z(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(z,"recordExecutionAwake");async function Q(e,t,n){const i=m([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&P(W)&&s?.pid!=null){const S=D(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=U(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Q,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),R(o.node_id)),o!==void 0})}a(I,"endExecution");async function Z(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(Z,"endLaunchingExecution");async function ee(e,t){return await I(e,t)}a(ee,"abortExecution");async function te(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),R(e)),Number(o.changes)===1})}a(te,"endLiveExecution");async function ne(e=t=>m([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!C(c.process_identity))continue;const s=e(c.pid);s===void 0||!O(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ne,"migrateLegacyExecutionIdentities");async function ae(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ae,"requestExecutionStop");async function ie(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(ie,"executionsWithStopRequestedBefore");async function w(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(w,"latestExecutionForNode");async function oe(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(oe,"hasRunningRemoteExecution");async function re(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(re,"hasLaunchingExecution");async function se(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(se,"liveProcessExecutionNodeIds");async function ce(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ce,"liveExecutionNodeIds");const A="profile_pause",T="profile_pause_absorbed";async function ue(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(ue,"markProfilePauseStop");async function de(e){return(await w(e))?.stopReason===A}a(de,"hasProfilePauseStop");async function pe(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,A);return Number(t.changes)>0}a(pe,"absorbProfilePauseStop");function Ee(e){return e.stopReason===T}a(Ee,"hasAbsorbedProfilePauseStop");const f="exited:";async function _e(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(_e,"recordExecutionExit");function xe(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(xe,"hasObservedExit");async function le(e){const t=await w(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(le,"takeObservedExit");export{b as ExecutionAlreadyLive,H as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,ee as abortExecution,pe as absorbProfilePauseStop,J as beginExecution,I as endExecution,Z as endLaunchingExecution,te as endLiveExecution,ie as executionsWithStopRequestedBefore,Ee as hasAbsorbedProfilePauseStop,re as hasLaunchingExecution,xe as hasObservedExit,de as hasProfilePauseStop,oe as hasRunningRemoteExecution,w as latestExecutionForNode,j as liveExecutionForNode,ce as liveExecutionNodeIds,se as liveProcessExecutionNodeIds,ue as markProfilePauseStop,ne as migrateLegacyExecutionIdentities,z as recordExecutionAwake,_e as recordExecutionExit,V as recordExecutionIdle,Q as recordExecutionPid,ae as requestExecutionStop,G as setExecutionLaunchJson,le as takeObservedExit};
@@ -0,0 +1,9 @@
1
+ -- 026-cron-deadline-body.sql — `crons.deadline_body`: the message a node deadline (`crtr node wait deadline`) sends its anchor
2
+ -- when it falls due. The cron lane sends it itself; a deadline no longer runs a shell command. A deadline armed before this
3
+ -- carries its body in a fixed heredoc (`crtr node message send ... <<'CRTR_DEADLINE[_n]'`, body, delimiter); the body is
4
+ -- copied into the column. An added column: `schema_min_reader` is not touched, so the previous release (version 25) still
5
+ -- opens the result. Copied rows keep their command, so that release still fires them; a deadline armed after this stores
6
+ -- only a comment as its command, so a version-25 daemon would consume it without sending its message.
7
+ ALTER TABLE crons ADD COLUMN IF NOT EXISTS deadline_body text;
8
+ UPDATE crons SET deadline_body = (regexp_match(command, E'<<''(CRTR_DEADLINE(?:_[0-9]+)?)''\\n(.*)\\n\\1$'))[2]
9
+ WHERE cancel_on_wake = 1 AND deadline_body IS NULL AND command ~ E'^crtr cron cancel "\\$CRTR_CRON_ID"\\ncrtr node message send ';
@@ -0,0 +1,4 @@
1
+ -- 027-cron-fires.sql — `crons.fires`: how many times a cron has fired. A hosted cron ends after HOSTED_CRON_MAX_FIRES (NL-1110);
2
+ -- the run log keeps only the last 20 runs, so it cannot be counted from there. An added column: `schema_min_reader` is not touched,
3
+ -- so the previous release (version 26) still opens the result. Existing rows start at 0.
4
+ ALTER TABLE crons ADD COLUMN IF NOT EXISTS fires integer NOT NULL DEFAULT 0;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 25;
4
+ export declare const CANVAS_SCHEMA_VERSION = 27;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=25;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=27;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1,10 +1,10 @@
1
- var G=Object.defineProperty;var c=(e,i)=>G(e,"name",{value:i,configurable:!0});import{renderRoot as V,renderBranch as B,renderLeafArgv as W,withAsyncHelpState as K,collapseWideChildren as L,rootPromotedChildren as J}from"./help.js";import{beginPreview as D,publishPreviewResult as Q,readStdinRaw as M,peekStdinRaw as X,emit as Y,handle as Z,setJsonOutput as ee,isJsonOutput as ne}from"./io.js";import{renderResult as te}from"./render.js";import{CrtrError as R}from"./errors.js";import{validateValue as ie}from"../api/command-manifest/result.js";import{isManifestStaleError as re}from"./manifest-stale.js";import{operationIdContext as ae}from"./events/operation-id.js";import{ExitCode as _}from"../types.js";import{envNodeId as oe,providerProjectionOverBrokerRelay as se}from"../shared/env.js";import{readFileSync as de}from"node:fs";import{spawnSync as le}from"node:child_process";import{constants as fe}from"node:os";import{resolve as ce}from"node:path";function F(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(const i of Object.values(e))F(i);return Object.freeze(e)}c(F,"freezeCommandMetadata");function Ve(e){const i=F(e.help),{helpState:r}=e;if(r!==void 0&&e.effectiveHelp!==void 0)throw new Error(`leaf ${e.name} declares both helpState and effectiveHelp`);return Object.freeze({kind:"leaf",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:i,effectiveHelp:e.effectiveHelp??(r===void 0?void 0:n=>K(i,r,n)),slash:e.slash===void 0?void 0:F(e.slash),hookEligible:e.hookEligible,plugin:e.plugin,machineSelector:e.machineSelector,run:e.run,render:e.render,preview:e.preview,stdoutExact:e.stdoutExact})}c(Ve,"defineLeaf");function O(e){return e.kind==="branch"&&e.children.length>0&&I(e)===0?"hidden":e.tier??"normal"}c(O,"effectiveTier");function I(e){return e.kind!=="branch"?0:(e.help.listing??[]).filter(i=>i.tier!=="hidden").length}c(I,"visibleSubCount");function Be(e){if(e.passthrough!==void 0&&e.children.length>0)throw new Error(`defineBranch("${e.name}"): a passthrough branch must declare no children (found ${e.children.length})`);return e.help.listing=e.children.map(i=>{const r=I(i);return{name:i.name,description:i.description??"",whenToUse:i.whenToUse??"",tier:O(i),kind:i.kind,...i.plugin!==void 0?{plugin:i.plugin}:{},...r>0?{subCount:r}:{}}}),{kind:"branch",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:e.help,effectiveHelp:e.effectiveHelp,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,refusal:e.refusal,children:e.children}}c(Be,"defineBranch");function Je(e){const i=[],r=c(n=>{if(n.slash!==void 0&&i.push(n.slash),n.kind==="branch")for(const a of n.children)r(a)},"visit");for(const n of e.subtrees)r(n);return i}c(Je,"collectSlashSpecs");function Me(e){const i=e.subtrees.filter(n=>n.rootEntry!==void 0&&O(n)!=="hidden").map(n=>{const a=(n.help.listing??[]).filter(s=>s.tier!=="hidden"),l=J(a).map(s=>({path:`${n.name} ${s.name}`,desc:s.tier==="important"?s.description:void 0}));return{name:n.name,concept:n.rootEntry.concept,desc:n.rootEntry.desc,useWhen:n.rootEntry.useWhen,dynamicState:n.rootEntry.dynamicState,subcommands:l.length>0?l:void 0,otherSubcommandCount:a.length-l.length}});return{kind:"root",help:{tagline:e.tagline,commands:i,globals:e.globals},subtrees:e.subtrees}}c(Me,"defineRoot");function ue(e){if(e.kind==="root")return e.subtrees.filter(i=>O(i)!=="hidden").map(i=>i.name);if(e.kind==="branch"){const{listed:i,unlisted:r}=L(e.children.filter(n=>O(n)!=="hidden"));return[...i.map(n=>n.name),...r>0?[`(and ${r} more)`]:[]]}return[]}c(ue,"childNames");function he(e,i){let r=e;const n=[];let a=0;for(;a<i.length;){const l=i[a];if(l==="-h"||l==="--help")break;if(r.kind==="root"){const s=r.subtrees.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else if(r.kind==="branch"){const s=r.children.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else break}return{node:r,path:n,remaining:i.slice(a)}}c(he,"walk");function me(e){return e.kind==="root"?V(e.help):e.kind==="branch"?B(e.help):W(e.help)}c(me,"renderNode");async function z(e,i,r){if(r!==void 0&&e.kind==="leaf")return W(e.effectiveHelp!==void 0?await e.effectiveHelp(r):e.help,r);const n=e.kind==="leaf"&&e.effectiveHelp!==void 0?W(await e.effectiveHelp()):e.kind==="branch"&&e.effectiveHelp!==void 0?B(await e.effectiveHelp()):me(e);if(i.length===0)return n;const{hasEffectiveCommandPlugins:a}=await import("./command-plugins/presence.js");if(!a())return n;const[{collectHelpAddenda:l},{SUBTREE_NAMES:s,coreCommandPathsCovering:o,extensibleCoreBranches:$}]=await Promise.all([import("./command-plugins/help-addenda.js"),import("../build-root.js")]),v=await l(i.join(" "),{reservedCoreNames:new Set(s),coreCommandPaths:o,extensibleCoreBranches:$});return n+v.map(S=>`
1
+ var G=Object.defineProperty;var c=(e,i)=>G(e,"name",{value:i,configurable:!0});import{renderRoot as V,renderBranch as B,renderLeafArgv as W,withAsyncHelpState as K,collapseWideChildren as L,rootPromotedChildren as J}from"./help.js";import{beginPreview as D,publishPreviewResult as Q,readStdinRaw as M,peekStdinRaw as X,emit as Y,handle as Z,setJsonOutput as ee,isJsonOutput as ne}from"./io.js";import{renderResult as te}from"./render.js";import{CrtrError as R}from"./errors.js";import{validateValue as ie}from"../api/command-manifest/result.js";import{isManifestStaleError as re}from"./manifest-stale.js";import{operationIdContext as ae}from"./events/operation-id.js";import{ExitCode as _}from"../types.js";import{envNodeId as oe,providerProjectionOverBrokerRelay as se}from"../shared/env.js";import{readFileSync as de}from"node:fs";import{spawnSync as le}from"node:child_process";import{constants as fe}from"node:os";import{resolve as ce}from"node:path";function F(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(const i of Object.values(e))F(i);return Object.freeze(e)}c(F,"freezeCommandMetadata");function Ve(e){const i=F(e.help),{helpState:r}=e;if(r!==void 0&&e.effectiveHelp!==void 0)throw new Error(`leaf ${e.name} declares both helpState and effectiveHelp`);return Object.freeze({kind:"leaf",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:i,effectiveHelp:e.effectiveHelp??(r===void 0?void 0:n=>K(i,r,n)),slash:e.slash===void 0?void 0:F(e.slash),hookEligible:e.hookEligible,plugin:e.plugin,machineSelector:e.machineSelector,run:e.run,render:e.render,preview:e.preview,stdoutExact:e.stdoutExact})}c(Ve,"defineLeaf");function O(e){return e.kind==="branch"&&e.children.length>0&&I(e)===0?"hidden":e.tier??"normal"}c(O,"effectiveTier");function I(e){return e.kind!=="branch"?0:(e.help.listing??[]).filter(i=>i.tier!=="hidden").length}c(I,"visibleSubCount");function Be(e){if(e.passthrough!==void 0&&e.children.length>0)throw new Error(`defineBranch("${e.name}"): a passthrough branch must declare no children (found ${e.children.length})`);return e.help.listing=e.children.map(i=>{const r=I(i);return{name:i.name,description:i.description??"",whenToUse:i.whenToUse??"",tier:O(i),kind:i.kind,...i.plugin!==void 0?{plugin:i.plugin}:{},...r>0?{subCount:r}:{}}}),{kind:"branch",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:e.help,effectiveHelp:e.effectiveHelp,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,refusal:e.refusal,children:e.children}}c(Be,"defineBranch");function Je(e){const i=[],r=c(n=>{if(n.slash!==void 0&&i.push(n.slash),n.kind==="branch")for(const a of n.children)r(a)},"visit");for(const n of e.subtrees)r(n);return i}c(Je,"collectSlashSpecs");function Me(e){const i=e.subtrees.filter(n=>n.rootEntry!==void 0&&O(n)!=="hidden").map(n=>{const a=(n.help.listing??[]).filter(s=>s.tier!=="hidden"),l=J(a).map(s=>({path:`${n.name} ${s.name}`,desc:s.tier==="important"?s.description:void 0}));return{name:n.name,concept:n.rootEntry.concept,desc:n.rootEntry.desc,useWhen:n.rootEntry.useWhen,dynamicState:n.rootEntry.dynamicState,subcommands:l.length>0?l:void 0,otherSubcommandCount:a.length-l.length}});return{kind:"root",help:{tagline:e.tagline,commands:i,globals:e.globals},subtrees:e.subtrees}}c(Me,"defineRoot");function ue(e){if(e.kind==="root")return e.subtrees.filter(i=>O(i)!=="hidden").map(i=>i.name);if(e.kind==="branch"){const{listed:i,unlisted:r}=L(e.children.filter(n=>O(n)!=="hidden"));return[...i.map(n=>n.name),...r>0?[`(and ${r} more)`]:[]]}return[]}c(ue,"childNames");function he(e,i){let r=e;const n=[];let a=0;for(;a<i.length;){const l=i[a];if(l==="-h"||l==="--help")break;if(r.kind==="root"){const s=r.subtrees.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else if(r.kind==="branch"){const s=r.children.find(o=>o.name===l);if(s===void 0)break;r=s,n.push(s.name),a++}else break}return{node:r,path:n,remaining:i.slice(a)}}c(he,"walk");function me(e){return e.kind==="root"?V(e.help):e.kind==="branch"?B(e.help):W(e.help)}c(me,"renderNode");async function z(e,i,r){if(r!==void 0&&e.kind==="leaf")return W(e.effectiveHelp!==void 0?await e.effectiveHelp(r):e.help,r);const n=e.kind==="leaf"&&e.effectiveHelp!==void 0?W(await e.effectiveHelp()):e.kind==="branch"&&e.effectiveHelp!==void 0?B(await e.effectiveHelp()):me(e);if(i.length===0)return n;const{hasEffectiveCommandPlugins:a}=await import("./command-plugins/presence.js");if(!a())return n;const[{collectHelpAddenda:l},{SUBTREE_NAMES:s,coreCommandPathsCovering:o,extensibleCoreBranches:y}]=await Promise.all([import("./command-plugins/help-addenda.js"),import("../build-root.js")]),v=await l(i.join(" "),{reservedCoreNames:new Set(s),coreCommandPaths:o,extensibleCoreBranches:y});return n+v.map(P=>`
2
2
 
3
- <plugin-help plugin="${S.plugin}">
4
- ${S.text}
5
- </plugin-help>`).join("")}c(z,"renderNodeWithAddenda");function pe(e){return e.some(i=>i==="-h"||i==="--help")}c(pe,"helpRequested");function ge(e,i){if(e.kind!=="leaf"||i.length!==2)return;const[r,n]=i;if(n!=="-h"&&n!=="--help"||!r.startsWith("--")||r.includes("="))return;const a=r.slice(2);return(e.help.params??[]).find(s=>s.kind==="flag"&&s.name===a)?.focusedHelp!==void 0?a:void 0}c(ge,"focusedHelpFlag");function we(e,i){let r=0;for(let n=0;n<e.length;n++){if(r===i.length)return e.slice(n);e[n]!=="--json"&&e[n]===i[r]&&r++}return[]}c(we,"rawArgsAfterPath");function ve(e,i){const r=le(e.bin,i,{stdio:"inherit"});if(r.error!==void 0){const n=r.error;throw new R("binary_missing",`${e.bin} could not be run (${n.code??n.message})`,_.USAGE,{received:e.bin,next:e.installHint})}if(r.status!==null&&process.exit(r.status),r.signal!==null){const n=fe.signals[r.signal];n!==void 0&&process.exit(128+n)}process.exit(1)}c(ve,"runPassthrough");function be(e,i,r){const n=ue(e),a=n.length>0?n.join(", "):"(none)",l=i.length>0?`crtr ${i.join(" ")} -h`:"crtr -h",s=n.some(o=>o.startsWith("(and "));return new R("unknown_path",`unknown subcommand: ${r}`,_.USAGE,{received:r,next:s?`Valid children include: ${a}. Run \`${l}\` for how to find the rest.`:`Valid children: ${a}. Run \`${l}\` for the full list.`})}c(be,"unknownPathError");function xe(e){const i="If it comes from Northlight, it needs a Northlight account: `crtr sys signin`.";return new R("not_joined",`\`crtr ${e}\` isn't a command here. ${i}`,_.USAGE,{received:e,next:i})}c(xe,"notJoinedError");async function ke(){if(se())return!1;try{const{readConfig:e}=await import("./config.js"),{readMachineConfig:i}=await import("../daemon/machine-link/config.js");return i()===void 0&&!e("user").runtime?.issuer}catch{return!1}}c(ke,"runtimeUnjoined");function m(e,i,r,n,a){return new R(e,i,_.USAGE,{received:r,field:n,next:a!==void 0?a:"Run the command with -h to see the parameter schema."})}c(m,"parseArgvError");function k(e){return e.replace(/-([a-z])/g,(i,r)=>r.toUpperCase())}c(k,"flagNameToKey");async function $e(e,i,r){const n={},a=new Set,l=new Map,s=e.filter(t=>t.kind==="positional"),o=e.find(t=>t.kind==="stdin"),$=e.find(t=>t.kind==="context-file"),v=e.filter(t=>t.kind==="flag"),S=new Map(v.map(t=>[t.name,t])),P=v.some(t=>t.sensitive===!0);for(const t of v)t.type==="bool"?n[k(t.name)]=t.default!==void 0?t.default:!1:t.default!==void 0&&(n[k(t.name)]=t.default);const w=[];let b=0,N=!1,u=0;for(;u<i.length;){const t=i[u];if(t==="--"&&!N){N=!0,u++;continue}if(!N&&t.startsWith("--")){const h=t.indexOf("=");let d,C;if(h!==-1?(d=t.slice(2,h),C=t.slice(h+1)):d=t.slice(2),d==="context-file"){if($===void 0)throw m("unknown_flag","unknown flag: --context-file","--context-file",void 0,"This leaf does not accept --context-file.");const f=C!==void 0?C:i[++u];if(f===void 0)throw m("missing_parameter","--context-file requires a PATH argument","--context-file","context-file");let x;try{x=de(f,"utf8")}catch{throw m("invalid_type",`--context-file: cannot read file: ${f}`,f,"context-file","Provide a readable file path.")}let q;try{q=JSON.parse(x)}catch{throw m("invalid_type",`--context-file: file is not valid JSON: ${f}`,f,"context-file","Ensure the file contains a valid JSON object.")}const T=k($.name);n[T]=q,l.set(T,ce(f)),a.add(T),u++;continue}const A=S.has(d)||!d.startsWith("no-")?void 0:S.get(d.slice(3));if(A!==void 0&&A.type==="bool"){if(C!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${C}`,A.name,`Use --${d} (presence = false) with no value.`);const f=k(A.name);a.add(f),n[f]=!1,u++;continue}const E=S.get(d);if(E===void 0)throw m("unknown_flag",`unknown flag: --${d}`,`--${d}`,void 0,"Use --<flag-name> for declared flags only. Run -h for the schema.");const H=k(d);if(a.add(H),E.type==="bool"){if(C!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${C}`,d,`Use --${d} (presence = true) or --no-${d} (false), with no value.`);n[H]=!0,u++;continue}const y=C!==void 0?C:i[++u];if(y===void 0||C===void 0&&y.startsWith("--")){const f=E.focusedHelp!==void 0&&(r?.leafPath?.length??0)>0?`Run \`crtr ${r.leafPath.join(" ")} --${d} -h\` and read the focused value contract before retrying.`:void 0;throw m("missing_parameter",`--${d} requires a value`,`--${d}`,d,f)}let j;if(E.type==="int"){const f=Number(y);if(!Number.isInteger(f))throw m("invalid_type",`--${d} must be an integer`,y,d,`Provide an integer value for --${d}.`);j=f}else if(E.type==="enum"){const f=E.choices;if(f!==void 0&&!f.includes(y))throw m("invalid_type",`--${d} must be one of: ${f.join(", ")}`,y,d,`Retry with one of: ${f.join(", ")}.`);j=y}else if(E.type==="json"){let f;try{f=JSON.parse(y)}catch{throw m("invalid_type",`--${d} is not valid JSON`,y,d,`Pass one JSON value for --${d}; run -h for its shape.`)}const x=E.shape===void 0?null:ie(E.shape,f,`--${d}`);if(x!==null)throw m("invalid_type",`${x.path} must be ${x.expected}, got ${x.receivedType}`,y,x.path,`Fix ${x.path}; run -h for the shape of --${d}.`);j=f}else j=y;if(E.repeatable===!0){const f=n[H],x=Array.isArray(f)?f:[];x.push(j),n[H]=x}else n[H]=j;u++;continue}const p=s[b];if(p!==void 0){const h=k(p.name);if(p.repeatable===!0){const d=n[h]??[];d.push(t),n[h]=d}else n[h]=t,b++;w.push(t),a.add(h),u++;continue}if(w.length>0){if(o!==void 0&&s.length===0){w.push(t),u++;continue}throw o!==void 0?m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument."):m("bad_invocation",P?"unexpected extra positional argument (value withheld: this leaf takes a secret)":`unexpected extra positional argument: ${t}`,P?void 0:i.join(" "),void 0,"Use declared flags or positional parameters. Run -h for the schema.")}if(s.length===0&&(o===void 0||o.allowPositional===!1))throw m("bad_invocation",P?"this leaf takes no positional arguments (value withheld: this leaf takes a secret)":`this leaf takes no positional arguments: ${t}`,P?void 0:t,void 0,"Use --flag for parameters. Run -h for the schema.");w.push(t),u++}let g=!1;if(o!==void 0){if(w.length>1&&s.length===0){const t=o.positionalStdinConflict?.(n);throw t!==void 0?m("bad_invocation",t.message,void 0,t.field,t.next):m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument.")}if(w.length>0&&s.length===0&&o.allowPositional!==!1){const t=w[0];if(t==="-"){const p=await M();(p.trim()!==""||!o.required)&&(n[k(o.name)]=p),g=!0}else{if((await X()).trim()!==""){const h=o.positionalStdinConflict?.(n);throw m("bad_invocation",h?.message??`both a positional argument ("${t}") and piped stdin were provided for ${o.name}`,t,h?.field??o.name,h?.next??"Pass exactly one: either the positional argument or piped stdin, not both.")}n[k(o.name)]=t,g=!0}}else{const t=await M();t!==""&&(t.trim()!==""||!o.required)&&(n[k(o.name)]=t,g=!0)}}g&&o!==void 0&&a.add(k(o.name));for(const t of e){if(t.kind!=="flag"&&t.kind!=="positional"||t.defaultFromEnv===void 0)continue;const p=k(t.name);if(a.has(p))continue;const h=process.env[t.defaultFromEnv];h===void 0||h===""||(n[p]=t.kind==="positional"&&t.repeatable===!0?[h]:h,a.add(p))}const U=[];for(const t of e){const p=k(t.name),h=t.kind==="flag"&&t.type==="bool"&&!a.has(p);if(t.required&&(h||n[p]===void 0||n[p]===null)){const d=t.kind==="positional"?`positional ${t.name.toUpperCase()}`:t.kind==="flag"?`--${t.name}`:t.kind==="context-file"?"--context-file":"stdin";U.push({display:d,name:t.name})}}if(U.length>0){const t=U.map(d=>d.display).join(", "),p=r?.leafPath,h=p!==void 0&&p.length>0?`\`crtr ${p.join(" ")} -h\``:"this command with -h";throw m("missing_parameter",U.length===1?`required parameter is missing: ${t}`:`required parameters are missing: ${t}`,void 0,U.map(d=>d.name).join(", "),`Run ${h} and read the full schema before re-issuing \u2014 do not guess parameters one at a time.`)}return r?.onProvidedParams!==void 0&&r.onProvidedParams(a),r?.onContextFilePaths!==void 0&&r.onContextFilePaths(l),n}c($e,"parseArgv");function ye(e){const i=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){i.push(...e.slice(n));break}const l=a.startsWith("--machine=")?a.slice(10):void 0;if(a!=="--machine"&&l===void 0){i.push(a);continue}const s=l??e[n+1];if(s===void 0||s===""||l===void 0&&s.startsWith("-"))throw m("missing_parameter","--machine requires a machine id","--machine","machine","Pass the machine_id of one of the candidates a `machine_required` answer lists.");l===void 0&&n++,r=s}return r===void 0?{rest:i}:{rest:i,machine:r}}c(ye,"takeMachineSelector");const Se=new Set(["--json","--no-autostart"]);async function Ie(e,i){const r=i.slice(2);r.includes("--json")&&ee(!0);const n=r.filter(o=>!Se.has(o));if(n.length===0||n.length===1&&(n[0]==="-h"||n[0]==="--help")){const o=oe()?{...e.help,commands:await Promise.all(e.help.commands.map(async $=>{const v=e.subtrees.find(b=>b.name===$.name);if(v?.effectiveHelp===void 0)return $;const P=((await v.effectiveHelp()).listing??[]).filter(b=>b.tier!=="hidden"),w=J(P).map(b=>({path:`${v.name} ${b.name}`,desc:b.tier==="important"?b.description:void 0}));return{...$,subcommands:w.length?w:void 0,otherSubcommandCount:P.length-w.length}}))}:e.help;process.stdout.write(V(o)+`
3
+ <plugin-help plugin="${P.plugin}">
4
+ ${P.text}
5
+ </plugin-help>`).join("")}c(z,"renderNodeWithAddenda");function pe(e){return e.some(i=>i==="-h"||i==="--help")}c(pe,"helpRequested");function ge(e,i){if(e.kind!=="leaf"||i.length!==2)return;const[r,n]=i;if(n!=="-h"&&n!=="--help"||!r.startsWith("--")||r.includes("="))return;const a=r.slice(2);return(e.help.params??[]).find(s=>s.kind==="flag"&&s.name===a)?.focusedHelp!==void 0?a:void 0}c(ge,"focusedHelpFlag");function we(e,i){let r=0;for(let n=0;n<e.length;n++){if(r===i.length)return e.slice(n);e[n]!=="--json"&&e[n]===i[r]&&r++}return[]}c(we,"rawArgsAfterPath");function ve(e,i){const r=le(e.bin,i,{stdio:"inherit"});if(r.error!==void 0){const n=r.error;throw new R("binary_missing",`${e.bin} could not be run (${n.code??n.message})`,_.USAGE,{received:e.bin,next:e.installHint})}if(r.status!==null&&process.exit(r.status),r.signal!==null){const n=fe.signals[r.signal];n!==void 0&&process.exit(128+n)}process.exit(1)}c(ve,"runPassthrough");function be(e,i,r){const n=ue(e),a=n.length>0?n.join(", "):"(none)",l=i.length>0?`crtr ${i.join(" ")} -h`:"crtr -h",s=n.some(o=>o.startsWith("(and "));return new R("unknown_path",`unknown subcommand: ${r}`,_.USAGE,{received:r,next:s?`Valid children include: ${a}. Run \`${l}\` for how to find the rest.`:`Valid children: ${a}. Run \`${l}\` for the full list.`})}c(be,"unknownPathError");function xe(e){const i="If it comes from Northlight, it needs a Northlight account: `crtr sys signin`.";return new R("not_joined",`\`crtr ${e}\` isn't a command here. ${i}`,_.USAGE,{received:e,next:i})}c(xe,"notJoinedError");async function ke(){if(se())return!1;try{const{readConfig:e}=await import("./config.js"),{readMachineConfig:i}=await import("../daemon/machine-link/config.js");return i()===void 0&&!e("user").runtime?.issuer}catch{return!1}}c(ke,"runtimeUnjoined");function m(e,i,r,n,a){return new R(e,i,_.USAGE,{received:r,field:n,next:a!==void 0?a:"Run the command with -h to see the parameter schema."})}c(m,"parseArgvError");function $(e){return e.replace(/-([a-z])/g,(i,r)=>r.toUpperCase())}c($,"flagNameToKey");async function $e(e,i,r){const n={},a=new Set,l=new Map,s=e.filter(t=>t.kind==="positional"),o=e.find(t=>t.kind==="stdin"),y=e.find(t=>t.kind==="context-file"),v=e.filter(t=>t.kind==="flag"),P=new Map(v.map(t=>[t.name,t])),C=v.some(t=>t.sensitive===!0);for(const t of v)t.type==="bool"?n[$(t.name)]=t.default!==void 0?t.default:!1:t.default!==void 0&&(n[$(t.name)]=t.default);const w=[];let b=0,U=!1,u=0;for(;u<i.length;){const t=i[u];if(t==="--"&&!U){U=!0,u++;continue}if(!U&&t.startsWith("--")){const h=t.indexOf("=");let d,E;if(h!==-1?(d=t.slice(2,h),E=t.slice(h+1)):d=t.slice(2),d==="context-file"){if(y===void 0)throw m("unknown_flag","unknown flag: --context-file","--context-file",void 0,"This leaf does not accept --context-file.");const f=E!==void 0?E:i[++u];if(f===void 0)throw m("missing_parameter","--context-file requires a PATH argument","--context-file","context-file");let k;try{k=de(f,"utf8")}catch{throw m("invalid_type",`--context-file: cannot read file: ${f}`,f,"context-file","Provide a readable file path.")}let q;try{q=JSON.parse(k)}catch{throw m("invalid_type",`--context-file: file is not valid JSON: ${f}`,f,"context-file","Ensure the file contains a valid JSON object.")}const T=$(y.name);n[T]=q,l.set(T,ce(f)),a.add(T),u++;continue}const A=P.has(d)||!d.startsWith("no-")?void 0:P.get(d.slice(3));if(A!==void 0&&A.type==="bool"){if(E!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${E}`,A.name,`Use --${d} (presence = false) with no value.`);const f=$(A.name);a.add(f),n[f]=!1,u++;continue}const x=P.get(d);if(x===void 0)throw m("unknown_flag",`unknown flag: --${d}`,`--${d}`,void 0,"Use --<flag-name> for declared flags only. Run -h for the schema.");const j=$(d);if(a.has(j)&&x.type!=="bool"&&x.repeatable!==!0)throw m("bad_invocation",`--${d} given twice; it takes one value`,`--${d}`,d,`Pass --${d} once.`);if(a.add(j),x.type==="bool"){if(E!==void 0)throw m("invalid_type",`boolean flag --${d} takes no value`,`--${d}=${E}`,d,`Use --${d} (presence = true) or --no-${d} (false), with no value.`);n[j]=!0,u++;continue}const S=E!==void 0?E:i[++u];if(S===void 0||E===void 0&&S.startsWith("--")){const f=x.focusedHelp!==void 0&&(r?.leafPath?.length??0)>0?`Run \`crtr ${r.leafPath.join(" ")} --${d} -h\` and read the focused value contract before retrying.`:void 0;throw m("missing_parameter",`--${d} requires a value`,`--${d}`,d,f)}let N;if(x.type==="int"){const f=Number(S);if(!Number.isInteger(f))throw m("invalid_type",`--${d} must be an integer`,S,d,`Provide an integer value for --${d}.`);N=f}else if(x.type==="enum"){const f=x.choices;if(f!==void 0&&!f.includes(S))throw m("invalid_type",`--${d} must be one of: ${f.join(", ")}`,S,d,`Retry with one of: ${f.join(", ")}.`);N=S}else if(x.type==="json"){let f;try{f=JSON.parse(S)}catch{throw m("invalid_type",`--${d} is not valid JSON`,S,d,`Pass one JSON value for --${d}; run -h for its shape.`)}const k=x.shape===void 0?null:ie(x.shape,f,`--${d}`);if(k!==null)throw m("invalid_type",`${k.path} must be ${k.expected}, got ${k.receivedType}`,S,k.path,`Fix ${k.path}; run -h for the shape of --${d}.`);N=f}else N=S;if(x.repeatable===!0){const f=n[j],k=Array.isArray(f)?f:[];k.push(N),n[j]=k}else n[j]=N;u++;continue}const p=s[b];if(p!==void 0){const h=$(p.name);if(p.repeatable===!0){const d=n[h]??[];d.push(t),n[h]=d}else n[h]=t,b++;w.push(t),a.add(h),u++;continue}if(w.length>0){if(o!==void 0&&s.length===0){w.push(t),u++;continue}throw o!==void 0?m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument."):m("bad_invocation",C?"unexpected extra positional argument (value withheld: this leaf takes a secret)":`unexpected extra positional argument: ${t}`,C?void 0:i.join(" "),void 0,"Use declared flags or positional parameters. Run -h for the schema.")}if(s.length===0&&(o===void 0||o.allowPositional===!1))throw m("bad_invocation",C?"this leaf takes no positional arguments (value withheld: this leaf takes a secret)":`this leaf takes no positional arguments: ${t}`,C?void 0:t,void 0,"Use --flag for parameters. Run -h for the schema.");w.push(t),u++}let g=!1;if(o!==void 0){if(w.length>1&&s.length===0){const t=o.positionalStdinConflict?.(n);throw t!==void 0?m("bad_invocation",t.message,void 0,t.field,t.next):m("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${o.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument.")}if(w.length>0&&s.length===0&&o.allowPositional!==!1){const t=w[0];if(t==="-"){const p=await M();(p.trim()!==""||!o.required)&&(n[$(o.name)]=p),g=!0}else{if((await X()).trim()!==""){const h=o.positionalStdinConflict?.(n);throw m("bad_invocation",h?.message??`both a positional argument ("${t}") and piped stdin were provided for ${o.name}`,t,h?.field??o.name,h?.next??"Pass exactly one: either the positional argument or piped stdin, not both.")}n[$(o.name)]=t,g=!0}}else{const t=await M();t!==""&&(t.trim()!==""||!o.required)&&(n[$(o.name)]=t,g=!0)}}g&&o!==void 0&&a.add($(o.name));for(const t of e){if(t.kind!=="flag"&&t.kind!=="positional"||t.defaultFromEnv===void 0)continue;const p=$(t.name);if(a.has(p))continue;const h=process.env[t.defaultFromEnv];h===void 0||h===""||(n[p]=t.kind==="positional"&&t.repeatable===!0?[h]:h,a.add(p))}const H=[];for(const t of e){const p=$(t.name),h=t.kind==="flag"&&t.type==="bool"&&!a.has(p);if(t.required&&(h||n[p]===void 0||n[p]===null)){const d=t.kind==="positional"?`positional ${t.name.toUpperCase()}`:t.kind==="flag"?`--${t.name}`:t.kind==="context-file"?"--context-file":"stdin";H.push({display:d,name:t.name})}}if(H.length>0){const t=H.map(d=>d.display).join(", "),p=r?.leafPath,h=p!==void 0&&p.length>0?`\`crtr ${p.join(" ")} -h\``:"this command with -h";throw m("missing_parameter",H.length===1?`required parameter is missing: ${t}`:`required parameters are missing: ${t}`,void 0,H.map(d=>d.name).join(", "),`Run ${h} and read the full schema before re-issuing \u2014 do not guess parameters one at a time.`)}return r?.onProvidedParams!==void 0&&r.onProvidedParams(a),r?.onContextFilePaths!==void 0&&r.onContextFilePaths(l),n}c($e,"parseArgv");function ye(e){const i=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){i.push(...e.slice(n));break}const l=a.startsWith("--machine=")?a.slice(10):void 0;if(a!=="--machine"&&l===void 0){i.push(a);continue}const s=l??e[n+1];if(s===void 0||s===""||l===void 0&&s.startsWith("-"))throw m("missing_parameter","--machine requires a machine id","--machine","machine","Pass the machine_id of one of the candidates a `machine_required` answer lists.");l===void 0&&n++,r=s}return r===void 0?{rest:i}:{rest:i,machine:r}}c(ye,"takeMachineSelector");const Se=new Set(["--json","--no-autostart"]);async function Ie(e,i){const r=i.slice(2);r.includes("--json")&&ee(!0);const n=r.filter(o=>!Se.has(o));if(n.length===0||n.length===1&&(n[0]==="-h"||n[0]==="--help")){const o=oe()?{...e.help,commands:await Promise.all(e.help.commands.map(async y=>{const v=e.subtrees.find(b=>b.name===y.name);if(v?.effectiveHelp===void 0)return y;const C=((await v.effectiveHelp()).listing??[]).filter(b=>b.tier!=="hidden"),w=J(C).map(b=>({path:`${v.name} ${b.name}`,desc:b.tier==="important"?b.description:void 0}));return{...y,subcommands:w.length?w:void 0,otherSubcommandCount:C.length-w.length}}))}:e.help;process.stdout.write(V(o)+`
6
6
  `),process.exitCode=_.SUCCESS;return}if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){const{readPackageVersion:o}=await import("../commands/sys/shared.js");process.stdout.write(o()+`
7
7
  `),process.exitCode=_.SUCCESS;return}let{node:a,path:l,remaining:s}=he(e,n);try{if(a.kind==="branch"&&a.passthrough!==void 0&&ve(a.passthrough,we(r,l)),a.kind==="branch"&&a.refusal!==void 0&&s[0]!=="-h"&&s[0]!=="--help")throw new R(a.refusal.code,a.refusal.message,a.refusal.exit,{next:a.refusal.next});if((a.kind==="root"||a.kind==="branch")&&s.length>0&&s[0]!=="-h"&&s[0]!=="--help")throw a.kind==="root"&&!s[0].startsWith("-")&&a.providerCatalogFailure!==void 0?a.providerCatalogFailure:a.kind==="root"&&!s[0].startsWith("-")&&await ke()?xe(s[0]):be(a,l,s[0]);if(pe(s)){process.stdout.write(await z(a,l,ge(a,s))+`
8
8
  `),process.exitCode=_.SUCCESS;return}if(a.kind==="root"||a.kind==="branch"){process.stdout.write(await z(a,l)+`
9
- `),process.exitCode=_.SUCCESS;return}const o=a;D(l.join(" "));const $=o.help.params!==void 0?o.help.params:[];let v=new Set,S=new Map,P=s,w;if(o.machineSelector===!0&&!$.some(g=>g.kind==="flag"&&g.name==="machine")){const g=ye(s);P=g.rest,w=g.machine}const b=await $e($,P,{leafPath:l,onProvidedParams:c(g=>{v=g},"onProvidedParams"),onContextFilePaths:c(g=>{S=g},"onContextFilePaths")}),N={providedParams:v,contextFilePaths:S,...w===void 0?{}:{machine:w}},u=await ae.fresh(()=>o.run(b,N));if(Q(u==null?u:o.preview?.(u)??u),u!=null)if(ne())Y(u);else{const g=o.render!==void 0?o.render(u):te(u,o.help);process.stdout.write(g+(o.stdoutExact?.(u)?"":`
9
+ `),process.exitCode=_.SUCCESS;return}const o=a;D(l.join(" "));const y=o.help.params!==void 0?o.help.params:[];let v=new Set,P=new Map,C=s,w;if(o.machineSelector===!0&&!y.some(g=>g.kind==="flag"&&g.name==="machine")){const g=ye(s);C=g.rest,w=g.machine}const b=await $e(y,C,{leafPath:l,onProvidedParams:c(g=>{v=g},"onProvidedParams"),onContextFilePaths:c(g=>{P=g},"onContextFilePaths")}),U={providedParams:v,contextFilePaths:P,...w===void 0?{}:{machine:w}},u=await ae.fresh(()=>o.run(b,U));if(Q(u==null?u:o.preview?.(u)??u),u!=null)if(ne())Y(u);else{const g=o.render!==void 0?o.render(u):te(u,o.help);process.stdout.write(g+(o.stdoutExact?.(u)?"":`
10
10
  `))}}catch(o){if(re(o))throw o;Z(o)}}c(Ie,"runCli");export{Se as GLOBAL_TOKENS,Je as collectSlashSpecs,Be as defineBranch,Ve as defineLeaf,Me as defineRoot,xe as notJoinedError,$e as parseArgv,me as renderNode,Ie as runCli,ye as takeMachineSelector,be as unknownPathError,he as walk};
@@ -1,3 +1,4 @@
1
+ import { type Cron } from '../canvas/crons.js';
1
2
  import { type CanvasDb } from '../canvas/db.js';
2
3
  import type { OperationId } from '../events/types.js';
3
4
  import type { Level, ListenDelivery } from '../graph/types.js';
@@ -74,6 +75,10 @@ export declare function listenDeliveryTier(delivery: ListenDelivery): {
74
75
  * arms afterwards survives it. A deadline that fires on its own deletes its row first, so finds
75
76
  * nothing here and no notice is queued. */
76
77
  export declare function consumeDeadlineOnWake(nodeId: string): Promise<void>;
78
+ /** A node deadline fell due: in one write, delete its row and queue its body to the anchor as urgent wake mail, which the
79
+ * lifecycle tick delivers by waking the node wherever it runs. No process runs. A row already gone (a wake consumed it, or
80
+ * a re-arm replaced it) delivers nothing. */
81
+ export declare function deliverDueDeadline(cron: Cron): Promise<void>;
77
82
  /** Queue one runtime notice to a node's inbox inside the caller's write transaction (no sender). */
78
83
  export declare function queueNodeNotice(db: CanvasDb, nodeId: string, notice: {
79
84
  body: string;
@@ -1,4 +1,4 @@
1
- var w=Object.defineProperty;var s=(t,e)=>w(t,"name",{value:e,configurable:!0});import{randomBytes as v,randomUUID as b}from"node:crypto";import{join as E}from"node:path";import{cancelCronsOnWake as N}from"../canvas/crons.js";import{withCanvasWrite as c,openDb as I}from"../canvas/db.js";import{getRow as x}from"../canvas/canvas.js";import{messagesDir as h}from"../canvas/paths.js";import{settleDeadControllerWait as k,settleMatchingControllerWait as R}from"../canvas/waits.js";import{generateOperationId as D,operationIdContext as S,validateOperationId as T}from"../events/operation-id.js";import{clipBody as O}from"../../shared/inbox-entry-body.js";function y(){let t;do t=v(16).toString("hex");while(t==="00000000000000000000000000000000");return t}s(y,"newId");function A(t,e){const r=JSON.stringify(t,(d,i)=>typeof i=="string"?i.replace(new RegExp("\\p{Cs}","gu"),"\uFFFD"):i);if(r===void 0)throw new TypeError(`${e} must be JSON-serializable`);return r}s(A,"stringify");async function C(t,e){return e!=="normal"&&e!=="deferred"?e:(await x(t))?.lifecycle==="terminal"?"urgent":e}s(C,"effectiveTier");function L(t,e){return E(h(t),`${e.replace(/[^0-9]/g,"")}-${b().slice(0,6)}.md`)}s(L,"overflowBodyPath");function M(t){if(typeof t!="object"||t===null)return"";const e=t.body;return typeof e=="string"?e.trim():""}s(M,"inlineBody");async function W(t,e){if(e.length===0)return[];const r=e.map(n=>n.messageId??y()),i=Number((await t.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(e.length)).seq)-e.length+1,a=s(n=>e.map((o,u)=>n(o,u)),"col");return await t.prepare(`INSERT INTO messages
1
+ var m=Object.defineProperty;var o=(t,e)=>m(t,"name",{value:e,configurable:!0});import{randomBytes as v,randomUUID as b}from"node:crypto";import{join as E}from"node:path";import{cancelCronsOnWake as N}from"../canvas/crons.js";import{withCanvasWrite as c,openDb as I}from"../canvas/db.js";import{getRow as h}from"../canvas/canvas.js";import{messagesDir as x}from"../canvas/paths.js";import{settleDeadControllerWait as k,settleMatchingControllerWait as R}from"../canvas/waits.js";import{generateOperationId as D,operationIdContext as S,validateOperationId as T}from"../events/operation-id.js";import{clipBody as O}from"../../shared/inbox-entry-body.js";function _(){let t;do t=v(16).toString("hex");while(t==="00000000000000000000000000000000");return t}o(_,"newId");function A(t,e){const r=JSON.stringify(t,(i,d)=>typeof d=="string"?d.replace(new RegExp("\\p{Cs}","gu"),"\uFFFD"):d);if(r===void 0)throw new TypeError(`${e} must be JSON-serializable`);return r}o(A,"stringify");async function L(t,e){return e!=="normal"&&e!=="deferred"?e:(await h(t))?.lifecycle==="terminal"?"urgent":e}o(L,"effectiveTier");function C(t,e){return E(x(t),`${e.replace(/[^0-9]/g,"")}-${b().slice(0,6)}.md`)}o(C,"overflowBodyPath");function M(t){if(typeof t!="object"||t===null)return"";const e=t.body;return typeof e=="string"?e.trim():""}o(M,"inlineBody");async function W(t,e){if(e.length===0)return[];const r=e.map(n=>n.messageId??_()),d=Number((await t.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(e.length)).seq)-e.length+1,a=o(n=>e.map((s,u)=>n(s,u)),"col");return await t.prepare(`INSERT INTO messages
2
2
  (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition,
3
3
  event, object_id, level, actor_id, cause_message_id, depth)
4
4
  SELECT v.message_id, v.seq::bigint, v.operation_id, v.created_at, v.sender_node_id, v.sender_name, v.kind, v.label, v.body_ref, v.body_json::jsonb, v.disposition,
@@ -6,8 +6,8 @@ var w=Object.defineProperty;var s=(t,e)=>w(t,"name",{value:e,configurable:!0});i
6
6
  FROM unnest(?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[],
7
7
  ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[]) WITH ORDINALITY
8
8
  AS v(message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition,
9
- event, object_id, level, actor_id, cause_message_id, depth, n) ORDER BY v.n`).run(r,a((n,o)=>String(i+o)),a(n=>n.operationId),a(n=>n.createdAt),a(n=>n.senderNodeId),a(n=>n.senderName),a(n=>n.kind),a(n=>n.label),a(n=>n.bodyRef),a(n=>n.bodyJson===void 0?null:A(n.bodyJson,"message body")),a(n=>n.disposition),a(n=>n.event?.event??null),a(n=>n.event?.objectId??null),a(n=>n.event===void 0?null:String(n.event.level)),a(n=>n.event?.actorId??null),a(n=>n.causeMessageId??null),a(n=>String(n.depth??0))),r}s(W,"insertMessages");async function _(t,e){return(await W(t,[e]))[0]}s(_,"insertMessage");async function f(t,e,r,d,i,a,n){const o=y();return await t.prepare(`INSERT INTO deliveries
9
+ event, object_id, level, actor_id, cause_message_id, depth, n) ORDER BY v.n`).run(r,a((n,s)=>String(d+s)),a(n=>n.operationId),a(n=>n.createdAt),a(n=>n.senderNodeId),a(n=>n.senderName),a(n=>n.kind),a(n=>n.label),a(n=>n.bodyRef),a(n=>n.bodyJson===void 0?null:A(n.bodyJson,"message body")),a(n=>n.disposition),a(n=>n.event?.event??null),a(n=>n.event?.objectId??null),a(n=>n.event===void 0?null:String(n.event.level)),a(n=>n.event?.actorId??null),a(n=>n.causeMessageId??null),a(n=>String(n.depth??0))),r}o(W,"insertMessages");async function f(t,e){return(await W(t,[e]))[0]}o(f,"insertMessage");async function g(t,e,r,i,d,a,n){const s=_();return await t.prepare(`INSERT INTO deliveries
10
10
  (delivery_id, message_id, destination_id, urgency, wake, state, idempotency_key, created_at, updated_at)
11
- VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`).run(o,e,r,d,i,n??null,a,a),o}s(f,"insertNodeDelivery");function g(t,e){const r=new Date().toISOString(),d=t.operationId===void 0?S.current()??D():T(t.operationId);let i=t.bodyRef??null,a=t.bodyJson;if(i===null&&e!==null&&t.senderNodeId!=="human"){const n=M(a),o=O(n);o.clipped&&(i=L(e,r),a={...a,body:o.text,body_full:n})}return{createdAt:r,operationId:d,bodyRef:i,bodyJson:a}}s(g,"finalizeNodeMail");async function j(t,e){const r=g(e,t);return await c(async d=>{const i=await d.prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(t);if(i?.run_id&&(await d.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(i.run_id))?.deleting_at)throw new Error("run is deleting");if(e.idempotencyKey!==void 0){const l=await d.prepare(`SELECT d.delivery_id, d.message_id, d.urgency, m.created_at
12
- FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE d.idempotency_key = ?`).get(e.idempotencyKey);if(l!==void 0)return{messageId:l.message_id,deliveryId:l.delivery_id,urgency:l.urgency,createdAt:l.created_at}}const a=Date.now(),n=await C(t,e.urgency),o=await _(d,{messageId:e.messageId,operationId:r.operationId,createdAt:r.createdAt,senderNodeId:e.senderNodeId??null,senderName:e.senderName??null,kind:e.kind,label:e.label,bodyRef:r.bodyRef,bodyJson:r.bodyJson,disposition:e.disposition??null}),u=await f(d,o,t,n,e.wake,a,e.idempotencyKey);return await R(t,e.senderNodeId??null,a,d),await e.withinEnqueue?.(d,o),e.wake===1&&n!=="deferred"&&await m(t),{messageId:o,deliveryId:u,urgency:n,createdAt:r.createdAt}})}s(j,"enqueueNodeMail");function z(t){switch(t){case"interrupt":return{urgency:"critical",wake:1};case"steer":return{urgency:"urgent",wake:1};case"after-turn":return{urgency:"normal",wake:1};case"next-turn":return{urgency:"deferred",wake:0}}}s(z,"listenDeliveryTier");async function p(t,e,r){const d={kind:"update",label:r.label??"notice",bodyJson:{body:r.body},urgency:r.tier,wake:r.wake},i=g(d,e),a=Date.now(),n=await _(t,{operationId:i.operationId,createdAt:i.createdAt,senderNodeId:null,senderName:null,kind:d.kind,label:d.label,bodyRef:i.bodyRef,bodyJson:i.bodyJson,disposition:null}),o=await f(t,n,e,r.tier,r.wake,a);return{messageId:n,deliveryId:o,urgency:r.tier,createdAt:i.createdAt}}s(p,"insertNodeNotice");async function m(t){await c(async e=>{for(const r of await N(t))await p(e,t,{body:`Your cron ${r.name}, next scheduled for ${r.fire_at}, was canceled by this wake. Re-create it if you still need it.`,label:"cron canceled",tier:"normal",wake:1})})}s(m,"consumeDeadlineOnWake");async function G(t,e,r){const d=await p(t,e,r);return r.wake===1&&r.tier!=="deferred"&&await m(e),d}s(G,"queueNodeNotice");async function V(t,e=Date.now()){return Number((await(await I()).prepare("UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id = ? AND canceled_at IS NULL").run(e,e,t)).changes)===1}s(V,"cancelDelivery");async function Q(t,e={}){return await c(async r=>{const d=["d.destination_id = ?","d.canceled_at IS NULL","d.state IN ('pending', 'handed_off')"],i=[t];e.senderNodeId!==void 0&&(d.push("m.sender_node_id IS NOT DISTINCT FROM ?"),i.push(e.senderNodeId)),e.kind!==void 0&&(d.push("m.kind = ?"),i.push(e.kind));const a=await r.prepareUncached(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE ${d.join(" AND ")}`).all(...i);if(a.length===0)return[];const n=Date.now();return await r.prepareUncached(`UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id IN (${a.map(()=>"?").join(",")})`).run(n,n,...a.map(o=>o.delivery_id)),a.map(o=>o.delivery_id)})}s(Q,"cancelPendingNodeMail");async function X(t,e){return await c(async r=>{const d=Date.now(),i=await r.prepare(`SELECT target.status AS controller_status FROM waits w LEFT JOIN nodes target ON target.node_id = w.target_id
13
- WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);if(i===void 0||i.controller_status==="active"||i.controller_status==="idle")return null;const a=await j(t,{kind:"urgent",label:"declared controller is no longer live",bodyJson:{body:`Controller ${e} is no longer live; the declared message wait was cleared.`},urgency:"urgent",wake:1});if(!await k(t,e,d,r))throw new Error(`controller wait changed while notifying ${t}`);return a})}s(X,"enqueueControllerDeathNotice");export{V as cancelDelivery,Q as cancelPendingNodeMail,m as consumeDeadlineOnWake,C as effectiveTier,X as enqueueControllerDeathNotice,j as enqueueNodeMail,g as finalizeNodeMail,_ as insertMessage,W as insertMessages,z as listenDeliveryTier,y as newId,G as queueNodeNotice};
11
+ VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`).run(s,e,r,i,d,n??null,a,a),s}o(g,"insertNodeDelivery");function p(t,e){const r=new Date().toISOString(),i=t.operationId===void 0?S.current()??D():T(t.operationId);let d=t.bodyRef??null,a=t.bodyJson;if(d===null&&e!==null&&t.senderNodeId!=="human"){const n=M(a),s=O(n);s.clipped&&(d=C(e,r),a={...a,body:s.text,body_full:n})}return{createdAt:r,operationId:i,bodyRef:d,bodyJson:a}}o(p,"finalizeNodeMail");async function j(t,e){const r=p(e,t);return await c(async i=>{const d=await i.prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(t);if(d?.run_id&&(await i.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(d.run_id))?.deleting_at)throw new Error("run is deleting");if(e.idempotencyKey!==void 0){const l=await i.prepare(`SELECT d.delivery_id, d.message_id, d.urgency, m.created_at
12
+ FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE d.idempotency_key = ?`).get(e.idempotencyKey);if(l!==void 0)return{messageId:l.message_id,deliveryId:l.delivery_id,urgency:l.urgency,createdAt:l.created_at}}const a=Date.now(),n=await L(t,e.urgency),s=await f(i,{messageId:e.messageId,operationId:r.operationId,createdAt:r.createdAt,senderNodeId:e.senderNodeId??null,senderName:e.senderName??null,kind:e.kind,label:e.label,bodyRef:r.bodyRef,bodyJson:r.bodyJson,disposition:e.disposition??null}),u=await g(i,s,t,n,e.wake,a,e.idempotencyKey);return await R(t,e.senderNodeId??null,a,i),await e.withinEnqueue?.(i,s),e.wake===1&&n!=="deferred"&&await w(t),{messageId:s,deliveryId:u,urgency:n,createdAt:r.createdAt}})}o(j,"enqueueNodeMail");function z(t){switch(t){case"interrupt":return{urgency:"critical",wake:1};case"steer":return{urgency:"urgent",wake:1};case"after-turn":return{urgency:"normal",wake:1};case"next-turn":return{urgency:"deferred",wake:0}}}o(z,"listenDeliveryTier");async function y(t,e,r){const i={kind:"update",label:r.label??"notice",bodyJson:{body:r.body},urgency:r.tier,wake:r.wake},d=p(i,e),a=Date.now(),n=await f(t,{operationId:d.operationId,createdAt:d.createdAt,senderNodeId:null,senderName:null,kind:i.kind,label:i.label,bodyRef:d.bodyRef,bodyJson:d.bodyJson,disposition:null}),s=await g(t,n,e,r.tier,r.wake,a);return{messageId:n,deliveryId:s,urgency:r.tier,createdAt:d.createdAt}}o(y,"insertNodeNotice");async function w(t){await c(async e=>{for(const r of await N(t))await y(e,t,{body:`Your cron ${r.name}, next scheduled for ${r.fire_at}, was canceled by this wake. Re-create it if you still need it.`,label:"cron canceled",tier:"normal",wake:1})})}o(w,"consumeDeadlineOnWake");async function G(t){if(t.anchor_node===null||t.deadline_body===null)throw new Error(`cron ${t.cron_id} is not a node deadline`);const e=t.anchor_node,r=t.deadline_body;await c(async i=>{const d=await i.prepare("DELETE FROM crons WHERE cron_id = ? AND state = 'active' AND run_state = 'idle'").run(t.cron_id);Number(d.changes)!==0&&await y(i,e,{body:r,label:"deadline reached",tier:"urgent",wake:1})})}o(G,"deliverDueDeadline");async function V(t,e,r){const i=await y(t,e,r);return r.wake===1&&r.tier!=="deferred"&&await w(e),i}o(V,"queueNodeNotice");async function Q(t,e=Date.now()){return Number((await(await I()).prepare("UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id = ? AND canceled_at IS NULL").run(e,e,t)).changes)===1}o(Q,"cancelDelivery");async function X(t,e={}){return await c(async r=>{const i=["d.destination_id = ?","d.canceled_at IS NULL","d.state IN ('pending', 'handed_off')"],d=[t];e.senderNodeId!==void 0&&(i.push("m.sender_node_id IS NOT DISTINCT FROM ?"),d.push(e.senderNodeId)),e.kind!==void 0&&(i.push("m.kind = ?"),d.push(e.kind));const a=await r.prepareUncached(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE ${i.join(" AND ")}`).all(...d);if(a.length===0)return[];const n=Date.now();return await r.prepareUncached(`UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id IN (${a.map(()=>"?").join(",")})`).run(n,n,...a.map(s=>s.delivery_id)),a.map(s=>s.delivery_id)})}o(X,"cancelPendingNodeMail");async function Z(t,e){return await c(async r=>{const i=Date.now(),d=await r.prepare(`SELECT target.status AS controller_status FROM waits w LEFT JOIN nodes target ON target.node_id = w.target_id
13
+ WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);if(d===void 0||d.controller_status==="active"||d.controller_status==="idle")return null;const a=await j(t,{kind:"urgent",label:"declared controller is no longer live",bodyJson:{body:`Controller ${e} is no longer live; the declared message wait was cleared.`},urgency:"urgent",wake:1});if(!await k(t,e,i,r))throw new Error(`controller wait changed while notifying ${t}`);return a})}o(Z,"enqueueControllerDeathNotice");export{Q as cancelDelivery,X as cancelPendingNodeMail,w as consumeDeadlineOnWake,G as deliverDueDeadline,L as effectiveTier,Z as enqueueControllerDeathNotice,j as enqueueNodeMail,p as finalizeNodeMail,f as insertMessage,W as insertMessages,z as listenDeliveryTier,_ as newId,V as queueNodeNotice};
@@ -1,7 +1,7 @@
1
- var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{getNode as s,fullName as d,isSafeNodeId as k,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as N}from"../wake.js";import{renderKnowledge as v,renderWorkspaceOpen as x}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as _}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as f,contextDirNote as w,orchestratorContextNote as p,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as V}from"../../shared/generated-context.js";async function A(e,r){const n=r!==void 0?r:await s(e);return n===null?"":$(n.cwd,n.profile_id)}a(A,"profileNote");async function E(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const i=await s(o);if(i===null)break;n.unshift(i),o=i.parent??null}return n}a(E,"ancestorTrunk");const F=5;async function j(e){return(await Y(await g(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>l(r.status)-l(n.status))}a(j,"childNodes");async function B(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await E(e,n),o=await j(e);return C(e,n.kind,n.mode,t,o)}a(B,"buildGraphMap");async function R(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&k(n)?await s(n):null,o=t!==null?`${n} ("${d(t)}")`:n??"";return S(e,r?.kind??"general",r?.mode??"base",n,o)}a(R,"buildIdentityAssertion");function T(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(T,"armerPhrase");async function K(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:d(n)}:{},armedAt:e.created,recur:e.recur}}a(K,"cronWakeOrigin");function q(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
1
+ var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{getNode as s,latestExecutionForNode as k,fullName as d,isSafeNodeId as g,subscriptionsOf as N}from"../canvas/index.js";import{cadenceDisplay as v}from"../wake.js";import{renderKnowledge as x,renderWorkspaceOpen as _}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as $}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as f,contextDirNote as w,orchestratorContextNote as p,profileNote as C,renderGraphMap as S,buildIdentityAssertion as E,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as Z}from"../../shared/generated-context.js";async function A(e,r){const n=r!==void 0?r:await s(e);return n===null?"":C(n.cwd,n.profile_id)}a(A,"profileNote");async function j(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const i=await s(o);if(i===null)break;n.unshift(i),o=i.parent??null}return n}a(j,"ancestorTrunk");const K=5;async function B(e){return(await Y(await N(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>l(r.status)-l(n.status))}a(B,"childNodes");async function R(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await j(e,n),o=await B(e);return S(e,n.kind,n.mode,t,o)}a(R,"buildGraphMap");async function T(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&g(n)?await s(n):null,o=t!==null?`${n} ("${d(t)}")`:n??"";return E(e,r?.kind??"general",r?.mode??"base",n,o)}a(T,"buildIdentityAssertion");function D(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(D,"armerPhrase");async function q(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:d(n)}:{},armedAt:e.created,recur:e.recur}}a(q,"cronWakeOrigin");function z(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?v(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
2
  ${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
- </crtr-wake>`;const t=T(e);return`<crtr-wake>
3
+ </crtr-wake>`;const t=D(e);return`<crtr-wake>
4
4
  ${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}a(q,"buildWakeBearings");function D(e){return O(e?.managed_worktree)}a(D,"managedWorktreeNote");async function W(e,r,n){const t=await s(e),o=["<crtr-bearings>",await R(e,t)],i=await B(e,t);i!==""&&o.push("","## Your place in the canvas",i),o.push("","## Your documents and context directory",w(e,t?.grantee));const u=await A(e,t);u!==""&&o.push("",u);const c=D(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await _(e)??"",m=t?.cwd!==void 0?f(t.cwd):"";return[o.join(`
5
+ </crtr-wake>`}a(z,"buildWakeBearings");function W(e){return O(e?.managed_worktree)}a(W,"managedWorktreeNote");async function H(e,r,n){const t=await s(e),o=["<crtr-bearings>",await T(e,t)],i=await R(e,t);i!==""&&o.push("","## Your place in the canvas",i),o.push("","## Your documents and context directory",w(e,t?.grantee));const u=await A(e,t);u!==""&&o.push("",u);const c=W(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await $(e)??"",m=t?.cwd!==void 0&&(await k(e))?.runner==="process"?f(t.cwd):"";return[o.join(`
6
6
  `),r,n,h,m].filter(y=>y!=="").join(`
7
- `)}a(W,"bearingsShell");async function z(e,r){const n=await v(r),t=await x(r);return{content:await W(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}a(z,"buildContextBearings");export{V as CONTEXT_INTRO_CUSTOM_TYPE,z as buildContextBearings,B as buildGraphMap,f as buildProjectContextBlock,q as buildWakeBearings,w as contextDirNote,K as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
7
+ `)}a(H,"bearingsShell");async function J(e,r){const n=await x(r),t=await _(r);return{content:await H(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}a(J,"buildContextBearings");export{Z as CONTEXT_INTRO_CUSTOM_TYPE,J as buildContextBearings,R as buildGraphMap,f as buildProjectContextBlock,z as buildWakeBearings,w as contextDirNote,q as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};