@north-light/cli 0.3.603 → 0.3.605
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/clients/attach/viewer.js +433 -433
- package/dist/commands/api-client.d.ts +4 -0
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/daemon-generation.d.ts +1 -1
- package/dist/commands/daemon-generation.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/core/canvas/canvas.js +20 -20
- package/dist/core/canvas/schema-pg/005-fleet-blobs.sql +1 -1
- package/dist/core/import/export/cloud.d.ts +8 -3
- package/dist/core/import/export/cloud.js +1 -1
- package/dist/core/import/export/files.d.ts +1 -0
- package/dist/core/import/export/files.js +1 -1
- package/dist/core/providers/bundles.js +2 -2
- package/dist/core/runs/operations.js +6 -6
- package/dist/core/runtime/runner/blaxel/runner.d.ts +1 -1
- package/dist/core/runtime/runner/blaxel/runner.js +3 -3
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +3 -0
- package/dist/core/runtime/runner/delete-sandboxes.js +1 -0
- package/dist/core/runtime/runner/machine/executor.d.ts +14 -1
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +3 -3
- package/dist/core/storage/attachments.d.ts +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/api/server.d.ts +1 -2
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/crtrd.js +13 -13
- package/dist/daemon/due.js +4 -4
- package/dist/daemon/reconcilers/recipe-image.d.ts +15 -1
- package/dist/daemon/reconcilers/recipe-image.js +5 -6
- package/dist/daemon/reconcilers/storage-due-work.d.ts +3 -4
- package/dist/daemon/reconcilers/storage-due-work.js +3 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -40,6 +40,10 @@ export declare function readColdStartDiagnostic(): string | undefined;
|
|
|
40
40
|
export declare function remoteTarget(): {
|
|
41
41
|
client(timeoutMs?: number): CrtrClient;
|
|
42
42
|
} | undefined;
|
|
43
|
+
/** True when this process is a node whose `CRTR_API_SOCKET` relay forwards to Northlight's shared control plane rather than to a daemon on this computer:
|
|
44
|
+
* a node on a Mac moved into Northlight (`machine.json`; its machine daemon serves no `/v1`) or a fleet node (`CRTR_API_URL` names the control plane).
|
|
45
|
+
* `remoteTarget()` reports undefined for it because the transport is a local socket. */
|
|
46
|
+
export declare function relayReachesControlPlane(): boolean;
|
|
43
47
|
/** A move whose cloud run reached `done` but whose computer has not switched over: the account holds the records, the local daemon stays drained,
|
|
44
48
|
* and no command may run against either side until `crtr sys signin` finishes it (design D14). The record is deleted only once the machine-role daemon
|
|
45
49
|
* is up (`finishMove`, or that daemon's own start), so a `machine.json` written before a failed restart does not lift this. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).filter(
|
|
1
|
+
var T=Object.defineProperty;var a=(r,t)=>T(r,"name",{value:t,configurable:!0});import{closeSync as N,existsSync as E,fstatSync as A,openSync as O,readFileSync as m,readSync as x}from"node:fs";import{dirname as I,join as l}from"node:path";import{gunzipSync as M}from"node:zlib";import{CrtrClient as p,ApiError as u}from"../api/index.js";import{localClient as f}from"../api/node-transport.js";import{northlightFetch as F,notSignedIn as D,readPersonCredential as P}from"../core/directory/person-credential.js";import{isMoveCommitted as U,moveUnfinishedError as k,readMachineConfig as w}from"../daemon/machine-link/config.js";import{northlightUnreachable as L}from"../core/directory/reach.js";import{apiErrorToCliError as _}from"../core/io.js";import{autostartDisabled as b,daemonAutostartStartupFailure as K,ensureDaemon as B}from"../daemon/manage.js";import{DAEMON_STARTUP_WINDOW_MS as g}from"../daemon/startup-policy.js";import{readState as W}from"../core/config.js";import{resolveRemoteCanvasTarget as j}from"../core/remote-canvas-target.js";import{RemoteCanvasSource as G}from"../core/canvas/remote-canvas-source.js";import{BROKER_RELEASED_MARKER as z,BROKER_RELAY_GENERATION as q,crtrHome as H}from"../core/canvas/paths.js";import{envTestNodeSocketWindowMs as Y,isSandboxedNode as $,providerProjectionOverBrokerRelay as J}from"../shared/env.js";import{CrtrError as C,ownerOnly as V}from"../core/errors.js";import{ExitCode as v}from"../types.js";function d(r){return{...r,fault:r.fault??null}}a(d,"withRowFault");function X(r,t){throw r instanceof u?_(r,t):r}a(X,"rethrowAsCliError");async function Nt(r){try{return await S().getNode(r)}catch(t){if(t instanceof u&&t.status===404)return null;X(t)}}a(Nt,"getNodeOrNull");const Q="crtr_run_",Z=4096,tt=20;function et(){let r;try{r=O(l(H(),"crtrd.log"),"r");const{size:t}=A(r),e=Math.max(0,t-Z),s=t-e;if(s<=0)return;const n=Buffer.alloc(s);x(r,n,0,s,e);const o=n.toString("utf8").split(`
|
|
2
|
+
`).filter(c=>c.trim()!=="").slice(-tt).join(`
|
|
3
3
|
`).trim();return o===""?void 0:`crtrd.log (tail):
|
|
4
|
-
${o}`}catch{return}finally{if(r!==void 0)try{
|
|
4
|
+
${o}`}catch{return}finally{if(r!==void 0)try{N(r)}catch{}}}a(et,"readColdStartDiagnostic");function nt(){if(process.env.CRTR_API_SOCKET)return;const r=process.env.CRTR_API_TOKEN,t=process.env.CRTR_API_URL;if(r!==void 0&&r.startsWith(Q)&&t)return{client:a(i=>new p({baseUrl:t,headers:{authorization:`Bearer ${r}`},...i!==void 0?{timeoutMs:i}:{}}),"client")};const e=w();if(e===void 0)return;if(P()===void 0)throw D("this computer is imported into Northlight, so crtr needs your sign-in");const s=F(e.directoryUrl,e.apiUrl),n=a((i,o)=>s(i,o).catch(c=>{throw c instanceof C?y(c):c}),"authed");return{client:a(i=>st(new p({baseUrl:e.apiUrl,fetch:n,...i!==void 0?{timeoutMs:i}:{}}),e.apiUrl),"client")}}a(nt,"remoteTarget");function rt(){return!!process.env.CRTR_API_SOCKET&&(w()!==void 0||J())}a(rt,"relayReachesControlPlane");function st(r,t){return new Proxy(r,{get(e,s){const n=Reflect.get(e,s,e);return typeof n!="function"?n:(...i)=>{const o=n.apply(e,i);return o instanceof Promise?o.catch(c=>{throw c instanceof u&&c.code==="request_timeout"?y(L(c,t)):c}):o}}})}a(st,"unreachableOnTimeout");function y(r){const t=typeof r.details?.next=="string"?r.details.next:void 0;return new u(r.exitCode===v.NETWORK?503:401,r.code,r.message,{error:r.code,message:r.message,...t===void 0?{}:{next:t}})}a(y,"asApiError");function it(){return U()?k():void 0}a(it,"moveUnfinished");function S(r){if(r?.local!==!0){const s=it();if(s!==void 0)throw s}if(r?.local===!0&&rt())throw new C("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",v.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});const t=r?.local===!0?void 0:nt();if(t!==void 0)return t.client(r?.timeoutMs);const e=process.env.CRTR_API_SOCKET;if(e){const s=a(()=>{if(!E(e))try{const i=I(e),o=m(l(i,z),"utf8"),c=m(l(i,q),"utf8");if(o===c&&o!=="")return new u(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},"availabilityFailure"),n=s();if(n!==void 0)throw _(n,"Run the command from the node's own turn instead.");return f({autostart:!1,availabilityFailure:s,coldStartPollWindowMs:(b()?Y():void 0)??g,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}})}return b()?f({autostart:!1,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}}):f({...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},onColdSocket:a(async()=>{B()},"onColdSocket"),coldStartDiagnostic:et,coldStartFailure:K,coldStartPollWindowMs:g})}a(S,"cliClient");const ot=2e3;class R{static{a(this,"ApiCanvasSource")}client;rosterCache=null;rosterInFlight=null;constructor(t=S()){this.client=t}async roster(){const t=Date.now();return this.rosterCache!==null&&t-this.rosterCache.at<ot?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(e=>{const s={snapshot:e,subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i={node_id:n.to_id,active:n.active,created:n.created},o={node_id:n.from_id,active:n.active,created:n.created},c=s.subscriptions.get(n.from_id);c===void 0?s.subscriptions.set(n.from_id,[i]):c.push(i);const h=s.subscribers.get(n.to_id);h===void 0?s.subscribers.set(n.to_id,[o]):h.push(o)}return this.rosterCache={at:Date.now(),index:s},s}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(t){try{return await t()}catch(e){if(e instanceof u&&e.status===404)return null;throw e}}async getNode(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async getRow(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async listNodes(t){const e=t?.status,s=t?.under===void 0?{}:{under:t.under,under_inclusive:!0};let n;if(Array.isArray(e)){const i=new Set(e);n=(await this.client.listNodes(s)).filter(c=>i.has(c.status))}else n=await this.client.listNodes({...e!==void 0?{status:e}:{},...s});return n.map(i=>d(i))}async browseSnapshot(){const t=await this.client.canvasBrowseCompressed(),e=JSON.parse(M(t).toString("utf8")),s={subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i=s.subscriptions.get(n.from_id)??[];i.push({node_id:n.to_id,active:n.active,created:n.created}),s.subscriptions.set(n.from_id,i);const o=s.subscribers.get(n.to_id)??[];o.push({node_id:n.from_id,active:n.active,created:n.created}),s.subscribers.set(n.to_id,o)}return this.rosterCache={at:Date.now(),index:s},e.nodes.map(n=>d(n))}async panelRoster(){const t=await this.roster();return t.snapshot!==void 0?t.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(t){return this.roster().then(e=>e.subscriptions.get(t)??[])}async subscribersOf(t){return this.roster().then(e=>e.subscribers.get(t)??[])}async view(t){const e=new Set([t]),s=[],n=(await this.subscriptionsOf(t)).map(i=>i.node_id);for(;n.length>0;){const i=n.shift();if(!e.has(i)){e.add(i),s.push(i);for(const o of await this.subscriptionsOf(i))e.has(o.node_id)||n.push(o.node_id)}}return s}async ticketCountsForNodes(t){return(await this.client.attentionCounts([...t])).counts}async ticketCountsForView(t){return this.ticketCountsForNodes([t,...await this.view(t)])}async newestReport(t){return(await this.client.getReports(t,{limit:1}))[0]??null}async hasActiveLiveSubscription(t){const e=(await this.subscriptionsOf(t)).filter(s=>s.active);for(const s of e){const n=await this.getRow(s.node_id);if(n&&(n.status==="active"||n.status==="idle"))return!0}return!1}}function Et(r,t=$()){const e=r?.scope??"user";if(t){if(r?.canvasName!==void 0)throw V("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new R}const s=r?.canvasName??W(e).activeCanvas??null;if(!s)return new R;const{previewEndpoint:n,relayToken:i}=j(s,e);return new G(n,i)}a(Et,"cliCanvasSource");export{R as ApiCanvasSource,Z as COLD_START_DIAGNOSTIC_TAIL_BYTES,Et as cliCanvasSource,S as cliClient,Nt as getNodeOrNull,it as moveUnfinished,et as readColdStartDiagnostic,rt as relayReachesControlPlane,nt as remoteTarget,X as rethrowAsCliError};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/** Refuse, naming both generations, when this CLI runs from an installed generation and the live local daemon runs another, or predates reporting one. Remote targets and source checkouts are not compared: a CLI with no generation is skipped, and so is a daemon that reports `generation_id: null`. */
|
|
1
|
+
/** Refuse, naming both generations, when this CLI runs from an installed generation and the live local daemon runs another, or predates reporting one. Remote targets (including a node's relay to the shared control plane, whose generation is not this computer's) and source checkouts are not compared: a CLI with no generation is skipped, and so is a daemon that reports `generation_id: null`. */
|
|
2
2
|
export declare function assertLocalDaemonMatchesCli(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var
|
|
1
|
+
var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});import{cliClient as s,moveUnfinished as d,relayReachesControlPlane as m,remoteTarget as c}from"./api-client.js";import{CrtrError as u}from"../core/errors.js";import{ExitCode as l}from"../types.js";import{processGeneration as f,readPackageVersion as i}from"./sys/shared.js";async function w(){const e=f();if(e===null)return;const t=d();if(t!==void 0)throw t;if(c()!==void 0||m())return;const n=await s().status();if(n.generation_id===null||n.generation_id===e.id)return;const r=n.generation_id;throw new u("daemon_generation_mismatch",`this crtr is generation ${e.id} (${i()}), but the running crtrd is ${r===void 0?"too old to report its generation":`generation ${r}`} (${n.runtime_version})`,l.NETWORK,{cli_generation:e.id,cli_version:i(),daemon_generation:r??null,daemon_version:n.runtime_version,next:"Run `crtr sys daemon restart` to move the daemon onto this generation."})}o(w,"assertLocalDaemonMatchesCli");export{w as assertLocalDaemonMatchesCli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=Object.defineProperty;var o=(t,e)=>w(t,"name",{value:e,configurable:!0});import{defineLeaf as u,defineBranch as f}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as g}from"../../core/wake.js";import{DaemonNotPreparedError as y,probeDaemonHealth as p,probeErrorMessage as b,spawnDaemon as h,stopDaemonProcess as v,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as l,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{localClient as c}from"../../api/node-transport.js";import{defineSysBranch as q}from"./branch.js";import{selectedGeneration as x}from"./shared.js";const I=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."},{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.","Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async t=>{try{return await h({targetPhase:t.prepare===!0?"prepared":"ready",ignoreJoinLock:t.force===!0})}catch(e){throw e instanceof y?new d({error:"daemon_not_prepared",message:e.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):e}},"run")}),D=100;async function S(t,e){const a=Date.now(),r=a+e;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<r;){try{const n=await p(Math.min(1e3,Math.max(1,r-Date.now())));if(s=n.startup_phase,i=n.startup_blocked??`daemon is ${n.startup_phase}`,n.startup_phase==="blocked")throw new d({error:"startup_blocked",message:n.startup_blocked??"daemon startup is blocked",received:n.startup_phase,field:"phase",next:"Repair the reported blocker paths with `crtr sys migrate`, then retry the await."});if(n.startup_phase===t)return{startup_phase:t,waited_ms:Date.now()-a};if(t==="prepared"&&n.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:n.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(n){if(n instanceof d)throw n;i=n instanceof Error?n.message:String(n)}await new Promise(n=>setTimeout(n,Math.min(D,Math.max(0,r-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${t} within ${e}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(S,"awaitDaemonPhase");const E=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async t=>{const e=t.timeout,a=g(e);if(a===null||a<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${e}`,received:e,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return S(t.phase,a)},"run")}),R=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async t=>await c({autostart:!1}).admitDaemon(),"run")});async function P(){try{return(await c({autostart:!1}).status()).generation_id??void 0}catch{return}}o(P,"servingGenerationId");const A=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async t=>{const e=l();if(!(e!==null&&m(e)))return{running:!1};try{const r=await p(),s=await P(),i=x().generation?.id;return{running:!0,serving:r.ok,pid:e,...r.startup_phase===void 0?{}:{startup_phase:r.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(r){return{running:!0,serving:!1,pid:e,probe_error:b(r)}}},"run")}),j=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async t=>{if(!k()){const e=await h();return{restarted:!1,started:e.started,...e.pid!==void 0?{pid:e.pid}:{},...e.existing_pid!==void 0?{pid:e.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}try{const e=await T({local:!0}).restartDaemon();return{restarted:e.accepted,pid:e.predecessor_pid,grace_ms:e.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(e){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${e.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),U=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async t=>{const e=l(),a=e!==null&&m(e);try{let r=!1;a&&(r=await v(e)==="killed");const s=_(null);return!a&&s.length===0?{stopped:!1}:{stopped:!0,...a?{pid:e}:{},...s.length>0?{strays_killed:s}:{},...r?{force_killed:!0}:{}}}catch(r){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${a?` pid ${e}`:""}: ${r.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),L=f({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[I,E,R,j,A,U]});function W(){return q([L])}o(W,"registerDaemonControlSys");export{L as daemonBranch,W as registerDaemonControlSys};
|
|
1
|
+
var w=Object.defineProperty;var o=(n,e)=>w(n,"name",{value:e,configurable:!0});import{defineLeaf as u,defineBranch as f}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as g}from"../../core/wake.js";import{DaemonNotPreparedError as y,probeDaemonHealth as p,probeErrorMessage as b,spawnDaemon as h,stopDaemonProcess as v,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as l,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{localClient as c}from"../../api/node-transport.js";import{defineSysBranch as q}from"./branch.js";import{selectedGeneration as x}from"./shared.js";const I=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."},{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.","Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async n=>{try{return await h({targetPhase:n.prepare===!0?"prepared":"ready",ignoreJoinLock:n.force===!0})}catch(e){throw e instanceof y?new d({error:"daemon_not_prepared",message:e.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):e}},"run")}),D=100;async function S(n,e){const t=Date.now(),a=t+e;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<a;){try{const r=await p(Math.min(1e3,Math.max(1,a-Date.now())));if(s=r.startup_phase,i=r.startup_blocked??`daemon is ${r.startup_phase}`,r.startup_phase==="blocked")throw new d({error:"startup_blocked",message:r.startup_blocked??"daemon startup is blocked",received:r.startup_phase,field:"phase",next:"Repair the reported blocker paths with `crtr sys migrate`, then retry the await."});if(r.startup_phase===n)return{startup_phase:n,waited_ms:Date.now()-t};if(n==="prepared"&&r.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:r.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(r){if(r instanceof d)throw r;i=r instanceof Error?r.message:String(r)}await new Promise(r=>setTimeout(r,Math.min(D,Math.max(0,a-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${e}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(S,"awaitDaemonPhase");const E=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async n=>{const e=n.timeout,t=g(e);if(t===null||t<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${e}`,received:e,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return S(n.phase,t)},"run")}),R=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async n=>await c({autostart:!1}).admitDaemon(),"run")});async function P(){try{return(await c({autostart:!1}).status()).generation_id??void 0}catch{return}}o(P,"servingGenerationId");const A=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async n=>{const e=l();if(!(e!==null&&m(e)))return{running:!1};try{const a=await p(),s=await P(),i=x().generation?.id;return{running:!0,serving:a.ok,pid:e,...a.startup_phase===void 0?{}:{startup_phase:a.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(a){return{running:!0,serving:!1,pid:e,probe_error:b(a)}}},"run")}),j=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async n=>{const e=T({local:!0});if(!k()){const t=await h();return{restarted:!1,started:t.started,...t.pid!==void 0?{pid:t.pid}:{},...t.existing_pid!==void 0?{pid:t.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}try{const t=await e.restartDaemon();return{restarted:t.accepted,pid:t.predecessor_pid,grace_ms:t.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(t){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${t.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),U=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async n=>{const e=l(),t=e!==null&&m(e);try{let a=!1;t&&(a=await v(e)==="killed");const s=_(null);return!t&&s.length===0?{stopped:!1}:{stopped:!0,...t?{pid:e}:{},...s.length>0?{strays_killed:s}:{},...a?{force_killed:!0}:{}}}catch(a){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${t?` pid ${e}`:""}: ${a.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),L=f({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[I,E,R,j,A,U]});function W(){return q([L])}o(W,"registerDaemonControlSys");export{L as daemonBranch,W as registerDaemonControlSys};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var oe=Object.defineProperty;var o=(e,n)=>oe(e,"name",{value:n,configurable:!0});import{envNodeId as b}from"../../shared/env.js";import{lstatSync as re,realpathSync as C,rmdirSync as se,rmSync as de,statSync as ue}from"node:fs";import{basename as le,dirname as H,isAbsolute as ce,join as S,relative as _e,resolve as pe,sep as fe}from"node:path";import{removeTreeBeneath as M}from"../spaces/open-beneath.js";import{emitEvent as Ee}from"../events/emit.js";import{withCanvasWrite as p,openDb as s}from"./db.js";import{conversationStore as we,ConversationNotFoundError as ye}from"../conversation-store/index.js";import{hasUnseenWakeMail as me,UNSEEN_WAKE_MAIL_SQL as Ne}from"./deliveries.js";import{isAppRun as P}from"./app-run.js";import{registerOutcomeAction as $}from"./outcome-actions.js";import{publish as Re}from"../graph/events.js";import{nodeObject as Se}from"../graph/objects.js";import{findNodeBySessionFileSql as Oe}from"./sessions.js";import{hydrateFault as he}from"./recovery.js";import{hasUnreconciledWorktree as Te,openWorktree as Le,readWorktree as De,worktreeFromRow as ge}from"./worktrees.js";import{isPidAlive as Ae,isPidPresent as q,recordedPidLiveness as ve}from"./pid.js";import{ensureHome as ke,jobDir as Ue,nodeDir as xe,nodeRunDir as B}from"./paths.js";import{appForNode as je,ensureNodeDirs as Ie,nodeAgentDir as We}from"./node-agent-paths.js";import{appSpace as L}from"../layout.js";import{createObject as Fe,getById as D,ownerForGrantee as be,setObjectKind as Ce,setObjectName as He}from"../graph/objects.js";import{profileObject as Me}from"../graph/reader.js";import{writeActsFor as z}from"../permissions/facts.js";import{CrtrError as Pe}from"../errors.js";import{deleteNodeWithOwned as $e}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as qe,SUBTREE_IDS_SQL as Be}from"./tree.js";import{filterAsync as m,mapAsync as O}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}o(E,"jsonValue");async function gn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}o(gn,"assertRunNotDeleting");async function J(e,n,t){try{return await Me(e,n,t)}catch(a){if(a instanceof Pe&&a.code==="not_found")return null;throw a}}o(J,"profileObjectFor");async function ze(e,n){const t=await be(n,e.grantee??"app:terminal"),a=e.profile_id?await J(n,e.profile_id,t):null;await Fe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await z(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}o(ze,"seedRow");function Y(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return he(Object.fromEntries(n))}o(Y,"faultFrom");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,usage_json:e.usage_json??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=q(n.pi_pid),a=Y(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=e.turn_open_at!==null&&e.turn_closed_at===null&&t,n}o(f,"rowFrom");async function g(e,n){return n??=await De(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}o(g,"metaFrom");async function An(e,n={}){return ke(),await p(async t=>{await ze(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await Le(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await $(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Ie(e.node_id),await h(e.node_id)}o(An,"createNode");async function h(e){const n=await(await s()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await g(n)}o(h,"getNode");async function vn(e){if(e.length===0)return[];const n=v.map(i=>`w.${i} AS worktree_${i}`).join(", "),t=await(await s()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(i=>[i.node_id,i]));return await O(e.map(i=>a.get(i)).filter(i=>i!==void 0),async i=>await g(i,V(i)))}o(vn,"getNodes");const Je=1440*60*1e3;function Q(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}o(Q,"createRequestRecord");async function kn(e){const n=await(await s()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:Q(n)}o(kn,"findCreateRequest");async function Un(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Je);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Q(a)})}o(Un,"reserveCreateRequest");async function xn(e=Date.now()){return Number((await(await s()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}o(xn,"pruneExpiredCreateRequests");async function jn(e,n){await(await s()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}o(jn,"recordCreateRequestNode");async function In(e,n){const t=await s();return await t.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(n,e),(await t.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}o(In,"reserveCreateRequestNode");async function Wn(e,n){await(await s()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}o(Wn,"completeCreateRequest");async function Fn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}o(Fn,"abandonCreateRequest");function bn(e){return pe(e)}o(bn,"canonicalSessionFile");async function Cn(e){const n=await Oe(e);return n===null?null:await h(n)}o(Cn,"findNodeBySessionFile");async function Hn(e){const n=await(await s()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}o(Hn,"getRow");async function Mn(e){const n=await(await s()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}o(Mn,"getRowByPane");async function Pn(e){return(await(await s()).prepare(`SELECT * FROM node_rows
|
|
1
|
+
var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0});import{envNodeId as C}from"../../shared/env.js";import{lstatSync as de,realpathSync as H,rmdirSync as ue,rmSync as ce,statSync as le}from"node:fs";import{basename as _e,dirname as M,isAbsolute as pe,join as S,relative as fe,resolve as Ee,sep as we}from"node:path";import{removeTreeBeneath as P}from"../spaces/open-beneath.js";import{emitEvent as ye}from"../events/emit.js";import{deleteNodeSandboxes as $}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as me,ConversationNotFoundError as Ne}from"../conversation-store/index.js";import{hasUnseenWakeMail as Re,UNSEEN_WAKE_MAIL_SQL as Se}from"./deliveries.js";import{isAppRun as q}from"./app-run.js";import{registerOutcomeAction as B}from"./outcome-actions.js";import{publish as he}from"../graph/events.js";import{nodeObject as Oe}from"../graph/objects.js";import{findNodeBySessionFileSql as Te}from"./sessions.js";import{hydrateFault as Le}from"./recovery.js";import{hasUnreconciledWorktree as De,openWorktree as ge,readWorktree as Ae,worktreeFromRow as ve}from"./worktrees.js";import{isPidAlive as ke,isPidPresent as z,recordedPidLiveness as Ue}from"./pid.js";import{ensureHome as xe,jobDir as je,nodeDir as We,nodeRunDir as J}from"./paths.js";import{appForNode as be,ensureNodeDirs as Ie,nodeAgentDir as Fe}from"./node-agent-paths.js";import{appSpace as L}from"../layout.js";import{createObject as Ce,getById as D,ownerForGrantee as He,setObjectKind as Me,setObjectName as Pe}from"../graph/objects.js";import{profileObject as $e}from"../graph/reader.js";import{writeActsFor as Y}from"../permissions/facts.js";import{CrtrError as qe}from"../errors.js";import{deleteNodeWithOwned as Be}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as ze,SUBTREE_IDS_SQL as Je}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function kn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(kn,"assertRunNotDeleting");async function Q(e,n,t){try{return await $e(e,n,t)}catch(a){if(a instanceof qe&&a.code==="not_found")return null;throw a}}i(Q,"profileObjectFor");async function Ye(e,n){const t=await He(n,e.grantee??"app:terminal"),a=e.profile_id?await Q(n,e.profile_id,t):null;await Ce(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Y(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Ye,"seedRow");function V(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return Le(Object.fromEntries(n))}i(V,"faultFrom");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,usage_json:e.usage_json??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=z(n.pi_pid),a=V(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=e.turn_open_at!==null&&e.turn_closed_at===null&&t,n}i(f,"rowFrom");async function g(e,n){return n??=await Ae(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(g,"metaFrom");async function Un(e,n={}){return xe(),await p(async t=>{await Ye(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await ge(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await B(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Ie(e.node_id),await O(e.node_id)}i(Un,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await g(n)}i(O,"getNode");async function xn(e){if(e.length===0)return[];const n=v.map(o=>`w.${o} AS worktree_${o}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(o=>[o.node_id,o]));return await h(e.map(o=>a.get(o)).filter(o=>o!==void 0),async o=>await g(o,G(o)))}i(xn,"getNodes");const Qe=1440*60*1e3;function K(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(K,"createRequestRecord");async function jn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:K(n)}i(jn,"findCreateRequest");async function Wn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Qe);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return K(a)})}i(Wn,"reserveCreateRequest");async function bn(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(bn,"pruneExpiredCreateRequests");async function In(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(In,"recordCreateRequestNode");async function Fn(e,n){const t=await d();return await t.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(n,e),(await t.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Fn,"reserveCreateRequestNode");async function Cn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Cn,"completeCreateRequest");async function Hn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Hn,"abandonCreateRequest");function Mn(e){return Ee(e)}i(Mn,"canonicalSessionFile");async function Pn(e){const n=await Te(e);return n===null?null:await O(n)}i(Pn,"findNodeBySessionFile");async function $n(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i($n,"getRow");async function qn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(qn,"getRowByPane");async function Bn(e){return(await(await d()).prepare(`SELECT * FROM node_rows
|
|
2
2
|
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL
|
|
3
3
|
AND deadline_at <= ? AND status IN ('active','idle') AND kind != 'human'
|
|
4
|
-
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}
|
|
5
|
-
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),
|
|
4
|
+
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(Bn,"dueNodeDeadlines");async function zn(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(zn,"setNodeDeadline");async function Jn(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
|
|
5
|
+
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let r=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(r+=Number((await o.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return r})}i(Jn,"shiftProfileNodeDeadlines");function A(e,n){if(e==null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="bigint"||e instanceof Uint8Array)return e;throw new TypeError(`${n} must be a SQLite scalar`)}i(A,"sqlInput");async function Yn(e,n){const t=[],a=i((r,s=r)=>{Object.prototype.hasOwnProperty.call(n,r)&&t.push([s,A(n[r],r)])},"add");if(a("description"),a("title"),a("icon"),a("cycles"),a("mode"),a("lifecycle"),a("cwd"),a("host_kind"),a("profile_id"),a("parent"),a("spawned_by"),a("creator"),a("fork_from"),a("fork_source_file"),a("model_override"),Object.prototype.hasOwnProperty.call(n,"passive_default")&&t.push(["passive_default",n.passive_default===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"cycle_pending")&&t.push(["cycle_pending",n.cycle_pending===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"persona_ack")&&t.push(["persona_ack_json",E(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",E(n.review_binding,"review_binding")]),Object.prototype.hasOwnProperty.call(n,"isolated"))throw new TypeError("isolated cannot change after node creation");Object.prototype.hasOwnProperty.call(n,"scopes")&&t.push(["scopes_json",E(n.scopes,"scopes")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",E(n.launch,"launch")]);const o=i(r=>Object.prototype.hasOwnProperty.call(n,r),"has");return await p(async r=>{const s=await D(r,e);if(s===null||s.type!=="node")throw new Error(`unknown node: ${e}`);if(o("name")&&await Pe(r,s,A(n.name,"name")),o("kind")&&await Me(r,s,A(n.kind,"kind")),t.length===0)return;if(o("profile_id")){const u=await r.prepare("SELECT app FROM nodes WHERE node_id = ?").get(e),_=u?.app?await D(r,u.app):null;if(_){const w=n.profile_id?await Q(r,n.profile_id,_):null;await r.prepare("UPDATE objects SET owner = ? WHERE id = ?").run((w??_).id,e);const N=(await r.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(e)).sub;w===null&&N&&await Y(r,e,N)}}if((await r.prepareUncached(`UPDATE nodes SET ${t.map(([u])=>`${u} = ?`).join(", ")} WHERE node_id = ?`).run(...t.map(([,u])=>u),e)).changes!==1)throw new Error(`unknown node: ${e}`)}),await O(e)}i(Yn,"updateNode");async function Qn(e,n){await(await d()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}i(Qn,"setStatus");async function Vn(e,n){await(await d()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}i(Vn,"setIntent");async function Kn(e,n,t={}){if(t.outcome===void 0){const o=[],r=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),r.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),r.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),r.push(n.terminal_reason??null));const s=["node_id = ?"];r.push(e),t.fromStatuses!==void 0&&(s.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),r.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&s.push("final_report IS NULL");const c=await(await d()).prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${s.join(" AND ")}`).run(...r);return Number(c.changes)}const a=t.outcome;return await p(async o=>{const r=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(r.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(r.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(r.push("terminal_reason = ?"),s.push(n.terminal_reason??null));const c=i((N,R)=>a.supersede===!0?"?":`CASE WHEN outcome_at IS NULL THEN ? ELSE ${R} END`,"outcomeValue");r.push(`outcome_kind = ${c(a.kind,"outcome_kind")}`,`outcome_reason = ${c(a.reason,"outcome_reason")}`,`outcome_detail_json = ${c(a.detailJson,"outcome_detail_json")}`,`outcome_revision = ${a.supersede===!0?"outcome_revision + 1":"CASE WHEN outcome_at IS NULL THEN outcome_revision + 1 ELSE outcome_revision END"}`,`outcome_at = ${c(a.at,"outcome_at")}`),s.push(a.kind,a.reason,a.detailJson,a.at);const u=["node_id = ?"];s.push(e),t.fromStatuses!==void 0&&(u.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),s.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&u.push("final_report IS NULL");const _=await o.prepareUncached(`UPDATE nodes SET ${r.join(", ")} WHERE ${u.join(" AND ")}`).run(...s);if(Number(_.changes)===0)return 0;const w=await o.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(a.supersede===!0||w.outcome_at===a.at)&&a.documentJson!==null&&a.documentJson!==void 0&&await he(o,{event:"outcome",object:await Oe(o,e),actor:null,attrs:{revision:Number((await o.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}i(Kn,"transitionStatusIntent");async function Gn(e){return(await(await d()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}i(Gn,"getFinalReport");async function Xn(e,n){return(await(await d()).prepare("UPDATE nodes SET final_report = NULL, finalized_at = NULL WHERE node_id = ? AND final_report = ?").run(e,n)).changes>0}i(Xn,"clearFinalReportIfMatches");async function Zn(e,n){await(await d()).prepare('UPDATE nodes SET tmux_session = ?, "window" = ?, pane = ? WHERE node_id = ?').run(n.tmux_session??null,n.window??null,n.pane??null,e)}i(Zn,"setPresence");async function et(e,n){await(await d()).prepare("UPDATE nodes SET launched_at = ?, frozen_at = NULL, respawn_not_before = NULL WHERE node_id = ?").run(n,e)}i(et,"recordLaunch");async function nt(e,n){await(await d()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}i(nt,"recordSettledTurn");async function tt(e,n){await(await d()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}i(tt,"setFrozen");async function at(e){await(await d()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}i(at,"clearFrozen");async function it(e,n){await(await d()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}i(it,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",v=["state","cleanup_state","path","branch","repo_root","base_ref","base_sha","created_at","closed_at","next_attempt_at","attempts","quarantined","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json","abandoned_json","land_intent_json","disposal_json"];function G(e){return e.worktree_state===null?null:ve(Object.fromEntries(v.map(n=>[n,e[`worktree_${n}`]])))}i(G,"worktreeFromProjection");async function ot(e){const n=v.map(a=>`w.${a} AS worktree_${a}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.profile_id = ? ORDER BY n.created`).all(e);return await h(t,async a=>await g(a,G(a)))}i(ot,"listNodesByProfile");async function rt(){return(await(await d()).prepare(`SELECT
|
|
6
6
|
node_id, name, description, kind, mode, lifecycle, status, cwd, profile_id,
|
|
7
7
|
grantee, parent, created, frozen_at, terminal_reason, final_report,
|
|
8
8
|
telemetry_tokens_in, telemetry_updated_at, pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -10,13 +10,13 @@ var oe=Object.defineProperty;var o=(e,n)=>oe(e,"name",{value:n,configurable:!0})
|
|
|
10
10
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
11
11
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
12
12
|
fault_provider_error_json
|
|
13
|
-
FROM node_rows WHERE ${
|
|
13
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(rt,"browseNodes");async function st(e,n){await(await d()).prepare(`UPDATE nodes
|
|
14
14
|
SET telemetry_tokens_in = ?,
|
|
15
15
|
telemetry_context_tokens = COALESCE(?, telemetry_context_tokens),
|
|
16
16
|
telemetry_last_activity = COALESCE(?, telemetry_last_activity),
|
|
17
17
|
telemetry_updated_at = ?
|
|
18
18
|
WHERE node_id = ?
|
|
19
|
-
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}
|
|
19
|
+
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}i(st,"updateNodeTelemetry");async function dt(){return(await(await d()).prepare(`SELECT
|
|
20
20
|
node_id, name, description, cycles, kind, status, frozen_at,
|
|
21
21
|
telemetry_context_tokens, telemetry_last_activity,
|
|
22
22
|
pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -24,14 +24,14 @@ var oe=Object.defineProperty;var o=(e,n)=>oe(e,"name",{value:n,configurable:!0})
|
|
|
24
24
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
25
25
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
26
26
|
fault_provider_error_json
|
|
27
|
-
FROM node_rows WHERE ${
|
|
27
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=z(t),o=V(n);return{node_id:n.node_id,name:n.name,description:n.description??null,cycles:n.cycles??null,kind:n.kind,status:n.status,frozen_at:n.frozen_at??null,pi_pid:t,telemetry_context_tokens:n.telemetry_context_tokens??null,telemetry_last_activity:n.telemetry_last_activity??null,fault:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:n.turn_open_at!==null&&n.turn_closed_at===null&&a}})}i(dt,"graphNodes");async function Ve(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${ze}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${Je})`),t.push(e.under,e.under))),e?.lifecycle!==void 0&&(n.push("lifecycle = ?"),t.push(e.lifecycle)),e?.kind!==void 0&&(n.push("kind = ?"),t.push(e.kind)),e?.mode!==void 0&&(n.push("mode = ?"),t.push(e.mode)),e?.profileId!==void 0&&(n.push("profile_id = ?"),t.push(e.profileId)),e?.profilePrefix!==void 0&&(n.push("profile_id LIKE ? ESCAPE '\\'"),t.push(`${e.profilePrefix.replace(/[\\%_]/g,o=>`\\${o}`)}%`)),e?.parent!==void 0&&(n.push("parent = ?"),t.push(e.parent)),e?.topLevel===!0&&n.push("parent IS NULL"),e?.hanging===!0&&n.push("parent IS NOT NULL AND parent NOT IN (SELECT node_id FROM node_rows)"),e?.status!==void 0){const o=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${o.map(()=>"?").join(",")})`),t.push(...o)}return e?.withRecordedPid===!0&&n.push("pi_pid IS NOT NULL"),e?.withRecordedPidOrFrozen===!0&&n.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),(await(await d()).prepareUncached(`SELECT * FROM node_rows WHERE ${n.join(" AND ")} ORDER BY created`).all(...t)).map(f)}i(Ve,"listNodes");const Ke=`SELECT
|
|
28
28
|
node_id, created, launched_at, last_settled_at, finalized_at,
|
|
29
29
|
outcome_at, last_activity_at, pane, "window", tmux_session
|
|
30
30
|
FROM nodes
|
|
31
|
-
WHERE ${
|
|
31
|
+
WHERE ${m}
|
|
32
32
|
AND status IN ('done', 'canceled', 'dead')
|
|
33
33
|
AND (pane IS NOT NULL OR "window" IS NOT NULL OR tmux_session IS NOT NULL)
|
|
34
|
-
ORDER BY created`;async function
|
|
34
|
+
ORDER BY created`;async function ut(){return await(await d()).prepare(Ke).all()}i(ut,"listTerminalPlacementResidue");const Ge=`WITH candidates AS MATERIALIZED (
|
|
35
35
|
SELECT node_id FROM nodes WHERE status IN ('active', 'idle')
|
|
36
36
|
UNION
|
|
37
37
|
SELECT node_id FROM nodes
|
|
@@ -45,23 +45,23 @@ var oe=Object.defineProperty;var o=(e,n)=>oe(e,"name",{value:n,configurable:!0})
|
|
|
45
45
|
AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
46
46
|
AND v.kind != 'human'
|
|
47
47
|
AND (v.status IN ('active', 'idle') OR (v.status IN ('done', 'canceled', 'dead') AND (v.pi_pid IS NOT NULL OR v.frozen_at IS NOT NULL)))
|
|
48
|
-
ORDER BY v.created`;async function
|
|
49
|
-
WHERE ${
|
|
50
|
-
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${
|
|
51
|
-
ORDER BY v.created`).all()).map(f)}
|
|
48
|
+
ORDER BY v.created`;async function ct(){return(await(await d()).prepare(Ge).all()).map(f)}i(ct,"listNodesForSupervision");const X=i(e=>`(${e}.status = 'done' AND ${e}.intent = 'parked' AND ${e}.lifecycle = 'resident' AND ${e}.final_report IS NULL AND ${e}.deleting_at IS NULL)`,"PARKED_RESIDENT_SQL"),Xe=i(e=>`(${e}.status IN ('active', 'idle') OR ${X(e)} OR (${e}.status IN ('done', 'canceled', 'dead') AND ${e}.frozen_at IS NOT NULL AND ${e}.final_report IS NULL))`,"RESUMABLE_NODE_SQL");async function lt(e){return await(await d()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${Xe("nodes")} AND node_id != ?`).all(e)}i(lt,"resumableNodeCwds");async function _t(){return(await(await d()).prepare(`SELECT v.* FROM node_rows v
|
|
49
|
+
WHERE ${X("v")}
|
|
50
|
+
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${Se("d")}) AND v.kind != 'human' AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
51
|
+
ORDER BY v.created`).all()).map(f)}i(_t,"listParkedResidentsWithWakeMail");async function pt(e,n){await(await d()).prepare("INSERT INTO warm_pool (node_id, recipe_key, created) VALUES (?, ?, ?) ON CONFLICT (node_id) DO UPDATE SET recipe_key = excluded.recipe_key, created = excluded.created").run(e,n,new Date().toISOString())}i(pt,"registerWarmSpare");async function ft(e){return(await(await d()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}i(ft,"unregisterWarmSpare");async function k(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
|
|
52
52
|
n.status AS status, n.pi_pid AS pi_pid, n.pi_pid_identity AS pi_pid_identity
|
|
53
|
-
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(
|
|
54
|
-
FROM node_rows WHERE ${
|
|
53
|
+
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(k,"warmSpareRowsFor");async function Et(){return await k(await d())}i(Et,"listWarmSpares");async function wt(e){return await(await d()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}i(wt,"isWarmSpare");function Z(e){return e.status!=="active"&&e.status!=="idle"?!1:Ue(e.pi_pid,e.pi_pid_identity)==="alive"}i(Z,"spareIsClaimable");async function yt(e,n,t={}){return await p(async a=>{const o=(await k(a,e)).find(Z);return o===void 0||t.requestKey!==void 0&&(await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'warm_claimed' WHERE request_key = ? AND node_id IS NULL").run(o.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(o.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,o.node_id),t.outcomeDelivery!==void 0&&await B(a,o.node_id,t.outcomeDelivery),o.node_id)})}i(yt,"claimWarmSpare");async function mt(e){return(await k(await d(),e)).filter(Z).length}i(mt,"warmSpareCount");async function Nt(e){return(await(await d()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}i(Nt,"childrenOf");async function Rt(){return(await(await d()).prepareUncached(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created, description
|
|
54
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(Rt,"rosterNodes");async function St(e){return(await(await d()).prepareUncached(`SELECT * FROM node_rows
|
|
55
55
|
WHERE parent IS NULL AND kind != 'human'
|
|
56
56
|
AND status IN ('active','idle') AND cwd = ?
|
|
57
|
-
AND ${
|
|
58
|
-
ORDER BY created DESC`).all(e)).map(f)}
|
|
59
|
-
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:
|
|
57
|
+
AND ${m}
|
|
58
|
+
ORDER BY created DESC`).all(e)).map(f)}i(St,"listResumableRoots");export*from"./tree.js";async function ht(e,n,t){return await p(async a=>{const o=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ? FOR UPDATE").get(e);return o===void 0?{kind:"missing"}:n(o)?{kind:"terminal",status:o.status,final_report:o.final_report}:{kind:"ran",result:await t()}})}i(ht,"withFreshTerminalGuard");async function T(e){return await De(e)}i(T,"hasUnreconciledManagedWorktree");async function ee(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||await T(e.node_id)||e.node_id===C()||q(e)?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}i(ee,"isCollectible");async function U(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),t=await(await d()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${n}) AND s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ORDER BY s.created_at, s.seq`).all(...e);return[...new Map(t.map(a=>[a.session_id,{id:a.session_id,path:a.transcript_path,dir:S(L(a.grantee).conversations,a.node_id)}])).values()]}i(U,"nodeConversationIds");async function x(e){const n=await d(),t=n.prepare("SELECT 1 FROM sessions WHERE session_id = ? LIMIT 1"),a=n.prepare(`SELECT 1 FROM nodes n WHERE n.fork_source_file LIKE '%\\_' || ? || '.jsonl' ESCAPE '\\'
|
|
59
|
+
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:o,path:r,dir:s}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&de(r,{throwIfNoEntry:!1})!==void 0){if(!Ze(s,r)){console.error(`[canvas] not deleting transcript outside its node's conversations directory: ${r}`);continue}try{await me().delete(o,r)}catch(c){if(!(c instanceof Ne))throw c}}}i(x,"deleteNodeConversations");function Ze(e,n){try{const t=fe(H(e),S(H(M(n)),_e(n)));return t!==""&&t!==".."&&!t.startsWith(`..${we}`)&&!pe(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}i(Ze,"isBeneath");async function j(e,n){const t=await D(e,n);return t===null||t.deleted_at!==null?!1:(await Be(e,t),!0)}i(j,"deleteNodeObject");async function W(e){return{nodeId:e,app:await O(e)===null?null:await be(e)}}i(W,"nodeFiles");async function ne({nodeId:e,app:n}){n!==null&&P(L(n).nodes,await Fe(e,n)),P(M(J(e)),J(e))}i(ne,"removeNodeAppTrees");function te({nodeId:e}){return[We(e)]}i(te,"nodeOwnedDirs");function ae({nodeId:e,app:n}){if(n!==null)try{ue(S(L(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}i(ae,"removeNodeConversationDir");async function b(e){await ne(e);for(const n of te(e))ce(n,{recursive:!0,force:!0});ae(e)}i(b,"removeNodeFiles");async function ie(e){const n=await $(e);if(n.length>0)throw new Error(`the sandbox of node(s) ${n.join(", ")} could not be deleted; the node rows are kept`)}i(ie,"requireSandboxesDeleted");async function Ot(e){if(await T(e))return{deleted:!1};await ie([e]);const n=await W(e),t=await U([e]),a=await p(async o=>(await j(o,e),{deleted:!0}));return await x(t),await b(n),a}i(Ot,"deleteNode");async function Tt(e){const n=[...new Set(e)];if(n.length===0)return[];const t=await y(n,T);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);await ie(n);const a=await h(n,W),o=await U(n),r=n.map(()=>"?").join(","),s=(await(await d()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${r}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),c=await y(s,async u=>await p(async _=>await j(_,u)));await x(o);for(const u of c){const _=a[n.indexOf(u)];await F(_,async()=>await b(_))}return c}i(Tt,"deleteNodes");async function Lt(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,o=new Date(a).toISOString(),r=C()??"",s=await d(),c=i(l=>re(l)<a,"quiet"),u=i(l=>({node_id:l.node_id,status:l.status,created:l.created}),"toPruned"),_=await en(),w=(await y((await s.prepare(`SELECT * FROM node_rows
|
|
60
60
|
WHERE status IN ('dead', 'done', 'canceled') AND created < ?
|
|
61
|
-
ORDER BY created`).all(
|
|
61
|
+
ORDER BY created`).all(o)).map(f),async l=>await ee(l,{pastTtl:!0})&&c(l)&&!_.has(l.node_id)&&!await e.held(l.node_id))).map(u),N=t?(await y((await s.prepare(`SELECT * FROM node_rows
|
|
62
62
|
WHERE status IN ('active', 'idle') AND created < ?
|
|
63
|
-
ORDER BY created`).all(
|
|
63
|
+
ORDER BY created`).all(o)).map(f),async l=>l.node_id!==r&&!ke(l.pi_pid??null)&&(l.frozen_at??null)===null&&(l.respawn_not_before??null)===null&&l.intent!=="idle-release"&&!q(l)&&!await Re(l.node_id)&&!await T(l.node_id)&&c(l)&&!await e.held(l.node_id))).map(u):[],R=await I([...w,...N]);return n||R.length===0?{pruned:R,dryRun:n}:{pruned:await oe(R,e.removeDirs),dryRun:n}}i(Lt,"pruneNodes");async function en(){const e=await(await d()).prepare(`SELECT DISTINCT d.owner AS owner FROM watches w
|
|
64
64
|
JOIN objects d ON d.id = w.object AND d.type = 'document' AND d.deleted_at IS NULL
|
|
65
65
|
JOIN objects o ON o.id = w.watcher AND o.deleted_at IS NULL
|
|
66
66
|
LEFT JOIN nodes n ON n.node_id = w.watcher
|
|
67
|
-
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}
|
|
67
|
+
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}i(en,"ownersOfWatchedDocuments");async function I(e){const t=(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ?"),a=new Set(e.map(o=>o.node_id));return await y(e,async o=>(await t.all(o.node_id,o.node_id)).every(r=>a.has(r.node_id)))}i(I,"retainRunRootsWithMembers");async function oe(e,n){const t=new Set(await $(e.map(s=>s.node_id))),a=t.size===0?e:await I(e.filter(s=>!t.has(s.node_id)));if(a.length===0)return[];const o=await h(a,async s=>await W(s.node_id)),r=await U(a.map(s=>s.node_id));for(const s of a)await p(async c=>await j(c,s.node_id));if(await x(r),n!==void 0){for(const s of o)await F(s,async()=>{await ne(s),ae(s)});return n(o.flatMap(te)),a}for(const s of o)await F(s,async()=>await b(s));return a}i(oe,"deletePrunedNodes");async function F(e,n){try{await n()}catch(t){ye({level:"error",event:"canvas.node_files.remove_failed",error:t,fields:{node_id:e.nodeId}})}}i(F,"eachNodeBestEffort");function re(e){let n=0;for(const t of[e.created,e.launched_at,e.last_settled_at,e.finalized_at,e.outcome_at,e.last_activity_at]){if(t==null)continue;const a=Date.parse(t);Number.isFinite(a)&&a>n&&(n=a)}try{const t=le(S(je(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}i(re,"lastActivityMs");async function Dt(e){const n=e.dryRun??!1,t=await Ve(),a=await y(t,async u=>await ee(u)&&!await e.held(u.node_id)),o=t.length-a.length,r=Math.max(0,e.maxNodes-o),s=a.map(u=>({row:u,recency:re(u)})).sort((u,_)=>_.recency-u.recency).slice(r).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created})),c=await I(s);return n||c.length===0?{pruned:c,dryRun:n}:{pruned:await oe(c),dryRun:n}}i(Dt,"pruneToLimit");export{X as PARKED_RESIDENT_SQL,Xe as RESUMABLE_NODE_SQL,Hn as abandonCreateRequest,kn as assertRunNotDeleting,rt as browseNodes,Mn as canonicalSessionFile,Nt as childrenOf,yt as claimWarmSpare,Xn as clearFinalReportIfMatches,at as clearFrozen,Cn as completeCreateRequest,Un as createNode,Ot as deleteNode,Tt as deleteNodes,Bn as dueNodeDeadlines,jn as findCreateRequest,Pn as findNodeBySessionFile,Gn as getFinalReport,O as getNode,xn as getNodes,$n as getRow,qn as getRowByPane,dt as graphNodes,ee as isCollectible,wt as isWarmSpare,re as lastActivityMs,Ve as listNodes,ot as listNodesByProfile,ct as listNodesForSupervision,_t as listParkedResidentsWithWakeMail,St as listResumableRoots,ut as listTerminalPlacementResidue,Et as listWarmSpares,W as nodeFiles,Ge as nodesForSupervisionSql,bn as pruneExpiredCreateRequests,Lt as pruneNodes,Dt as pruneToLimit,In as recordCreateRequestNode,et as recordLaunch,it as recordRespawnAttempt,nt as recordSettledTurn,pt as registerWarmSpare,b as removeNodeFiles,Wn as reserveCreateRequest,Fn as reserveCreateRequestNode,lt as resumableNodeCwds,Rt as rosterNodes,tt as setFrozen,Vn as setIntent,zn as setNodeDeadline,Zn as setPresence,Qn as setStatus,Jn as shiftProfileNodeDeadlines,Ke as terminalPlacementResidueSql,Kn as transitionStatusIntent,ft as unregisterWarmSpare,Yn as updateNode,st as updateNodeTelemetry,mt as warmSpareCount,ht as withFreshTerminalGuard};
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
-- Null for a use recorded before this release, and for any use whose bytes the storage service still holds.
|
|
8
8
|
ALTER TABLE upload_uses ADD COLUMN IF NOT EXISTS blob_key text;
|
|
9
9
|
|
|
10
|
-
-- D100: the node blob-deletion pass in `storage-due-work` claims node rows
|
|
10
|
+
-- D100: the node blob-deletion pass in `storage-due-work` claims deleted node rows. Partial, so it
|
|
11
11
|
-- holds only the soft-deleted node rows, not every object. A plain CREATE INDEX (the chain runs each step in a transaction, so not
|
|
12
12
|
-- CONCURRENTLY): it blocks writes to `objects` for the time it takes to scan the table.
|
|
13
13
|
CREATE INDEX IF NOT EXISTS objects_node_deleted ON objects(deleted_at) WHERE type = 'node';
|
|
@@ -5,8 +5,9 @@ export declare const STORE_ORDER: readonly ImportStoreNameDTO[];
|
|
|
5
5
|
export declare class ImportCloud {
|
|
6
6
|
private readonly apiUrl;
|
|
7
7
|
private readonly token;
|
|
8
|
+
private readonly retryBaseMs;
|
|
8
9
|
/** `token` is a fixed import token, or a getter for a person bearer (5-minute tokens, so a long import asks per call). */
|
|
9
|
-
constructor(apiUrl: string, token: string | (() => Promise<string>));
|
|
10
|
+
constructor(apiUrl: string, token: string | (() => Promise<string>), retryBaseMs?: number);
|
|
10
11
|
private call;
|
|
11
12
|
start(request: ImportStartRequest): Promise<ImportStartedDTO>;
|
|
12
13
|
uploadUrls(run: string, keys: string[]): Promise<ImportUploadUrlsDTO>;
|
|
@@ -18,6 +19,10 @@ export declare class ImportCloud {
|
|
|
18
19
|
environment_id: string;
|
|
19
20
|
credential: string;
|
|
20
21
|
}>;
|
|
21
|
-
/**
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* PUT bytes to a signed URL, retrying what is transient: a failed, dropped or stalled connection (socket closed or reset, no progress within the attempt's deadline)
|
|
24
|
+
* and a 408, 429 or 5xx answer, with doubling backoff, up to `PUT_ATTEMPTS` tries. A 403 is a signed URL that has expired (or been refused): when `freshUrl`
|
|
25
|
+
* is given the URL is replaced by one from `uploadUrls`, once. Any other answer, or running out of tries, throws naming `key`.
|
|
26
|
+
*/
|
|
27
|
+
put(url: string, data: Buffer, key: string, freshUrl?: () => Promise<string>): Promise<void>;
|
|
23
28
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var d=(p,t)=>f(p,"name",{value:t,configurable:!0});import{general as u}from"../../errors.js";const g="stores.json",y=["auth","credentials","env","settings","plugins"],$=8,m=15e3,T=6e4;class O{static{d(this,"ImportCloud")}apiUrl;token;retryBaseMs;constructor(t,e,r=500){this.apiUrl=t,this.token=e,this.retryBaseMs=r}async call(t,e,r){const o=await fetch(new URL(e,this.apiUrl),{method:t,headers:{authorization:`Bearer ${typeof this.token=="string"?this.token:await this.token()}`,...r===void 0?{}:{"content-type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)}}),n=await o.text();if(!o.ok){let a;try{a=JSON.parse(n).error?.code}catch{a=void 0}throw u(`${t} ${e} answered ${o.status}: ${n.slice(0,500)}`,{status:o.status,...typeof a=="string"?{code:a}:{}})}return n===""?void 0:JSON.parse(n)}start(t){return this.call("POST","/v1/imports",t)}uploadUrls(t,e){return this.call("POST",`/v1/imports/${t}/upload-urls`,{keys:e})}putStore(t,e,r){return this.call("PUT",`/v1/imports/${t}/stores/${e}`,r)}load(t){return this.call("POST",`/v1/imports/${t}/load`,{})}get(t){return this.call("GET",`/v1/imports/${t}`)}machineCredential(t,e=!1){return this.call("POST",`/v1/imports/${t}/machine-credential${e?"?rotate=1":""}`,{})}async put(t,e,r,o){let n=!1;for(let a=1;;a+=1){let c,l;try{const s=await fetch(t,{method:"PUT",body:e,signal:AbortSignal.timeout(T+Math.ceil(e.length/50))});if(s.ok){await s.arrayBuffer();return}const i=s.status;let h="";try{h=(await s.text()).slice(0,300)}catch{}if(c=`answered ${i}: ${h}`,i===403&&o!==void 0&&!n){n=!0,t=await o();continue}l=i===408||i===429||i>=500}catch(s){const i=s.cause;c=`failed: ${s instanceof Error?s.message:String(s)}${typeof i?.code=="string"?` (${i.code})`:""}`,l=!0}if(!l)throw u(`upload of ${r} ${c}`,{key:r});if(a>=$)throw u(`upload of ${r} ${c} after ${a} tries`,{key:r});await new Promise(s=>setTimeout(s,Math.min(this.retryBaseMs*2**(a-1),m)*(.5+Math.random()/2)))}}}export{O as ImportCloud,g as STORE_FILE,y as STORE_ORDER};
|
|
@@ -17,6 +17,7 @@ export declare class Uploader {
|
|
|
17
17
|
constructor(cloud: ImportCloud, run: string, progress: (line: string) => void);
|
|
18
18
|
/** Upload source blobs, each to `imports/<run>/blobs/<its key>`: the upload route signs only under the run's own prefix, and the lane moves each blob to its key. */
|
|
19
19
|
upload(objects: readonly LocalObject[]): Promise<void>;
|
|
20
|
+
private freshUrl;
|
|
20
21
|
/** Upload bytes held in memory (row files, source.json, node archives). */
|
|
21
22
|
uploadBytes(key: string, data: Buffer): Promise<void>;
|
|
22
23
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});import{readFileSync as j,readdirSync as M,statSync as R}from"node:fs";import{basename as z,join as m,relative as N,sep as S}from"node:path";import{runtimeRoot as x}from"../../layout.js";import{bundleKeys as U}from"../bundle/layout.js";import{runBlobKey as k}from"../bundle/blob-keys.js";function w(i,e,t=i){let n;try{n=M(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(const o of n){const u=m(i,o.name);o.isDirectory()?w(u,e,t):o.isFile()&&!o.name.endsWith(".tmp")&&!o.name.includes(".tmp-")&&e(u,N(t,u).split(S).join("/"))}}a(w,"walk");function W(){const i=x(),e=[];w(m(i,"blobs"),(t,n)=>e.push({key:n,path:t}));for(const t of["requests","reviews"])w(m(i,t),(n,o)=>{const[u,...c]=o.split("/");c.length>0&&e.push({key:U.request(u,c.join("/")),path:n})});return e}a(W,"localObjects");function _(i,e,t){return t===null||!t.startsWith("/")||t.startsWith(e.endsWith("/")?e:`${e}/`)?null:{key:U.request(i,`source/${z(t)}`),path:t}}a(_,"reviewSourceObject");const d=100,L=128,T=128*1024*1024;class Y{static{a(this,"Uploader")}cloud;run;progress;sent=new Map;uploaded=0;missing=[];constructor(e,t,n){this.cloud=e,this.run=t,this.progress=n}async upload(e){const t=[];for(const r of e){let s;try{s=R(r.path)}catch(h){if(h.code==="ENOENT"){this.missing.push(r.path);continue}throw h}const l=`${s.size}:${s.mtimeMs}`;this.sent.get(r.key)!==l&&t.push({...r,stamp:l,size:s.size})}const n=new Map,o=a(r=>{let s=n.get(r);return s===void 0&&(s=this.cloud.uploadUrls(this.run,t.slice(r*d,(r+1)*d).map(l=>k(this.run,l.key))).then(l=>l.urls),s.catch(()=>{}),n.set(r,s)),s},"urlsFor");let u=0,c=!1,p=0,f=[];const y=a(()=>{const r=f;f=[];for(const s of r)s()},"wake"),E=a(async()=>{try{for(;!c&&u<t.length;){const r=u++,s=t[r],l=Math.floor(r/d);n.delete(l-1),(l+1)*d<t.length&&o(l+1);const h=k(this.run,s.key),g=(await o(l))[h];if(g===void 0)throw new Error(`no upload URL returned for ${s.key}`);for(;!c&&p>0&&p+s.size>T;)await new Promise(O=>f.push(O));if(c)return;p+=s.size;try{await this.cloud.put(g,j(s.path),h,()=>this.freshUrl(h))}finally{p-=s.size,y()}this.sent.set(s.key,s.stamp),this.uploaded+=1,this.uploaded%d===0&&this.progress(`uploaded ${this.uploaded}`)}}catch(r){throw c=!0,y(),r}},"worker"),$=await Promise.allSettled(Array.from({length:Math.min(L,t.length)},E));for(const r of $)if(r.status==="rejected")throw r.reason;t.length>0&&this.progress(`uploaded ${t.length}/${t.length}`)}async freshUrl(e){const t=(await this.cloud.uploadUrls(this.run,[e])).urls[e];if(t===void 0)throw new Error(`no upload URL returned for ${e}`);return t}async uploadBytes(e,t){await this.cloud.put(await this.freshUrl(e),t,e,()=>this.freshUrl(e))}}export{Y as Uploader,W as localObjects,_ as reviewSourceObject};
|