@north-light/cli 0.3.729 → 0.3.731
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/errors.d.ts +5 -0
- package/dist/api/errors.js +1 -1
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/history.d.ts +1 -1
- package/dist/core/canvas/history.js +8 -8
- package/dist/core/canvas/schema-pg/033-node-sandbox-deleted.sql +3 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/conversation-store/row-store.js +13 -13
- package/dist/core/environment-starter-script.d.ts +1 -1
- package/dist/core/environment-starter-script.js +4 -1
- package/dist/core/model-auth/activations.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +14 -3
- package/dist/core/runtime/runner/delete-sandboxes.js +11 -3
- package/dist/daemon/api/bridge.js +2 -2
- package/dist/daemon/api/handlers/canvas.js +1 -1
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/errors.js +11 -0
- package/packages/crouter-api/dist/core/canvas/executions.js +1 -0
- package/packages/crouter-api/dist/core/canvas/history.js +3 -3
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -2
- package/packages/crouter-api/dist/core/environment-starter-script.js +4 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +4 -1
- package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +55 -7
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
package/dist/api/errors.d.ts
CHANGED
|
@@ -43,6 +43,11 @@ export { APIError as ApiError };
|
|
|
43
43
|
/** A local API transport failure has stable status/code identity, independent
|
|
44
44
|
* of message prose. */
|
|
45
45
|
export declare function isDaemonTransportApiError(error: unknown): error is APIError;
|
|
46
|
+
/** A daemon answer that says nothing about the caller's data: the daemon was unreachable, starting, draining for a
|
|
47
|
+
* restart (503 `startup_blocked`), overloaded, or failed server-side. Retrying the same request later can succeed, so a
|
|
48
|
+
* long-lived caller (a broker's inbox poll) retries it rather than treating it as corrupt state. A 4xx other than
|
|
49
|
+
* 408/429 is about the request itself and is not transient. */
|
|
50
|
+
export declare function isTransientDaemonApiError(error: unknown): error is APIError;
|
|
46
51
|
/** The daemon refused the caller's node token. A teardown revokes the broker's token before its process stops, so a broker
|
|
47
52
|
* that sees this on a poll is being shut down, not hitting a corrupt state. */
|
|
48
53
|
export declare function isTokenRevokedApiError(error: unknown): error is APIError;
|
package/dist/api/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var r=(t,e)=>d(t,"name",{value:e,configurable:!0});class a extends Error{static{r(this,"APIError")}status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,i,n,o,u,s){super(n),this.name="APIError",this.status=e,this.code=i,this.headers=new Headers(u),o!==void 0&&(this.details=o),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}}function c(t){return t instanceof a?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||t.code==="runtime_starting"||t.code==="northlight_unreachable")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}r(c,"isDaemonTransportApiError");function h(t){if(!(t instanceof a))return!1;const{status:e,code:i,retryable:n}=t;return c(t)||n===!0||i==="startup_blocked"||e===408||e===429||e>=500}r(h,"isTransientDaemonApiError");function p(t){return t instanceof a&&t.status===401}r(p,"isTokenRevokedApiError");function _(t){if(typeof t!="object"||t===null)return!1;const e=t.error;if(typeof e!="object"||e===null)return!1;const{code:i,message:n}=e;return typeof i=="string"&&typeof n=="string"}r(_,"isErrorBody");export{a as APIError,a as ApiError,c as isDaemonTransportApiError,_ as isErrorBody,p as isTokenRevokedApiError,h as isTransientDaemonApiError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as P}from"./pid.js";import{existsSync as U,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&U(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!P(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function T(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(T,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",L="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await T(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(L,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===L}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await T(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,T as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
|
|
1
|
+
var D=Object.defineProperty;var a=(e,t)=>D(e,"name",{value:t,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as U}from"./pid.js";import{existsSync as P,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i),await n.prepare("UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL").run(e);const p=g(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&P(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!U(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function L(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(L,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",T="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await L(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===T}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await L(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,L as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
|
|
@@ -95,7 +95,7 @@ export interface ResolvedRef {
|
|
|
95
95
|
/** Rendered body. */
|
|
96
96
|
body: string;
|
|
97
97
|
/** The verbatim record (session bytes or jsonl line); null for an inbox entry. */
|
|
98
|
-
raw: string | null;
|
|
98
|
+
raw: (() => Promise<string | null>) | null;
|
|
99
99
|
path: string | null;
|
|
100
100
|
}
|
|
101
101
|
/** Resolve a `<node-id>:inbox/<n>`, `<node-id>:session` or
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var S=Object.defineProperty;var
|
|
1
|
+
var S=Object.defineProperty;var a=(n,s)=>S(n,"name",{value:s,configurable:!0});import{envNodeId as M}from"../../shared/env.js";import{getNode as p,listNodes as j,view as v}from"./canvas.js";import{openDb as E}from"./db.js";import{readTextIfExists as O}from"../fs-utils.js";import{conversationIdFromPath as y,conversationStore as g,ConversationNotFoundError as I}from"../conversation-store/index.js";import{reportBodyByName as C}from"../feed/reports.js";import{readStamps as A}from"../runtime/stamp/protocol.js";import{forEachAsync as B}from"../async-array.js";const nn=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],en=["user","assistant","toolResult"];async function R(){const n=M();if(n!==void 0&&n!==""){const s=await p(n);if(s!==null)return s.cwd}return process.cwd()}a(R,"callerCwd");function x(n){const s=Date.parse(n);return Number.isNaN(s)?0:s}a(x,"toMs");async function k(n){return(await(await E()).prepare(`SELECT m.created_at, m.sender_node_id, d.urgency, m.kind, m.label, m.body_ref, m.body_json
|
|
2
2
|
FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
3
3
|
WHERE d.destination_id = ? AND d.wake = 1
|
|
4
|
-
ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}
|
|
5
|
-
`),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,c=n.ref!==null?o?typeof r=="string"?r:O(n.ref)??"":await C(n.ref)??"":i,u=c!==""&&c!==n.label,
|
|
4
|
+
ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}a(k,"allInboxEntries");async function _(n){const s=[`from: ${n.from??"system"}`,`tier: ${n.tier}`].join(`
|
|
5
|
+
`),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,c=n.ref!==null?o?typeof r=="string"?r:O(n.ref)??"":await C(n.ref)??"":i,u=c!==""&&c!==n.label,d=[s,e];return n.ref!==null&&d.push(`ref: ${n.ref}`),u&&d.push(c),d.join(`
|
|
6
6
|
|
|
7
|
-
`)}
|
|
8
|
-
`)}
|
|
9
|
-
`).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:
|
|
7
|
+
`)}a(_,"inboxEntryBody");async function D(n,s,e,t){const i=`inbox/${String(t).padStart(6,"0")}`,o=await _(e),r={ref:`${n.node_id}:${i}`,nodeId:n.node_id,relpath:i,source:"inbox",ts:e.ts,tsMs:x(e.ts),title:`[${e.kind}] from ${e.from??"system"}: ${e.label}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>o,"loadBody"),origin:"inbox"};return typeof e.from=="string"&&e.from!==""&&(r.from=e.from),r}a(D,"inboxArtifact");async function N(n){const s=(await p(n))?.pi_session_file,e=typeof s=="string"?y(s):null;if(e===null)return null;try{return(await g().header(e)).path}catch(t){if(t instanceof I)return null;throw t}}a(N,"resolveSessionFile");function T(n){if(typeof n=="string")return n;if(!Array.isArray(n))return"";const s=[];for(const e of n){if(e===null||typeof e!="object")continue;const t=e;t.type==="text"&&typeof t.text=="string"?s.push(t.text):t.type==="toolCall"&&s.push(`Tool: ${typeof t.name=="string"?t.name:"call"}`)}return s.join(`
|
|
8
|
+
`)}a(T,"textFromBlocks");function F(n){return n==null?"unknown":n.type==="human"?"human":n.kind}a(F,"originToken");function L(n){if(n==null||n.type!=="runtime")return;const s=n.entries;if(s===void 0||s.length===0)return;const e=new Set;for(const t of s){const i=t.fromName??t.from;typeof i=="string"&&i!==""&&e.add(i)}return e.size===0?void 0:[...e].join(", ")}a(L,"sendersOf");async function $(n){const s=await N(n);if(s===null)return[];const e=(await g().read(y(s))).entries,t=new Map;for(const o of A(e)){if(o.kind!=="message")continue;const r=o.payload;typeof r.msgTs=="number"&&t.set(r.msgTs,r.origin)}const i=[];for(const o of e){if(o===null||typeof o!="object")continue;const r=o;if(r.type!=="message")continue;const c=r.message;if(c===null||typeof c!="object")continue;const u=c,d=typeof u.role=="string"?u.role:"";if(d==="")continue;const f=typeof u.timestamp=="number"?u.timestamp:void 0,l=typeof r.timestamp=="string"?r.timestamp:f!==void 0?new Date(f).toISOString():"",m=T(u.content),b={index:i.length,role:d,text:m,ts:l,tsMs:f??x(l)};if(d==="user"){const w=f!==void 0&&t.has(f)?t.get(f):null;b.origin=F(w);const h=L(w);h!==void 0&&(b.from=h)}i.push(b)}return i}a($,"sessionMessages");async function J(n,s){const e=(await g().read(y(n))).entries;let t=0;for(const i of e){if(i.type!=="message")continue;const o=i.message;if(!(o===null||typeof o!="object"||typeof o.role!="string")){if(t===s)return JSON.stringify(i);t++}}return null}a(J,"rawSessionLine");function K(n,s,e){const t=`session/${String(e.index).padStart(6,"0")}`,i=e.text.split(`
|
|
9
|
+
`).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>e.text,"loadBody"),role:e.role};return e.origin!==void 0&&(o.origin=e.origin),e.from!==void 0&&(o.from=e.from),o}a(K,"transcriptArtifact");async function W(n){return(await p(n))?.description??""}a(W,"nodeDescOf");async function tn(n,s){const e=await P(n),t=s.kinds,i=s.statuses,o=e.filter(d=>!(t!==void 0&&t.length>0&&!t.includes(d.kind)||i!==void 0&&i.length>0&&!i.includes(d.status))),r=s.types!==void 0&&s.types.length>0?s.types:["inbox"],c=new Set(r),u=[];for(const d of o){const f=await W(d.node_id);if(c.has("inbox")&&await B(await k(d.node_id),async(l,m)=>u.push(await D(d,f,l,m))),c.has("transcript"))for(const l of await $(d.node_id))u.push(K(d,f,l))}return u.filter(d=>s.sinceMs!==void 0&&d.tsMs<s.sinceMs||s.untilMs!==void 0&&d.tsMs>s.untilMs?!1:G(d,s))}a(tn,"buildCorpus");function G(n,s){const{origins:e,roles:t,from:i}=s;return!(e!==void 0&&e.length>0&&(n.origin===void 0||!e.includes(n.origin))||t!==void 0&&t.length>0&&(n.role===void 0||!t.includes(n.role))||i!==void 0&&i!==""&&(n.from===void 0||!n.from.toLowerCase().includes(i.toLowerCase())))}a(G,"matchesMessageFilters");function sn(n,s){const e=new Map;for(const t of n){let i;switch(s){case"origin":i=t.origin;break;case"role":i=t.role;break;case"node":i=`${t.nodeName} (${t.nodeId})`;break;case"kind":i=t.nodeKind;break;case"type":i=t.source;break;case"day":i=t.ts.slice(0,10)||void 0;break}i===void 0||i===""||e.set(i,(e.get(i)??0)+1)}return[...e.entries()].map(([t,i])=>({key:t,count:i})).sort((t,i)=>i.count-t.count||t.key.localeCompare(i.key))}a(sn,"groupCorpus");async function P(n){const s=await j(),e=new Map(s.map(i=>[i.node_id,i]));if(n.nodes!==void 0&&n.nodes.length>0)return n.nodes.map(i=>e.get(i)).filter(i=>i!==void 0);if(n.under!==void 0&&n.under!=="")return[n.under,...await v(n.under)].map(o=>e.get(o)).filter(o=>o!==void 0);if(n.allCwds===!0)return s;const t=n.cwd!==void 0&&n.cwd!==""?n.cwd:await R();return s.filter(i=>i.cwd===t)}a(P,"scopedRows");async function on(n){const s=n.indexOf(":");if(s===-1)return null;const e=n.slice(0,s),t=n.slice(s+1),i=await p(e);if(i===null)return null;if(t.startsWith("inbox/")){const o=Number(t.slice(6)),r=(await k(e))[o];return r===void 0?null:{nodeId:e,relpath:t,source:"inbox",ts:r.ts,nodeName:i.name,body:await _(r),raw:null,path:null}}if(t==="session"||t.startsWith("session/")){const o=await N(e);if(o===null)return null;const r=await $(e);if(t==="session"){const d=r.map(f=>`## ${f.role}${f.origin!==void 0?` (origin: ${f.origin})`:""}
|
|
10
10
|
|
|
11
11
|
${f.text}`).join(`
|
|
12
12
|
|
|
13
|
-
`);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:
|
|
14
|
-
`).join("")})
|
|
13
|
+
`);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:d,raw:a(async()=>{const{header:f,entries:l}=await g().read(y(o));return[f,...l].map(m=>`${JSON.stringify(m)}
|
|
14
|
+
`).join("")},"raw"),path:o}}const c=Number(t.slice(8)),u=r[c];return u===void 0?null:{nodeId:e,relpath:t,source:"transcript",ts:u.ts,nodeName:i.name,body:u.text,raw:a(()=>J(o,c),"raw"),path:o}}return null}a(on,"resolveRef");export{en as MESSAGE_ROLES,nn as ORIGIN_TOKENS,tn as buildCorpus,R as callerCwd,sn as groupCorpus,on as resolveRef};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
-- 033-node-sandbox-deleted.sql — when the retention pass deleted a finished node's Blaxel sandbox while keeping its rows, so the pass
|
|
2
|
+
-- does not delete it again every sweep. A new execution clears it. Added column only.
|
|
3
|
+
ALTER TABLE nodes ADD COLUMN IF NOT EXISTS sandbox_deleted_at text;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 33;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=33;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var J=Object.defineProperty;var
|
|
2
|
-
`).join(""),"encode")
|
|
3
|
-
`).filter(Boolean).map(e=>JSON.parse(e)),"decode"),N=
|
|
4
|
-
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(e,e);return{parts:s.filter(a=>a.kind==="part").map(({seq:a,blob_key:t,bytes:r,entries:n,created:
|
|
5
|
-
`).subarray(c-t,d-t)),t+=
|
|
1
|
+
var J=Object.defineProperty;var _=(o,e)=>J(o,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{existsSync as x,readFileSync as P,rmSync as Y}from"node:fs";import{join as V}from"node:path";import{SessionManager as G}from"@earendil-works/pi-coding-agent";import{blobStore as y}from"../blobs/index.js";import{openDb as E,withCanvasWrite as b}from"../canvas/db.js";import{appSpace as z}from"../layout.js";import{timedSpan as D}from"../logged-step-timings.js";import{addStepTiming as K}from"../step-timings.js";import{appendConversationEvents as M,rootRepromptPending as A}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as T}from"./index.js";const R="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",C=_((o,e,s)=>`conversations/${o}/${e}/${s}.jsonl`,"keyFor"),W=_(o=>o.map(e=>JSON.stringify(e)+`
|
|
2
|
+
`).join(""),"encode"),$=_(o=>o.split(`
|
|
3
|
+
`).filter(Boolean).map(e=>JSON.parse(e)),"decode"),N=_(()=>new Date().toISOString(),"at");async function m(o,e,s=!1){const a=await o.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1${s?" FOR UPDATE OF s":""}`).get(e);if(!a)throw new T(e);return a}_(m,"binding");async function h(o,e){return await o.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(e)}_(h,"parts");async function q(o,e){return await o.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(e)}_(q,"tail");async function H(o,e){const s=await o.prepare(`SELECT 'part' AS kind, seq, blob_key, NULL AS body, bytes, entries, created FROM conversation_parts WHERE conversation_id = ?
|
|
4
|
+
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(e,e);return{parts:s.filter(a=>a.kind==="part").map(({seq:a,blob_key:t,bytes:r,entries:n,created:i})=>({seq:Number(a),blob_key:t,bytes:Number(r),entries:Number(n),created:i})),tail:s.filter(a=>a.kind==="tail").map(({seq:a,body:t,bytes:r,created:n})=>({seq:Number(a),body:t,bytes:Number(r),created:n}))}}_(H,"snapshot");const I=4*1024*1024,Q=4,X=16;async function*B(o,e,s){const a=[];let t=0;const r=_(()=>{for(;t<o&&a.length<s;){const n=e(t++);n.catch(()=>{}),a.push(n)}},"fill");for(r();a.length>0;){const n=await a.shift();r(),yield n}}_(B,"readAhead");async function S(o,e,s){const a=[];let t=0;const r=await y(),n=[];for(const i of o.parts){const c=Math.max(e,t),d=Math.min(s,t+i.bytes);c<d&&n.push({key:i.blob_key,range:{start:c-t,length:d-c}}),t+=i.bytes}for await(const i of B(n.length,async c=>{const d=await r.get(n[c].key,n[c].range);if(!d)throw new Error(`missing conversation object: ${n[c].key}`);return d},X))a.push(i);for(const i of o.tail){const c=Math.max(e,t),d=Math.min(s,t+i.bytes);c<d&&a.push(Buffer.from(i.body+`
|
|
5
|
+
`).subarray(c-t,d-t)),t+=i.bytes}return Buffer.concat(a)}_(S,"bytesOf");async function*k(o){const e=o.parts.reduce((a,t)=>a+t.bytes,0)+o.tail.reduce((a,t)=>a+t.bytes,0);let s="";for await(const a of B(Math.ceil(e/I),t=>S(o,t*I,Math.min(e,(t+1)*I)),Q)){const t=s+a.toString("latin1"),r=t.lastIndexOf(`
|
|
6
6
|
`);s=t.slice(r+1);for(const n of t.slice(0,r+1).split(`
|
|
7
|
-
`))n&&(yield Buffer.from(n,"latin1").toString("utf8"))}s&&(yield Buffer.from(s,"latin1").toString("utf8"))}
|
|
8
|
-
`).filter(Boolean).length-1),N())||!n?.run_id||n.event_offset===null)return;const w=n.source_session_id?[]:await M(
|
|
9
|
-
`);return
|
|
10
|
-
`)),path:r}}if(!s||
|
|
11
|
-
`);
|
|
12
|
-
`);return l>0&&w.shift(),{header:t,entries:c(
|
|
7
|
+
`))n&&(yield Buffer.from(n,"latin1").toString("utf8"))}s&&(yield Buffer.from(s,"latin1").toString("utf8"))}_(k,"linesOf");const U=new Map;async function j(o,e,s){const a=await E();if(await a.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(o)||!x(s))return;let t=P(s);const r=t.lastIndexOf(10);if(r<0)return;t=t.subarray(0,r+1);const n=await a.prepare("SELECT s.binding_id, s.node_id, s.event_offset, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY "+R+" LIMIT 1").get(o);let i=[];if(n?.run_id&&n.event_offset!==null){const u=Number(n.event_offset);if(t.length<u)throw new Error(`conversation shorter than indexed offset: ${o}`);i=$(t.subarray(u).toString("utf8")).filter(l=>l.type!=="session")}const c=n?.run_id?await A(n.run_id,n.node_id,i):!1,d=C(e,o,0);await(await y()).put(d,t),await b(async u=>{if(!await u.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(o,d,t.length,Math.max(0,t.toString("utf8").split(`
|
|
8
|
+
`).filter(Boolean).length-1),N())||!n?.run_id||n.event_offset===null)return;const w=n.source_session_id?[]:await M(u,n.run_id,n.node_id,i,JSON.parse(n.input_ids_json),c);await u.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(t.length,i.at(-1)?.id??null,JSON.stringify(w),n.binding_id)})}_(j,"importOne");async function L(o,e){const s=await e.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1`).get(o),a=U.get(o);if(!s&&!a)throw new T(o);let t=(await h(e,o))[0];if(!t){const c=a?.path??s?.transcript_path??void 0;c&&await j(o,a?.node??s.node_id,c),t=(await h(e,o))[0]}if(!t||t.seq!==0)throw new T(o);const r=await(await y()).get(t.blob_key,{start:0,length:Math.min(t.bytes,256*1024)});if(!r)throw new Error(`missing conversation object: ${t.blob_key}`);const n=r.indexOf(10);if(n<0)throw new Error(`invalid conversation header: ${o}`);const i=JSON.parse(r.subarray(0,n).toString("utf8"));if(i.type!=="session"||i.id!==o)throw new Error(`invalid conversation header: ${o}`);return{header:i,path:s?.transcript_path??a?.path??"",binding:s}}_(L,"initial");function _e(){const o={async create(e,s,a,t){const r=await E(),n=await D("owner_read",async()=>await r.prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(e));if(!n)throw new Error(`missing conversation owner ${e}`);const i=s.id,c=V(z(n.grantee).conversations,e,`${s.timestamp.replace(/[:.]/g,"-")}_${i}.jsonl`),d=W([s,...a]),u=C(e,i,0),l=n.run_id?await A(n.run_id,e,a):!1;return K("blob_bytes",Buffer.byteLength(d)),await D("blob_put",async()=>await(await y()).put(u,d)),await D("transaction",()=>b(async w=>{if(await w.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(i))throw new Error(`conversation already exists: ${i}`);const p=N(),f=s.parentSession?await w.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(s.parentSession):void 0;if(await w.prepare("INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)").run(v(),i,e,c,f?f.session_id:null,p,p,p),await w.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(i,u,Buffer.byteLength(d),a.length,p),n.run_id&&!f){const g=await M(w,n.run_id,e,a,[],l);await w.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(a.at(-1)?.id??null,JSON.stringify(g),i,e)}},{timingName:"create_tx"})),{conversation_id:i,path:c}},async append(e,s){if(!s.length)return;const a=await m(await E(),e),t=a.run_id?await A(a.run_id,a.node_id,s):!1;await b(async r=>{const n=await m(r,e,!0);if(!(await h(r,e)).length)throw new T(e);const i=[];for(const c of s){const d=JSON.stringify(c);if(await r.prepare("INSERT INTO conversation_entries (conversation_id, entry_id, body, bytes, execution_id, created) VALUES (?, ?, ?, ?, NULL, ?) ON CONFLICT (conversation_id, entry_id) DO NOTHING RETURNING entry_id").get(e,c.id,d,Buffer.byteLength(d)+1,N())&&(i.push(c),c.type==="custom"&&c.customType==="crtr-cycle")){await r.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0 FOR UPDATE").get(e);const l=[...await h(r,e),...await q(r,e)].reduce((w,p)=>w+Number(p.bytes),0)-Buffer.byteLength(d)-1;await r.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0").run(l,e)}}if(n.run_id&&i.length){const c=await M(r,n.run_id,n.node_id,i,JSON.parse(n.input_ids_json??"[]"),t);await r.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(i.at(-1).id,JSON.stringify(c),n.binding_id)}})},async readLines(e){const s=await E(),{path:a}=await L(e,s);return{path:a,lines:k(await H(s,e))}},async read(e,s){const a=await E(),{header:t,path:r}=await L(e,a),n=await H(a,e),i=n.parts.reduce((p,f)=>p+f.bytes,0)+n.tail.reduce((p,f)=>p+f.bytes,0),c=_(p=>$(p).filter(f=>f.type!=="session"),"entriesOf"),d=_(async()=>{const p=await a.prepare("SELECT cycle_offset FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(e);let f=p?.cycle_offset==null?null:Number(p.cycle_offset);if(f===null){f=0;let g=0;for await(const O of k(n)){if(O.includes('"crtr-cycle"')){const F=JSON.parse(O);F.type==="custom"&&F.customType==="crtr-cycle"&&(f=g)}g+=Buffer.byteLength(O)+1}await b(async O=>{await O.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0 AND cycle_offset IS NULL").run(f,e)})}return f},"cycleOffset");if(s==="cycle"){const p=await d();return{header:t,entries:c((await S(n,p,i)).toString("utf8")),path:r}}if(s&&"beforeCycle"in s){const p=await d(),f=Math.max(0,p-s.beforeCycle),g=(await S(n,f>0?f-1:0,p)).toString("utf8").split(`
|
|
9
|
+
`);return f>0&&g.shift(),{header:t,entries:c(g.join(`
|
|
10
|
+
`)),path:r}}if(!s||i<=s.head+s.tail){const p=[];for await(const f of k(n))p.push(...c(f));return{header:t,entries:p,path:r}}const u=(await S(n,0,Math.max(0,s.head))).toString("utf8").split(`
|
|
11
|
+
`);u.pop();const l=Math.max(0,i-s.tail),w=(await S(n,l>0?l-1:0,i)).toString("utf8").split(`
|
|
12
|
+
`);return l>0&&w.shift(),{header:t,entries:c(u.join(`
|
|
13
13
|
`)),tail:c(w.join(`
|
|
14
|
-
`)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,
|
|
15
|
-
`).join("");return await(await y()).put(
|
|
14
|
+
`)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,i)=>n+i.bytes,0)+r.tail.reduce((n,i)=>n+i.bytes,0)}},async list(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${R}`).all(),t=[];for(const r of a){if(e&&r.node_id!==e)continue;const n=await o.header(r.session_id);t.push({conversation_id:r.session_id,node_id:r.node_id,...n})}return t.sort((r,n)=>n.mtime-r.mtime)},async replace(e,s,a){if(s.id!==e)throw new Error("replacement header id differs from conversation id");const t=await E(),r=await m(t,e);if(r.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${r.node_id}/${e}/0-${v()}.jsonl`,i=W([s,...a]);await(await y()).put(n,i);const c=await b(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const l=await h(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(i),a.length,N()),l});for(const d of c)await(await y()).delete(d.blob_key)},async fork(e,s,a,t){const r=await o.read(e);let n=r.entries;if(a!==void 0){const i=G.inMemory(r.header.cwd,void 0,[r.header,...n]);i.createBranchedSession(a),n=i.getEntries()}return(await o.create(s??(await L(e,await E())).binding?.node_id??U.get(e).node,{...r.header,id:v(),timestamp:N(),cwd:t??r.header.cwd,parentSession:r.path},n)).conversation_id},async delete(e,s){const a=await E(),t=await h(a,e);await b(async r=>{await r.prepare("DELETE FROM sessions WHERE session_id = ?").run(e),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e)});for(const r of t)await(await y()).delete(r.blob_key);s&&Y(s,{force:!0})},async commit(e){return await b(async s=>{const a=await m(s,e,!0),t=await q(s,e),r=await h(s,e);if(!t.length)return r.at(-1)?.seq??0;const n=(r.at(-1)?.seq??0)+1,i=C(a.node_id,e,n),c=t.map(d=>d.body+`
|
|
15
|
+
`).join("");return await(await y()).put(i,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await s.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,i,Buffer.byteLength(c),t.length,N()),await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(e,t.at(-1).seq),n})},async importLegacy(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${e?"AND n.run_id = ?":""} ORDER BY s.session_id, ${R}`).all(...e?[e]:[]);for(const t of a)await j(t.session_id,t.node_id,t.transcript_path)},recover(e){for(const s of e)s.transcript_path&&U.set(s.session_id,{node:s.node_id,path:s.transcript_path})}};return o}_(_e,"createRowStore");function Z(o,e,s){const a=o.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${e}`);const t=JSON.parse(o.subarray(0,a).toString("utf8"));if(t.type!=="session"||t.id!==e)throw new Error(`invalid conversation header: ${e}`);const r=s(t.cwd);return r===t.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...t,cwd:r})),o.subarray(a)])}_(Z,"withHeaderCwd");async function ue(o,e,s){const a=await E(),t=await m(a,o),r=(await h(a,o))[0];if(!r||r.seq!==0)return!1;const n=await(await y()).get(r.blob_key);if(!n)throw new Error(`missing conversation object: ${r.blob_key}`);const i=Z(n,o,u=>u===e?s:u);if(i===null)return!1;const c=`conversations/${t.node_id}/${o}/0-${v()}.jsonl`;await(await y()).put(c,i);const d=await b(async u=>await u.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ?, cycle_offset = CASE WHEN cycle_offset > 0 THEN cycle_offset + ? - bytes ELSE cycle_offset END WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,i.length,i.length,o,r.blob_key)!==void 0);if(await(await y()).delete(d?r.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${o}`);return!0}_(ue,"relocateConversationHeader");export{_e as createRowStore,B as readAhead,ue as relocateConversationHeader,Z as withHeaderCwd};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\"
|
|
1
|
+
export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\". Files you create for it must be chowned to it. A node runs with HOME set to its app's home\n# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.\n# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,\n# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.\n# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run `pnpm install` in a sandbox,\n# or install at build time below.\n# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# To install a repository's packages at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
|
|
@@ -4,7 +4,10 @@ const e=`#!/usr/bin/env bash
|
|
|
4
4
|
# How it runs
|
|
5
5
|
# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.
|
|
6
6
|
# - Your repositories are already checked out at /work/<repo name> before this runs.
|
|
7
|
-
# - The sandbox user is "crtr"
|
|
7
|
+
# - The sandbox user is "crtr". Files you create for it must be chowned to it. A node runs with HOME set to its app's home
|
|
8
|
+
# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.
|
|
9
|
+
# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,
|
|
10
|
+
# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.
|
|
8
11
|
# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
|
|
9
12
|
# or install at build time below.
|
|
10
13
|
# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var n=(t,i)=>f(t,"name",{value:i,configurable:!0});import{randomUUID as m}from"node:crypto";import{afterCommit as w,openDb as s}from"../canvas/db.js";import{personIdAsync as E,runAsPerson as h}from"../canvas/person.js";import{personHasSnapshot as S}from"../scoped-state/person-store.js";import{loadPersonSettings as y}from"../scoped-state/person-rows.js";import{directoryIssuer as p}from"../directory/issuer.js";import{emitEvent as l}from"../events/emit.js";import{describeOutboundFailure as A,outboundFetch as g,outboundJson as k,outboundRefusal as _}from"../events/outbound.js";import{mintDirectoryToken as T}from"../grants/sync.js";const O=5e3,D=10*6e4,R=5e3,N=1e4,u=new Map;async function L(t){if(p()===null)return null;const i=await E(),a=t.id??m();return await(await s()).prepare(`INSERT INTO credential_activations(activation_id,person,kind,provider,activated_at) VALUES(?,?,?,?,?)${t.idempotent?" ON CONFLICT (activation_id) DO NOTHING":""}`).run(a,i,t.kind,t.provider,new Date().toISOString()),w(()=>{v(a).catch(()=>{})}),a}n(L,"recordActivation");async function J(t,i,a,e){return h(t,async()=>(S()||await y(t),L({kind:i,provider:a,id:e,idempotent:e!==void 0})))}n(J,"recordCredentialActivation");async function K(t){return await(await s()).prepare("SELECT 1 FROM credential_activations WHERE activation_id=?").get(t)!==void 0}n(K,"activationRecorded");function M(t){return Math.min(D,O*2**Math.max(0,t-1))}n(M,"backoffMs");function v(t){let i=u.get(t);return i||(i=b(t).finally(()=>u.delete(t)),u.set(t,i)),i}n(v,"deliverActivation");async function b(t){const i=p();if(i===null)throw new Error("credential activation needs a directory-connected runtime");const a=await s(),e=await a.prepare("SELECT activation_id,person,kind,provider,activated_at FROM credential_activations WHERE activation_id=?").get(t);if(!e)throw new Error(`no credential activation ${t}`);await a.prepare("UPDATE credential_activations SET attempts=attempts+1, last_attempt_at=? WHERE activation_id=?").run(new Date().toISOString(),t);const r=`${i}/v1/runtime/credential-activations`;try{const o=await T(i),d=await g("credential_activation",r,{method:"POST",headers:{Authorization:`Bearer ${o.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({activation_id:e.activation_id,user_id:e.person,kind:e.kind,provider:e.provider,activated_at:e.activated_at}),signal:AbortSignal.timeout(1e4)});if(d.status===400)throw await a.prepare("DELETE FROM credential_activations WHERE activation_id=? AND acknowledged_at IS NULL").run(t),l({level:"warn",event:"model_auth.activation.rejected",fields:{activation_id:t,kind:e.kind,provider:e.provider}}),_("credential_activation",r,"directory rejected the credential activation: 400");if(!d.ok)throw _("credential_activation",r,`directory refused the credential activation: ${d.status}`);const c=await k("credential_activation",r,d);if(c.trial!=="closed"&&c.trial!=="not_active")throw new TypeError(`directory answered the credential activation without a trial state: ${JSON.stringify(c.trial)}`);return await a.prepare("UPDATE credential_activations SET acknowledged_at=? WHERE activation_id=? AND acknowledged_at IS NULL").run(new Date().toISOString(),t),l({level:"info",event:"model_auth.activation.acknowledged",fields:{activation_id:t,kind:e.kind,provider:e.provider,trial:c.trial}}),c.trial}catch(o){throw l({level:"warn",event:"model_auth.activation.delivery_failed",error:o,fields:{activation_id:t,...A(o)}}),o}}n(b,"attempt");async function V(t,i=N){let a;const e=new Promise(r=>{a=setTimeout(()=>r({status:"pending"}),i)});try{return await Promise.race([v(t).then(r=>({status:"acknowledged",trial:r}),()=>({status:"pending"})),e])}finally{clearTimeout(a)}}n(V,"awaitActivationAck");async function F(t=Date.now()){if(p()===null)return 0;const i=await(await s()).prepare("SELECT activation_id,attempts,last_attempt_at FROM credential_activations WHERE acknowledged_at IS NULL ORDER BY activated_at").all();let a=0;for(const e of i)u.has(e.activation_id)||e.last_attempt_at!==null&&Date.parse(e.last_attempt_at)+M(Number(e.attempts))>t||(v(e.activation_id).catch(()=>{}),a++);return a}n(F,"sweepActivations");function z(t=R){let i=!1;const a=n(()=>{i||(i=!0,F().catch(r=>l({level:"error",event:"model_auth.activation.sweep_failed",error:r})).finally(()=>{i=!1}))},"tick"),e=setInterval(a,t);return e.unref(),a(),()=>clearInterval(e)}n(z,"startActivationDelivery");export{O as BASE_BACKOFF_MS,D as MAX_BACKOFF_MS,K as activationRecorded,V as awaitActivationAck,v as deliverActivation,L as recordActivation,J as recordCredentialActivation,z as startActivationDelivery,F as sweepActivations};
|
|
@@ -25,6 +25,9 @@ export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
|
|
|
25
25
|
/** The run user's npmrc. pnpm 12 ignores an env-expanded `_authToken` in a repository's `.npmrc`, so the GitHub Packages auth line lives here; it names the
|
|
26
26
|
* variable, never its value. `store-dir` pins one pnpm store in the image that every repository's `pnpm install` links from. */
|
|
27
27
|
export declare const RUN_USER_NPMRC: string[];
|
|
28
|
+
/** A node runs with HOME set to its app's home (`/var/lib/crtr/apps/<app>/home`), not `/home/crtr`, so npm and pnpm would never read the npmrc above;
|
|
29
|
+
* this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
|
|
30
|
+
export declare const RUN_USER_NPMRC_ENV = "ENV NPM_CONFIG_USERCONFIG=/home/crtr/.npmrc";
|
|
28
31
|
export declare const REPOS_DIR = "repos";
|
|
29
32
|
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
30
33
|
export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as
|
|
1
|
+
var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as v,lstatSync as z,mkdirSync as W,readFileSync as V,readdirSync as J,readlinkSync as X,rmSync as Z,writeFileSync as _}from"node:fs";import{join as E,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",D="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
|
|
2
2
|
slim = false
|
|
3
|
-
`,at="1.1.0",
|
|
4
|
-
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${
|
|
5
|
-
`)}c(
|
|
6
|
-
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&
|
|
3
|
+
`,at="1.1.0",b="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],lt=`ENV NPM_CONFIG_USERCONFIG=/home/${p}/.npmrc`,B=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),N="repos",G="/work/.crtr/setup.log",C="/work/.crtr/setup-failed",M="/usr/local/bin/gh",pt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],L=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ut=c(t=>(t??"").split(`
|
|
4
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${L(t)} "exited $?" >> ${C}`,"guarded");function dt(t,r,i=!1){const s=ut(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${pt.map(L).join(" ")} > ${M} && chmod 755 ${M}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${D} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${C} ${G}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${N}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work"),e.push(`RUN ${B()}`);for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${L(o)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${B()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(lt,`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
5
|
+
`)}c(dt,"recipeDockerfile");const ht=c((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function Ut(t){const r=t.git??ht,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(E(t.dir,N),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),E(N,n.name)],a,t.dir)}_(E(t.dir,st),it),_(E(t.dir,"Dockerfile"),dt(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
|
|
6
|
+
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
|
|
7
7
|
`)?t.recipe.setup_script:`${t.recipe.setup_script}
|
|
8
|
-
`)}c(
|
|
8
|
+
`)}c(Ut,"prepareBuildDir");function F(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:V(a),mode:v.S_IFREG|n.mode&511})}}c(F,"walk");function ft(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE(g.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+g.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ft,"zipDirectory");async function R(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(R,"api");async function H(t,r){const{status:i,json:s}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function xt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(xt,"deleteImage");const mt=60*6e4;async function Nt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),g=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await R(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ft(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const O=s.timeoutMs??mt,K=e+O;let T=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,k=g(f).filter(m=>m>I).sort((m,x)=>m-x);if(h==="BUILT"&&k.length>=2){T??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],S=c(w=>Date.parse(w??"")>=x,"touchedSince"),y=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),A=n()-T>=(s.tagGraceMs??6e4),P=(y.length>0?y:A?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(A)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${O} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}c(Nt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,mt as BUILD_TIMEOUT_MS,M as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,N as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,lt as RUN_USER_NPMRC_ENV,ot as SANDBOX_API_IMAGE,C as SETUP_FAILED_FILE,G as SETUP_LOG_FILE,b as SETUP_SCRIPT_FILE,Nt as buildImage,xt as deleteImage,Lt as environmentImageName,H as getImage,Ut as prepareBuildDir,dt as recipeDockerfile,Rt as removeBuildDir,ft as zipDirectory};
|
|
@@ -1,8 +1,19 @@
|
|
|
1
|
+
/** A launch that has not reached `running` in this long never will: its row no longer keeps the node's sandbox. */
|
|
2
|
+
export declare const STALE_LAUNCH_MS: number;
|
|
1
3
|
/** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
|
|
2
4
|
* those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
|
|
3
5
|
export declare function deleteNodeSandboxes(nodeIds: readonly string[]): Promise<string[]>;
|
|
4
6
|
/** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
|
|
5
|
-
* (its fires run there). Called after each of those ends; a failure is left to the
|
|
6
|
-
* wake mail reopens it in the same sandbox.
|
|
7
|
-
* takes, so no new execution can start in
|
|
7
|
+
* (its fires run there). Called after each of those ends; a failure is left to the retention pass. A parked node is not ended:
|
|
8
|
+
* wake mail reopens it in the same sandbox. A launch stuck in `launching` past {@link STALE_LAUNCH_MS} does not hold the sandbox.
|
|
9
|
+
* The check and the DELETE run holding the node row's lock, which `beginExecution` also takes, so no new execution can start in
|
|
10
|
+
* the sandbox between them. */
|
|
8
11
|
export declare function deleteSandboxOfEndedNode(nodeId: string): void;
|
|
12
|
+
/** Delete the sandbox of every finished, canceled, dead or parked node quiet for `quietMs`, keeping its rows; app runs included.
|
|
13
|
+
* `quiet` decides the activity test ({@link lastActivityMs} reads disk too); `held` excludes nodes retention must not touch.
|
|
14
|
+
* Each node is marked `sandbox_deleted_at` so later passes skip it until a new execution clears the mark. Returns the deleted count. */
|
|
15
|
+
export declare function deleteQuietNodeSandboxes(opts: {
|
|
16
|
+
quiet: (nodeId: string) => Promise<boolean>;
|
|
17
|
+
held: (nodeId: string) => Promise<boolean>;
|
|
18
|
+
now?: number;
|
|
19
|
+
}): Promise<number>;
|
|
@@ -1,6 +1,14 @@
|
|
|
1
|
-
var
|
|
1
|
+
var u=Object.defineProperty;var o=(e,n)=>u(e,"name",{value:n,configurable:!0});import{afterCommit as S,openDb as l,withCanvasWrite as s}from"../../canvas/db.js";import{emitEvent as i}from"../../events/emit.js";const N=60*6e4,c=`EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id
|
|
2
|
+
AND (x.state = 'running' OR (x.state = 'launching' AND x.started_at > ?)))`;function _(e=Date.now()){return new Date(e-N).toISOString()}o(_,"staleLaunchCutoff");async function O(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),d=await(await l()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${n})`).all(...e),a=[];for(const{node_id:t}of d)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(t)}catch(r){a.push(t),i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:t,error:r})}return a}o(O,"deleteNodeSandboxes");function f(e){S(()=>{s(async n=>{await n.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
|
|
2
3
|
AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
|
|
3
4
|
AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
|
|
4
|
-
AND NOT
|
|
5
|
+
AND NOT ${c}
|
|
5
6
|
AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
|
|
6
|
-
FOR UPDATE OF n`).get(e)!==void 0&&await(await import("./index.js")).runnerForExecution("blaxel").delete(e)}).catch(n=>{i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:e,error:n})})})}o(
|
|
7
|
+
FOR UPDATE OF n`).get(e,_())!==void 0&&(await(await import("./index.js")).runnerForExecution("blaxel").delete(e),await n.prepare("UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?").run(new Date().toISOString(),e))}).catch(n=>{i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:e,error:n})})})}o(f,"deleteSandboxOfEndedNode");async function w(e){const n=_(e.now),d=await(await l()).prepare(`SELECT n.node_id FROM nodes n WHERE n.status IN ('done', 'canceled', 'dead')
|
|
8
|
+
AND n.sandbox_deleted_at IS NULL
|
|
9
|
+
AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
|
|
10
|
+
AND NOT ${c}
|
|
11
|
+
AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)`).all(n);let a=0;for(const{node_id:t}of d)if(!(!await e.quiet(t)||await e.held(t)))try{await s(async E=>await E.prepare(`SELECT 1 AS ok FROM nodes n WHERE n.node_id = ? AND n.status IN ('done', 'canceled', 'dead')
|
|
12
|
+
AND n.sandbox_deleted_at IS NULL AND NOT ${c}
|
|
13
|
+
AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
|
|
14
|
+
FOR UPDATE OF n`).get(t,n)===void 0?!1:(await(await import("./index.js")).runnerForExecution("blaxel").delete(t),await E.prepare("UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?").run(new Date().toISOString(),t),!0))&&a++}catch(r){i({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:t,error:r})}return a}o(w,"deleteQuietNodeSandboxes");export{N as STALE_LAUNCH_MS,O as deleteNodeSandboxes,w as deleteQuietNodeSandboxes,f as deleteSandboxOfEndedNode};
|
|
@@ -3,6 +3,6 @@ content-type: application/json; charset=utf-8\r
|
|
|
3
3
|
content-length: ${Buffer.byteLength(m)}\r
|
|
4
4
|
connection: close\r
|
|
5
5
|
\r
|
|
6
|
-
`+m;try{r.end(p)}catch{try{r.destroy()}catch{}}}i(g,"refuseUpgrade");function re(r,e){const{status:a,body:n}=me(e);g(r,a,"Refused",n.error.code,n.error.message)}i(re,"refuseWithError");function He(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(He,"reviveOptedOut");function Le(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Le,"wakeParkedRequested");function te(r){return r===1e3||r===1001||r===1005}i(te,"isCleanViewerClose");function _(r,e,a){a.catch(n=>M({level:"error",event:e,node_id:r,error:n}))}i(_,"detach");async function ne(r){const e=await Be(r);return e===null||e.runner==="process"?{kind:"unix",path:he(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Te(e.executionId,Date.now()),await Ce(e.executionId)),Oe(e.runner).viewerAddress(e))}i(ne,"brokerViewAddress");function ze(r,e){return e.kind==="machine"?Ne(e.environmentId,r):e.kind==="wss"?Me(e.url,e.headers):xe(r)}i(ze,"connectBrokerView");function Je(r,e,a){return e.kind==="wss"?G(e.url,e.headers,void 0,a):Re(r,a)}i(Je,"probeBrokerView");async function je(r,e,a,n,c){const m=[];let p=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>p(t)),!K(e)){c?.destroy();try{r.close(1008,U(`invalid node id: ${e}`))}catch{}return}if(await Q(e)===null){c?.destroy();try{r.close(1011,U(`no node ${e}`))}catch{}return}const u=performance.now();await R(e,{link:"viewer\u2194crtrd"});const b=performance.now(),o=c??ze(e,a),f=i(()=>Math.round((performance.now()-b)*10)/10,"sinceOpen"),h=i((t,
|
|
7
|
-
`)?
|
|
6
|
+
`+m;try{r.end(p)}catch{try{r.destroy()}catch{}}}i(g,"refuseUpgrade");function re(r,e){const{status:a,body:n}=me(e);g(r,a,"Refused",n.error.code,n.error.message)}i(re,"refuseWithError");function He(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(He,"reviveOptedOut");function Le(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Le,"wakeParkedRequested");function te(r){return r===1e3||r===1001||r===1005}i(te,"isCleanViewerClose");function _(r,e,a){a.catch(n=>M({level:"error",event:e,node_id:r,error:n}))}i(_,"detach");async function ne(r){const e=await Be(r);return e===null||e.runner==="process"?{kind:"unix",path:he(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Te(e.executionId,Date.now()),await Ce(e.executionId)),Oe(e.runner).viewerAddress(e))}i(ne,"brokerViewAddress");function ze(r,e){return e.kind==="machine"?Ne(e.environmentId,r):e.kind==="wss"?Me(e.url,e.headers):xe(r)}i(ze,"connectBrokerView");function Je(r,e,a){return e.kind==="wss"?G(e.url,e.headers,void 0,a):Re(r,a)}i(Je,"probeBrokerView");async function je(r,e,a,n,c){const m=[];let p=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>p(t)),!K(e)){c?.destroy();try{r.close(1008,U(`invalid node id: ${e}`))}catch{}return}if(await Q(e)===null){c?.destroy();try{r.close(1011,U(`no node ${e}`))}catch{}return}const u=performance.now();await R(e,{link:"viewer\u2194crtrd"});const b=performance.now(),o=c??ze(e,a),f=i(()=>Math.round((performance.now()-b)*10)/10,"sinceOpen"),h=i((t,l={})=>{M({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:a.kind,channel:o.channel??"",since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10,...l}})},"bridgeMark");c===void 0&&h("channel_opened");const A=new ke(_e);let k=!1,$=!1,B,H=!1,L=!1,S,z=!1,T="controller",J=Promise.resolve(),C=!1;const O=[];let V=!1,N=!1,j=!1,x=0;const q=i(()=>{c===void 0&&h("channel_connected"),H=!0,!k&&C&&_(e,"daemon.bridge.presence_failed",Y(e,r)),_(e,"daemon.bridge.connect_failed",R(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",q);const y=i((t,l,s=!1)=>{if(!k){if(k=!0,_(e,"daemon.bridge.presence_failed",s?Fe(e,r):Pe(e,r)),B?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,U(l))}catch{}}},"teardown");B=Ue(r,I,a.kind==="machine"?1/0:ee);const oe=i(async t=>{B?.noteActivity();let l;const s=performance.now();try{l=A.push(t)}catch(w){const E=w instanceof ve?`broker sent an oversized frame (${w.message})`:`failed to decode a broker frame for ${e}`;y(1009,E);return}!N&&l.some(w=>w?.type==="welcome")&&(N=!0,x=performance.now(),h("welcome_decoded",{decode_ms:Math.round((x-s)*10)/10,chunk_bytes:t.length,since_hello_ms:S===void 0?-1:Math.round((x-S)*10)/10})),O.push(...l),V||await ie()},"onData"),ie=i(async()=>{V=!0;try{for(;O.length>0&&!k;){const t=O.splice(0),l=N&&!j&&t.some(d=>d?.type==="welcome"),s=performance.now();let w;try{w=await n(T),l&&(j=!0,h("welcome_authorized",{auth_ms:Math.round((performance.now()-s)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}catch(d){M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),y(1011,"revoked");return}if(k)return;if(!w){y(1008,"revoked");return}let E=!1;for(const d of t){if(r.readyState!==r.OPEN)continue;const v=d?.type==="welcome",P=performance.now();r.send(JSON.stringify(d)),v&&(E=!0,h("welcome_forwarded",{send_ms:Math.round((performance.now()-P)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}if(C&&E)try{await We(e,r)&&await Se(e)}catch(d){M({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{V=!1}},"drainOutbound");o.on("data",t=>_(e,"daemon.bridge.data_failed",oe(t)));const ae=i(async t=>{const l=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const s=W("relay\u2194broker",t);await D(e,{link:"relay\u2194broker",op:"bridge socket",kind:s.kind,retry:s.disposition==="fatal"?{disposition:"fatal"}:{disposition:"auto",by:"client"},message:t.message})}finally{y(1011,l,!0)}},"onSocketError");o.on("error",t=>_(e,"daemon.bridge.socket_error_failed",ae(t)));const ce=i(async t=>{if(!(k||t))try{await R(e,{link:"relay\u2194broker"})}finally{y(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>_(e,"daemon.bridge.socket_close_failed",ce(t)));const se=i(async(t,l)=>{const s=l.toString("utf8");if(k){te(t)&&await R(e,{link:"viewer\u2194crtrd"});return}try{if(te(t))await R(e,{link:"viewer\u2194crtrd"});else if(!$){$=!0;const w=W("viewer\u2194crtrd",{code:t,reason:s});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:w.kind,retry:{disposition:"auto"},message:s||`remote attach closed (${t})`})}}finally{y(t,s||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,l)=>_(e,"daemon.bridge.ws_close_failed",se(t,l)));const le=i(async()=>{try{if(!$){$=!0;const t=W("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{y(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>_(e,"daemon.bridge.ws_error_failed",le())),p=i(t=>{if(k||o.destroyed)return;B?.noteActivity();const s=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!L)try{const v=JSON.parse(s);v?.type==="hello"&&(h("hello_received"),S=performance.now(),L=!0,T=v.role==="observer"?"observer":"controller",C=v.attends!==!1,C&&H&&_(e,"daemon.bridge.presence_failed",Y(e,r)))}catch{}const w=s.endsWith(`
|
|
7
|
+
`)?s:s+`
|
|
8
8
|
`,E=i(()=>{try{o.write(w)}catch{}},"write"),d=S===void 0?!1:z===!1;d&&(z=!0),J=J.then(async()=>{if(k)return;const v=performance.now(),P=await n(T);d&&h("hello_authorized",{auth_ms:Math.round((performance.now()-v)*10)/10,since_hello_ms:Math.round((performance.now()-S)*10)/10}),P?(E(),d&&h("hello_written",{since_hello_ms:Math.round((performance.now()-S)*10)/10})):y(1008,"revoked")}).catch(v=>{M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:v}),y(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))p(t);c!==void 0&&(c.destroyed?y(1011,`no running broker for ${e}`,!0):q())}i(je,"bridgeConnection");async function hr(r,e,a,n,c){await Ae("attach_upgrade",{node:n},r,()=>qe(r,e,a,n,c))}i(hr,"handleAttachUpgrade");async function qe(r,e,a,n,c){const m=we(),p=m===void 0?c:o=>pe(m,()=>c(o));e.on("error",()=>{});let u,b=!1;try{if(!K(n)){g(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await F("admission",async()=>await Q(n)===null)){g(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(He(r)){o=await ne(n);let f;if(o.kind==="machine"?(u=await X(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Je(n,o,o.kind==="wss"?Z:250),!f){g(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const A=await F("revive_decision",async()=>await Ee(n,{resume:!0,capacity:"refuse"},Le(r)));if(A.parked){g(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=A.result.launch?.exited}catch(A){re(e,A);return}if(o=await F("address_lookup",async()=>await ne(n)),o.kind==="machine"&&(u=await X(o.environmentId,n,f,Z)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await G(o.url,o.headers,f):await $e(n,f))){o.kind==="machine"?re(e,de(`the broker for ${n} on its machine did not accept a viewer after revive`)):g(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;be("upgrading"),De.handleUpgrade(r,e,a,f=>{b=!0,_(n,"daemon.bridge.connection_failed",je(f,n,o,p,u).catch(h=>{throw u?.destroy(),h}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Ve(o)){g(e,400,"Bad Request","invalid_request",f);return}g(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{b||u?.destroy()}}i(qe,"attachUpgrade");export{I as REMOTE_ATTACH_HEARTBEAT_MS,ee as REMOTE_ATTACH_QUIET_MS,hr as handleAttachUpgrade,te as isCleanViewerClose,g as refuseUpgrade,Ue as startRemoteAttachHeartbeat};
|
|
@@ -3,7 +3,7 @@ var Q=Object.defineProperty;var u=(t,e)=>Q(t,"name",{value:e,configurable:!0});i
|
|
|
3
3
|
`).forEach((c,b)=>{l.test(c)&&r.push({ref:p.ref,node:`${p.nodeName} (${p.nodeId})`,ts:p.ts,line:b+1,text:c.trim()})});r.sort((p,n)=>p.ref.localeCompare(n.ref)||p.line-n.line);const m=r.slice(a,a+s),f=a+s<r.length?x(a+s):null;return{status:200,body:{hits:m,next_cursor:f,total:r.length}}}u(Me,"handleHistoryGrep");async function Ae(t){const e=Ie(t.body),s=(e.query??"").trim(),o=e.weigh_body===!0,a=e.full===!0,l=Math.max(1,e.snippet_lines??1),r=Math.min(100,Math.max(1,e.limit??20)),m=e.per_node===!0;if(m&&(e.nodes===void 0||e.nodes.length===0))throw new T(400,"invalid_request","`per_node` requires a non-empty `nodes` list",{param:"nodes"});const f=await L(e,t),h=e.cursor!==void 0?H(e.cursor):0,p=s.toLowerCase().split(/\s+/).filter(i=>i.length>0);let n=f,c;const b=e.sort??(p.length>0?"relevance":"recency");if(p.length>0&&b==="relevance"){c=new Map;const i=[];for(const _ of f){const E=_.title.toLowerCase(),K=_.nodeName.toLowerCase(),V=_.nodeDesc.toLowerCase(),$=o?_.loadBody().toLowerCase():null;let k=0;for(const I of p)E.includes(I)&&(k+=10),K.includes(I)&&(k+=5),V.includes(I)&&(k+=3),$!==null&&$.includes(I)&&(k+=1);k>0&&(c.set(_.ref,k),i.push(_))}n=i}else p.length>0&&(n=f.filter(i=>{const _=`${i.title}
|
|
4
4
|
${i.nodeName}
|
|
5
5
|
${i.nodeDesc}${o?`
|
|
6
|
-
`+i.loadBody():""}`.toLowerCase();return p.some(E=>_.includes(E))}));let d=je(n,b,c);if(m){const i=new Set;d=d.filter(_=>!i.has(_.nodeId)&&i.add(_.nodeId))}const g=m?d:d.slice(h,h+r),w=!m&&h+r<d.length?x(h+r):null;return{status:200,body:{hits:g.map(i=>{const _={ref:i.ref,node:`${i.nodeName} (${i.nodeId})`,kind:i.nodeKind,source:i.source,ts:i.ts,...m?{node_id:i.nodeId}:{}};return b==="relevance"&&c!==void 0&&(_.score=c.get(i.ref)??0),a?_.body=i.loadBody():_.snippet=Oe(i,p,l),_}),next_cursor:w,total:d.length}}}u(Ae,"handleHistorySearch");async function Te(t){const e=(t.query.get("ref")??"").trim();if(!e.includes(":"))throw y(`ref must be <node-id>:inbox/<n>, <node-id>:session, or <node-id>:session/<n>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search`. Reports and documents are `crtr canvas read <name>`."});const s=await ce(e);if(s===null)throw me(`no inbox entry or message for ref: ${e}`,{ref:e,next:"Re-run `crtr canvas history search` for a current ref. Reports and documents are `crtr canvas read <name>`."});if((await v(t))?.has(s.nodeId)===!1)throw new T(404,"not_found","artifact not found");const o=s.source,l=t.query.get("format")==="raw"
|
|
6
|
+
`+i.loadBody():""}`.toLowerCase();return p.some(E=>_.includes(E))}));let d=je(n,b,c);if(m){const i=new Set;d=d.filter(_=>!i.has(_.nodeId)&&i.add(_.nodeId))}const g=m?d:d.slice(h,h+r),w=!m&&h+r<d.length?x(h+r):null;return{status:200,body:{hits:g.map(i=>{const _={ref:i.ref,node:`${i.nodeName} (${i.nodeId})`,kind:i.nodeKind,source:i.source,ts:i.ts,...m?{node_id:i.nodeId}:{}};return b==="relevance"&&c!==void 0&&(_.score=c.get(i.ref)??0),a?_.body=i.loadBody():_.snippet=Oe(i,p,l),_}),next_cursor:w,total:d.length}}}u(Ae,"handleHistorySearch");async function Te(t){const e=(t.query.get("ref")??"").trim();if(!e.includes(":"))throw y(`ref must be <node-id>:inbox/<n>, <node-id>:session, or <node-id>:session/<n>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search`. Reports and documents are `crtr canvas read <name>`."});const s=await ce(e);if(s===null)throw me(`no inbox entry or message for ref: ${e}`,{ref:e,next:"Re-run `crtr canvas history search` for a current ref. Reports and documents are `crtr canvas read <name>`."});if((await v(t))?.has(s.nodeId)===!1)throw new T(404,"not_found","artifact not found");const o=s.source,l=(t.query.get("format")==="raw"?await s.raw?.():null)??s.body;return{status:200,body:{ref:e,node:`${s.nodeName} (${s.nodeId})`,source:o,ts:s.ts,content:l}}}u(Te,"handleHistoryRead");function Le(t){for(const[o]of t.query)if(o!=="live")throw y(`unknown snapshot query parameter: ${o}`);const e=t.query.getAll("live");if(e.length>1)throw y("live must appear at most once");const s=e[0];if(s===void 0||s==="false"||s==="0")return!1;if(s==="true"||s==="1")return!0;throw y("live must be true or false")}u(Le,"snapshotLiveOnly");async function $e(t){const e=new Set((await P()).map(n=>n.node_id)),s=await v(t),o=(await se(G,e,Le(t))).filter(n=>s===null||s.has(n.node_id)),a=await M(o.map(n=>n.node_id));await re(G,o,a);const l=await te(o.map(n=>n.node_id)),r=await J(o,async n=>{const c=n.srcRow,b=c?.host_kind??"tmux";return{node_id:n.node_id,name:n.name,title:n.handle??n.name,description:n.description??null,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle??c?.lifecycle,status:n.status,cwd:n.cwd,profile_id:n.profile_id??null,parent:c?.parent??null,created:n.created,host_kind:b,enterable:b==="broker",attention_count:n.asks,...c?.cycles!=null?{cycles:c.cycles}:{},...n.mtimeMs!==void 0?{last_activity:new Date(n.mtimeMs).toISOString()}:{},ctx_tokens:n.ctx_tokens,streaming:n.streaming??!1,jobs_active:c!==void 0&&oe(c.pi_pid)?(await ne(await A(),n.node_id)).length:0,waiting_for:l.get(n.node_id)?.controllerId??null,hanging:n.hanging??null,viewed:n.viewed??!1,final_report:c?.final_report??null,finalized_at:c?.finalized_at??null}}),m=new Map;for(const n of await N(s)){const c=m.get(n.from_id);c===void 0?m.set(n.from_id,[n.to_id]):c.push(n.to_id)}const f=new Set(o.map(n=>n.node_id)),h=Object.fromEntries(o.map(n=>[n.node_id,(m.get(n.node_id)??[]).filter(c=>f.has(c))]));return{status:200,body:{generated_at:O(),nodes:r,subscriptions:h}}}u($e,"handleSnapshot");function U(t){const e=t.host_kind??"tmux";return{node_id:t.node_id,name:t.name,kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,host_kind:e,enterable:e==="broker",parent:t.parent,created:t.created,description:t.description}}u(U,"toRosterNodeDTO");async function De(){const t=(await F()).map(U),e=(await N()).map(o=>({from_id:o.from_id,to_id:o.to_id,active:o.active,created:o.created})),s=(await B()).map(o=>({node_id:o.nodeId,object_id:o.objectId,object_type:o.objectType,object_name:o.objectName,created:new Date(o.createdAt).toISOString()}));return{generated_at:O(),nodes:t,edges:e,object_waits:s}}u(De,"buildRoster");async function Fe(t){const e=t.params.id,o=(await(await A()).prepareUncached(`WITH RECURSIVE up(id) AS (
|
|
7
7
|
SELECT CAST(? AS text)
|
|
8
8
|
UNION
|
|
9
9
|
SELECT w.watcher FROM up JOIN watches w ON w.object = up.id AND w.in_tree = 1
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var I=Object.defineProperty;var p=(w,e)=>I(w,"name",{value:e,configurable:!0});import{rm as A}from"node:fs/promises";import{closeFocusRow as N,getFocusById as T,listFocuses as P,listNodes as C}from"../../core/canvas/index.js";import{pruneExpiredIdempotencyKeys as D}from"../../core/runs/operations.js";import{getNode as y,lastActivityMs as h,listTerminalPlacementResidue as x,pruneExpiredCreateRequests as F,pruneNodes as M}from"../../core/canvas/canvas.js";import{lastContextStripMs as b,stripContextDir as L}from"../../core/canvas/context-strip.js";import{isAppRun as W}from"../../core/canvas/app-run.js";import{isSafeNodeId as l}from"../../core/canvas/paths.js";import{emitEvent as a}from"../../core/events/emit.js";import{operationIdContext as s}from"../../core/events/operation-id.js";import{listLivePanesAsync as G,tearDownNode as V}from"../../core/runtime/placement.js";import{reapStaleSpares as k}from"../../core/runtime/warm-pool.js";import{GroveInstanceSweepReconciler as q}from"./grove-instance-sweep.js";import{ManagedWorktreeSweepReconciler as O}from"./managed-worktree-sweep.js";import{compactRunEvents as U}from"../../core/runs/events.js";import{archiveExpiredRunEvents as H}from"../../core/events/run-event-chunks.js";import{blobStore as Y}from"../../core/blobs/index.js";import{runThrottledLane as d}from"./throttled-lane.js";import{openDb as g}from"../../core/canvas/db.js";import{touchMachineEnvironment as z}from"../../core/environments.js";import{retentionHold as m}from"./live-obligation.js";import{deleteQuietNodeSandboxes as B}from"../../core/runtime/runner/delete-sandboxes.js";import{pruneMemoryReads as K}from"../../core/canvas/memory-reads.js";import{existsSync as Q}from"node:fs";import{launcherRequest as $}from"../../launcher/client.js";import{LAUNCHER_SOCKET as X}from"../../launcher/spec.js";import{cachePassDue as Z}from"../../launcher/limits/policy.js";const j=10*6e4,u=60*1e3,E=60*1e3,v=5*6e4,S=2,J=1440*6e4,ee=2e3,te=6e4;class Ce{static{p(this,"StorageMaintenanceReconciler")}focusGcInFlight=!1;lastCachePassAt=null;cachePassInFlight=!1;worktreeSweep=new O;groveInstanceSweep=new q;async run(e,t){await this.reapDeadResidue(e,t.held),this.scheduleFocusGc(t),await this.gcWarmPool(e),await this.touchEnvironment(e),await this.gcCreateRequests(e),await this.gcViewerAttachments(e);try{await d("run-event-maintenance","",e,ee,te,async r=>{await H(await Y(),e);const n=await U(e,r.state===null?0:Number(r.state));await r.save(String(n.cursor))})}catch(r){console.warn(`run event maintenance failed: ${String(r)}`)}await d("memory-read-prune","",e,60*6e4,10*6e4,async()=>{try{await K(e)}catch(r){console.warn(`memory-read log prune failed: ${String(r)}`)}}),await d("storage-analyze","",e,1440*6e4,10*6e4,async()=>{await(await g()).exec("ANALYZE")}),await this.sweepRetention(e,t),this.scheduleCachePass(e,t),this.scheduleContextStrip(e,t),this.worktreeSweep.run(e,t),this.groveInstanceSweep.run(e,t)}scheduleCachePass(e,t){this.cachePassInFlight||!Z(this.lastCachePassAt,e)||process.platform!=="linux"||!Q(X)||t.lifecycle.acceptsDetachedWork()&&(this.lastCachePassAt=e,this.cachePassInFlight=!0,t.lifecycle.registerDetached($({operation:"cache.purge"}).then(()=>{}).catch(r=>{s.fresh(()=>{a({level:"warn",event:"app.cache.pass_failed",error:r})})}).then(()=>{this.cachePassInFlight=!1})))}msSinceTerminalActivity(e,t){const r=h(e);return r===0?Number.POSITIVE_INFINITY:t-r}async sweepRetention(e,t){t.lifecycle.acceptsDetachedWork()&&await d("retention-sweep","",e,v,v,()=>s.fresh(async()=>{try{const r=await M({ttlDays:S,held:await m(t.fleet),removeDirs:p(i=>{t.lifecycle.registerDetached(Promise.all(i.map(c=>A(c,{recursive:!0,force:!0}))).then(()=>{}).catch(c=>{s.fresh(()=>{a({level:"error",event:"canvas.retention.failed",error:c})})}))},"removeDirs")});r.pruned.length>0&&a({level:"info",event:"canvas.retention.pruned",outcome:"succeeded",fields:{pruned_count:r.pruned.length}});const n=await m(t.fleet),o=e-S*24*60*6e4,f=await B({now:e,held:n,quiet:p(async i=>{const c=await y(i);return c!==null&&h(c)<o},"quiet")});f>0&&a({level:"info",event:"canvas.retention.sandboxes_deleted",outcome:"succeeded",fields:{deleted_count:f}})}catch(r){a({level:"error",event:"canvas.retention.failed",error:r})}}))}scheduleContextStrip(e,t){t.lifecycle.acceptsDetachedWork()&&t.lifecycle.registerDetached(d("context-strip","",e,v,10*6e4,()=>this.stripFinishedContexts(e,t)).then(()=>{},r=>{a({level:"error",event:"canvas.context_strip.failed",error:r})}))}async stripFinishedContexts(e,t){const r=await m(t.fleet),n=p(async i=>i!==null&&["done","canceled","dead"].includes(i.status)&&(i.pi_pid??null)===null&&(i.frozen_at??null)===null&&!W(i)&&h(i)<e-J&&!await r(i.node_id),"eligible");let o=0,f=0;try{for(const i of await C({status:["done","canceled","dead"]})){if(!l(i.node_id)||!await n(i))continue;const c=await b(i.node_id);if(c!==null&&c>=h(i)||!await n(await y(i.node_id)))continue;let _;try{_=await L(i.node_id)}catch(R){s.fresh(()=>{a({level:"warn",event:"canvas.context_strip.node_failed",error:R,fields:{node_id:i.node_id}})});continue}_.removed.length>0&&(o+=1,f+=_.bytes)}}catch(i){s.fresh(()=>{a({level:"error",event:"canvas.context_strip.failed",error:i})})}o>0&&s.fresh(()=>{a({level:"info",event:"canvas.context_strip.completed",outcome:"succeeded",fields:{node_count:o,bytes:f}})})}async reapDeadResidue(e,t){let r;try{r=await x()}catch(n){s.fresh(()=>{a({level:"error",event:"residue.reap_scan.failed",error:n})});return}for(const n of r)if(!t.has(n.node_id)){try{if(this.msSinceTerminalActivity(n,e)<j)continue}catch(o){s.fresh(()=>{a({level:"error",event:"residue.reap.failed",...l(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})});continue}await s.fresh(async()=>{try{a({level:"info",event:"residue.reaped",...l(n.node_id)?{node_id:n.node_id}:{},fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}}),await V(n.node_id)}catch(o){a({level:"error",event:"residue.reap.failed",...l(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})}})}}scheduleFocusGc(e){if(this.focusGcInFlight||!e.lifecycle.acceptsDetachedWork())return;this.focusGcInFlight=!0;const t=this.gcStaleFocuses().finally(()=>{this.focusGcInFlight=!1});e.lifecycle.registerDetached(t)}async gcStaleFocuses(){let e;try{e=await P()}catch(r){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:r})});return}if(e.length===0)return;let t;try{t=await G()}catch(r){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:r})});return}if(t!==null)for(const r of e){if(r.pane===null||t.has(r.pane))continue;if(!await s.fresh(async()=>{try{return(await T(r.focus_id))?.pane!==r.pane||(a({level:"info",event:"focus.gc.removed",...l(r.node_id)?{node_id:r.node_id}:{},fields:{focus_id:r.focus_id,focus_node_id:r.node_id,pane:r.pane}}),await N(r.focus_id)),!0}catch(o){return a({level:"error",event:"focus.gc.failed",error:o}),!1}}))return}}async gcCreateRequests(e){await d("create-request-gc","",e,E,E,()=>s.fresh(async()=>{const t=await F(e),r=await D(e);r>0&&a({level:"info",event:"canvas.idempotency_keys.reaped",outcome:"succeeded",fields:{reaped_count:r}}),t>0&&a({level:"info",event:"canvas.create_requests.reaped",outcome:"succeeded",fields:{reaped_count:t}})}))}async gcViewerAttachments(e){await d("viewer-attachment-gc","",e,u,u,()=>s.fresh(async()=>{const t=Number((await(await g()).prepare("DELETE FROM viewer_attachments WHERE expires_at <= ?").run(new Date(e).toISOString())).changes);t>0&&a({level:"info",event:"viewer_attachments.reaped",outcome:"succeeded",fields:{reaped_count:t}})}))}async touchEnvironment(e){await d("environment-touch","",e,u,u,()=>s.fresh(async()=>{try{await z(new Date(e).toISOString())}catch(t){a({level:"warn",event:"environment.touch.failed",error:t})}}))}async gcWarmPool(e){await d("warm-pool-gc","",e,u,u,()=>s.fresh(async()=>{const t=await k();t.length>0&&a({level:"info",event:"warm_pool.spares_reaped",outcome:"succeeded",fields:{reaped_count:t.length}})}))}}export{J as CONTEXT_STRIP_GRACE_MS,j as DEAD_REAP_GRACE_MS,v as RETENTION_SWEEP_INTERVAL_MS,S as RETENTION_TTL_DAYS,Ce as StorageMaintenanceReconciler};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`):""}h(ge,"messageText");function B(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(B,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ve,"boundedRuntimeReason");class we{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=J();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=k(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=x();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=B(i)?be(i):"reload";B(i)||E({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=x();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(b=void 0);for(const a of d)M(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return b===this&&b.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),z()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new H(e,i),this.clearTimer(),E({level:"error",event:t,outcome:"failed",error:i,error_class:T(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof H)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,E({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:"poll"}});return}if(se(i)){this.clearTimer(),E({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),D()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(l=>l.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const l=a.entry.entry_id;this.claims.has(l)||(a.entry=ee(a.entry,t),this.claims.set(l,a),a.handoff==="inherited"&&!i?y.fresh(o=>{this.pendingHandoffs.push({...I([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=x();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||U()||this.pendingHandoffs.length>=_||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&w()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=w()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&w()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(f=>f.entry_id)),s=new Set(i.map(f=>f.entry_id)),d=t.filter(f=>n.has(f.entry_id)||s.has(f.entry_id)),a=this.isIdle()&&d.length>0&&d.every(f=>f.tier==="deferred"),l=this.visibleRoute(i)==="critical",o=!a&&!l&&e.length>0,c=!a&&!l&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await Q(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...V(n));return i}digest(t,e){try{return L(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=_&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=I(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{y.fresh(o=>{a=o,v({level:"info",event:"inbox.delivery.started",operation_id:o,fields:g(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),F(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const l={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(l),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&M(l,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",l=a===void 0||i.length===0?void 0:k(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,c)=>{const f=s&&c===i.length-1;this.pi.sendMessage({customType:C,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:f?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,l)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:C,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(l=>l.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?k(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(o=p)});const c=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const f=this.digest(c,i),m=f.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(w()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of f){const p=I(u.entries,"visible");y.fresh(R=>{v({level:"info",event:"inbox.delivery.started",operation_id:R,fields:g(p)}),this.pendingHandoffs.push({...p,operationId:R,settlesThroughBridge:!0})})}const q=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)q.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...l]=d;for(const o of l)for(const c of o.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const f of e.hiddenEntries)n.add(f.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>_)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||U())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>_)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=I(i,e)}catch(l){this.raiseReadFatal("poll",l)}let d;try{await y.fresh(async l=>{d=l,v({level:"info",event:"inbox.delivery.started",operation_id:l,fields:g(s)});for(const o of n)await t.sendCustomMessage({customType:C,content:o,display:!0})})}catch(l){throw d===void 0&&this.raiseReadFatal("poll",l),F(d,s,"send",l),l}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&M(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(l=>l.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)F(d.operationId,d,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),D()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=new Set(this.buffer.map(f=>f.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(f=>f.awaitingDequeue!==void 0).flatMap(f=>[...f.entryIds])),l=this.pendingHandoffs.filter(f=>(n||f.settleAtAgentSettled!==!0)&&f.entryIds.every(m=>!a.has(m))),o=new Set(l.flatMap(f=>[...f.entryIds])),c=[...this.claims.keys()].filter(f=>s||o.has(f)&&!d.has(f));return c.length===0?"settled":(this.pendingCommit={handoffs:l,entryIds:c,receipts:c.map(f=>{const m=this.claims.get(f);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){b?.dispose("reload",!1);const e=new we(r,t,++ce);b=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}h(Ee,"registerCanvasInboxWatcher");var qe=Ee;export{qe as default,Ee as registerCanvasInboxWatcher};
|
|
1
|
+
var J=Object.defineProperty;var h=(r,t)=>J(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as L,envNodeId as G,envProfileId as X,envWatcherDebounceMs as j,envWatcherTickMs as z,envWatcherBackstopMs as V}from"../shared/env.js";import{coalesceBrokerInbox as Y,entryCards as K}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Q,claimBrokerMail as Z,brokerExtensionState as ee,brokerRecovery as te,mutateBrokerFault as D,recordConversationWriteFault as ie}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ne}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as N}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as se,startupClaimsHeld as re}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ae}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as de,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as le,generateAndCommitInitialName as fe}from"./broker-local.js";import{emitEvent as O}from"../core/events/emit.js";import{errorClassFromError as he}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as ue}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as P,brokerIdleTurnStart as ce,brokerRunTurnBusy as me,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as pe}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,ye=3e4,ge=5*6e4,H="inbox daemon unreachable",U=16;let v,be=0;class B extends Error{static{h(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function ve(){return{tickMs:z(),debounceMs:j()}}h(ve,"resolveCadence");function w(){const r=G();return r===void 0||r.trim()===""?void 0:r}h(w,"currentNodeId");function q(){const r=X();return r!==void 0&&r!==""&&ue(r)}h(q,"profilePaused");function _(r){try{return he(r)}catch{return{class:"unknown"}}}h(_,"safeErrorClass");function E(r){try{O(r)}catch{}}h(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}h(g,"emitFreshBestEffort");function T(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}h(T,"emitStoredBestEffort");function we(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}h(we,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-U;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,U),...i>0?{sourceOperationIdsOmitted:i}:{}}}h(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}h(b,"deliveryFields");function _e(r){T(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}h(_e,"emitDeliveryCompleted");function M(r,t,e,i){T(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}h(M,"emitDeliveryFailure");function R(r,t){T(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}h(R,"emitDeliveryAbandoned");function Ee(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
+
`):""}h(Ee,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(W,"isSessionShutdownReason");function Ie(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(Ie,"disposalReasonForShutdown");function ke(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ke,"boundedRuntimeReason");class xe{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=L();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(o=>o.awaitingDequeue!==void 0))return;const n=C(Ee(i.content)),s=this.pendingHandoffs.find(o=>o.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?Ie(i):"reload";W(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ke(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const o of this.signalUnsubscribers.splice(0))o();const s=n;{const o=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of o)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),V()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(ye,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<ge)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;D(n,{op:"record",input:{link:"daemon\u2192node",op:H,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&te(t).then(e=>e.fault?.op===H?D(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&me())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new B(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof B)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(re()){this.waitingForStartup||(this.waitingForStartup=!0,se(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),P()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await Z(t,"wake",this.reportBodies)}catch(a){throw S(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let o=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ne(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?y.fresh(d=>{this.pendingHandoffs.push({...x([a.entry],"visible"),operationId:d,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),o=!0))}return o&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||q()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),o=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),a=this.isIdle()&&o.length>0&&o.every(l=>l.tier==="deferred"),f=this.visibleRoute(i)==="critical",d=!a&&!f&&e.length>0,c=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(d)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await ee(t)).situational_card}catch(o){this.raiseSituationalFatal(n,o)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...K(n));return i}digest(t,e){try{return Y(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let o;try{o=x(e,t)}catch(d){this.raiseReadFatal(n,d)}let a;try{y.fresh(d=>{a=d,E({level:"info",event:"inbox.delivery.started",operation_id:d,fields:b(o)}),i()})}catch(d){return a===void 0&&this.raiseReadFatal(n,d),M(a,o,"send",d),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...o,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,o){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(d=>d.entry_id)}),i.forEach((d,c)=>{const l=s&&c===i.length-1;this.pi.sendMessage({customType:F,content:d,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},o,f)}sendVisible(t,e,i,n,s,o){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:F,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(de(i,n),s==="idle"){const a=ce();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},o,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(o=>e.has(o.entry_id)),n=new Set(i.map(o=>o.entry_id)),s=this.buffer.filter(o=>!n.has(o.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const d of e.visibleEntries)n.add(d.entry_id);for(const d of e.hiddenEntries)n.add(d.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id))};if(this.runNode&&s==="steer"){let d=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(d=p)});const c=e.visibleEntries.slice(0,d+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(c,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const $=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)$.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const o=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=o;for(const d of f)for(const c of d.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const d=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,d,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const d=this.sendVisible(a.entries,a.cards,a.text,we(a),s,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await le(t,a.text).catch(()=>{}),fe(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||q())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const o of i)await this.sendPromptJoinDelivery(t,"visible",o.entries,[...o.cards,o.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(f){this.raiseReadFatal("poll",f)}let o;try{await y.fresh(async f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const d of n)await t.sendCustomMessage({customType:F,content:d,display:!0})})}catch(f){throw o===void 0&&this.raiseReadFatal("poll",f),M(o,s,"send",f),f}o===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:o,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Q(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const o of e.receipts){const a=s.results.find(f=>f.delivery_id===o.delivery_id);if(a?.outcome!==o.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(o=>o.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const o of e.handoffs)M(o.operationId,o,"receipt_commit",s);return O({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ie(t,s),P()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(o=>!s.has(o.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(o=>!this.claims.has(o)));for(const s of n)i&&_e(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ae(),o=new Set(this.buffer.map(l=>l.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),f=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!a.has(m))),d=new Set(f.flatMap(l=>[...l.entryIds])),c=[...this.claims.keys()].filter(l=>s||d.has(l)&&!o.has(l));return c.length===0?"settled":(this.pendingCommit={handoffs:f,entryIds:c,receipts:c.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Se(r,t){v?.dispose("reload",!1);const e=new xe(r,t,++be);v=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[pe]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(Se,"installWatcher");function Ce(r){const t=Se(r,ve());return()=>t.dispose("shutdown",!1)}h(Ce,"registerCanvasInboxWatcher");var Ge=Ce;export{Ge as default,Ce as registerCanvasInboxWatcher};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.731",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.731",
|
|
162
|
+
"@north-light/plugin": "0.3.731",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -55,6 +55,17 @@ export function isDaemonTransportApiError(error) {
|
|
|
55
55
|
|| error.code === 'northlight_unreachable')) || (error.status === 504 && (error.code === 'request_timeout' || error.code === 'deadline_exceeded'))
|
|
56
56
|
|| (error.status >= 500 && error.code === 'daemon_health_unavailable');
|
|
57
57
|
}
|
|
58
|
+
/** A daemon answer that says nothing about the caller's data: the daemon was unreachable, starting, draining for a
|
|
59
|
+
* restart (503 `startup_blocked`), overloaded, or failed server-side. Retrying the same request later can succeed, so a
|
|
60
|
+
* long-lived caller (a broker's inbox poll) retries it rather than treating it as corrupt state. A 4xx other than
|
|
61
|
+
* 408/429 is about the request itself and is not transient. */
|
|
62
|
+
export function isTransientDaemonApiError(error) {
|
|
63
|
+
if (!(error instanceof APIError))
|
|
64
|
+
return false;
|
|
65
|
+
const { status, code, retryable } = error;
|
|
66
|
+
return isDaemonTransportApiError(error) || retryable === true || code === 'startup_blocked'
|
|
67
|
+
|| status === 408 || status === 429 || status >= 500;
|
|
68
|
+
}
|
|
58
69
|
/** The daemon refused the caller's node token. A teardown revokes the broker's token before its process stops, so a broker
|
|
59
70
|
* that sees this on a poll is being shut down, not hitting a corrupt state. */
|
|
60
71
|
export function isTokenRevokedApiError(error) {
|
|
@@ -88,6 +88,7 @@ export async function beginExecution(nodeId, input) {
|
|
|
88
88
|
if (superseded.changes > 0)
|
|
89
89
|
await clearPendingParkIn(db, nodeId);
|
|
90
90
|
await revokeNodeTokens(db, 'node_id', nodeId, at);
|
|
91
|
+
await db.prepare('UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL').run(nodeId);
|
|
91
92
|
const executionId = randomUUID();
|
|
92
93
|
const attempt = input.attempt ?? Number((await db.prepare('SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?').get(nodeId)).next);
|
|
93
94
|
await db.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)")
|
|
@@ -454,10 +454,10 @@ export async function resolveRef(ref) {
|
|
|
454
454
|
ts: messages[messages.length - 1]?.ts ?? node.created,
|
|
455
455
|
nodeName: node.name,
|
|
456
456
|
body: rendered,
|
|
457
|
-
raw:
|
|
457
|
+
raw: async () => {
|
|
458
458
|
const { header, entries } = await conversationStore().read(conversationIdFromPath(file));
|
|
459
459
|
return [header, ...entries].map((entry) => `${JSON.stringify(entry)}\n`).join('');
|
|
460
|
-
}
|
|
460
|
+
},
|
|
461
461
|
path: file,
|
|
462
462
|
};
|
|
463
463
|
}
|
|
@@ -472,7 +472,7 @@ export async function resolveRef(ref) {
|
|
|
472
472
|
ts: msg.ts,
|
|
473
473
|
nodeName: node.name,
|
|
474
474
|
body: msg.text,
|
|
475
|
-
raw:
|
|
475
|
+
raw: () => rawSessionLine(file, index),
|
|
476
476
|
path: file,
|
|
477
477
|
};
|
|
478
478
|
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 33;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -265,8 +265,13 @@ export function createRowStore() {
|
|
|
265
265
|
lines.shift();
|
|
266
266
|
return { header, entries: entriesOf(lines.join('\n')), path };
|
|
267
267
|
}
|
|
268
|
-
|
|
269
|
-
|
|
268
|
+
// Line by line: a conversation over V8's string limit (~512 MB) cannot be decoded as one string.
|
|
269
|
+
if (!window || size <= window.head + window.tail) {
|
|
270
|
+
const entries = [];
|
|
271
|
+
for await (const line of linesOf(snap))
|
|
272
|
+
entries.push(...entriesOf(line));
|
|
273
|
+
return { header, entries, path };
|
|
274
|
+
}
|
|
270
275
|
const front = (await bytesOf(snap, 0, Math.max(0, window.head))).toString('utf8').split('\n');
|
|
271
276
|
front.pop();
|
|
272
277
|
// One byte before the tail window says whether it begins on a line boundary.
|
|
@@ -7,7 +7,10 @@ export const STARTER_SETUP_SCRIPT = `#!/usr/bin/env bash
|
|
|
7
7
|
# How it runs
|
|
8
8
|
# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.
|
|
9
9
|
# - Your repositories are already checked out at /work/<repo name> before this runs.
|
|
10
|
-
# - The sandbox user is "crtr"
|
|
10
|
+
# - The sandbox user is "crtr". Files you create for it must be chowned to it. A node runs with HOME set to its app's home
|
|
11
|
+
# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.
|
|
12
|
+
# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,
|
|
13
|
+
# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.
|
|
11
14
|
# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
|
|
12
15
|
# or install at build time below.
|
|
13
16
|
# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
|
|
@@ -30,6 +30,9 @@ export const RUN_USER_NPMRC = [
|
|
|
30
30
|
'//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}',
|
|
31
31
|
`store-dir=/home/${RUN_USER}/.local/share/pnpm/store`,
|
|
32
32
|
];
|
|
33
|
+
/** A node runs with HOME set to its app's home (`/var/lib/crtr/apps/<app>/home`), not `/home/crtr`, so npm and pnpm would never read the npmrc above;
|
|
34
|
+
* this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
|
|
35
|
+
export const RUN_USER_NPMRC_ENV = `ENV NPM_CONFIG_USERCONFIG=/home/${RUN_USER}/.npmrc`;
|
|
33
36
|
const writeRunUserNpmrc = () => `printf '%s\\n' ${RUN_USER_NPMRC.map((l) => `'${l}'`).join(' ')} > /home/${RUN_USER}/.npmrc`;
|
|
34
37
|
export const REPOS_DIR = 'repos';
|
|
35
38
|
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
@@ -93,7 +96,7 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
|
|
|
93
96
|
// A setup script may have written a resolved token into an npmrc; the run user's npmrc is rewritten to the token-free lines.
|
|
94
97
|
if (packagesToken)
|
|
95
98
|
out.push('RUN rm -f /work/.npmrc', `RUN ${writeRunUserNpmrc()} && chown ${RUN_USER}:${RUN_USER} /home/${RUN_USER}/.npmrc`);
|
|
96
|
-
out.push(`USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
|
|
99
|
+
out.push(RUN_USER_NPMRC_ENV, `USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
|
|
97
100
|
return out.join('\n');
|
|
98
101
|
}
|
|
99
102
|
const runGit = (args, env, cwd) => new Promise((resolve, reject) => {
|
|
@@ -3,6 +3,15 @@
|
|
|
3
3
|
// on the Blaxel runner deletes the sandbox). Every path that deletes node rows calls this first.
|
|
4
4
|
import { afterCommit, openDb, withCanvasWrite } from '../../canvas/db.js';
|
|
5
5
|
import { emitEvent } from '../../events/emit.js';
|
|
6
|
+
/** A launch that has not reached `running` in this long never will: its row no longer keeps the node's sandbox. */
|
|
7
|
+
export const STALE_LAUNCH_MS = 60 * 60_000;
|
|
8
|
+
/** SQL true when node `n` has an execution that still holds its sandbox: a running one, or a launch younger than {@link STALE_LAUNCH_MS}.
|
|
9
|
+
* Binds one parameter, the stale-launch cutoff as an ISO time. */
|
|
10
|
+
const OPEN_EXECUTION = `EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id
|
|
11
|
+
AND (x.state = 'running' OR (x.state = 'launching' AND x.started_at > ?)))`;
|
|
12
|
+
function staleLaunchCutoff(now = Date.now()) {
|
|
13
|
+
return new Date(now - STALE_LAUNCH_MS).toISOString();
|
|
14
|
+
}
|
|
6
15
|
/** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
|
|
7
16
|
* those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
|
|
8
17
|
export async function deleteNodeSandboxes(nodeIds) {
|
|
@@ -23,18 +32,57 @@ export async function deleteNodeSandboxes(nodeIds) {
|
|
|
23
32
|
return failed;
|
|
24
33
|
}
|
|
25
34
|
/** A node that finished, was canceled or died keeps its sandbox only while a broker still runs in it or a standing cron is anchored to it
|
|
26
|
-
* (its fires run there). Called after each of those ends; a failure is left to the
|
|
27
|
-
* wake mail reopens it in the same sandbox.
|
|
28
|
-
* takes, so no new execution can start in
|
|
35
|
+
* (its fires run there). Called after each of those ends; a failure is left to the retention pass. A parked node is not ended:
|
|
36
|
+
* wake mail reopens it in the same sandbox. A launch stuck in `launching` past {@link STALE_LAUNCH_MS} does not hold the sandbox.
|
|
37
|
+
* The check and the DELETE run holding the node row's lock, which `beginExecution` also takes, so no new execution can start in
|
|
38
|
+
* the sandbox between them. */
|
|
29
39
|
export function deleteSandboxOfEndedNode(nodeId) {
|
|
30
40
|
afterCommit(() => void withCanvasWrite(async (db) => {
|
|
31
41
|
const ended = await db.prepare(`SELECT 1 AS ended FROM nodes n WHERE n.node_id = ?
|
|
32
42
|
AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
|
|
33
43
|
AND (n.status IN ('canceled', 'dead') OR (n.status = 'done' AND n.intent IS DISTINCT FROM 'parked'))
|
|
34
|
-
AND NOT
|
|
44
|
+
AND NOT ${OPEN_EXECUTION}
|
|
35
45
|
AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
|
|
36
|
-
FOR UPDATE OF n`).get(nodeId);
|
|
37
|
-
if (ended
|
|
38
|
-
|
|
46
|
+
FOR UPDATE OF n`).get(nodeId, staleLaunchCutoff());
|
|
47
|
+
if (ended === undefined)
|
|
48
|
+
return;
|
|
49
|
+
await (await import('./index.js')).runnerForExecution('blaxel').delete(nodeId);
|
|
50
|
+
await db.prepare('UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?').run(new Date().toISOString(), nodeId);
|
|
39
51
|
}).catch((error) => { emitEvent({ level: 'error', event: 'canvas.node_sandbox.delete_failed', node_id: nodeId, error }); }));
|
|
40
52
|
}
|
|
53
|
+
/** Delete the sandbox of every finished, canceled, dead or parked node quiet for `quietMs`, keeping its rows; app runs included.
|
|
54
|
+
* `quiet` decides the activity test ({@link lastActivityMs} reads disk too); `held` excludes nodes retention must not touch.
|
|
55
|
+
* Each node is marked `sandbox_deleted_at` so later passes skip it until a new execution clears the mark. Returns the deleted count. */
|
|
56
|
+
export async function deleteQuietNodeSandboxes(opts) {
|
|
57
|
+
const cutoff = staleLaunchCutoff(opts.now);
|
|
58
|
+
const candidates = await (await openDb()).prepare(`SELECT n.node_id FROM nodes n WHERE n.status IN ('done', 'canceled', 'dead')
|
|
59
|
+
AND n.sandbox_deleted_at IS NULL
|
|
60
|
+
AND EXISTS (SELECT 1 FROM executions x WHERE x.node_id = n.node_id AND x.runner = 'blaxel')
|
|
61
|
+
AND NOT ${OPEN_EXECUTION}
|
|
62
|
+
AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)`).all(cutoff);
|
|
63
|
+
let deleted = 0;
|
|
64
|
+
for (const { node_id } of candidates) {
|
|
65
|
+
if (!await opts.quiet(node_id) || await opts.held(node_id))
|
|
66
|
+
continue;
|
|
67
|
+
try {
|
|
68
|
+
const done = await withCanvasWrite(async (db) => {
|
|
69
|
+
// Re-check under the node lock `beginExecution` takes, so no execution starts in the sandbox while it is deleted.
|
|
70
|
+
const still = await db.prepare(`SELECT 1 AS ok FROM nodes n WHERE n.node_id = ? AND n.status IN ('done', 'canceled', 'dead')
|
|
71
|
+
AND n.sandbox_deleted_at IS NULL AND NOT ${OPEN_EXECUTION}
|
|
72
|
+
AND NOT EXISTS (SELECT 1 FROM crons c WHERE c.anchor_node = n.node_id AND c.cancel_on_wake = 0)
|
|
73
|
+
FOR UPDATE OF n`).get(node_id, cutoff);
|
|
74
|
+
if (still === undefined)
|
|
75
|
+
return false;
|
|
76
|
+
await (await import('./index.js')).runnerForExecution('blaxel').delete(node_id);
|
|
77
|
+
await db.prepare('UPDATE nodes SET sandbox_deleted_at = ? WHERE node_id = ?').run(new Date().toISOString(), node_id);
|
|
78
|
+
return true;
|
|
79
|
+
});
|
|
80
|
+
if (done)
|
|
81
|
+
deleted++;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
emitEvent({ level: 'error', event: 'canvas.node_sandbox.delete_failed', node_id, error });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return deleted;
|
|
88
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.731",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.731",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.731",
|
|
31
|
+
"@north-light/identity": "0.3.731"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.731",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.731",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.731",
|
|
32
|
+
"@north-light/plugin": "0.3.731",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.731",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.731",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.731",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.731",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.731",
|
|
11927
|
+
"@north-light/identity": "0.3.731"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.731",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.731",
|
|
11936
|
+
"@north-light/identity": "0.3.731",
|
|
11937
|
+
"@north-light/plugin": "0.3.731",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|