@north-light/cli 0.3.599 → 0.3.600

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.
@@ -0,0 +1,2 @@
1
+ /** Refuse, naming both generations, when this CLI runs from an installed generation and the live local daemon runs another, or predates reporting one. Remote targets and source checkouts are not compared: a CLI with no generation is skipped, and so is a daemon that reports `generation_id: null`. */
2
+ export declare function assertLocalDaemonMatchesCli(): Promise<void>;
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var i=(n,t)=>a(n,"name",{value:t,configurable:!0});import{cliClient as s,moveUnfinished as d,remoteTarget as m}from"./api-client.js";import{CrtrError as u}from"../core/errors.js";import{ExitCode as c}from"../types.js";import{processGeneration as f,readPackageVersion as o}from"./sys/shared.js";async function v(){const n=f();if(n===null)return;const t=d();if(t!==void 0)throw t;if(m()!==void 0)return;const e=await s().status();if(e.generation_id===null||e.generation_id===n.id)return;const r=e.generation_id;throw new u("daemon_generation_mismatch",`this crtr is generation ${n.id} (${o()}), but the running crtrd is ${r===void 0?"too old to report its generation":`generation ${r}`} (${e.runtime_version})`,c.NETWORK,{cli_generation:n.id,cli_version:o(),daemon_generation:r??null,daemon_version:e.runtime_version,next:"Run `crtr sys daemon restart` to move the daemon onto this generation."})}i(v,"assertLocalDaemonMatchesCli");export{v as assertLocalDaemonMatchesCli};
@@ -0,0 +1,19 @@
1
+ -- 013-grant-removal-reset.sql — a grant's removal cascade is owed again whenever the grant changes. One transaction, additions only:
2
+ -- `schema_min_reader` is not touched, so the previous release (version 11) still opens the result. It never names the trigger, and
3
+ -- the trigger changes no column that release reads.
4
+ --
5
+ -- `removal_done_at` says "the removal cascade for this removal has run" and is crouter's alone (design-fleet "Data model"). The
6
+ -- directory re-approves a removed grant under the same `id` (rev + 1, status active) and removes it again, writing only `rev` and
7
+ -- `status`; nothing cleared the mark, so the second removal never cascaded and the app's node was relaunched forever. Clearing it
8
+ -- here, in the row, covers every writer: the directory, grant sync, and a re-add that no sync ever saw active. A writer that sets
9
+ -- `removal_done_at` itself (the cascade's completion) is left alone.
10
+ CREATE FUNCTION crtr_grant_removal_reset() RETURNS trigger LANGUAGE plpgsql AS $$
11
+ BEGIN
12
+ IF NEW.removal_done_at IS NOT DISTINCT FROM OLD.removal_done_at
13
+ AND (NEW.rev IS DISTINCT FROM OLD.rev OR NEW.status IS DISTINCT FROM OLD.status) THEN
14
+ NEW.removal_done_at := NULL;
15
+ END IF;
16
+ RETURN NEW;
17
+ END $$;
18
+ CREATE TRIGGER crtr_grant_removal_reset BEFORE UPDATE ON grants
19
+ FOR EACH ROW EXECUTE FUNCTION crtr_grant_removal_reset();
@@ -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 = 12;
4
+ export declare const CANVAS_SCHEMA_VERSION = 13;
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=12;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=13;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};
@@ -101,6 +101,7 @@ export declare function grantRecord(grantId: string): Promise<GrantRecord | null
101
101
  * even when its computed columns lag; all are null when the row is gone. */
102
102
  export interface GrantStanding {
103
103
  standing: 'active' | 'inactive' | 'lagging';
104
+ rev: number | null;
104
105
  sub: string | null;
105
106
  grantee: string | null;
106
107
  status: GrantRecord['status'] | null;
@@ -1,11 +1,10 @@
1
- var w=Object.defineProperty;var t=(e,r)=>w(e,"name",{value:r,configurable:!0});import{createHash as O}from"node:crypto";import{parseScope as h}from"@north-light/identity";import{openDb as d,withCanvasWrite as m}from"../canvas/db.js";import{isUnsandboxedMachine as j}from"../runtime/unsandboxed.js";import{replaceWrittenBy as A,userSubject as b}from"../permissions/facts.js";import{GROUP_TYPE as R}from"../permissions/builtin.js";const D=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function I(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(I,"runtimeScope");async function i(e,r,n=[]){const s=I();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE ${r}${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function L(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!D.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(L,"dependencyOf");function E(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=L(s);a&&(r[n]=a)}return r}t(E,"dependenciesOf");function C(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of k){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(C,"inferenceEndpointOf");function _(e){if(e.computed_rev!==e.rev||e.scopes_json===null||e.resolved_scopes_json===null)throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:E(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?C(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(_,"record");function p(e){if(!e||e.status!=="active")return null;try{return $(_(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(p,"active");function g(e){return e.grantee!=="app:terminal"&&j()}t(g,"mirrorOnly");async function Y(){return(await G()).filter(e=>!g(e))}t(Y,"localGrants");const x="[A-Za-z0-9_-]{1,64}",M=new RegExp(`^(${x}):(${x})$`);function F(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=M.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(F,"providerIdsFromGrants");async function Z(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(F(r.flatMap(n=>{try{return[_(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(Z,"grantedProviderIds");function K(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(K,"isProviderBundleRow");async function Q(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=p(n);return s===null?[]:[s]})}t(Q,"activeGrantsOfPerson");async function G(){return(await i("*","true")).flatMap(e=>{try{return[_(e)]}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return[];throw r}})}t(G,"allGrants");function U(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(U,"grantExpired");function $(e){if(e.status!=="active"||U(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>h(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t($,"activeRecord");function v(e){return Array.isArray(e)?`[${e.map(v).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${v(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(v,"canonicalJson");function ee(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return O("sha256").update(v(r)).digest("base64url").slice(0,22)}t(ee,"grantVersion");async function re(e){return!!await u("1","id = ?",[e])}t(re,"hasGrant");async function ne(e){return await u("rev, status","id = ?",[e])??null}t(ne,"grantSyncState");async function te(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(te,"grantSyncStateFor");async function H(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return _(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(H,"grantRecord");async function se(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=p(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(se,"grantStanding");async function ae(e){return(await i("id",e)).map(r=>r.id)}t(ae,"grantIdsWhere");async function oe(e){return(e?(await H(e))?.payer:null)??"user"}t(oe,"payerOfGrant");async function W(e){return p(await u("*","id = ?",[e]))}t(W,"activeGrant");async function ce(e,r){return p(await u("*","grantee = ? AND sub = ?",[e,r]))}t(ce,"grantFor");async function ie(e){if(g({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}t(ie,"activeGrantForApp");async function ue(e){const r=await W(e);return r&&r.run_notice_url&&!g(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(ue,"runNoticeTarget");async function pe(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}t(pe,"terminalGrant");async function de(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(de,"grantsSource");async function le(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(le,"hasSyncedGrants");async function _e(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(_e,"dropLocalGrantMirror");async function fe(){return await m(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(fe,"backfillComputedRev");function ye(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(ye,"teamsOf");async function ge(e,r,n,s=[]){const a=new Set;for(const o of e){if(a.has(o.id)||!o.id||!o.runtime||!o.sub||!o.grantee||!Number.isInteger(o.rev)||!["active","revoked","removed"].includes(o.status))throw new TypeError("invalid grant sync response");a.add(o.id),l(o.scopes),l(o.resolved_scopes)}await m(async o=>{let f=0;const y=[...a];f+=Number((await(y.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${y.map(()=>"?").join(",")})`).run(...y):o.prepareUncached("DELETE FROM grants").run())).changes);const S=o.prepare(`INSERT INTO grants
1
+ var N=Object.defineProperty;var t=(e,r)=>N(e,"name",{value:r,configurable:!0});import{createHash as O}from"node:crypto";import{parseScope as h}from"@north-light/identity";import{openDb as d,withCanvasWrite as m}from"../canvas/db.js";import{isUnsandboxedMachine as j}from"../runtime/unsandboxed.js";import{replaceWrittenBy as A,userSubject as b}from"../permissions/facts.js";import{GROUP_TYPE as R}from"../permissions/builtin.js";const D=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function I(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(I,"runtimeScope");async function c(e,r,n=[]){const s=I();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE ${r}${s.sql}`).all(...n,...s.args)}t(c,"grantRows");async function u(e,r,n=[]){return(await c(e,r,n))[0]}t(u,"grantRow");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function L(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!D.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(L,"dependencyOf");function x(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=L(s);a&&(r[n]=a)}return r}t(x,"dependenciesOf");function C(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of k){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(C,"inferenceEndpointOf");function f(e){if(e.computed_rev!==e.rev||e.scopes_json===null||e.resolved_scopes_json===null)throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:x(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?C(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function p(e){if(!e||e.status!=="active")return null;try{return $(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(p,"active");function g(e){return e.grantee!=="app:terminal"&&j()}t(g,"mirrorOnly");async function Y(){return(await G()).filter(e=>!g(e))}t(Y,"localGrants");const E="[A-Za-z0-9_-]{1,64}",M=new RegExp(`^(${E}):(${E})$`);function F(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=M.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(F,"providerIdsFromGrants");async function Z(e){const r=await c("*","sub = ? AND status = 'active'",[e]);return new Set(F(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(Z,"grantedProviderIds");function K(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(K,"isProviderBundleRow");async function Q(e){return(await c("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=p(n);return s===null?[]:[s]})}t(Q,"activeGrantsOfPerson");async function G(){return(await c("*","true")).flatMap(e=>{try{return[f(e)]}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return[];throw r}})}t(G,"allGrants");function U(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(U,"grantExpired");function $(e){if(e.status!=="active"||U(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>h(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t($,"activeRecord");function v(e){return Array.isArray(e)?`[${e.map(v).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${v(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(v,"canonicalJson");function ee(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return O("sha256").update(v(r)).digest("base64url").slice(0,22)}t(ee,"grantVersion");async function re(e){return!!await u("1","id = ?",[e])}t(re,"hasGrant");async function ne(e){return await u("rev, status","id = ?",[e])??null}t(ne,"grantSyncState");async function te(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(te,"grantSyncStateFor");async function P(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(P,"grantRecord");async function se(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=p(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(se,"grantStanding");async function ae(e){return(await c("id",e)).map(r=>r.id)}t(ae,"grantIdsWhere");async function oe(e){return(e?(await P(e))?.payer:null)??"user"}t(oe,"payerOfGrant");async function W(e){return p(await u("*","id = ?",[e]))}t(W,"activeGrant");async function ie(e,r){return p(await u("*","grantee = ? AND sub = ?",[e,r]))}t(ie,"grantFor");async function ce(e){if(g({grantee:e}))return null;const r=await c("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}t(ce,"activeGrantForApp");async function ue(e){const r=await W(e);return r&&r.run_notice_url&&!g(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(ue,"runNoticeTarget");async function pe(e){const r=await c("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}t(pe,"terminalGrant");async function de(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(de,"grantsSource");async function le(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(le,"hasSyncedGrants");async function fe(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(fe,"dropLocalGrantMirror");async function _e(){return await m(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(_e,"backfillComputedRev");function ye(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(ye,"teamsOf");async function ge(e,r,n,s=[]){const a=new Set;for(const o of e){if(a.has(o.id)||!o.id||!o.runtime||!o.sub||!o.grantee||!Number.isInteger(o.rev)||!["active","revoked","removed"].includes(o.status))throw new TypeError("invalid grant sync response");a.add(o.id),l(o.scopes),l(o.resolved_scopes)}await m(async o=>{let _=0;const y=[...a];_+=Number((await(y.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${y.map(()=>"?").join(",")})`).run(...y):o.prepareUncached("DELETE FROM grants").run())).changes);const S=o.prepare(`INSERT INTO grants
2
2
  (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
3
3
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, rev = excluded.rev,
6
6
  scopes_json = excluded.scopes_json, resolved_scopes_json = excluded.resolved_scopes_json, spend_cap = excluded.spend_cap,
7
7
  expires_at = excluded.expires_at, status = excluded.status, revoked_at = excluded.revoked_at, approved_at = excluded.approved_at,
8
- removal_done_at = CASE WHEN excluded.status = 'removed' AND grants.status = 'removed' THEN grants.removal_done_at END,
9
8
  payer = excluded.payer, dependencies_json = excluded.dependencies_json, run_notice_url = excluded.run_notice_url,
10
9
  inference_endpoint_json = excluded.inference_endpoint_json, synced_at = excluded.synced_at, computed_rev = excluded.computed_rev
11
10
  WHERE (grants.runtime, grants.sub, grants.grantee, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
@@ -13,4 +12,4 @@ var w=Object.defineProperty;var t=(e,r)=>w(e,"name",{value:r,configurable:!0});i
13
12
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
14
13
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
15
14
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
16
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)f+=Number((await S.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(E(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await A(o,"directory",R,"member",s.flatMap(({team:c,members:T})=>T.map(N=>({resourceId:c,subject:b(N)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),f>0&&await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(ge,"replaceGrants");async function ve(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(ve,"grantsGeneration");export{W as activeGrant,ie as activeGrantForApp,Q as activeGrantsOfPerson,$ as activeRecord,G as allGrants,fe as backfillComputedRev,E as dependenciesOf,_e as dropLocalGrantMirror,U as grantExpired,ce as grantFor,ae as grantIdsWhere,H as grantRecord,se as grantStanding,ne as grantSyncState,te as grantSyncStateFor,ee as grantVersion,Z as grantedProviderIds,ve as grantsGeneration,de as grantsSource,re as hasGrant,le as hasSyncedGrants,C as inferenceEndpointOf,K as isProviderBundleRow,Y as localGrants,g as mirrorOnly,oe as payerOfGrant,F as providerIdsFromGrants,ge as replaceGrants,ue as runNoticeTarget,ye as teamsOf,pe as terminalGrant};
15
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const i of e)_+=Number((await S.run(i.id,i.runtime,i.sub,i.grantee,i.rev,JSON.stringify(i.scopes),JSON.stringify(i.resolved_scopes),i.spend_cap,i.expires_at,i.status,i.revoked_at,i.approved_at,i.payer,JSON.stringify(x(i.dependencies)),i.run_notice_url??null,i.inference_endpoint?JSON.stringify(i.inference_endpoint):null,i.synced_at,i.rev)).changes);await A(o,"directory",R,"member",s.flatMap(({team:i,members:T})=>T.map(w=>({resourceId:i,subject:b(w)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),_>0&&await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(ge,"replaceGrants");async function ve(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(ve,"grantsGeneration");export{W as activeGrant,ce as activeGrantForApp,Q as activeGrantsOfPerson,$ as activeRecord,G as allGrants,_e as backfillComputedRev,x as dependenciesOf,fe as dropLocalGrantMirror,U as grantExpired,ie as grantFor,ae as grantIdsWhere,P as grantRecord,se as grantStanding,ne as grantSyncState,te as grantSyncStateFor,ee as grantVersion,Z as grantedProviderIds,ve as grantsGeneration,de as grantsSource,re as hasGrant,le as hasSyncedGrants,C as inferenceEndpointOf,K as isProviderBundleRow,Y as localGrants,g as mirrorOnly,oe as payerOfGrant,F as providerIdsFromGrants,ge as replaceGrants,ue as runNoticeTarget,ye as teamsOf,pe as terminalGrant};
@@ -1,3 +1,3 @@
1
- var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as U}from"node:fs";import{conversationIdFromPath as _,conversationStore as h,ConversationNotFoundError as H}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as N,beginExecution as me,ExecutionAlreadyLive as de,recordExecutionPid as he,abortExecution as F,endLiveExecution as pe,unbindSession as G,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as $e}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineLaunchUncertainError as Be,MachineOfflineError as De}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as Y}from"./blaxel-environment.js";import{recordLaunchFailure as Me}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as q,remoteMachineEnvironmentOf as Te,checkBilledWake as Le,EnvironmentImagePending as ze,imageForWake as Ue}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as He,liveExecutionForNode as Ge,setExecutionLaunchJson as Ke}from"../canvas/executions.js";import{isDrained as We}from"../../daemon/drain.js";import{appMemoryFull as Je,appMemoryTooSmall as je,boundFleet as Q,brokerCapReached as Z,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Ve}from"./memory-admission.js";import{beginBootFaultAttempt as Xe,clearFault as Ye,hasAdmittedTurn as qe,readFault as Qe}from"../canvas/recovery.js";import{clearNodeLedger as I,forkNodeLedger as Ze,noticeChangedWhileDone as Ie}from"./ledger.js";import{forkSourceNode as er,rootOfSpine as rr}from"./nodes.js";import{ApiError as ir}from"../../api/errors.js";import{grantSnapshotMissing as tr}from"../../daemon/readiness.js";import{checkStart as nr}from"./start-check.js";import{isReviewCompanionBound as ar}from"../review/companion.js";import{assertProfileActive as or}from"../profiles/manifest.js";import{isPidAlive as sr}from"../canvas/pid.js";import{crtrHome as lr,jobDir as cr}from"../canvas/paths.js";import{contextDir as ur,ensureNodeDirs as fr,nodeAgentDir as wr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as mr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as dr}from"../command-hooks/transport/exec-lifecycle.js";async function hr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await h().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof H)return{};throw a}}s(hr,"resumeArgs");async function ee(e){const r=_(e);if(r===null)return!1;try{return await h().header(r),!0}catch(i){if(i instanceof H)return!1;throw i}}s(ee,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await h().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function vr(e){const r=_(e);if(r===null)return!0;const i=(await h().header(r)).header.cwd;return typeof i!="string"||U(i)}s(vr,"sessionCwdExists");async function _r(e,r,i,t){const a=r.pi_session_file;if(!a||!await ee(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&sr(u.pi_pid)?{}:t&&!await vr(a)?{}:await hr(r,i)}s(_r,"resumableSessionArgs");async function yr(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(yr,"isUnstartedBirth");async function fi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await re(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function mi(e,r,i){return re(e,{...r,viewerAttach:!0},i)}s(mi,"decideAttachRevive");async function re(e,r,i){const t=Ae()?await R(e):null;return t===null?await ie(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ie(e,r,i))}s(re,"decideRevive");async function ie(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);or(t.profile_id),ue(t.grantee);const a=Q(),u=t.grantee==="app:terminal"&&await tr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await nr(t),await Y(t.profile_id??null)!==null&&await Le(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new ir(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await te(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await We();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const p=!k&&await a.reserveSlot(e);let o=null;if(p){try{o=await Ve(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw je(o);if(!p||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Je(o):Z(P().automaticReviveCap,await a.occupancy());return await te(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{a.releaseReservation(e)}}s(ie,"decideReviveAsCaller");async function te(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await pe(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(te,"freezeForWait");async function kr(e,r){const i=await Y(r.profile_id??null),t=await Te(r.profile_id??null)!==null;if(!(i!==null||t)&&!U(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(kr,"assertRecordedCwdExists");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await kr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await N(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await ar(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await G(e),r.pi_session_id=null,r.pi_session_file=null);const p=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(p&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=p&&typeof o=="string";if(w&&!await ee(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ne}=P();if(t!==null){const l=await Ue(t);if(l.state==="pending")throw new ze(t,l.error)}const ae=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Q().epoch(),cap:ne,...t!==null?{runner:"blaxel",release:q()}:a?{runner:"machine",release:q()}:{}})}catch(l){if(l instanceof He)throw Z(l.cap,l.live);if(l instanceof de)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await N(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await _r(e,r,x,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await yr(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await qe(e)&&!await pr(d.resumeSessionPath)?(await E(e))?.trim():void 0,M=S!==void 0&&S!=="",oe=w||D||M,T=r.cycle_pending===!0||B;await N(e,{cycle_pending:T}),r.cycle_pending=T,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await G(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),$=_(o);if($===null)throw new Error(`invalid fork source ${o}`);const le=(await h().header(await h().fork($,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await Ze(e,(await er(o))?.node_id??null)}else if(M)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await I(e)}else{const n=await Re(r,f);c=y(r,{...d,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await I(e)}c.env={...c.env,CRTR_SUBTREE:await rr(e)},m!==null&&(c.env[$e]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Ie(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Qe(e))?.op!=="conversation_write_failed"&&await Ye(e,{preserveEpisode:!0});const L=await Xe(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await fr(e,r.grantee);const se=mr(r.cwd,r.profile_id).plans.get("node:start")??[];await dr(se,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await wr(e),contextDir:await ur(e),jobDir:cr(e)},runtime:{isBirth:oe,canvasHome:lr(),profile:r.profile_id??null}}),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ke(f,z);let b;try{const n=await Ge(e);if(b=await ae.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof De)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
1
+ var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as U}from"node:fs";import{conversationIdFromPath as _,conversationStore as h,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as N,beginExecution as me,ExecutionAlreadyLive as de,recordExecutionPid as he,abortExecution as F,endLiveExecution as pe,unbindSession as H,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as $e}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineLaunchUncertainError as Be,MachineOfflineError as De}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as Y}from"./blaxel-environment.js";import{recordLaunchFailure as Me}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as q,remoteMachineEnvironmentOf as Te,checkBilledWake as Le,EnvironmentImagePending as ze,imageForWake as Ue}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as Ge,liveExecutionForNode as He,setExecutionLaunchJson as Ke}from"../canvas/executions.js";import{isDrained as We}from"../../daemon/drain.js";import{appMemoryFull as Je,appMemoryTooSmall as je,boundFleet as Q,brokerCapReached as Z,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Ve}from"./memory-admission.js";import{beginBootFaultAttempt as Xe,clearFault as Ye,hasAdmittedTurn as qe,readFault as Qe}from"../canvas/recovery.js";import{clearNodeLedger as I,forkNodeLedger as Ze,noticeChangedWhileDone as Ie}from"./ledger.js";import{forkSourceNode as er,rootOfSpine as rr}from"./nodes.js";import{ApiError as ir}from"../../api/errors.js";import{grantSnapshotMissing as tr}from"../../daemon/readiness.js";import{checkGrantActive as nr,checkStart as ar}from"./start-check.js";import{isReviewCompanionBound as or}from"../review/companion.js";import{assertProfileActive as sr}from"../profiles/manifest.js";import{isPidAlive as lr}from"../canvas/pid.js";import{crtrHome as cr,jobDir as ur}from"../canvas/paths.js";import{contextDir as fr,ensureNodeDirs as wr,nodeAgentDir as mr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as dr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const a=await h().header(t);return r?{resumeSessionPath:a.path}:{resumeSessionPath:a.path,newCycle:!0}}catch(a){if(a instanceof G)return{};throw a}}s(pr,"resumeArgs");async function ee(e){const r=_(e);if(r===null)return!1;try{return await h().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(ee,"conversationExists");async function vr(e){const r=_(e);return r===null?!0:(await h().read(r)).entries.some(i=>i.type==="message")}s(vr,"sessionHasConversation");async function _r(e){const r=_(e);if(r===null)return!0;const i=(await h().header(r)).header.cwd;return typeof i!="string"||U(i)}s(_r,"sessionCwdExists");async function yr(e,r,i,t){const a=r.pi_session_file;if(!a||!await ee(a))return{};const u=await we(a);return u!==null&&u.node_id!==e&&lr(u.pi_pid)?{}:t&&!await _r(a)?{}:await pr(r,i)}s(yr,"resumableSessionArgs");async function kr(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(kr,"isUnstartedBirth");async function wi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(wi,"hasFreshGroundState");async function mi(e,r){const i=await re(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(mi,"reviveNode");async function di(e,r,i){return re(e,{...r,viewerAttach:!0},i)}s(di,"decideAttachRevive");async function re(e,r,i){const t=Ae()?await R(e):null;return t===null?await ie(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>ie(e,r,i))}s(re,"decideRevive");async function ie(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);sr(t.profile_id),ue(t.grantee);const a=Q(),u=t.grantee==="app:terminal"&&await tr();if(!await a.has(e)&&!await a.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await nr(t),await ar(t),await Y(t.profile_id??null)!==null&&await Le(t)),await a.has(e))return await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(await a.isClaimed(e))return{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new ir(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await te(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await We();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const p=!k&&await a.reserveSlot(e);let o=null;if(p){try{o=await Ve(e)}catch(w){throw a.releaseReservation(e),w}o.verdict!=="admitted"&&a.releaseReservation(e)}if(o?.verdict==="too_small")throw je(o);if(!p||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Je(o):Z(P().automaticReviveCap,await a.occupancy());return await te(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await a.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await br(e,t,r)}}finally{a.releaseReservation(e)}}s(ie,"decideReviveAsCaller");async function te(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await pe(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(te,"freezeForWait");async function gr(e,r){const i=await Y(r.profile_id??null),t=await Te(r.profile_id??null)!==null;if(!(i!==null||t)&&!U(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(gr,"assertRecordedCwdExists");async function br(e,r,i){const{blaxelEnvironment:t,remoteMachine:a}=await gr(e,r),u=t!==null||a;r.host_kind!=="broker"&&(await N(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await or(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await H(e),r.pi_session_id=null,r.pi_session_file=null);const p=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(p&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=p&&typeof o=="string";if(w&&!await ee(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ne}=P();if(t!==null){const l=await Ue(t);if(l.state==="pending")throw new ze(t,l.error)}const ae=t!==null?X("blaxel"):a?X("machine"):Pe;let f;try{f=await me(e,{daemonEpoch:Q().epoch(),cap:ne,...t!==null?{runner:"blaxel",release:q()}:a?{runner:"machine",release:q()}:{}})}catch(l){if(l instanceof Ge)throw Z(l.cap,l.live);if(l instanceof de)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await N(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,d=w?{}:await yr(e,r,x,!u),g=d.resumeSessionPath!==void 0,B=g&&d.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await kr(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await qe(e)&&!await vr(d.resumeSessionPath)?(await E(e))?.trim():void 0,M=S!==void 0&&S!=="",oe=w||D||M,T=r.cycle_pending===!0||B;await N(e,{cycle_pending:T}),r.cycle_pending=T,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await H(e),r.pi_session_id=null,r.pi_session_file=null);let c,m=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const n=await E(e),$=_(o);if($===null)throw new Error(`invalid fork source ${o}`);const le=(await h().header(await h().fork($,e))).path;c=y(r,{resumeSessionPath:le,...n!=null&&n!==""?{prompt:n}:{}}),n!=null&&n!==""&&(m=C()),await Ze(e,(await er(o))?.node_id??null)}else if(M)c=y(r,{...d,prompt:S}),m=C(),await V(c,r);else if(v)c=y(r,{...d,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(m={type:"runtime",kind:"restart-continuation"});else if(D){const n=(await E(e))?.trim();c=y(r,n!==void 0&&n!==""?{prompt:n}:{}),n!==void 0&&n!==""&&(m=C(),await V(c,r)),await I(e)}else{const n=await Re(r,f);c=y(r,{...d,prompt:await be(r,n,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&n.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(n.unreadMessageIds)),m=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await I(e)}c.env={...c.env,CRTR_SUBTREE:await rr(e)},m!==null&&(c.env[$e]=Ce(m)),r.status==="done"&&r.last_settled_at!=null&&await Ie(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Qe(e))?.op!=="conversation_write_failed"&&await Ye(e,{preserveEpisode:!0});const L=await Xe(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await wr(e,r.grantee);const se=dr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(se,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await mr(e),contextDir:await fr(e),jobDir:ur(e)},runtime:{isBirth:oe,canvasHome:cr(),profile:r.profile_id??null}}),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ke(f,z);let b;try{const n=await He(e);if(b=await ae.start({executionId:f,nodeId:e,attempt:n?.attempt??1,sandboxName:n?.sandboxName??null,release:n?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(n){if(n instanceof De)throw n;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:n instanceof Error?n.message:String(n)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${n.message}
2
2
 
3
- It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await he(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Be||(await F(f,{reason:"launch_failed"}),await Me(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(gr,"launchRevive");export{kr as assertRecordedCwdExists,mi as decideAttachRevive,fi as hasFreshGroundState,hr as resumeArgs,wi as reviveNode};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${n.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await he(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Be||(await F(f,{reason:"launch_failed"}),await Me(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(br,"launchRevive");export{gr as assertRecordedCwdExists,di as decideAttachRevive,wi as hasFreshGroundState,pr as resumeArgs,mi as reviveNode};
@@ -45,6 +45,9 @@ export interface BuildImageOptions {
45
45
  /** Give up after this long in a non-terminal state. Default 20 minutes. */
46
46
  timeoutMs?: number;
47
47
  sleep?: (ms: number) => Promise<void>;
48
+ /** How long after Blaxel reports BUILT to keep waiting for a tag this build created before taking an existing one as reused. Default 60 seconds. */
49
+ tagGraceMs?: number;
50
+ now?: () => number;
48
51
  }
49
52
  interface ImageDoc {
50
53
  metadata?: {
@@ -52,6 +55,7 @@ interface ImageDoc {
52
55
  events?: Array<{
53
56
  message?: string;
54
57
  status?: string;
58
+ time?: string;
55
59
  }>;
56
60
  };
57
61
  spec?: {
@@ -1,5 +1,5 @@
1
- var T=Object.defineProperty;var p=(t,e)=>T(t,"name",{value:e,configurable:!0});import{spawn as O}from"node:child_process";import{constants as L,lstatSync as v,mkdirSync as B,readFileSync as D,readdirSync as A,readlinkSync as P,rmSync as C,writeFileSync as R}from"node:fs";import{join as I,relative as G}from"node:path";import{crc32 as M,deflateRawSync as F}from"node:zlib";import{BlaxelApiError as j}from"./client.js";const Y="public.ecr.aws/docker/library/node:24-alpine",z="ghcr.io/blaxel-ai/sandbox:latest",E="crtr",y="/var/lib/crtr/recipe-pi-agent",K="1.1.0",U="recipe-setup.sh",$="repos",J=p(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),H=p(t=>(t??"").split(`
2
- `).map(e=>e.trim()).filter(e=>e!==""),"lines");function V(t,e){const s=H(t.pi_packages),n=[`FROM ${Y}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${z} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${E} -s /bin/sh ${E} && mkdir -p /work/.crtr ${y} && chown -R ${E} /work /var/lib/crtr`];t.repositories.length>0&&n.push(`COPY --chown=${E} ${$}/ /work/`),s.length>0&&n.push(`RUN npm install -g @earendil-works/pi-coding-agent@${K}`),t.setup_script!==null&&t.setup_script.trim()!==""&&n.push(`COPY ${U} /tmp/${U}`),n.push(`USER ${E}`,"WORKDIR /work");for(const r of s)n.push(`RUN HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${y} pi install ${J(r)}`);return t.setup_script!==null&&t.setup_script.trim()!==""&&n.push(`RUN bash /tmp/${U}`),n.push(`RUN echo ${Math.trunc(e)} > /work/.crtr/recipe-revision`,"USER root",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),n.join(`
3
- `)}p(V,"recipeDockerfile");const W=p((t,e,s)=>new Promise((n,r)=>{const i=O("git",t,{cwd:s,env:{...process.env,...e,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let o="";i.stderr.on("data",a=>{o+=a.toString()}),i.on("error",r),i.on("close",a=>{a===0?n():r(new Error(`git ${t[0]} failed (${a}): ${o.slice(0,300)}`))})}),"runGit");async function ot(t){const e=t.git??W,s=t.cloneUrl??(r=>`https://github.com/${r}.git`);B(I(t.dir,$),{recursive:!0});const n=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 r of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(r.name)||r.name==="."||r.name==="..")throw new Error(`repository name ${JSON.stringify(r.name)} is not a plain directory name`);await e(["clone","--quiet","--branch",r.default_branch,s(r.github_full_name),I($,r.name)],n,t.dir)}R(I(t.dir,"Dockerfile"),V(t.recipe,t.revision)),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&R(I(t.dir,U),t.recipe.setup_script.endsWith(`
1
+ var D=Object.defineProperty;var l=(t,e)=>D(t,"name",{value:e,configurable:!0});import{spawn as P}from"node:child_process";import{constants as N,lstatSync as G,mkdirSync as C,readFileSync as M,readdirSync as F,readlinkSync as j,rmSync as Y,writeFileSync as k}from"node:fs";import{join as g,relative as z}from"node:path";import{crc32 as K,deflateRawSync as J}from"node:zlib";import{BlaxelApiError as H}from"./client.js";const V="public.ecr.aws/docker/library/node:24-alpine",W="ghcr.io/blaxel-ai/sandbox:latest",I="crtr",O="/var/lib/crtr/recipe-pi-agent",Z="1.1.0",E="recipe-setup.sh",$="repos",q=l(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),Q=l(t=>(t??"").split(`
2
+ `).map(e=>e.trim()).filter(e=>e!==""),"lines");function X(t,e){const a=Q(t.pi_packages),r=[`FROM ${V}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${W} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${I} -s /bin/sh ${I} && mkdir -p /work/.crtr ${O} && chown -R ${I} /work /var/lib/crtr`];t.repositories.length>0&&r.push(`COPY --chown=${I} ${$}/ /work/`),a.length>0&&r.push(`RUN npm install -g @earendil-works/pi-coding-agent@${Z}`),t.setup_script!==null&&t.setup_script.trim()!==""&&r.push(`COPY ${E} /tmp/${E}`),r.push(`USER ${I}`,"WORKDIR /work");for(const n of a)r.push(`RUN HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${O} pi install ${q(n)}`);return t.setup_script!==null&&t.setup_script.trim()!==""&&r.push(`RUN bash /tmp/${E}`),r.push(`RUN echo ${Math.trunc(e)} > /work/.crtr/recipe-revision`,"USER root",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),r.join(`
3
+ `)}l(X,"recipeDockerfile");const tt=l((t,e,a)=>new Promise((r,n)=>{const o=P("git",t,{cwd:a,env:{...process.env,...e,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let s="";o.stderr.on("data",i=>{s+=i.toString()}),o.on("error",n),o.on("close",i=>{i===0?r():n(new Error(`git ${t[0]} failed (${i}): ${s.slice(0,300)}`))})}),"runGit");async function lt(t){const e=t.git??tt,a=t.cloneUrl??(n=>`https://github.com/${n}.git`);C(g(t.dir,$),{recursive:!0});const r=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 e(["clone","--quiet","--branch",n.default_branch,a(n.github_full_name),g($,n.name)],r,t.dir)}k(g(t.dir,"Dockerfile"),X(t.recipe,t.revision)),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&k(g(t.dir,E),t.recipe.setup_script.endsWith(`
4
4
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
5
- `)}p(ot,"prepareBuildDir");function N(t,e,s){for(const n of A(e).sort()){const r=I(e,n),i=v(r),o=G(t,r).split("\\").join("/");i.isDirectory()?N(t,r,s):i.isSymbolicLink()?s.push({name:o,data:Buffer.from(P(r)),mode:L.S_IFLNK|511}):i.isFile()&&s.push({name:o,data:D(r),mode:L.S_IFREG|i.mode&511})}}p(N,"walk");function Z(t){const e=[];N(t,t,e);const s=[],n=[];let r=0;for(const a of e){const d=Buffer.from(a.name),h=F(a.data),w=M(a.data),c=Buffer.alloc(30);c.writeUInt32LE(67324752,0),c.writeUInt16LE(20,4),c.writeUInt16LE(2048,6),c.writeUInt16LE(8,8),c.writeUInt32LE(33,12),c.writeUInt32LE(w,14),c.writeUInt32LE(h.length,18),c.writeUInt32LE(a.data.length,22),c.writeUInt16LE(d.length,26),s.push(c,d,h);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(w,16),l.writeUInt32LE(h.length,20),l.writeUInt32LE(a.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(a.mode<<16>>>0,38),l.writeUInt32LE(r,42),n.push(l,d),r+=c.length+d.length+h.length}const i=Buffer.concat(n),o=Buffer.alloc(22);return o.writeUInt32LE(101010256,0),o.writeUInt16LE(e.length,8),o.writeUInt16LE(e.length,10),o.writeUInt32LE(i.length,12),o.writeUInt32LE(r,16),Buffer.concat([...s,i,o])}p(Z,"zipDirectory");async function x(t,e,s,n,r=[]){const i=`${t.controlUrl??"https://api.blaxel.ai/v0"}${s}`,o=await(t.fetch??fetch)(i,{method:e,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...n===void 0?{}:{body:JSON.stringify(n)}}),a=await o.text();let d=null;if(a!=="")try{d=JSON.parse(a)}catch{d={raw:a}}if(!o.ok&&!r.includes(o.status))throw new j(o.status,null,`Blaxel ${e} ${i} failed (${o.status}): ${a.slice(0,300)}`);return{status:o.status,headers:o.headers,json:d}}p(x,"api");async function S(t,e){const{status:s,json:n}=await x(t,"GET",`/images/sandbox/${encodeURIComponent(e)}`,void 0,[404]);return s===404?null:n}p(S,"getImage");async function st(t,e){await x(t,"DELETE",`/images/sandbox/${encodeURIComponent(e)}`,void 0,[404])}p(st,"deleteImage");async function at(t,e,s,n={}){const r=n.sleep??(u=>new Promise(f=>setTimeout(f,u))),i=Date.now(),o=await S(t,e),a=new Set((o?.spec?.tags??[]).map(u=>u.name)),d=o?.metadata?.events?.length??0,w=(await x(t,"POST","/images",{resourceType:"sandbox",name:e})).headers.get("x-blaxel-upload-url");if(w===null)throw new Error(`Blaxel gave no upload URL for image ${e}`);const c=await(t.fetch??fetch)(w,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(Z(s))});if(!c.ok)throw new Error(`uploading the build context of image ${e} failed (${c.status}): ${(await c.text()).slice(0,300)}`);const l=i+(n.timeoutMs??20*6e4);for(;;){const u=await S(t,e),f=u?.metadata?.status;if(f==="BUILT"&&(u?.metadata?.events?.length??0)>=d+2){const m=(u?.spec?.tags??[]).filter(g=>g.name!==void 0),_=m.filter(g=>!a.has(g.name)),b=(_.length>0?_:m).sort((g,k)=>(k.updatedAt??"").localeCompare(g.updatedAt??""))[0]?.name;if(b===void 0)throw new Error(`Blaxel built image ${e} but no new tag appeared`);return{ref:`sandbox/${e}:${b}`,buildMs:Date.now()-i}}if(f==="FAILED"||f==="TERMINATED"){const m=u?.metadata?.events??[];throw new Error(`building image ${e} ${f.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(Date.now()>l)throw new Error(`building image ${e} did not finish within ${n.timeoutMs??20*6e4} ms (last status ${f??"none"})`);await r(n.pollMs??3e3)}}p(at,"buildImage");const it=p(t=>`env-${t}`,"environmentImageName");function ct(t){C(t,{recursive:!0,force:!0})}p(ct,"removeBuildDir");export{Y as NODE_BASE_IMAGE,y as RECIPE_PI_AGENT_DIR,$ as REPOS_DIR,U as SETUP_SCRIPT_FILE,at as buildImage,st as deleteImage,it as environmentImageName,S as getImage,ot as prepareBuildDir,V as recipeDockerfile,ct as removeBuildDir,Z as zipDirectory};
5
+ `)}l(lt,"prepareBuildDir");function T(t,e,a){for(const r of F(e).sort()){const n=g(e,r),o=G(n),s=z(t,n).split("\\").join("/");o.isDirectory()?T(t,n,a):o.isSymbolicLink()?a.push({name:s,data:Buffer.from(j(n)),mode:N.S_IFLNK|511}):o.isFile()&&a.push({name:s,data:M(n),mode:N.S_IFREG|o.mode&511})}}l(T,"walk");function et(t){const e=[];T(t,t,e);const a=[],r=[];let n=0;for(const i of e){const u=Buffer.from(i.name),h=J(i.data),U=K(i.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(U,14),p.writeUInt32LE(h.length,18),p.writeUInt32LE(i.data.length,22),p.writeUInt16LE(u.length,26),a.push(p,u,h);const c=Buffer.alloc(46);c.writeUInt32LE(33639248,0),c.writeUInt16LE(788,4),c.writeUInt16LE(20,6),c.writeUInt16LE(2048,8),c.writeUInt16LE(8,10),c.writeUInt32LE(33,14),c.writeUInt32LE(U,16),c.writeUInt32LE(h.length,20),c.writeUInt32LE(i.data.length,24),c.writeUInt16LE(u.length,28),c.writeUInt32LE(i.mode<<16>>>0,38),c.writeUInt32LE(n,42),r.push(c,u),n+=p.length+u.length+h.length}const o=Buffer.concat(r),s=Buffer.alloc(22);return s.writeUInt32LE(101010256,0),s.writeUInt16LE(e.length,8),s.writeUInt16LE(e.length,10),s.writeUInt32LE(o.length,12),s.writeUInt32LE(n,16),Buffer.concat([...a,o,s])}l(et,"zipDirectory");async function x(t,e,a,r,n=[]){const o=`${t.controlUrl??"https://api.blaxel.ai/v0"}${a}`,s=await(t.fetch??fetch)(o,{method:e,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...r===void 0?{}:{body:JSON.stringify(r)}}),i=await s.text();let u=null;if(i!=="")try{u=JSON.parse(i)}catch{u={raw:i}}if(!s.ok&&!n.includes(s.status))throw new H(s.status,null,`Blaxel ${e} ${o} failed (${s.status}): ${i.slice(0,300)}`);return{status:s.status,headers:s.headers,json:u}}l(x,"api");async function v(t,e){const{status:a,json:r}=await x(t,"GET",`/images/sandbox/${encodeURIComponent(e)}`,void 0,[404]);return a===404?null:r}l(v,"getImage");async function pt(t,e){await x(t,"DELETE",`/images/sandbox/${encodeURIComponent(e)}`,void 0,[404])}l(pt,"deleteImage");async function dt(t,e,a,r={}){const n=r.sleep??(f=>new Promise(m=>setTimeout(m,f))),o=r.now??Date.now,s=o(),i=await v(t,e),u=new Set((i?.spec?.tags??[]).map(f=>f.name)),h=i?.metadata?.events?.length??0,p=(await x(t,"POST","/images",{resourceType:"sandbox",name:e})).headers.get("x-blaxel-upload-url");if(p===null)throw new Error(`Blaxel gave no upload URL for image ${e}`);const c=await(t.fetch??fetch)(p,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(et(a))});if(!c.ok)throw new Error(`uploading the build context of image ${e} failed (${c.status}): ${(await c.text()).slice(0,300)}`);const A=s+(r.timeoutMs??20*6e4);let _=null;for(;;){const f=await v(t,e),m=f?.metadata?.status;if(m==="BUILT"&&(f?.metadata?.events?.length??0)>=h+2){_??=o();const w=(f?.spec?.tags??[]).filter(d=>d.name!==void 0),b=(f?.metadata?.events??[]).slice(h).map(d=>d.time??"").filter(d=>d!=="").sort()[0],L=l(d=>b!==void 0&&Date.parse(d??"")>=Date.parse(b),"touchedSince"),R=w.filter(d=>!u.has(d.name)||L(d.createdAt)||L(d.updatedAt)),y=o()-_>=(r.tagGraceMs??6e4),S=(R.length>0?R:y?w:[]).sort((d,B)=>(B.updatedAt??"").localeCompare(d.updatedAt??""))[0]?.name;if(S!==void 0)return{ref:`sandbox/${e}:${S}`,buildMs:o()-s};if(y)throw new Error(`Blaxel built image ${e} but no tag appeared`)}if(m==="FAILED"||m==="TERMINATED"){const w=f?.metadata?.events??[];throw new Error(`building image ${e} ${m.toLowerCase()}: ${w[w.length-1]?.message??"no message"}`)}if(o()>A)throw new Error(`building image ${e} did not finish within ${r.timeoutMs??20*6e4} ms (last status ${m??"none"})`);await n(r.pollMs??3e3)}}l(dt,"buildImage");const ut=l(t=>`env-${t}`,"environmentImageName");function ft(t){Y(t,{recursive:!0,force:!0})}l(ft,"removeBuildDir");export{V as NODE_BASE_IMAGE,O as RECIPE_PI_AGENT_DIR,$ as REPOS_DIR,E as SETUP_SCRIPT_FILE,dt as buildImage,pt as deleteImage,ut as environmentImageName,v as getImage,lt as prepareBuildDir,X as recipeDockerfile,ft as removeBuildDir,et as zipDirectory};
@@ -9,7 +9,13 @@ export interface StartIdentity {
9
9
  export declare function startCandidateOf(who: StartIdentity): Promise<StartCandidate | null>;
10
10
  /** Throw `402 cap_exhausted` (limit named) when a limit covering every charge of this identity's payer is reached. */
11
11
  export declare function checkStart(who: StartIdentity): Promise<void>;
12
+ /** Throw `401 grant_revoked` when the node's own grant has a row that is revoked, removed or expired: a launch would create a sandbox
13
+ * whose start script is then refused at the token mint. A grant whose computed columns lag its revision is not refused (the
14
+ * directory's second write completes it), nor is one with no row (that is not a removal: the token mint answers for it). A node with
15
+ * no grant id has no grant to check, and a terminal node's token is minted from the person's current terminal grant, not from the
16
+ * id it recorded. */
17
+ export declare function checkGrantActive(who: StartIdentity): Promise<void>;
12
18
  /** The refusal, without throwing, for callers that settle a refused state instead of failing (cron fire). */
13
19
  export declare function startRefusal(who: StartIdentity): Promise<Refusal | null>;
14
- /** Whether an error is the start check's `402 cap_exhausted` refusal. */
20
+ /** Whether an error is a start refusal: the start check's `402 cap_exhausted`, or `401 grant_revoked` for a node whose grant is not active. */
15
21
  export declare function isStartRefusal(error: unknown): error is RunError;
@@ -1 +1 @@
1
- var c=Object.defineProperty;var n=(a,t)=>c(a,"name",{value:t,configurable:!0});import{check as o,findRefusal as s,payerOf as u}from"../ledger/index.js";import{RunError as l}from"../runs/operations.js";import{payerOfGrant as p}from"../grants/mirror.js";import{callerTerminalGrant as f}from"../grants/terminal.js";async function e(a){const t=a.grantee??"app:terminal",r=a.sub??(t==="app:terminal"?(await f())?.sub:void 0)??null;if(r===null)return null;const i=await p(a.grant_id);return{scope:"start",payer:u({call:"start",grantPayer:i,sub:r,grantee:t}).payer,sub:r,grantee:t}}n(e,"startCandidateOf");async function R(a){const t=await e(a);t!==null&&await o(t)}n(R,"checkStart");async function b(a){const t=await e(a);return t===null?null:await s(t)}n(b,"startRefusal");function O(a){return a instanceof l&&a.code==="cap_exhausted"}n(O,"isStartRefusal");export{R as checkStart,O as isStartRefusal,e as startCandidateOf,b as startRefusal};
1
+ var s=Object.defineProperty;var n=(t,a)=>s(t,"name",{value:a,configurable:!0});import{check as o,findRefusal as u,payerOf as l}from"../ledger/index.js";import{RunError as e}from"../runs/operations.js";import{grantStanding as p,payerOfGrant as d}from"../grants/mirror.js";import{callerTerminalGrant as f}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",r=t.sub??(a==="app:terminal"?(await f())?.sub:void 0)??null;if(r===null)return null;const c=await d(t.grant_id);return{scope:"start",payer:l({call:"start",grantPayer:c,sub:r,grantee:a}).payer,sub:r,grantee:a}}n(i,"startCandidateOf");async function v(t){const a=await i(t);a!==null&&await o(a)}n(v,"checkStart");async function w(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await p(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new e(401,"grant_revoked","the node's grant is not active")}n(w,"checkGrantActive");async function R(t){const a=await i(t);return a===null?null:await u(a)}n(R,"startRefusal");function b(t){return t instanceof e&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(b,"isStartRefusal");export{w as checkGrantActive,v as checkStart,b as isStartRefusal,i as startCandidateOf,R as startRefusal};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var a=(t,e)=>v(t,"name",{value:e,configurable:!0});import{openDb as l}from"../../core/canvas/db.js";import{isCloudRole as _}from"../../core/canvas/person.js";import{endLiveExecution as E,liveExecutionForNode as y}from"../../core/canvas/executions.js";import{emitEvent as c}from"../../core/events/emit.js";import{afterRevocationStop as S}from"../../core/grants/on-sync.js";import{allGrants as u,grantIdsWhere as h,grantStanding as m,mirrorOnly as g}from"../../core/grants/mirror.js";import{removeApp as b,removePersonData as k}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as x,wakeGrantWaiters as N}from"../../core/grants/watch.js";import{discardOrphanedTokens as p,discardTokensForGrant as O}from"../../core/providers/token-cache.js";import{runnerForExecution as T}from"../../core/runtime/runner/index.js";import{closeGrantStreams as L,heldGrantIds as R}from"../../core/runs/events.js";import{stopNodeSandboxes as D}from"../../core/spaces/stop.js";import{brokerSignalBus as G}from"../broker-signals/bus.js";import{withRowClaim as P}from"./row-claim.js";const A=6e4;function f(t,e,r){c({level:"error",event:`daemon.grants.${t}`,error:e,fields:r})}a(f,"failed");function C(t,e,r){try{const o=e.sub===null||e.grantee===null?p(r):O({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},r);o.tokens>0&&c({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:o.tokens}})}catch(o){f("outbound_tokens_discard_failed",o,{grant:t})}}a(C,"discardTokens");async function w(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){c({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}a(w,"reconcileProviderBundles");async function W(t,e){if(N(t),e.standing==="inactive"){const r=L(t);r>0&&c({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:r}})}await w()}a(W,"serveEffects");async function F(t,e){const r=await P("nodes",t,A,async o=>{const n=await y(t);if(n===null)return;await o.assertOwned(),c({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:n.executionId}});const i=a(async()=>{await o.assertOwned(),await E(t,{reason:"permission_revoked"}),await S(t)},"finish");if(n.runner==="process"){const d=await D(t,"permission_revoked",{holdRecovery:!0,after:i});if(!d.confirmed)throw d.error??new Error(`stop of ${t} was not confirmed`);return}const s=await T(n.runner).stop(n,{reason:"permission_revoked"});if(!s.confirmed)throw s.error??new Error(`stop of ${t} was not confirmed`);await i()})}a(F,"stopRevokedNode");async function M(t,e){if(!(e.grantee!==null&&g({grantee:e.grantee}))){if(e.standing==="inactive"){const r=await(await l()).prepare("SELECT DISTINCT n.node_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id = ?").all(t);for(const{node_id:o}of r)try{await F(o,t)}catch(n){f("node_stop_failed",n,{grant:t,node_id:o})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await b(e.grantee,e.sub):_()?await k(e.grantee,e.sub):c({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await l()).prepare("UPDATE grants SET removal_done_at = ? WHERE id = ? AND removal_done_at IS NULL").run(new Date().toISOString(),t)}catch(r){f("removal_failed",r,{grant:t,grantee:e.grantee})}}}a(M,"laneEffects");async function U(t,e){const r=await m(e);C(e,r,await u()),await Promise.all([t.serves?W(e,r):void 0,t.runsLanes&&r.standing!=="lagging"?M(e,r):void 0])}a(U,"applyGrantEffects");async function $(t){const e=new Set;if(t.serves)for(const o of R())e.add(o);if(t.runsLanes){const o=await(await l()).prepare("SELECT DISTINCT n.grant_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id IS NOT NULL").all();for(const{grant_id:n}of o)e.add(n)}const r=[];for(const o of e)(await m(o)).status===null&&r.push(o);return r}a($,"goneGrantIds");async function re(t){const e=new Map,r=a(n=>{const i=(e.get(n)??Promise.resolve()).then(()=>U(t,n)).catch(s=>f("effects_failed",s,{grant:n})).finally(()=>{e.get(n)===i&&e.delete(n)});return e.set(n,i),i},"run"),o=a(async()=>{const n=t.serves?w():void 0;try{t.serves&&x(),p(await u());const i=new Set(await h(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const s of await $(t))i.add(s);await Promise.all([...i].map(r))}catch(i){f("catch_up_failed",i,{})}await n},"catchUp");return await G.subscribe(n=>{r(n)},{kinds:["grant"],onListenStart:a(()=>{o()},"onListenStart")})}a(re,"startGrantEffects");export{U as applyGrantEffects,re as startGrantEffects};
1
+ var v=Object.defineProperty;var a=(t,e)=>v(t,"name",{value:e,configurable:!0});import{openDb as l}from"../../core/canvas/db.js";import{isCloudRole as _}from"../../core/canvas/person.js";import{endLiveExecution as E,liveExecutionForNode as y}from"../../core/canvas/executions.js";import{emitEvent as c}from"../../core/events/emit.js";import{afterRevocationStop as S}from"../../core/grants/on-sync.js";import{allGrants as u,grantIdsWhere as h,grantStanding as m,mirrorOnly as b}from"../../core/grants/mirror.js";import{removeApp as g,removePersonData as k}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as N,wakeGrantWaiters as x}from"../../core/grants/watch.js";import{discardOrphanedTokens as p,discardTokensForGrant as O}from"../../core/providers/token-cache.js";import{runnerForExecution as T}from"../../core/runtime/runner/index.js";import{closeGrantStreams as L,heldGrantIds as D}from"../../core/runs/events.js";import{stopNodeSandboxes as R}from"../../core/spaces/stop.js";import{brokerSignalBus as G}from"../broker-signals/bus.js";import{withRowClaim as A}from"./row-claim.js";const P=6e4;function f(t,e,r){c({level:"error",event:`daemon.grants.${t}`,error:e,fields:r})}a(f,"failed");function C(t,e,r){try{const n=e.sub===null||e.grantee===null?p(r):O({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},r);n.tokens>0&&c({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:n.tokens}})}catch(n){f("outbound_tokens_discard_failed",n,{grant:t})}}a(C,"discardTokens");async function w(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){c({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}a(w,"reconcileProviderBundles");async function W(t,e){if(x(t),e.standing==="inactive"){const r=L(t);r>0&&c({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:r}})}await w()}a(W,"serveEffects");async function F(t,e){const r=await A("nodes",t,P,async n=>{const o=await y(t);if(o===null)return;await n.assertOwned(),c({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:o.executionId}});const i=a(async()=>{await n.assertOwned(),await E(t,{reason:"permission_revoked"}),await S(t)},"finish");if(o.runner==="process"){const d=await R(t,"permission_revoked",{holdRecovery:!0,after:i});if(!d.confirmed)throw d.error??new Error(`stop of ${t} was not confirmed`);return}const s=await T(o.runner).stop(o,{reason:"permission_revoked"});if(!s.confirmed)throw s.error??new Error(`stop of ${t} was not confirmed`);await i()})}a(F,"stopRevokedNode");async function M(t,e){if(!(e.grantee!==null&&b({grantee:e.grantee}))){if(e.standing==="inactive"){const r=await(await l()).prepare("SELECT DISTINCT n.node_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id = ?").all(t);for(const{node_id:n}of r)try{await F(n,t)}catch(o){f("node_stop_failed",o,{grant:t,node_id:n})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await g(e.grantee,e.sub):_()?await k(e.grantee,e.sub):c({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await l()).prepare("UPDATE grants SET removal_done_at = ? WHERE id = ? AND rev = ? AND removal_done_at IS NULL").run(new Date().toISOString(),t,e.rev)}catch(r){f("removal_failed",r,{grant:t,grantee:e.grantee})}}}a(M,"laneEffects");async function U(t,e){const r=await m(e);C(e,r,await u()),await Promise.all([t.serves?W(e,r):void 0,t.runsLanes&&r.standing!=="lagging"?M(e,r):void 0])}a(U,"applyGrantEffects");async function $(t){const e=new Set;if(t.serves)for(const n of D())e.add(n);if(t.runsLanes){const n=await(await l()).prepare("SELECT DISTINCT n.grant_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id IS NOT NULL").all();for(const{grant_id:o}of n)e.add(o)}const r=[];for(const n of e)(await m(n)).status===null&&r.push(n);return r}a($,"goneGrantIds");async function re(t){const e=new Map,r=a(o=>{const i=(e.get(o)??Promise.resolve()).then(()=>U(t,o)).catch(s=>f("effects_failed",s,{grant:o})).finally(()=>{e.get(o)===i&&e.delete(o)});return e.set(o,i),i},"run"),n=a(async()=>{const o=t.serves?w():void 0;try{t.serves&&N(),p(await u());const i=new Set(await h(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const s of await $(t))i.add(s);await Promise.all([...i].map(r))}catch(i){f("catch_up_failed",i,{})}await o},"catchUp");return await G.subscribe(o=>{r(o)},{kinds:["grant"],onListenStart:a(()=>{n()},"onListenStart")})}a(re,"startGrantEffects");export{U as applyGrantEffects,re as startGrantEffects};
@@ -1 +1 @@
1
- var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{clearFrozen as f,getNode as g,getRow as D}from"../../../core/canvas/index.js";import{openDb as c}from"../../../core/canvas/db.js";import{fullName as z}from"../../../core/canvas/labels.js";import{isSafeNodeId as d}from"../../../core/canvas/paths.js";import{emitEvent as _}from"../../../core/events/emit.js";import{operationIdContext as L}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as T}from"../../../core/canvas/deliveries.js";import{publishNotice as C}from"../../../core/runtime/close.js";import{transition as u}from"../../../core/runtime/lifecycle.js";import{isStartRefusal as y}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as M}from"./node-person.js";import{MachineLaunchUncertainError as b,MachineOfflineError as m}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as I}from"../../../core/runtime/reopen.js";import{reviveNode as w}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as O}from"../../../core/canvas/recovery.js";import{mapAsync as P}from"../../../core/async-array.js";const h=6,U=10*6e4,x=2e4;async function H(i){const e=await(await c()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(e?.idle_release_attempts??0),acknowledgedCount:Number(e?.idle_release_acked_count??0),lastAttempt:e?.idle_release_last_attempt_at==null?void 0:Date.parse(e.idle_release_last_attempt_at)}}s(H,"readEpisode");async function F(i,e,a,t,r){const n=await(await c()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(r).toISOString(),t,i,e);return Number(n.changes)===1}s(F,"claimAttempt");async function W(i,e){await(await c()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(e.attempts,e.lastAttempt===void 0?null:new Date(e.lastAttempt).toISOString(),e.acknowledgedCount,i)}s(W,"writeEpisode");function $(i,e){if(e)return 2;const a=i.launched_at;if(a==null)return 1;const t=i.last_settled_at;return t==null?2:Date.parse(t)>Date.parse(a)?1:2}s($,"thawTier");function B(i,e){const a=i.row.frozen_at,t=e.row.frozen_at;return a==null?t==null?0:1:t==null?-1:Date.parse(a)-Date.parse(t)}s(B,"compareThaw");class le{static{s(this,"FreezeLaneReconciler")}async endEpisode(e){await(await c()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(e)}async run(e,a){const t=await P(a.candidates,async n=>({...n,tier:$(n.row,await k(n.row.node_id))}));t.sort(B);const r={stalled:0,waitingOnMail:0};for(const n of t)await L.fresh(()=>M(n.row,()=>this.enact(e,n,a.fleet)))==="frozen"&&(n.tier===1?r.stalled+=1:r.waitingOnMail+=1);return r}async enact(e,a,t){const r=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(e,a.row):(await t.applyDeadRowPolicy(r),await t.has(r)?"launched":(await D(r))?.frozen_at!=null?"frozen":"skipped")}catch(n){return _({level:"error",event:"node.lifecycle.enact_failed",...d(r)?{node_id:r}:{},error:n,fields:{...d(r)?{}:{affected_node_id:r},enact:a.enact}}),"skipped"}}async enactReopen(e){await I(e.node_id);try{return(await w(e.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(y(a)||a instanceof A||a instanceof m)return await this.settleRefusedStart(e.node_id,a,"reopen");throw a}}async settleRefusedStart(e,a,t){return a instanceof b||await u(e,"release"),await f(e),_({level:"warn",event:"node.start.refused",node_id:e,error:a,fields:{enact:t}}),"skipped"}async enactThaw(e){const a=(await O(e.node_id))?.interrupted===!0;if(!a&&e.lifecycle==="resident"&&(await g(e.node_id))?.pi_session_id!=null&&!await k(e.node_id))return await u(e.node_id,"release"),await f(e.node_id),"skipped";try{return(await w(e.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(t){if(y(t)||t instanceof A||t instanceof m)return await this.settleRefusedStart(e.node_id,t,"thaw");const r=await g(e.node_id);throw r!==null&&(r.status==="active"||r.status==="idle")&&(await u(e.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:t instanceof Error?t.message:String(t)}}}),await f(e.node_id)),t}}async enactIdleRelease(e,a){const t=a.node_id,r=await T(t),n=await H(t),l=n.attempts===0||n.acknowledgedCount!==r,o=l?0:n.attempts;if(o>=h)return await this.endEpisode(t),_({level:"warn",event:"broker.idle_release.exhausted",...d(t)?{node_id:t}:{},fields:{...d(t)?{}:{affected_node_id:t},attempts:o,max_attempts:h}}),await u(t,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:o}}}),await C(t,"notice.crash",`Child crashed \u2014 ${z(a)} (${t}) failed to relaunch after ${o} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${t}\`.`,{reason:"child-crashed",child:t}),"skipped";const E=l?void 0:n.lastAttempt,S=Math.min(x*2**o,U);if(E!==void 0&&e-E<S||!await F(t,n.attempts,o+1,r,e))return"skipped";const v=s(()=>W(t,{attempts:l?0:o,lastAttempt:l?void 0:n.lastAttempt,acknowledgedCount:r}),"giveBack");let R;try{R=await w(t,{resume:!0,capacity:"freeze"})}catch(p){if(!(p instanceof m))throw p;return await v(),await this.settleRefusedStart(t,p,"idle-release")}return R.outcome==="frozen"?(await v(),"frozen"):(_({level:"info",event:"broker.revive.idle_release",...d(t)?{node_id:t}:{},attempt:o+1,fields:{...d(t)?{}:{affected_node_id:t},attempts:o+1,max_attempts:h}}),"launched")}}export{le as FreezeLaneReconciler,B as compareThaw,$ as thawTier};
1
+ var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{clearFrozen as f,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as z}from"../../../core/canvas/labels.js";import{isSafeNodeId as d}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as L}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as T}from"../../../core/canvas/deliveries.js";import{publishNotice as C}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{isStartRefusal as m}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as M}from"./node-person.js";import{MachineLaunchUncertainError as b,MachineOfflineError as w}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as I}from"../../../core/runtime/reopen.js";import{reviveNode as h}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as O}from"../../../core/canvas/recovery.js";import{mapAsync as P}from"../../../core/async-array.js";const E=6,U=10*6e4,x=2e4;async function H(i){const e=await(await _()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(e?.idle_release_attempts??0),acknowledgedCount:Number(e?.idle_release_acked_count??0),lastAttempt:e?.idle_release_last_attempt_at==null?void 0:Date.parse(e.idle_release_last_attempt_at)}}s(H,"readEpisode");async function F(i,e,a,t,r){const n=await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(r).toISOString(),t,i,e);return Number(n.changes)===1}s(F,"claimAttempt");async function W(i,e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(e.attempts,e.lastAttempt===void 0?null:new Date(e.lastAttempt).toISOString(),e.acknowledgedCount,i)}s(W,"writeEpisode");function $(i,e){if(e)return 2;const a=i.launched_at;if(a==null)return 1;const t=i.last_settled_at;return t==null?2:Date.parse(t)>Date.parse(a)?1:2}s($,"thawTier");function B(i,e){const a=i.row.frozen_at,t=e.row.frozen_at;return a==null?t==null?0:1:t==null?-1:Date.parse(a)-Date.parse(t)}s(B,"compareThaw");class le{static{s(this,"FreezeLaneReconciler")}async endEpisode(e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(e)}async run(e,a){const t=await P(a.candidates,async n=>({...n,tier:$(n.row,await k(n.row.node_id))}));t.sort(B);const r={stalled:0,waitingOnMail:0};for(const n of t)await L.fresh(()=>M(n.row,()=>this.enact(e,n,a.fleet)))==="frozen"&&(n.tier===1?r.stalled+=1:r.waitingOnMail+=1);return r}async enact(e,a,t){const r=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(e,a.row):(await t.applyDeadRowPolicy(r),await t.has(r)?"launched":(await D(r))?.frozen_at!=null?"frozen":"skipped")}catch(n){return u({level:"error",event:"node.lifecycle.enact_failed",...d(r)?{node_id:r}:{},error:n,fields:{...d(r)?{}:{affected_node_id:r},enact:a.enact}}),"skipped"}}async enactReopen(e){await I(e.node_id);try{return(await h(e.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(m(a)||a instanceof A||a instanceof w)return await this.settleRefusedStart(e.node_id,a,"reopen");throw a}}async settleRefusedStart(e,a,t){return a instanceof b||await p(e,"release"),await f(e),u({level:"warn",event:"node.start.refused",node_id:e,error:a,fields:{enact:t}}),"skipped"}async enactThaw(e){const a=(await O(e.node_id))?.interrupted===!0;if(!a&&e.lifecycle==="resident"&&(await y(e.node_id))?.pi_session_id!=null&&!await k(e.node_id))return await p(e.node_id,"release"),await f(e.node_id),"skipped";try{return(await h(e.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(t){if(m(t)||t instanceof A||t instanceof w)return await this.settleRefusedStart(e.node_id,t,"thaw");const r=await y(e.node_id);throw r!==null&&(r.status==="active"||r.status==="idle")&&(await p(e.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:t instanceof Error?t.message:String(t)}}}),await f(e.node_id)),t}}async enactIdleRelease(e,a){const t=a.node_id,r=await T(t),n=await H(t),l=n.attempts===0||n.acknowledgedCount!==r,o=l?0:n.attempts;if(o>=E)return await this.endEpisode(t),u({level:"warn",event:"broker.idle_release.exhausted",...d(t)?{node_id:t}:{},fields:{...d(t)?{}:{affected_node_id:t},attempts:o,max_attempts:E}}),await p(t,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:o}}}),await C(t,"notice.crash",`Child crashed \u2014 ${z(a)} (${t}) failed to relaunch after ${o} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${t}\`.`,{reason:"child-crashed",child:t}),"skipped";const v=l?void 0:n.lastAttempt,S=Math.min(x*2**o,U);if(v!==void 0&&e-v<S||!await F(t,n.attempts,o+1,r,e))return"skipped";const R=s(()=>W(t,{attempts:l?0:o,lastAttempt:l?void 0:n.lastAttempt,acknowledgedCount:r}),"giveBack");let g;try{g=await h(t,{resume:!0,capacity:"freeze"})}catch(c){if(!(c instanceof w||m(c)))throw c;return await R(),await this.settleRefusedStart(t,c,"idle-release")}return g.outcome==="frozen"?(await R(),"frozen"):(u({level:"info",event:"broker.revive.idle_release",...d(t)?{node_id:t}:{},attempt:o+1,fields:{...d(t)?{}:{affected_node_id:t},attempts:o+1,max_attempts:E}}),"launched")}}export{le as FreezeLaneReconciler,B as compareThaw,$ as thawTier};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.599",
3
+ "version": "0.3.600",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.599",
148
+ "@north-light/identity": "0.3.600",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.599",
3
+ "version": "0.3.600",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.599",
3
+ "version": "0.3.600",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.599",
9
+ "version": "0.3.600",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
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.599",
31
+ "@north-light/identity": "0.3.600",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.599",
11959
+ "version": "0.3.600",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.599",
11964
+ "version": "0.3.600",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.599",
11969
+ "version": "0.3.600",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.599",
11977
+ "version": "0.3.600",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.599",
11981
- "@north-light/identity": "0.3.599"
11980
+ "@north-light/api": "0.3.600",
11981
+ "@north-light/identity": "0.3.600"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.599",
11986
+ "version": "0.3.600",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.599",
11990
- "@north-light/identity": "0.3.599",
11991
- "@north-light/plugin": "0.3.599",
11989
+ "@north-light/api": "0.3.600",
11990
+ "@north-light/identity": "0.3.600",
11991
+ "@north-light/plugin": "0.3.600",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {