@north-light/cli 0.3.708 → 0.3.710
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/crons.d.ts +3 -0
- package/dist/clients/attach/chrome/inbox-strip.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/chrome/status-line.d.ts +1 -1
- package/dist/clients/attach/chrome/status-line.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +4 -0
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/overlays/graph.d.ts +3 -2
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/render/chat-view.d.ts +2 -0
- package/dist/clients/attach/render/chat-view.js +1 -1
- package/dist/clients/attach/render/doc-links.d.ts +1 -1
- package/dist/clients/attach/session/chrome-refresh.js +1 -1
- package/dist/clients/attach/session/connection.d.ts +10 -9
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/context.d.ts +1 -1
- package/dist/clients/attach/session/document-links.d.ts +1 -1
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/session/identity.d.ts +2 -0
- package/dist/clients/attach/session/identity.js +1 -1
- package/dist/clients/attach/session/input-wiring.d.ts +2 -0
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/layout-record.d.ts +13 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/pane-tag.d.ts +3 -1
- package/dist/clients/attach/session/pane-tag.js +1 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +4 -2
- package/dist/clients/attach/session/teardown.js +9 -7
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +2 -0
- package/dist/clients/attach/viewer.d.ts +7 -5
- package/dist/clients/attach/viewer.js +563 -558
- package/dist/commands/node/wait.js +2 -6
- package/dist/core/broker-client/client.d.ts +6 -3
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/crons.d.ts +11 -1
- package/dist/core/canvas/crons.js +14 -14
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
- package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command.js +5 -5
- package/dist/core/feed/messages.d.ts +5 -0
- package/dist/core/feed/messages.js +5 -5
- package/dist/core/runtime/bearings.js +4 -4
- package/dist/core/runtime/boot-root.js +4 -4
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
- package/dist/core/runtime/runner/blaxel/client.js +1 -1
- package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
- package/dist/core/runtime/runner/blaxel/runner.js +3 -3
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
- package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/types.d.ts +19 -3
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/bridge.d.ts +5 -0
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/handlers/crons.d.ts +2 -0
- package/dist/daemon/api/handlers/crons.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/ended.d.ts +3 -0
- package/dist/daemon/cron/ended.js +2 -2
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/cron/machine-fire.d.ts +9 -2
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/cron/passes.js +1 -1
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
- package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
- package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +3 -1
- package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
- package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
- package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
- package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
- package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +9 -4
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +111 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +86 -31
- package/packages/crouter-api/dist/commands/node/wait.js +2 -10
- package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
- package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
- package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/command.js +3 -0
- package/packages/crouter-api/dist/core/feed/messages.js +15 -0
- package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
- package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
- package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/core/runtime/starting-screen.d.ts +0 -12
- package/dist/core/runtime/starting-screen.js +0 -9
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
var p=Object.defineProperty;var
|
|
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")}),
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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(
|
|
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
|
|
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)
|
|
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,
|
|
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
|
|
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,
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Find only terminal nodes with an unreconciled, explicitly disposable worktree. A node that ever ran in a Blaxel sandbox
|
|
2
|
-
* is never a candidate: its sandbox is its worktree and the control plane has no checkout to sweep (D102).
|
|
3
|
-
*
|
|
2
|
+
* is never a candidate: its sandbox is its worktree and the control plane has no checkout to sweep (D102). A node whose profile
|
|
3
|
+
* points at an imported Mac is a candidate only while that Mac's link is live: its checkout is swept on the Mac.
|
|
4
4
|
* Keep due-time parsing in JS: Date.parse accepts more than SQLite's date
|
|
5
5
|
* functions, and malformed dates are due rather than permanently skipped. */
|
|
6
6
|
export declare function managedWorktreeSweepCandidates(now: number): Promise<string[]>;
|
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
var d=Object.defineProperty;var s=(t,o)=>d(t,"name",{value:o,configurable:!0});import{openDb as
|
|
1
|
+
var d=Object.defineProperty;var s=(t,o)=>d(t,"name",{value:o,configurable:!0});import{openDb as i}from"./db.js";async function l(t){const o=await(await i()).prepare(`
|
|
2
2
|
SELECT w.node_id, w.sweep_observed_json, w.next_attempt_at,
|
|
3
3
|
w.abandoned_json, w.land_intent_json, w.disposal_json
|
|
4
4
|
FROM worktrees w
|
|
5
5
|
JOIN nodes n ON n.node_id = w.node_id
|
|
6
6
|
WHERE n.status IN ('done', 'dead', 'canceled')
|
|
7
7
|
AND n.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
8
|
-
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.runner
|
|
8
|
+
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.runner = 'blaxel')
|
|
9
|
+
AND NOT EXISTS (SELECT 1 FROM profiles p JOIN environments env ON env.object = p.environment_id AND env.kind = 'machine'
|
|
10
|
+
WHERE p.id = n.profile_id AND NOT EXISTS (SELECT 1 FROM machine_links l WHERE l.environment = env.object AND l.lease_expires_at > ?))
|
|
9
11
|
AND w.state IN ('open', 'closed')
|
|
10
12
|
AND (w.state = 'open' OR w.cleanup_state IS NULL OR w.cleanup_state != 'complete')
|
|
11
13
|
AND (w.state = 'closed' OR (n.status = 'done' AND n.final_report IS NOT NULL))
|
|
12
14
|
ORDER BY n.created
|
|
13
|
-
`).all(),a=[];for(const e of o){try{for(const n of[e.sweep_observed_json,e.abandoned_json,e.land_intent_json,e.disposal_json])n!==null&&JSON.parse(n)}catch{continue}if(e.sweep_observed_json!==null&&e.next_attempt_at!==null){const n=Date.parse(e.next_attempt_at);if(!Number.isNaN(n)&&n>t)continue}a.push(e.node_id)}return a}s(
|
|
15
|
+
`).all(new Date(t).toISOString()),a=[];for(const e of o){try{for(const n of[e.sweep_observed_json,e.abandoned_json,e.land_intent_json,e.disposal_json])n!==null&&JSON.parse(n)}catch{continue}if(e.sweep_observed_json!==null&&e.next_attempt_at!==null){const n=Date.parse(e.next_attempt_at);if(!Number.isNaN(n)&&n>t)continue}a.push(e.node_id)}return a}s(l,"managedWorktreeSweepCandidates");export{l as managedWorktreeSweepCandidates};
|
|
@@ -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;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
-- 028-machine-calls-worktree-sweep.sql — `machine_calls.op` accepts `worktree.sweep`: the control plane's sweep asks a Mac to remove a finished node's
|
|
2
|
+
-- managed checkout and branch. The CHECK only widens, as 023 did, so `schema_min_reader` is not touched and the previous release (version 27) still opens the result.
|
|
3
|
+
ALTER TABLE machine_calls DROP CONSTRAINT IF EXISTS machine_calls_op_check;
|
|
4
|
+
ALTER TABLE machine_calls ADD CONSTRAINT machine_calls_op_check
|
|
5
|
+
CHECK (op IN ('start', 'wake', 'stop', 'status', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
|
|
6
|
+
'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'worktree.sweep', 'repo.identify'));
|
|
@@ -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 =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 28;
|
|
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=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=28;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};
|
package/dist/core/command.js
CHANGED
|
@@ -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
|
|
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="${
|
|
4
|
-
${
|
|
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
|
|
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
|
|
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
|
|
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,
|
|
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(
|
|
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
|
|
13
|
-
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);if(
|
|
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};
|