@north-light/cli 0.3.684 → 0.3.685

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.
@@ -46,6 +46,9 @@ export interface CanvasWriteOptions {
46
46
  savepoint?: boolean;
47
47
  /** Always undo the body's writes, even when it returns (a dry run). Nested, it runs in a SAVEPOINT rolled back at the end. */
48
48
  rollback?: boolean;
49
+ /** Name the step timings of this transaction when its request is collecting them: `<name>_checkout_wait`, `<name>_statements_count`,
50
+ * `<name>_statements_ms`, `<name>_other_ms` and `<name>_slow<n>_<statement label>` for the slowest few. Ignored for a joined transaction. */
51
+ timingName?: string;
49
52
  }
50
53
  /** Run `body` in one transaction on its own pooled connection, the only transaction entry point for the canvas database.
51
54
  * A call from inside the body's own async context joins it and only the outermost call commits. A call from any other
@@ -1,4 +1,4 @@
1
- var P=Object.defineProperty;var o=(e,t)=>P(e,"name",{value:t,configurable:!0});import{AsyncLocalStorage as D}from"node:async_hooks";import{randomBytes as M}from"node:crypto";import{appendFileSync as B,mkdirSync as k,readFileSync as N}from"node:fs";import{join as I}from"node:path";import h from"pg";import{resolveDatabaseUrl as U}from"../../daemon/postgres/supervisor.js";import{publishFileExclusive as q}from"../fs-utils.js";import{initializeEmptyLayout as G,runtimeRoot as l}from"../layout.js";import{translatePlaceholders as K,translateOnce as X}from"../statements.js";import{ensureHome as F}from"./paths.js";import{emitEvent as H}from"../events/emit.js";import{ensureSchema as J}from"./schema-chain.js";import{canvasDatabaseSchema as V,canvasSchemaDatabaseUrl as W,canvasSearchPathOptions as A}from"./schema-version.js";const Z="crtr_test_template";class z extends Error{static{o(this,"CanvasConstraintError")}constraint;code="23505";constructor(t,n,a){super(t,a),this.name="CanvasConstraintError",this.constraint=n}}function O(e){const t=process.env.CRTR_DB_OPEN_LEDGER;if(t)try{const n=`${new Date().toISOString()} ${process.pid} ${process.argv[1]??"<unknown>"} ${e.replace(/\/\/([^:@/]*):[^@/]*@/,"//$1@")}
2
- `;B(t,n)}catch{}}o(O,"recordOpenLedger");const j=6,Y=12,$=2;function R(e=process.env){const t=e.CRTR_DATABASE_POOL_MAX?.trim();if(t){const n=Number(t);if(!Number.isInteger(n)||n<$)throw new Error(`CRTR_DATABASE_POOL_MAX must be an integer of at least ${$}; got ${JSON.stringify(t)}`);return n}return e.CRTR_DATABASE_URL?Y:j}o(R,"canvasPoolSize");const L=3e4,Q=1e3,p=new D,tt=new Set([114,3802]),et={getTypeParser:o(((e,t)=>tt.has(e)?n=>n:e===20||e===1700?n=>{const a=Number(n);if(e===20&&!Number.isSafeInteger(a))throw new Error(`canvas db: bigint ${n} does not fit a JS number`);return a}:h.types.getTypeParser(e,t)),"getTypeParser")};class nt{static{o(this,"Handle")}url;db;pool=null;schema=null;constructor(t){this.url=t;const n=this;this.db={prepare:o(a=>this.statement(a,!0),"prepare"),prepareUncached:o(a=>this.statement(a,!1),"prepareUncached"),exec:o(a=>this.run({text:a}).then(()=>{}),"exec"),get inTransaction(){return C(n)}}}ready(){return this.schema??=ot(this.url).catch(t=>{throw this.schema=null,t}),this.schema}connections(){if(this.pool!==null)return this.pool;const t=new h.Pool({connectionString:this.url,types:et,application_name:`crtr-${process.pid}`,connectionTimeoutMillis:L,options:A(),max:R(),idleTimeoutMillis:1e4,allowExitOnIdle:!0});return t.on("connect",()=>O(this.url)),t.on("error",n=>console.warn(`[canvas db] pooled connection error: ${n.message}`)),this.pool=t}async checkout(){try{return await this.connections().connect()}catch(t){throw this.mapError(t)}}async run(t){const n=p.getStore();try{if(n!==void 0&&n.open&&n.handle===this){const a=performance.now();try{return await n.client.query(t)}finally{n.statementMs+=performance.now()-a}}return await this.connections().query(t)}catch(a){throw this.mapError(a)}}mapError(t){const n=t;return n.code==="23505"?new z(n.message??"unique constraint violation",n.constraint,{cause:t}):/timeout exceeded when trying to connect/i.test(n.message??"")?new Error(`canvas db: no pooled connection became free within ${L} ms (pool of ${R()}); a transaction body is holding connections across a slow await`,{cause:t}):t}statement(t,n){const a=n?(()=>{const r=K(t);return{text:r.text,name:r.name}})():{text:X(t).text},s=o(r=>this.run({...a,values:r.map(rt)}),"query");return{get:o(async(...r)=>(await s(r)).rows[0],"get"),all:o(async(...r)=>(await s(r)).rows,"all"),run:o(async(...r)=>({changes:(await s(r)).rowCount??0}),"run")}}async close(){const t=this.pool;this.pool=null,await t?.end().catch(()=>{})}}function rt(e){return ArrayBuffer.isView(e)&&!Buffer.isBuffer(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}o(rt,"bindable");function C(e){const t=p.getStore();return t!==void 0&&t.open&&t.handle===e}o(C,"ownsTransaction");async function ot(e){const t=o((u,d,y)=>{H({level:u,event:d,fields:y})},"emit"),n=V(),a=W(),s=a??e;O(s);const r=new h.Client({connectionString:s,application_name:`crtr-schema-${process.pid}`,connectionTimeoutMillis:1e4,...a===void 0?{options:A()}:{}});r.on("error",()=>{}),await r.connect();try{await J(r,{schema:n,emit:t})}finally{await r.end().catch(()=>{})}}o(ot,"applySchema");function at(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}o(at,"runningUnderNodeTest");function w(e,t){const n=/^(postgres(?:ql)?:\/\/[^/?#]*)(\/[^?#]*)?(.*)$/s.exec(e);if(n===null)throw new Error(`not a postgres URL: ${e.replace(/\/\/[^@/]*@/,"//")}`);return`${n[1]}/${t}${n[3]}`}o(w,"withDatabase");async function st(e){const t=I(l(),"test-db"),n=o(()=>{try{return N(t,"utf8").trim()||void 0}catch(u){if(u.code==="ENOENT")return;throw u}},"recorded"),a=n();if(a!==void 0)return w(e,a);k(l(),{recursive:!0});const s=`t_${M(8).toString("hex")}`,r=new h.Client({connectionString:w(e,"postgres")});r.on("error",()=>{}),await r.connect();try{if(await r.query(`CREATE DATABASE ${s} TEMPLATE ${Z} STRATEGY file_copy`),!q(t,`${s}
3
- `,384))return await r.query(`DROP DATABASE ${s}`),w(e,n())}finally{await r.end()}return w(e,s)}o(st,"testDatabaseUrl");async function ct(){const e=process.env.CRTR_TEST_PG_URL;if(e)return st(e);if(at())throw new Error("CRTR_TEST_PG_URL is not set: a test must reach its own Postgres (run the suite through the lane runner); refusing to open a real canvas database");return U(l())}o(ct,"canvasDatabaseUrl");const f=new Map,E=new Map;async function x(){G(),F();const e=await ct();E.set(l(),e);let t=f.get(e);return t===void 0&&f.set(e,t=new nt(e)),await t.ready(),t}o(x,"openHandle");async function bt(){return(await x()).db}o(bt,"openDb");async function At(){const e=E.get(l());if(e===void 0)return;E.delete(l());const t=f.get(e);t!==void 0&&(f.delete(e),await t.close())}o(At,"closeDb");async function Ot(){const e=[...f.values()];f.clear(),E.clear(),await Promise.all(e.map(t=>t.close()))}o(Ot,"closeAllDbs");function $t(e){const t=p.getStore();if(t===void 0||!t.open){queueMicrotask(e);return}t.afterCommit.push(e)}o($t,"afterCommit");let it=0;async function Rt(e,t={}){const n=await x(),a=n.db;if(C(n)){if(!t.savepoint&&!t.rollback)return e(a);const c=p.getStore(),i=`canvas_write_${++it}`;await n.run({text:`SAVEPOINT ${i}`});const S=c.afterCommit,_=S.length;let b;try{b=await e(a)}catch(v){throw await n.run({text:`ROLLBACK TO ${i}; RELEASE ${i}`}),S.splice(_),v}return await n.run({text:t.rollback?`ROLLBACK TO ${i}; RELEASE ${i}`:`RELEASE ${i}`}),t.rollback&&S.splice(_),b}const s=new Error("canvas write transaction entered here"),r=await n.checkout();let u;const d=o(c=>{u??=c},"onConnectionError");r.on("error",d);const y=performance.now();let g=!1,T=!1;const m={handle:n,client:r,open:!0,afterCommit:[],statementMs:0};try{await r.query("BEGIN");try{const c=await p.run(m,()=>e(a));return await r.query(t.rollback?"ROLLBACK":"COMMIT"),g=!t.rollback,c}catch(c){T=!0;try{await r.query("ROLLBACK")}catch(i){u??=i}throw n.mapError(c)}}finally{m.open=!1;const c=performance.now()-y;if(!T&&c-m.statementMs>Q&&console.warn(`[canvas db] write transaction held its connection ${Math.round(c)}ms (${Math.round(m.statementMs)}ms in its statements); its body did non-db work while holding a pooled connection and its row locks
4
- ${s.stack}`),r.removeListener("error",d),r.release(u),g)for(const i of m.afterCommit)queueMicrotask(i)}}o(Rt,"withCanvasWrite");export{z as CanvasConstraintError,$t as afterCommit,ct as canvasDatabaseUrl,R as canvasPoolSize,Ot as closeAllDbs,At as closeDb,bt as openDb,Rt as withCanvasWrite};
1
+ var N=Object.defineProperty;var o=(e,t)=>N(e,"name",{value:t,configurable:!0});import{AsyncLocalStorage as k}from"node:async_hooks";import{randomBytes as B}from"node:crypto";import{appendFileSync as I,mkdirSync as U,readFileSync as q}from"node:fs";import{join as G}from"node:path";import y from"pg";import{resolveDatabaseUrl as K}from"../../daemon/postgres/supervisor.js";import{publishFileExclusive as X}from"../fs-utils.js";import{initializeEmptyLayout as F,runtimeRoot as d}from"../layout.js";import{translatePlaceholders as H,translateOnce as J}from"../statements.js";import{ensureHome as V}from"./paths.js";import{addStepTiming as w,isCollectingStepTimings as W,statementLabel as Z}from"../step-timings.js";import{emitEvent as z}from"../events/emit.js";import{ensureSchema as j}from"./schema-chain.js";import{canvasDatabaseSchema as Y,canvasSchemaDatabaseUrl as Q,canvasSearchPathOptions as O}from"./schema-version.js";const tt="crtr_test_template";class et extends Error{static{o(this,"CanvasConstraintError")}constraint;code="23505";constructor(t,n,a){super(t,a),this.name="CanvasConstraintError",this.constraint=n}}function L(e){const t=process.env.CRTR_DB_OPEN_LEDGER;if(t)try{const n=`${new Date().toISOString()} ${process.pid} ${process.argv[1]??"<unknown>"} ${e.replace(/\/\/([^:@/]*):[^@/]*@/,"//$1@")}
2
+ `;I(t,n)}catch{}}o(L,"recordOpenLedger");const nt=6,rt=12,R=2;function x(e=process.env){const t=e.CRTR_DATABASE_POOL_MAX?.trim();if(t){const n=Number(t);if(!Number.isInteger(n)||n<R)throw new Error(`CRTR_DATABASE_POOL_MAX must be an integer of at least ${R}; got ${JSON.stringify(t)}`);return n}return e.CRTR_DATABASE_URL?rt:nt}o(x,"canvasPoolSize");const C=3e4,ot=1e3,E=new k,at=new Set([114,3802]),st={getTypeParser:o(((e,t)=>at.has(e)?n=>n:e===20||e===1700?n=>{const a=Number(n);if(e===20&&!Number.isSafeInteger(a))throw new Error(`canvas db: bigint ${n} does not fit a JS number`);return a}:y.types.getTypeParser(e,t)),"getTypeParser")};class ct{static{o(this,"Handle")}url;db;pool=null;schema=null;constructor(t){this.url=t;const n=this;this.db={prepare:o(a=>this.statement(a,!0),"prepare"),prepareUncached:o(a=>this.statement(a,!1),"prepareUncached"),exec:o(a=>this.run({text:a}).then(()=>{}),"exec"),get inTransaction(){return M(n)}}}ready(){return this.schema??=ut(this.url).catch(t=>{throw this.schema=null,t}),this.schema}connections(){if(this.pool!==null)return this.pool;const t=new y.Pool({connectionString:this.url,types:st,application_name:`crtr-${process.pid}`,connectionTimeoutMillis:C,options:O(),max:x(),idleTimeoutMillis:1e4,allowExitOnIdle:!0});return t.on("connect",()=>L(this.url)),t.on("error",n=>console.warn(`[canvas db] pooled connection error: ${n.message}`)),this.pool=t}async checkout(){try{return await this.connections().connect()}catch(t){throw this.mapError(t)}}async run(t){const n=E.getStore();try{if(n!==void 0&&n.open&&n.handle===this){const a=performance.now();try{return await n.client.query(t)}finally{const s=performance.now()-a;n.statementMs+=s,n.statements?.push({text:t.text,ms:s})}}return await this.connections().query(t)}catch(a){throw this.mapError(a)}}mapError(t){const n=t;return n.code==="23505"?new et(n.message??"unique constraint violation",n.constraint,{cause:t}):/timeout exceeded when trying to connect/i.test(n.message??"")?new Error(`canvas db: no pooled connection became free within ${C} ms (pool of ${x()}); a transaction body is holding connections across a slow await`,{cause:t}):t}statement(t,n){const a=n?(()=>{const r=H(t);return{text:r.text,name:r.name}})():{text:J(t).text},s=o(r=>this.run({...a,values:r.map(it)}),"query");return{get:o(async(...r)=>(await s(r)).rows[0],"get"),all:o(async(...r)=>(await s(r)).rows,"all"),run:o(async(...r)=>({changes:(await s(r)).rowCount??0}),"run")}}async close(){const t=this.pool;this.pool=null,await t?.end().catch(()=>{})}}function it(e){return ArrayBuffer.isView(e)&&!Buffer.isBuffer(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}o(it,"bindable");function M(e){const t=E.getStore();return t!==void 0&&t.open&&t.handle===e}o(M,"ownsTransaction");async function ut(e){const t=o((f,l,h)=>{z({level:f,event:l,fields:h})},"emit"),n=Y(),a=Q(),s=a??e;L(s);const r=new y.Client({connectionString:s,application_name:`crtr-schema-${process.pid}`,connectionTimeoutMillis:1e4,...a===void 0?{options:O()}:{}});r.on("error",()=>{}),await r.connect();try{await j(r,{schema:n,emit:t})}finally{await r.end().catch(()=>{})}}o(ut,"applySchema");function lt(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}o(lt,"runningUnderNodeTest");function S(e,t){const n=/^(postgres(?:ql)?:\/\/[^/?#]*)(\/[^?#]*)?(.*)$/s.exec(e);if(n===null)throw new Error(`not a postgres URL: ${e.replace(/\/\/[^@/]*@/,"//")}`);return`${n[1]}/${t}${n[3]}`}o(S,"withDatabase");async function mt(e){const t=G(d(),"test-db"),n=o(()=>{try{return q(t,"utf8").trim()||void 0}catch(f){if(f.code==="ENOENT")return;throw f}},"recorded"),a=n();if(a!==void 0)return S(e,a);U(d(),{recursive:!0});const s=`t_${B(8).toString("hex")}`,r=new y.Client({connectionString:S(e,"postgres")});r.on("error",()=>{}),await r.connect();try{if(await r.query(`CREATE DATABASE ${s} TEMPLATE ${tt} STRATEGY file_copy`),!X(t,`${s}
3
+ `,384))return await r.query(`DROP DATABASE ${s}`),S(e,n())}finally{await r.end()}return S(e,s)}o(mt,"testDatabaseUrl");async function ft(){const e=process.env.CRTR_TEST_PG_URL;if(e)return mt(e);if(lt())throw new Error("CRTR_TEST_PG_URL is not set: a test must reach its own Postgres (run the suite through the lane runner); refusing to open a real canvas database");return K(d())}o(ft,"canvasDatabaseUrl");const p=new Map,_=new Map;async function v(){F(),V();const e=await ft();_.set(d(),e);let t=p.get(e);return t===void 0&&p.set(e,t=new ct(e)),await t.ready(),t}o(v,"openHandle");async function xt(){return(await v()).db}o(xt,"openDb");async function Ct(){const e=_.get(d());if(e===void 0)return;_.delete(d());const t=p.get(e);t!==void 0&&(p.delete(e),await t.close())}o(Ct,"closeDb");async function Mt(){const e=[...p.values()];p.clear(),_.clear(),await Promise.all(e.map(t=>t.close()))}o(Mt,"closeAllDbs");function vt(e){const t=E.getStore();if(t===void 0||!t.open){queueMicrotask(e);return}t.afterCommit.push(e)}o(vt,"afterCommit");let dt=0;async function Pt(e,t={}){const n=await v(),a=n.db;if(M(n)){if(!t.savepoint&&!t.rollback)return e(a);const i=E.getStore(),c=`canvas_write_${++dt}`;await n.run({text:`SAVEPOINT ${c}`});const m=i.afterCommit,A=m.length;let $;try{$=await e(a)}catch(D){throw await n.run({text:`ROLLBACK TO ${c}; RELEASE ${c}`}),m.splice(A),D}return await n.run({text:t.rollback?`ROLLBACK TO ${c}; RELEASE ${c}`:`RELEASE ${c}`}),t.rollback&&m.splice(A),$}const s=new Error("canvas write transaction entered here"),r=W()?t.timingName:void 0,f=performance.now(),l=await n.checkout();r!==void 0&&w(`${r}_checkout_wait`,performance.now()-f);let h;const g=o(i=>{h??=i},"onConnectionError");l.on("error",g);const P=performance.now();let T=!1,b=!1;const u={handle:n,client:l,open:!0,afterCommit:[],statementMs:0,...r===void 0?{}:{statements:[]}};try{await l.query("BEGIN");try{const i=await E.run(u,()=>e(a));return await l.query(t.rollback?"ROLLBACK":"COMMIT"),T=!t.rollback,i}catch(i){b=!0;try{await l.query("ROLLBACK")}catch(c){h??=c}throw n.mapError(i)}}finally{u.open=!1;const i=performance.now()-P;if(r!==void 0&&u.statements!==void 0&&(w(`${r}_statements_count`,u.statements.length),w(`${r}_statements_ms`,u.statementMs),w(`${r}_other_ms`,i-u.statementMs),[...u.statements].sort((c,m)=>m.ms-c.ms).slice(0,3).forEach((c,m)=>w(`${r}_slow${m+1}_${Z(c.text)}`,c.ms))),!b&&i-u.statementMs>ot&&console.warn(`[canvas db] write transaction held its connection ${Math.round(i)}ms (${Math.round(u.statementMs)}ms in its statements); its body did non-db work while holding a pooled connection and its row locks
4
+ ${s.stack}`),l.removeListener("error",g),l.release(h),T)for(const c of u.afterCommit)queueMicrotask(c)}}o(Pt,"withCanvasWrite");export{et as CanvasConstraintError,vt as afterCommit,ft as canvasDatabaseUrl,x as canvasPoolSize,Mt as closeAllDbs,Ct as closeDb,xt as openDb,Pt as withCanvasWrite};
@@ -10,6 +10,9 @@ export declare function warmMachineCheckouts(environment: string, dirs: readonly
10
10
  /** The chain of `dir` as this process knows it: git here on a Mac or self-hosted install; on a cloud role the row the person's machine reported
11
11
  * most recently, git where nothing is stored (a Mac path is a missing directory there: `not-a-repo`, no git spawned, no error). */
12
12
  export declare function checkoutChainOf(db: CanvasDb, dir: string, person: () => Promise<string>): Promise<CheckoutIdentity[]>;
13
+ /** The chains of several directories in one read, keyed by directory (as given; each already resolved). On a cloud role, the newest row the person's
14
+ * machine reported for each; git where none is stored, or where the process has no person (a profile on no machine). Elsewhere, git. */
15
+ export declare function checkoutChainsOf(db: CanvasDb, dirs: readonly string[], person: () => Promise<string>): Promise<Map<string, CheckoutIdentity[]>>;
13
16
  /** Run the checkout lookups for `dirs` before a canvas write opens: on the machine environment of `profileId` (cloud role) ask the Mac and store
14
17
  * the answer; otherwise run git here. */
15
18
  export declare function warmCheckoutDirs(profileId: string | null | undefined, dirs: readonly string[]): Promise<void>;
@@ -1,3 +1,3 @@
1
- var p=Object.defineProperty;var a=(e,r)=>p(e,"name",{value:r,configurable:!0});import{resolve as s}from"node:path";import{withCanvasWrite as h}from"./canvas/db.js";import{isCloudRole as l,PersonOutsideRequestError as w}from"./canvas/person-state.js";import{emitEvent as u}from"./events/emit.js";import{timedStep as d}from"./step-timings.js";import{realpathOrSelf as m}from"./fs-utils.js";import{checkoutChain as c}from"./graph/repo-sync/identity.js";import{callMachine as E}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as y}from"./runtime/runner/machine/environment.js";import{MachineCallFailedError as O,MachineLostError as v,MachineOfflineError as _}from"./runtime/runner/machine/ops.js";const A={"repo.identify":a(async({dirs:e})=>{const r=performance.now(),i=await Promise.all(e.map(async n=>{const o=await c(m(s(n)));return o.every(t=>t.ok)?[n,o]:null}));return u({level:"info",event:"machine.repo_identify.timing",fields:{dirs:e.length,duration_ms:Math.round(performance.now()-r)}}),Object.fromEntries(i.filter(n=>n!==null))},"repo.identify")};async function C(e,r){const i=[...new Set(r.map(t=>s(t)))];if(i.length===0)return!0;let n;try{n=await d("repo_identify_call",()=>E(e,"repo.identify",{dirs:i}))}catch(t){if(!(t instanceof _||t instanceof v||t instanceof O))throw t;return u({level:"warn",event:"repo.identify.failed",error:t,fields:{environment:e,dirs:i.length}}),!1}const o=new Date().toISOString();return await h(async t=>{for(const f of i)n[f]!==void 0&&await t.prepare(`INSERT INTO checkout_identities (environment, dir, chain_json, observed_at) VALUES (?, ?, ?::jsonb, ?)
2
- ON CONFLICT (environment, dir) DO UPDATE SET chain_json = EXCLUDED.chain_json, observed_at = EXCLUDED.observed_at`).run(e,f,JSON.stringify(n[f]),o)}),!0}a(C,"warmMachineCheckouts");function S(e){const r=typeof e=="string"?JSON.parse(e):e;return Array.isArray(r)?r:[]}a(S,"chainOf");async function x(e,r,i){if(!l())return await c(r);let n;try{n=await i()}catch(t){if(t instanceof w)return await c(r);throw t}const o=await e.prepare(`SELECT c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
3
- WHERE p.person IN (?, ?) AND c.dir = ? ORDER BY c.observed_at DESC LIMIT 1`).get(n.replace(/^user:/,""),`user:${n.replace(/^user:/,"")}`,s(r));return o===void 0?await c(r):S(o.chain_json)}a(x,"checkoutChainOf");async function P(e,r){const i=l()&&e!=null?await y(e):null;if(i!==null){await C(i,r);return}for(const n of r)await c(m(s(n)))}a(P,"warmCheckoutDirs");export{x as checkoutChainOf,A as machineCheckoutHandlers,P as warmCheckoutDirs,C as warmMachineCheckouts};
1
+ var E=Object.defineProperty;var c=(t,r)=>E(t,"name",{value:r,configurable:!0});import{resolve as l}from"node:path";import{withCanvasWrite as O}from"./canvas/db.js";import{isCloudRole as p,PersonOutsideRequestError as y}from"./canvas/person-state.js";import{emitEvent as h}from"./events/emit.js";import{timedStep as v}from"./step-timings.js";import{realpathOrSelf as d}from"./fs-utils.js";import{checkoutChain as f}from"./graph/repo-sync/identity.js";import{callMachine as C}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as _}from"./runtime/runner/machine/environment.js";import{MachineCallFailedError as S,MachineLostError as N,MachineOfflineError as D}from"./runtime/runner/machine/ops.js";const J={"repo.identify":c(async({dirs:t})=>{const r=performance.now(),o=await Promise.all(t.map(async e=>{const a=await f(d(l(e)));return a.every(n=>n.ok)?[e,a]:null}));return h({level:"info",event:"machine.repo_identify.timing",fields:{dirs:t.length,duration_ms:Math.round(performance.now()-r)}}),Object.fromEntries(o.filter(e=>e!==null))},"repo.identify")};async function g(t,r){const o=[...new Set(r.map(n=>l(n)))];if(o.length===0)return!0;let e;try{e=await v("repo_identify_call",()=>C(t,"repo.identify",{dirs:o}))}catch(n){if(!(n instanceof D||n instanceof N||n instanceof S))throw n;return h({level:"warn",event:"repo.identify.failed",error:n,fields:{environment:t,dirs:o.length}}),!1}const a=new Date().toISOString();return await O(async n=>{for(const s of o)e[s]!==void 0&&await n.prepare(`INSERT INTO checkout_identities (environment, dir, chain_json, observed_at) VALUES (?, ?, ?::jsonb, ?)
2
+ ON CONFLICT (environment, dir) DO UPDATE SET chain_json = EXCLUDED.chain_json, observed_at = EXCLUDED.observed_at`).run(t,s,JSON.stringify(e[s]),a)}),!0}c(g,"warmMachineCheckouts");function k(t){const r=typeof t=="string"?JSON.parse(t):t;return Array.isArray(r)?r:[]}c(k,"chainOf");async function q(t,r,o){const e=l(r);return(await M(t,[e],o)).get(e)}c(q,"checkoutChainOf");async function M(t,r,o){const e=new Map,a=[...new Set(r)];if(!p()){for(const i of a)e.set(i,await f(i));return e}let n;try{n=await o()}catch(i){if(!(i instanceof y))throw i;for(const m of a)e.set(m,await f(m));return e}const s=n.replace(/^user:/,""),w=a.length===0?[]:await t.prepare(`SELECT DISTINCT ON (c.dir) c.dir, c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
3
+ WHERE p.person IN (?, ?) AND c.dir = ANY(?::text[]) ORDER BY c.dir, c.observed_at DESC`).all(s,`user:${s}`,a),u=new Map(w.map(i=>[i.dir,i.chain_json]));for(const i of a)e.set(i,u.has(i)?k(u.get(i)):await f(i));return e}c(M,"checkoutChainsOf");async function H(t,r){const o=p()&&t!=null?await _(t):null;if(o!==null){await g(o,r);return}for(const e of r)await f(d(l(e)))}c(H,"warmCheckoutDirs");export{q as checkoutChainOf,M as checkoutChainsOf,J as machineCheckoutHandlers,H as warmCheckoutDirs,g as warmMachineCheckouts};
@@ -1,3 +1,3 @@
1
- var $=Object.defineProperty;var s=(o,e)=>$(o,"name",{value:e,configurable:!0});import{coveredByAny as j,isSandboxedNode as H}from"../../shared/env.js";import{projectPaths as W}from"../../api/dto/profiles.js";import{existsSync as S}from"node:fs";import{CrtrError as D}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as F}from"@north-light/identity";import{activeGrant as C,grantFor as b,runtimeScope as B}from"../grants/mirror.js";import{withCanvasWrite as J}from"../canvas/db.js";import{ApiError as P}from"../../api/errors.js";import{pluginAppToken as k}from"../secrets.js";import{loadExactProfileManifest as G}from"../profiles/manifest.js";import{ensureOwner as x,getById as q,nodeObject as U,ownerForGrantee as Y,profileHandle as z}from"./objects.js";import{personId as K,personIdAsync as A}from"../canvas/person.js";import{OBJECT_TYPE as Q}from"../permissions/builtin.js";import{warmCheckoutDirs as L}from"../checkout-identities.js";import{fillProfileProjectRepo as V}from"../profiles/manifest.js";import{emitEvent as X}from"../events/emit.js";import{isCloudRole as _}from"../canvas/person-state.js";import{loadReadAccess as Z,mayRead as I,prefetchRepoReads as ee,reposForCwd as oe,warmCheckoutIdentities as O}from"./repo-sync/repos.js";async function M(o,e,t,r,n,a){const u=t===null?[]:n.projects(t),c=u.length===0?void 0:a??await A(),p=c===void 0?void 0:await Z(o,c);p!==void 0&&c!==void 0&&await ee(o,c,[e,...u.flatMap(i=>i.path!==void 0&&(_()||S(i.path))?[i.path]:[])],p);const f=await r(e,a,p),d=new Set(f.map(i=>i.repo.id)),m=[],E=[];for(const i of u){if(i.repo!==void 0&&!d.has(i.repo)){const l=await n.object(i.repo);l!==null&&l.type==="repo"&&l.deleted_at===null&&await I(o,c??a??await A(),l.id,p)&&(d.add(l.id),m.push(l))}if(i.path===void 0||!_()&&!S(i.path))continue;let w;try{w=await r(i.path,a,p)}catch(l){if(l instanceof D&&l.code==="git-lookup-failed")continue;throw l}for(const l of w)d.has(l.repo.id)||(d.add(l.repo.id),m.push(l.repo),E.push(l))}return{repos:f.map(i=>i.repo),checkouts:f,projectRepos:m,projectCheckouts:E}}s(M,"viewRepos");async function Fe(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?W(h(o).projects(t.profile_id)):[];if(_()){await te(t.profile_id,[t.cwd,...r]);return}await O(t.cwd);for(const n of r)S(n)&&await O(n)}s(Fe,"warmNodeRepos");async function te(o,e){if(await L(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await J(async n=>await oe(n,t.path)))[0];r!==void 0&&await V(o,t.path,r.id)}catch(r){X({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(te,"warmCloudNodeCheckouts");async function Ce(o,e,t){if(!_()){for(const n of t)await O(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await L(r?.profile_id,t)}s(Ce,"warmNodeDirs");async function be(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await N(o)};if(e.class==="app")return{class:"app",app:await R(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await N(o)};const c=await b(e.actor.app,e.sub);if(!c)throw new P(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const p=e.actor.node_scopes;return{class:"app",app:await R(o,e.actor.app),place:e.actor.place,launched:p,scopes:p===null?c.resolved:p.filter(f=>j(c.resolved,f))}}if(e.class==="cron"){const c=e.grant?(await C(e.grant))?.resolved??[]:[],p=e.scopes;return{class:"app",app:await R(o,e.app),scopes:p===null?c:p.filter(f=>j(c,f)),launched:p,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=h(o),n=await U(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),u=a.app===null?null:await r.object(a.app);if(!u)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:u,scopes:await T(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await M(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,u)}}s(be,"readerFor");async function ne(o,e,t,r=h(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),u=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
- sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!u)throw new Error(`no node ${e}`);const{grantee:c,sub:p,grant_id:f,scopes_json:d,cwd:m,profile_id:E,app:i}=u,w=i===null?null:await r.object(i);if(!w)throw new Error(`node ${e} has no app`);const l=d===null?null:JSON.parse(d);return{class:"node",node:a,app:w,scopes:await T(c,p??"",f,l,r,n),launched:l,cwd:m,...await M(o,m,E,t,r,p||void 0),profile:E===null?null:await r.profile(E,w)}}s(ne,"readerForNode");class re extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function xe(o,e,t=async()=>[],r=h(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await ae(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ne(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const c=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!c)throw new re;const p=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(c.id))?.external_id??"app:terminal",f=B(),d=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${f.sql}`).all(p,...f.args),m=s(g=>JSON.parse(g.resolved_scopes_json).filter(y=>y.mode==="always").map(y=>F(y.scope)),"always"),E=d.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(Q,e.id)).map(g=>g.subject_id)):null,i=E===null?void 0:d.find(g=>E.has(g.sub.replace(/^user:/,"")))?.sub,w=i===void 0?null:await r.grantFor(p,i),l=a.type==="person"?null:d.length===0?r.pluginScopes(p):d.length===1?m(d[0]):w?.resolved??null;return{class:"object",object:e,node:e,owner:a,app:c,scopes:l,...w===null?{}:{sub:w.sub},repos:a.type==="repo"?[a]:[]}}s(xe,"readerForObject");async function Ae(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>F(a.scope))}s(Ae,"appScopesNow");async function ae(o,e,t,r){const n=await N(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await R(o,t.app),u=t?.app==null?null:await r.grantFor(t.app,t.sub),c=t===null||u===null?null:t.node_scopes===null?u.resolved:t.node_scopes.filter(f=>j(u.resolved,f)),p=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:p,app:p,scopes:c,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(ae,"readerForStub");function h(o){return{grantById:C,grantFor:b,pluginScopes:s(e=>k(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await q(o,e),"object"),profile:s(async(e,t)=>await se(o,e,t),"profile"),projects:s(e=>H()?[]:v(e)?.manifest.projects??[],"projects")}}s(h,"liveLookups");function Le(o){const e=h(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Le,"publishLookups");async function T(o,e,t,r,n,a=!1){const u=t?await n.grantById(t):await n.grantFor(o,e),c=u&&u.grantee===o?u.resolved:null;if(c===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?c:r.filter(p=>j(c,p))}s(T,"nodeScopes");async function N(o){return await Y(o,K())}s(N,"personObject");async function R(o,e){return await x(o,"app","app",e,e.replace(/^app:/,""))}s(R,"appObject");async function se(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await x(o,"profile","profile",e,z(e,G(e).manifest.name),t)}s(se,"profileObject");export{re as NoOwningAppError,Ae as appScopesNow,h as liveLookups,se as profileObject,Le as publishLookups,be as readerFor,ne as readerForNode,xe as readerForObject,M as viewRepos,te as warmCloudNodeCheckouts,Ce as warmNodeDirs,Fe as warmNodeRepos};
1
+ var T=Object.defineProperty;var s=(o,e)=>T(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as H}from"../../api/dto/profiles.js";import{existsSync as y}from"node:fs";import{CrtrError as W}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as F}from"@north-light/identity";import{activeGrant as b,grantFor as C,runtimeScope as D}from"../grants/mirror.js";import{withCanvasWrite as B}from"../canvas/db.js";import{ApiError as J}from"../../api/errors.js";import{pluginAppToken as P}from"../secrets.js";import{loadExactProfileManifest as k}from"../profiles/manifest.js";import{ensureOwner as x,getById as G,nodeObject as q,ownerForGrantee as U,profileHandle as Y}from"./objects.js";import{personId as z,personIdAsync as K}from"../canvas/person.js";import{OBJECT_TYPE as Q}from"../permissions/builtin.js";import{warmCheckoutDirs as A}from"../checkout-identities.js";import{fillProfileProjectRepo as V}from"../profiles/manifest.js";import{emitEvent as X}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as Z,readableAmong as I,prefetchRepoReads as ee,reposForCwd as oe,warmCheckoutIdentities as O}from"./repo-sync/repos.js";async function L(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),p=l.length===0?void 0:a??await K(),c=p===void 0?void 0:await Z(o,p);c!==void 0&&p!==void 0&&await ee(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||y(i.path))?[i.path]:[])],c);const f=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),w=p===void 0?new Set:await I(o,p,f,c),g=await r(e,a,c),d=new Set(g.map(i=>i.repo.id)),m=[],E=[];for(const i of l){if(i.repo!==void 0&&!d.has(i.repo)){const u=await n.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&w.has(u.id)&&(d.add(u.id),m.push(u))}if(i.path===void 0||!R()&&!y(i.path))continue;let h;try{h=await r(i.path,a,c)}catch(u){if(u instanceof W&&u.code==="git-lookup-failed")continue;throw u}for(const u of h)d.has(u.repo.id)||(d.add(u.repo.id),m.push(u.repo),E.push(u))}return{repos:g.map(i=>i.repo),checkouts:g,projectRepos:m,projectCheckouts:E}}s(L,"viewRepos");async function Fe(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?H(j(o).projects(t.profile_id)):[];if(R()){await te(t.profile_id,[t.cwd,...r]);return}await O(t.cwd);for(const n of r)y(n)&&await O(n)}s(Fe,"warmNodeRepos");async function te(o,e){if(await A(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await B(async n=>await oe(n,t.path)))[0];r!==void 0&&await V(o,t.path,r.id)}catch(r){X({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(te,"warmCloudNodeCheckouts");async function be(o,e,t){if(!R()){for(const n of t)await O(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await A(r?.profile_id,t)}s(be,"warmNodeDirs");async function Ce(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await N(o)};if(e.class==="app")return{class:"app",app:await S(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await N(o)};const p=await C(e.actor.app,e.sub);if(!p)throw new J(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const c=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),place:e.actor.place,launched:c,scopes:c===null?p.resolved:c.filter(f=>_(p.resolved,f))}}if(e.class==="cron"){const p=e.grant?(await b(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(f=>_(p,f)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),n=await q(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:l,scopes:await M(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await L(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Ce,"readerFor");async function ne(o,e,t,r=j(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
+ sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:f,scopes_json:w,cwd:g,profile_id:d,app:m}=l,E=m===null?null:await r.object(m);if(!E)throw new Error(`node ${e} has no app`);const i=w===null?null:JSON.parse(w);return{class:"node",node:a,app:E,scopes:await M(p,c??"",f,i,r,n),launched:i,cwd:g,...await L(o,g,d,t,r,c||void 0),profile:d===null?null:await r.profile(d,E)}}s(ne,"readerForNode");class re extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function xe(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await ae(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ne(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const p=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!p)throw new re;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",f=D(),w=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${f.sql}`).all(c,...f.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(u=>u.mode==="always").map(u=>F(u.scope)),"always"),d=w.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(Q,e.id)).map(h=>h.subject_id)):null,m=d===null?void 0:w.find(h=>d.has(h.sub.replace(/^user:/,"")))?.sub,E=m===void 0?null:await r.grantFor(c,m),i=a.type==="person"?null:w.length===0?r.pluginScopes(c):w.length===1?g(w[0]):E?.resolved??null;return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...E===null?{}:{sub:E.sub},repos:a.type==="repo"?[a]:[]}}s(xe,"readerForObject");async function Ae(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>F(a.scope))}s(Ae,"appScopesNow");async function ae(o,e,t,r){const n=await N(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(f=>_(l.resolved,f)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(ae,"readerForStub");function j(o){return{grantById:b,grantFor:C,pluginScopes:s(e=>P(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await G(o,e),"object"),profile:s(async(e,t)=>await se(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Le(o){const e=j(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Le,"publishLookups");async function M(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(M,"nodeScopes");async function N(o){return await U(o,z())}s(N,"personObject");async function S(o,e){return await x(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function se(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await x(o,"profile","profile",e,Y(e,k(e).manifest.name),t)}s(se,"profileObject");export{re as NoOwningAppError,Ae as appScopesNow,j as liveLookups,se as profileObject,Le as publishLookups,Ce as readerFor,ne as readerForNode,xe as readerForObject,L as viewRepos,te as warmCloudNodeCheckouts,be as warmNodeDirs,Fe as warmNodeRepos};
@@ -1,5 +1,6 @@
1
1
  import type { Checkout, ObjectRow } from '../types.js';
2
2
  import { handleHint } from './identity.js';
3
+ import type { CheckoutIdentity } from './identity.js';
3
4
  import type { CanvasDb } from '../../canvas/db.js';
4
5
  import { subjectSet } from '../../permissions/evaluator.js';
5
6
  import { loadDefinitions } from '../../permissions/schemas.js';
@@ -26,10 +27,12 @@ export interface ReadAccess {
26
27
  path: string;
27
28
  person: string;
28
29
  }>;
30
+ /** Filled by `prefetchRepoReads`: the checkout chain of each resolved directory it was asked about. */
31
+ chains?: Map<string, CheckoutIdentity[]>;
29
32
  }
30
33
  export declare function loadReadAccess(db: CanvasDb, person: string): Promise<ReadAccess>;
31
- /** Whether `person` may read the object `id` by permission facts alone (no ceiling): the gate for a repo a profile names. */
32
- export declare function mayRead(db: CanvasDb, person: string, id: string, access?: ReadAccess): Promise<boolean>;
34
+ /** The ids among `ids` that `person` may read by permission facts alone (no ceiling), in one read: the gate for the repos a profile names. */
35
+ export declare function readableAmong(db: CanvasDb, person: string, ids: readonly string[], access?: ReadAccess): Promise<Set<string>>;
33
36
  /** The repo objects of one remote identity, any person's, that `person` may read (permission facts only, no ceiling), the person's own first and
34
37
  * then by age, oldest first. `heldByPerson` says whether the person has an identity row for it at all, readable or not. */
35
38
  export declare function readableRepos(db: CanvasDb, person: string, scheme: string, externalId: string, access?: ReadAccess): Promise<{
@@ -1,4 +1,4 @@
1
- var $=Object.defineProperty;var p=(e,o)=>$(e,"name",{value:o,configurable:!0});import{resolve as E,sep as N}from"node:path";import{CrtrError as R}from"../../errors.js";import{realpathOrSelf as y}from"../../fs-utils.js";import{ExitCode as O}from"../../../types.js";import{personIdAsync as x}from"../../canvas/person.js";import{ensureOwner as L}from"../objects.js";import{checkoutChain as j,handleHint as D}from"./identity.js";import{checkoutChainOf as S}from"../../checkout-identities.js";import{subjectSet as P}from"../../permissions/evaluator.js";import{loadDefinitions as T}from"../../permissions/schemas.js";import{compilePermission as A}from"../../permissions/compile.js";import{f as F,raw as b}from"../../permissions/sql.js";import{OBJECT_TYPE as k}from"../../permissions/builtin.js";async function M(e,o,r,n){return await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
- WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(o,r,n)??null}p(M,"existingRepo");async function H(e,o,r){const n=await M(e,await x(),o.scheme,o.externalId);if(n)return n;const i=r??o.handleHint;await e.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`repo-handle:${i}`);const c=e.prepare("SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL");let a=i;for(let s=2;await c.get(a);s++)a=`${i}-${s}`;return await L(e,"repo",o.scheme,o.externalId,a)}p(H,"ensureRepo");async function _(e,o){return{defs:await T(e),subjects:await P(e,o.replace(/^user:/,""))}}p(_,"loadReadAccess");async function ae(e,o,r,n){const{defs:i,subjects:c}=n??await _(e,o),a=A(i,c,k,"read",F`${r}::text`);return(await e.prepareUncached(`SELECT ${a.sql} AS ok`).get(...a.params))?.ok===!0}p(ae,"mayRead");async function W(e,o,r,n,i){const c=`${r}\0${n}`,a=i?.readable?.get(c);return a!==void 0?{readable:[...a.readable],heldByPerson:a.heldByPerson}:(await g(e,o,[{scheme:r,externalId:n}],i)).get(c)}p(W,"readableRepos");async function g(e,o,r,n){const{defs:i,subjects:c}=n??await _(e,o),a=A(i,c,k,"read",b("o.id")),s=r.length===0?[]:await e.prepareUncached(`SELECT o.*, i.person AS holder, i.scheme AS id_scheme, i.external_id AS id_external, ${a.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE o.type = 'repo' AND o.deleted_at IS NULL AND (i.scheme, i.external_id) IN (SELECT * FROM unnest(?::text[], ?::text[]))`).all(...a.params,r.map(t=>t.scheme),r.map(t=>t.externalId)),m=`user:${o.replace(/^user:/,"")}`,w=p(t=>t.holder===m&&t.owner===null,"own"),u=new Map;for(const t of r){const d=s.filter(l=>l.id_scheme===t.scheme&&l.id_external===t.externalId),h=d.filter(l=>l.ok).sort((l,f)=>Number(w(f))-Number(w(l))||l.created_at.localeCompare(f.created_at)||l.seq-f.seq).map(({holder:l,ok:f,id_scheme:q,id_external:J,...I})=>I);u.set(`${t.scheme}\0${t.externalId}`,{readable:h,heldByPerson:d.some(l=>l.holder===m)})}return u}p(g,"readableReposFor");const C=p(async e=>await e.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
4
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all(),"localPathRepos");async function ne(e,o,r,n){const i=new Map;for(const c of r){let a;try{a=await S(e,y(E(c)),async()=>o)}catch(s){if(s instanceof R&&s.code==="git-lookup-failed")continue;throw s}for(const s of a)s.ok&&i.set(`${s.scheme}\0${s.externalId}`,{scheme:s.scheme,externalId:s.externalId})}n.readable=await g(e,o,[...i.values()],n),n.localPaths=await C(e)}p(ne,"prefetchRepoReads");async function ie(e,o){return(await B(e,o)).map(r=>r.repo)}p(ie,"reposForCwd");async function se(e){await j(y(E(e)))}p(se,"warmCheckoutIdentities");async function B(e,o,r,n){const i=y(E(o)),c=[];let a=n;for(const t of await S(e,i,async()=>r??await x())){if(!t.ok)throw new R("git-lookup-failed",`cannot identify the repo at ${t.dir}: ${t.reason}`,O.GENERAL,{dir:t.dir});const d=r??await x();a??=await _(e,d);const{readable:h,heldByPerson:l}=await W(e,d,t.scheme,t.externalId,a);h.length===0&&!l&&h.push(await H(e,t));for(const f of h)c.push({root:t.root,repo:f})}const m=(n?.localPaths??await C(e)).filter(({path:t})=>i===t||i.startsWith(t.endsWith(N)?t:t+N)),w=m.length>0?r??await x():"";for(const{path:t,person:d,...h}of m)d===`user:${w.replace(/^user:/,"")}`&&c.push({root:t,repo:h});c.sort((t,d)=>d.root.length-t.root.length);const u=new Set;return c.filter(({repo:t})=>!u.has(t.id)&&(u.add(t.id),!0))}p(B,"checkoutsForCwd");export{B as checkoutsForCwd,H as ensureRepo,D as handleHint,_ as loadReadAccess,ae as mayRead,ne as prefetchRepoReads,W as readableRepos,ie as reposForCwd,se as warmCheckoutIdentities};
1
+ var k=Object.defineProperty;var p=(e,o)=>k(e,"name",{value:o,configurable:!0});import{resolve as E,sep as _}from"node:path";import{CrtrError as I}from"../../errors.js";import{realpathOrSelf as y}from"../../fs-utils.js";import{ExitCode as $}from"../../../types.js";import{personIdAsync as x}from"../../canvas/person.js";import{ensureOwner as j}from"../objects.js";import{checkoutChain as L,handleHint as D}from"./identity.js";import{checkoutChainOf as b,checkoutChainsOf as F}from"../../checkout-identities.js";import{subjectSet as M}from"../../permissions/evaluator.js";import{loadDefinitions as P}from"../../permissions/schemas.js";import{compilePermission as R}from"../../permissions/compile.js";import{raw as A}from"../../permissions/sql.js";import{OBJECT_TYPE as S}from"../../permissions/builtin.js";async function T(e,o,r,n){return await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
+ WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(o,r,n)??null}p(T,"existingRepo");async function H(e,o,r){const n=await T(e,await x(),o.scheme,o.externalId);if(n)return n;const i=r??o.handleHint;await e.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`repo-handle:${i}`);const s=e.prepare("SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL");let a=i;for(let c=2;await s.get(a);c++)a=`${i}-${c}`;return await j(e,"repo",o.scheme,o.externalId,a)}p(H,"ensureRepo");async function N(e,o){return{defs:await P(e),subjects:await M(e,o.replace(/^user:/,""))}}p(N,"loadReadAccess");async function ae(e,o,r,n){if(r.length===0)return new Set;const{defs:i,subjects:s}=n??await N(e,o),a=R(i,s,S,"read",A("o.id")),c=await e.prepareUncached(`SELECT o.id FROM objects o WHERE o.id = ANY(?::text[]) AND ${a.sql}`).all(r,...a.params);return new Set(c.map(h=>h.id))}p(ae,"readableAmong");async function W(e,o,r,n,i){const s=`${r}\0${n}`,a=i?.readable?.get(s);return a!==void 0?{readable:[...a.readable],heldByPerson:a.heldByPerson}:(await g(e,o,[{scheme:r,externalId:n}],i)).get(s)}p(W,"readableRepos");async function g(e,o,r,n){const{defs:i,subjects:s}=n??await N(e,o),a=R(i,s,S,"read",A("o.id")),c=r.length===0?[]:await e.prepareUncached(`SELECT o.*, i.person AS holder, i.scheme AS id_scheme, i.external_id AS id_external, ${a.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE o.type = 'repo' AND o.deleted_at IS NULL AND (i.scheme, i.external_id) IN (SELECT * FROM unnest(?::text[], ?::text[]))`).all(...a.params,r.map(t=>t.scheme),r.map(t=>t.externalId)),h=`user:${o.replace(/^user:/,"")}`,w=p(t=>t.holder===h&&t.owner===null,"own"),u=new Map;for(const t of r){const d=c.filter(l=>l.id_scheme===t.scheme&&l.id_external===t.externalId),f=d.filter(l=>l.ok).sort((l,m)=>Number(w(m))-Number(w(l))||l.created_at.localeCompare(m.created_at)||l.seq-m.seq).map(({holder:l,ok:m,id_scheme:B,id_external:q,...O})=>O);u.set(`${t.scheme}\0${t.externalId}`,{readable:f,heldByPerson:d.some(l=>l.holder===h)})}return u}p(g,"readableReposFor");const C=p(async e=>await e.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
4
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all(),"localPathRepos");async function ne(e,o,r,n){const i=new Map,s=await F(e,r.map(a=>y(E(a))),async()=>o);n.chains=new Map([...s].filter(([,a])=>a.every(c=>c.ok)));for(const a of s.values())for(const c of a)c.ok&&i.set(`${c.scheme}\0${c.externalId}`,{scheme:c.scheme,externalId:c.externalId});n.readable=await g(e,o,[...i.values()],n),n.localPaths=await C(e)}p(ne,"prefetchRepoReads");async function ie(e,o){return(await v(e,o)).map(r=>r.repo)}p(ie,"reposForCwd");async function se(e){await L(y(E(e)))}p(se,"warmCheckoutIdentities");async function v(e,o,r,n){const i=y(E(o)),s=[];let a=n;for(const t of n?.chains?.get(i)??await b(e,i,async()=>r??await x())){if(!t.ok)throw new I("git-lookup-failed",`cannot identify the repo at ${t.dir}: ${t.reason}`,$.GENERAL,{dir:t.dir});const d=r??await x();a??=await N(e,d);const{readable:f,heldByPerson:l}=await W(e,d,t.scheme,t.externalId,a);f.length===0&&!l&&f.push(await H(e,t));for(const m of f)s.push({root:t.root,repo:m})}const h=(n?.localPaths??await C(e)).filter(({path:t})=>i===t||i.startsWith(t.endsWith(_)?t:t+_)),w=h.length>0?r??await x():"";for(const{path:t,person:d,...f}of h)d===`user:${w.replace(/^user:/,"")}`&&s.push({root:t,repo:f});s.sort((t,d)=>d.root.length-t.root.length);const u=new Set;return s.filter(({repo:t})=>!u.has(t.id)&&(u.add(t.id),!0))}p(v,"checkoutsForCwd");export{v as checkoutsForCwd,H as ensureRepo,D as handleHint,N as loadReadAccess,ne as prefetchRepoReads,ae as readableAmong,W as readableRepos,ie as reposForCwd,se as warmCheckoutIdentities};
@@ -1,3 +1,3 @@
1
- var Ce=Object.defineProperty;var l=(e,r)=>Ce(e,"name",{value:r,configurable:!0});import{accessSync as Se,constants as Ee,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Te}from"./nodes.js";import{resolveProfileOperand as Pe}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as _,brokerLaunchFailed as K}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as w,fullName as we,jobDir as dn,recordExecutionPid as sn,abortExecution as T,setFrozen as G}from"../canvas/index.js";import{contextDir as V,nodeAgentDir as J}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as U,conversationStore as R}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Y}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as k}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as S}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Q,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Cn}from"../canvas/person.js";import{recordLaunch as Sn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as Z,timedStep as X}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Tn,unregisteredConcreteModel as Pn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}from"./start-check.js";function E(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(E,"launchFailureOutcome");async function qn(e,r,o){try{return await Q.launch(e,r,o)}catch(t){try{await S(e,"crash",{reason:"launch_failed",outcome:E(t)})}catch{}const a=t.message;throw K(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}l(qn,"launchBrokerOrCrash");function Gn(e){return _n({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}l(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:d}=r.status;return{text:`exited (code ${a??"null"}, signal ${d??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:d,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}l(Vn,"notReadyDescription");async function Jn(e,r){try{await S(e,"crash",{reason:"launch_failed",outcome:E(r)})}catch{}try{Q.teardown(e)}catch{}}l(Jn,"crashAndTearDown");async function Yn(e){const r=(await R().list()).map(({conversation_id:a,path:d})=>({id:a,path:d})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw _(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw _(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}l(Yn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw _("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=U(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw _(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await R().header(t)).path}const o=await w(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw _(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=U(t);if(a===null)throw _(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await R().header(a)).path}return await Yn(r)}l(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Pe(e).profileId:r!==null?(await w(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}l(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Tn(e.model,r,e.modelExact===!0)}l(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await zn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:d,...c}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...c,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}l(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Pn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw _(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(e,r);if(a!==void 0)throw _(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(ve,"assertLaunchModelRegistered");function Zn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}l(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(e);o!==null&&Z("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))Z(`mac_${t}`,a)}l(er,"recordStartCallTimings");async function nr(e,r,o){const{buildStartBundle:t}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:a}=await import("../../daemon/api/handlers/broker-ops.js");if(await Dn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Y().automaticReviveCap,runner:"machine",release:he()})}catch(s){return s instanceof ue?"full":(k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),"failed")}let c;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const s=await vn(e.node_id,o,e.cwd);await En(d,s);const P=d;await X("warm_repos",async()=>await bn(await gn(),e.node_id));const $=e.sub??await Cn(),L=await X("start_bundle",()=>t({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:$,launchJson:s,runner:"machine"}));c=await X("render_transaction",()=>yn(async v=>{const M=await a(e.node_id),F=await xn(v,P,e.node_id,new Date().toISOString());return await On(r,"start",{executionId:P,nodeId:e.node_id,attempt:1,sandboxName:null,release:he(),launchJson:s,cwd:e.cwd,resuming:!1,nodeToken:F,bundle:L,start:M})}))}catch(s){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),await T(d,{reason:"launch_failed"}),"failed"}let m;try{m=await In(r,"start",c)}catch(s){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),s instanceof Mn||s instanceof Fn&&s.sent?"uncertain":(await T(d,{reason:"launch_failed"}),"failed")}try{await er(c,m)}catch(s){k({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:s})}try{await X("record_launch",()=>Sn(e.node_id,new Date().toISOString()))}catch(s){k({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:s})}return"started"}l(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),d=e.root===!0,c=Zn(e.parent,a.nodeId??null,d),m=e.mode??"base",s=e.rootLifecycle??(d?"resident":"terminal"),P=d&&s==="resident",$=c===null?null:await w(c),L=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Te(e.nodeId);const v=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,M=v===void 0?null:await De(v),F=await Un([$,L,M],async f=>f?.isolated===!0||f?.run_id!=null&&(await w(f.run_id))?.isolated===!0);if(F&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const D=F||e.isolated===!0;if(D&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let h=D||e.worktree===!0?e.nodeId??await le():e.nodeId,O=D?e.run!==void 0&&d&&!F?e.cwd:Re(Me(e.run?.grantee??$?.grantee??"app:terminal").nodes,h):e.cwd;const p=await Qn(e.profile,c,O),A=D?null:await je(p,e.worktreeCwd??O);A!==null&&(O=A,h??=await le());const N=e.worktree===!0||A!==null,ne=e.run?.grant_id??$?.grant_id??null,B=e.run??L??$??M,re=await ke((await ce(e.kind,m,{lifecycle:s,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:O,profileId:p,app:B?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:O,profileId:p}),await Xn({grantee:B?.grantee??"app:terminal",sub:B?.sub,grant_id:B?.grant_id});const te=M?.node_id??null;let y,W=O;const j=N&&await ze(p)?await He(p,A??e.worktreeCwd??e.cwd,h,e.worktreeBase):void 0,z=N&&j===void 0?await Ge(p):null;try{N&&j===void 0&&(y=z!==null?await Xe(z,e.worktreeCwd??e.cwd,h,e.worktreeBase):await Ke(e.worktreeCwd??e.cwd,h,e.worktreeBase),W=y.path);const f=N?await ke((await ce(e.kind,m,{lifecycle:s,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:W,profileId:p,app:B?.grantee??"app:terminal"})).launch,ne,e.model):re;j!==void 0&&(f.worktree=j),N&&await ve(_e(f),{cwd:W,profileId:p});const n=await Fe({kind:e.kind,mode:m,lifecycle:s,cwd:W,name:e.name??e.kind,description:e.description,parent:d?null:c,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:d?c??void 0:void 0,profile_id:p,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:D,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:v,modelOverride:e.model===void 0?void 0:f.model,...y!==void 0?{managedWorktree:y}:{},...h!==void 0?{nodeId:h}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(o?.(n.node_id),e.forkFrom!==void 0)try{await jn(n.node_id,te??null)}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}const q=e.prompt!=="",ye=`${q&&e.wakeOrigin!==void 0?`${nn(e.wakeOrigin)}
1
+ var Se=Object.defineProperty;var c=(e,r)=>Se(e,"name",{value:r,configurable:!0});import{accessSync as Ce,constants as Ee,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Pe}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as U}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as p,fullName as we,jobDir as dn,recordExecutionPid as sn,abortExecution as L,setFrozen as V}from"../canvas/index.js";import{contextDir as J,nodeAgentDir as Y}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as X,conversationStore as D}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Q}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as I}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Z,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Sn}from"../canvas/person.js";import{recordLaunch as Cn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as q,timedStep as A}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Pn,unregisteredConcreteModel as Tn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}from"./start-check.js";function R(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}c(R,"launchFailureOutcome");async function qn(e,r,o){try{return await Z.launch(e,r,o)}catch(t){try{await I(e,"crash",{reason:"launch_failed",outcome:R(t)})}catch{}const a=t.message;throw U(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}c(qn,"launchBrokerOrCrash");function Gn(e){return _n({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}c(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:s}=r.status;return{text:`exited (code ${a??"null"}, signal ${s??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:s,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}c(Vn,"notReadyDescription");async function Jn(e,r){try{await I(e,"crash",{reason:"launch_failed",outcome:R(r)})}catch{}try{Z.teardown(e)}catch{}}c(Jn,"crashAndTearDown");async function Yn(e){const r=(await D().list()).map(({conversation_id:a,path:s})=>({id:a,path:s})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}c(Yn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=X(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await D().header(t)).path}const o=await p(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=X(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await D().header(a)).path}return await Yn(r)}c(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await p(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}c(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Pn(e.model,r,e.modelExact===!0)}c(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await zn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:s,...d}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...d,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}c(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Tn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}c(ve,"assertLaunchModelRegistered");function Zn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}c(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(e);o!==null&&q("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))q(`mac_${t}`,a)}c(er,"recordStartCallTimings");async function nr(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:s}=await import("../../daemon/api/handlers/broker-ops.js");if(await Dn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Q().automaticReviveCap,runner:"machine",release:he()})}catch(l){return l instanceof ue?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),"failed")}let w;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const l=await vn(e.node_id,o,e.cwd);await En(d,l);const b=d;q("execution_setup",performance.now()-t);const[N,m]=await A("warm_and_bundle",async()=>await Promise.allSettled([A("warm_repos",async()=>await bn(await gn(),e.node_id)),A("start_bundle",async()=>{const x=e.sub??await Sn();return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:x,launchJson:l,runner:"machine"})})]));if(N.status==="rejected")throw N.reason;if(m.status==="rejected")throw m.reason;const B=m.value;w=await A("render_transaction",()=>yn(async x=>{const S=await s(e.node_id),f=await xn(x,b,e.node_id,new Date().toISOString());return await On(r,"start",{executionId:b,nodeId:e.node_id,attempt:1,sandboxName:null,release:he(),launchJson:l,cwd:e.cwd,resuming:!1,nodeToken:f,bundle:B,start:S})},{timingName:"render_tx"}))}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),await L(d,{reason:"launch_failed"}),"failed"}let y;try{y=await In(r,"start",w)}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),l instanceof Mn||l instanceof Fn&&l.sent?"uncertain":(await L(d,{reason:"launch_failed"}),"failed")}try{await er(w,y)}catch(l){v({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:l})}try{await A("record_launch",()=>Cn(e.node_id,new Date().toISOString()))}catch(l){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:l})}return"started"}c(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),s=e.root===!0,d=Zn(e.parent,a.nodeId??null,s),w=e.mode??"base",y=e.rootLifecycle??(s?"resident":"terminal"),l=s&&y==="resident",b=d===null?null:await p(d),N=e.creator===void 0||e.creator===null?null:await p(e.creator);e.nodeId!==void 0&&await Pe(e.nodeId);const m=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,B=m===void 0?null:await De(m),x=await Un([b,N,B],async h=>h?.isolated===!0||h?.run_id!=null&&(await p(h.run_id))?.isolated===!0);if(x&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=x||e.isolated===!0;if(S&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let f=S||e.worktree===!0?e.nodeId??await le():e.nodeId,M=S?e.run!==void 0&&s&&!x?e.cwd:Re(Me(e.run?.grantee??b?.grantee??"app:terminal").nodes,f):e.cwd;const _=await Qn(e.profile,d,M),W=S?null:await je(_,e.worktreeCwd??M);W!==null&&(M=W,f??=await le());const P=e.worktree===!0||W!==null,ne=e.run?.grant_id??b?.grant_id??null,T=e.run??N??b??B,re=await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:M,profileId:_}),await Xn({grantee:T?.grantee??"app:terminal",sub:T?.sub,grant_id:T?.grant_id});const te=B?.node_id??null;let C,j=M;const z=P&&await ze(_)?await He(_,W??e.worktreeCwd??e.cwd,f,e.worktreeBase):void 0,H=P&&z===void 0?await Ge(_):null;try{P&&z===void 0&&(C=H!==null?await Xe(H,e.worktreeCwd??e.cwd,f,e.worktreeBase):await Ke(e.worktreeCwd??e.cwd,f,e.worktreeBase),j=C.path);const h=P?await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:j,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model):re;z!==void 0&&(h.worktree=z),P&&await ve(_e(h),{cwd:j,profileId:_});const n=await Fe({kind:e.kind,mode:w,lifecycle:y,cwd:j,name:e.name??e.kind,description:e.description,parent:s?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:s?d??void 0:void 0,profile_id:_,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:m,modelOverride:e.model===void 0?void 0:h.model,...C!==void 0?{managedWorktree:C}:{},...f!==void 0?{nodeId:f}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:h});if(o?.(n.node_id),e.forkFrom!==void 0)try{await jn(n.node_id,te??null)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const G=e.prompt!=="",ye=`${G&&e.wakeOrigin!==void 0?`${nn(e.wakeOrigin)}
2
2
 
3
- `:""}${e.prompt}`;m==="orchestrator"&&await en(n.node_id,{goal:e.prompt.trim()}),await rr(n);let oe;if(v!==void 0)try{const i=U(v);if(i===null)throw new Error(`invalid fork source ${v}`);const u=await R().fork(i,n.node_id);oe=(await R().header(u)).path}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}const g=We(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Be(n.node_id)},q){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[tn]=rn(i),await on(g,n)}const b=me();if(await fn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await $n(n.profile_id??null):null;if(u!==null){Z("birth",performance.now()-t);const C=await nr(n,u,g);if(C==="started"||C==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await G(n.node_id,i),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}if(Je()&&!$e(n.cwd))throw new Ve({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ie=await b.reserveSlot(n.node_id),x=ie?await un(n.node_id):null;if(x?.verdict==="too_small"){b.releaseReservation(n.node_id);const i=cn(x);throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}if(!ie||x?.verdict==="denied")return x?.verdict==="denied"&&b.releaseReservation(n.node_id),await G(n.node_id,new Date().toISOString()),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:x?.verdict==="denied"?{reason:"app_memory",free_bytes:x.free_bytes,needed_bytes:x.needed_bytes}:{reason:"broker_cap",live_count:await b.occupancy(),hard_cap:Y().automaticReviveCap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null};const be=await kn(n.node_id),{automaticReviveCap:xe}=Y();let I;try{I=await fe(n.node_id,{daemonEpoch:b.epoch(),cap:xe})}catch(i){if(!(i instanceof ue))throw i;return b.releaseReservation(n.node_id),await G(n.node_id,new Date().toISOString()),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null}}g.env={...g.env,CRTR_EXECUTION_ID:I};let H;try{H=await qn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await T(I,{reason:"launch_failed"}),i}finally{b.releaseReservation(n.node_id)}if(H.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await T(I,{reason:"launch_failed"}),await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),K(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await sn(I,n.node_id,H.pid)==="shutdown")throw await T(I,{reason:"superseded"}),Q.teardown(n.node_id),K(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(P&&e.readiness==="await"){const i=await pn(n.node_id,H.exited);if(!i.ready){const u=Vn(n.node_id,i);k({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const C=await be.explanation();throw await Jn(n.node_id,new Error(C??u.text)),K(C!==null?`the root broker ${n.node_id} could not start \u2014 ${C}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,C!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ae=null,de=null;if(!d&&c!==null&&Bn("user").auto_open_child_viewers)try{const i=await mn(c);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await wn(n.node_id,i.session??"",{name:we(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:q});u!==null&&u.pane!==null&&u.pane!==""&&(de=u.session,ae=hn(u.pane))}}catch{}return{node:await w(n.node_id),frozen:!1,window:ae,session:de}}catch(f){throw y!==void 0&&h!==void 0&&await w(h)===null&&(z!==null?await qe(z,y):await Ue(y)),f}}l(ge,"spawnChildPrepared");async function ct(e){return ge(e)}l(ct,"spawnChild");async function rr(e){const r=Hn(e.cwd,e.profile_id).plans.get("node:start")??[];await Kn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await J(e.node_id),contextDir:await V(e.node_id),jobDir:dn(e.node_id)},runtime:{isBirth:!0,canvasHome:an(),profile:e.profile_id??null}})}l(rr,"invokeBirthLifecycleHooks");const tr=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function ut(e,r,o){const t=await w(e);if(t===null)throw _(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await pe(e),d=await V(e);try{await R().header(U(a)),Se(d,Ee.R_OK)}catch(c){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${c.message}`)}return ge({kind:t.kind,mode:"base",cwd:t.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...o===void 0?{}:{actor:o},profile:t.profile_id,model:t.model_override??void 0,...r===void 0?{}:{scopes:r}},async c=>{const m=await V(c);ln(await J(e),d,await J(c),m,tr)})}l(ut,"forkNode");export{ke as appPaidLaunch,ve as assertLaunchModelRegistered,ut as forkNode,rr as invokeBirthLifecycleHooks,pe as resolveForkSource,Qn as resolveProfileId,Zn as resolveSpawner,ct as spawnChild,ge as spawnChildPrepared};
3
+ `:""}${e.prompt}`;w==="orchestrator"&&await en(n.node_id,{goal:e.prompt.trim()}),await rr(n);let oe;if(m!==void 0)try{const i=X(m);if(i===null)throw new Error(`invalid fork source ${m}`);const u=await D().fork(i,n.node_id);oe=(await D().header(u)).path}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const g=We(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Be(n.node_id)},G){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[tn]=rn(i),await on(g,n)}const E=me();if(await fn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await $n(n.profile_id??null):null;if(u!==null){q("birth",performance.now()-t);const O=await nr(n,u,g);if(O==="started"||O==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await V(n.node_id,i),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}if(Je()&&!$e(n.cwd))throw new Ve({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ie=await E.reserveSlot(n.node_id),$=ie?await un(n.node_id):null;if($?.verdict==="too_small"){E.releaseReservation(n.node_id);const i=cn($);throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(!ie||$?.verdict==="denied")return $?.verdict==="denied"&&E.releaseReservation(n.node_id),await V(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:$?.verdict==="denied"?{reason:"app_memory",free_bytes:$.free_bytes,needed_bytes:$.needed_bytes}:{reason:"broker_cap",live_count:await E.occupancy(),hard_cap:Q().automaticReviveCap}}),{node:await p(n.node_id),frozen:!0,window:null,session:null};const be=await kn(n.node_id),{automaticReviveCap:xe}=Q();let F;try{F=await fe(n.node_id,{daemonEpoch:E.epoch(),cap:xe})}catch(i){if(!(i instanceof ue))throw i;return E.releaseReservation(n.node_id),await V(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await p(n.node_id),frozen:!0,window:null,session:null}}g.env={...g.env,CRTR_EXECUTION_ID:F};let K;try{K=await qn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await L(F,{reason:"launch_failed"}),i}finally{E.releaseReservation(n.node_id)}if(K.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await L(F,{reason:"launch_failed"}),await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),U(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await sn(F,n.node_id,K.pid)==="shutdown")throw await L(F,{reason:"superseded"}),Z.teardown(n.node_id),U(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(l&&e.readiness==="await"){const i=await pn(n.node_id,K.exited);if(!i.ready){const u=Vn(n.node_id,i);v({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const O=await be.explanation();throw await Jn(n.node_id,new Error(O??u.text)),U(O!==null?`the root broker ${n.node_id} could not start \u2014 ${O}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,O!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ae=null,de=null;if(!s&&d!==null&&Bn("user").auto_open_child_viewers)try{const i=await mn(d);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await wn(n.node_id,i.session??"",{name:we(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:G});u!==null&&u.pane!==null&&u.pane!==""&&(de=u.session,ae=hn(u.pane))}}catch{}return{node:await p(n.node_id),frozen:!1,window:ae,session:de}}catch(h){throw C!==void 0&&f!==void 0&&await p(f)===null&&(H!==null?await qe(H,C):await Ue(C)),h}}c(ge,"spawnChildPrepared");async function ct(e){return ge(e)}c(ct,"spawnChild");async function rr(e){const r=Hn(e.cwd,e.profile_id).plans.get("node:start")??[];await Kn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await Y(e.node_id),contextDir:await J(e.node_id),jobDir:dn(e.node_id)},runtime:{isBirth:!0,canvasHome:an(),profile:e.profile_id??null}})}c(rr,"invokeBirthLifecycleHooks");const tr=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function ut(e,r,o){const t=await p(e);if(t===null)throw k(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await pe(e),s=await J(e);try{await D().header(X(a)),Ce(s,Ee.R_OK)}catch(d){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${d.message}`)}return ge({kind:t.kind,mode:"base",cwd:t.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...o===void 0?{}:{actor:o},profile:t.profile_id,model:t.model_override??void 0,...r===void 0?{}:{scopes:r}},async d=>{const w=await J(d);ln(await Y(e),s,await Y(d),w,tr)})}c(ut,"forkNode");export{ke as appPaidLaunch,ve as assertLaunchModelRegistered,ut as forkNode,rr as invokeBirthLifecycleHooks,pe as resolveForkSource,Qn as resolveProfileId,Zn as resolveSpawner,ct as spawnChild,ge as spawnChildPrepared};
@@ -3,6 +3,10 @@ export declare function collectStepTimings<T>(fn: () => Promise<T>): Promise<{
3
3
  value: T;
4
4
  steps: Array<[string, number]>;
5
5
  }>;
6
+ /** True when the running request is collecting steps. */
7
+ export declare function isCollectingStepTimings(): boolean;
8
+ /** A short stable label for a statement: its verb and first table (`select_nodes`, `insert_run_events`), never its parameters or text. */
9
+ export declare function statementLabel(text: string): string;
6
10
  /** Record a step's duration in ms, when a request is collecting. */
7
11
  export declare function addStepTiming(name: string, ms: number): void;
8
12
  /** ms since the collection began (0 outside one). */
@@ -1 +1 @@
1
- var i=Object.defineProperty;var n=(t,e)=>i(t,"name",{value:e,configurable:!0});import{AsyncLocalStorage as a}from"node:async_hooks";const o=new a;async function u(t){const e=[];return{value:await o.run({steps:e,start:performance.now()},t),steps:e}}n(u,"collectStepTimings");function c(t,e){o.getStore()?.steps.push([t,e])}n(c,"addStepTiming");function f(){const t=o.getStore();return t===void 0?0:performance.now()-t.start}n(f,"sinceCollectionStart");async function m(t,e){const r=performance.now();try{return await e()}finally{c(t,performance.now()-r)}}n(m,"timedStep");function l(t){return t.map(([e,r])=>`${e};dur=${r.toFixed(1)}`).join(", ")}n(l,"serverTimingHeader");export{c as addStepTiming,u as collectStepTimings,l as serverTimingHeader,f as sinceCollectionStart,m as timedStep};
1
+ var i=Object.defineProperty;var o=(e,t)=>i(e,"name",{value:t,configurable:!0});import{AsyncLocalStorage as a}from"node:async_hooks";import{monitorEventLoopDelay as s}from"node:perf_hooks";const r=new a;async function m(e){const t=[],n=s({resolution:5});n.enable();try{return{value:await r.run({steps:t,start:performance.now()},e),steps:t}}finally{n.disable(),n.count>0&&t.push(["event_loop_delay_max",n.max/1e6],["event_loop_delay_p99",n.percentile(99)/1e6])}}o(m,"collectStepTimings");function d(){return r.getStore()!==void 0}o(d,"isCollectingStepTimings");function g(e){const t=/^\s*(select|insert|update|delete|with|savepoint|release|rollback)\b/i.exec(e)?.[1]?.toLowerCase()??"other",n=/\b(?:from|into|update)\s+(?:only\s+)?([a-z_][a-z0-9_.]*)/i.exec(e)?.[1]?.toLowerCase().replace(/\W/g,"_");return n===void 0?t:`${t}_${n}`}o(g,"statementLabel");function c(e,t){r.getStore()?.steps.push([e,t])}o(c,"addStepTiming");function x(){const e=r.getStore();return e===void 0?0:performance.now()-e.start}o(x,"sinceCollectionStart");async function y(e,t){const n=performance.now();try{return await t()}finally{c(e,performance.now()-n)}}o(y,"timedStep");function w(e){return e.map(([t,n])=>`${t};dur=${n.toFixed(1)}`).join(", ")}o(w,"serverTimingHeader");export{c as addStepTiming,m as collectStepTimings,d as isCollectingStepTimings,w as serverTimingHeader,x as sinceCollectionStart,g as statementLabel,y as timedStep};
@@ -16,6 +16,9 @@ export declare function typedLimitKey(owner: ObjectRow): string;
16
16
  export declare function deliveryLimitFor(manifest: ProfileManifest | null, owner: ObjectRow, reader?: Reader): Rung;
17
17
  /** The profile id (`profiles.id`) of a profile canvas object, or null when it has no profile identity. */
18
18
  export declare function profileIdOfObject(db: CanvasDb, profileObject: string): Promise<string | null>;
19
+ /** Make every document, head, rule, name and body read this reader's deliveries make run once per distinct input. Only for a reader built for one
20
+ * render that writes no documents while it lives: the answers are those of the first read, whatever changes after. */
21
+ export declare function shareCorpusReads(reader: Reader): void;
19
22
  /** The reader's `permits(read)` fragment over the alias `o`, from the reader's shared scope. */
20
23
  export declare function readRule(db: CanvasDb, reader: Reader): Promise<Frag>;
21
24
  /** Fetch the bodies of every document in `docs` that has not read its own, in one query, so each `body()` call after it answers from memory. */
@@ -1,2 +1,2 @@
1
- var D=Object.defineProperty;var c=(e,t)=>D(e,"name",{value:t,configurable:!0});import{permits as H,resolveReader as L}from"../../permissions/evaluator.js";import{get as q,getMany as B}from"../../graph/bodies.js";import{resolveName as C,viewOf as I,viewResolutions as W}from"../../graph/names.js";import{rulesOn as Y,rulesOfMany as F}from"../../graph/rules.js";import{loadExactProfileManifest as T}from"../../profiles/manifest.js";import{assembleNodeSubject as K}from"../subject.js";import{mapAsync as U}from"../../async-array.js";function b(e){return e.type==="node"?e.id:e.name}c(b,"ownerHandle");function J(e){return`${e.type}:${b(e)}`}c(J,"typedLimitKey");function P(e,t,n){if(n?.class==="node"&&n.profile!==null&&n.profile.id===t.id)return"content";const s=e?.delivery_limits;return s?s[J(t)]??s[b(t)]??"content":"content"}c(P,"deliveryLimitFor");async function z(e,t){return(await e.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'profile'").get(t))?.external_id??null}c(z,"profileIdOfObject");async function G(e,t){if(t.class!=="node"||t.profile===null)return null;const n=await z(e,t.profile.id);if(n===null)throw new Error(`profile object ${t.profile.id} has no profile identity`);return T(n).manifest}c(G,"readerManifest");const N=new WeakMap;function h(e,t){let n=N.get(t);return n===void 0&&(n=(async()=>{const s=await I(e,t),i=await L(e,t);return{reader:t,context:{view:s,ev:i},read:await H(e,i,"read","o"),manifest:await G(e,t)}})(),N.set(t,n),n.catch(()=>N.delete(t))),n}c(h,"corpusScope");async function re(e,t){return(await h(e,t)).read}c(re,"readRule");async function g(e,t,n,s){return await e.prepareUncached(`SELECT o.*, d.heads_key, d.unlisted, d.source_path FROM objects o JOIN documents d ON d.object = o.id
2
- WHERE o.type = 'document' AND o.deleted_at IS NULL AND ${n} AND ${t.read.sql} ORDER BY o.seq`).all(...s,...t.read.params)}c(g,"documentRows");async function Q(e,t){const n=[...new Set(t.flatMap(a=>a.heads_key.split(",")))],s=n.length===0?[]:await e.prepare("SELECT rev_id, document, number, body_hash FROM revisions WHERE rev_id = ANY(?::text[])").all(n),i=new Map(s.map(a=>[a.rev_id,a])),d=new Map;for(const a of t){let r;for(const p of a.heads_key.split(",")){const l=i.get(p);if(l===void 0||l.document!==a.id)continue;const f=Number(l.number);(r===void 0||f>r.number)&&(r={number:f,body_hash:l.body_hash})}if(r===void 0)throw new Error(`document ${a.id} has no head revision ${a.heads_key}`);d.set(a.id,r.body_hash)}return d}c(Q,"headBodyHashes");async function M(e,t,n,s){if(n.length===0)return[];const{reader:i,context:d,manifest:a}=t,{view:r}=d,p=new Map(r.map((o,w)=>[o.id,w])),l=[...new Set(n.map(o=>o.owner).filter(o=>!p.has(o)))],f=new Map(r.map(o=>[o.id,o]));if(l.length>0)for(const o of await e.prepare("SELECT * FROM objects WHERE id = ANY(?::text[])").all(l))f.set(o.id,o);const y=s??await F(e,n.map(o=>o.id)),u=await Q(e,n),m=await W(e,d,n.map(o=>o.name));return await U(n,async o=>{const w=f.get(o.owner);if(w===void 0)throw new Error(`document ${o.id} has no owner row ${o.owner}`);const k=p.get(w.id)??r.length,_=b(w),x=m.get(o.name),j=x===void 0?await C(e,i,o.name,d):x===null?{missing:!0}:{object:{id:x}},R=u.get(o.id),{heads_key:O,unlisted:$,source_path:S,...A}=o,E={object:A,owner:w,ownerHandle:_,viewRank:k,ownNode:i.class==="node"&&o.owner===i.node.id,shipped:S!==null,kind:o.kind==="preference"?"preference":"knowledge",name:o.name,displayName:"object"in j&&j.object.id===o.id?o.name:`${_}/${o.name}`,preview:o.preview,unlisted:$!==0,headsKey:O,bodyHash:R,body:c(async()=>v.get(E)??V(E,await q(e,R)),"body"),rules:y.get(o.id)??[],limit:P(a,w,i)};return E})}c(M,"toDeliveryDocs");const v=new WeakMap;function V(e,t){return v.set(e,t),t}c(V,"remember");async function ce(e,t){const n=t.filter(i=>!v.has(i)),s=await B(e,n.map(i=>i.bodyHash));for(const i of n)v.set(i,s.get(i.bodyHash))}c(ce,"primeBodies");async function de(e,t,n){const s=await h(e,t),{view:i}=s.context,d=new Map;if(i.length===0)return[];const a={sql:`${s.read.sql} AND o.owner IN (${i.map(()=>"?").join(",")})`,params:[...s.read.params,...i.map(u=>u.id)]};for(const u of await Y(e,n,a))d.set(u.object,[...d.get(u.object)??[],u]);const r=t.class==="node"&&n.includes("boot")?await g(e,s,"o.owner = ?",[t.node.id]):[],p=[...new Set([...d.keys(),...r.map(u=>u.id)])],l=p.length===0?[]:await g(e,s,"o.id = ANY(?::text[])",[p]),f=new Map(i.map((u,m)=>[u.id,m])),y=c(u=>f.get(u.owner)??i.length,"rankOf");return await M(e,s,l.sort((u,m)=>y(u)-y(m)||u.seq-m.seq),d)}c(de,"loadCorpus");async function X(e,t,n){if(n.length===0)return[];const s=await h(e,t),i=n.map(a=>a.id),d=new Map((await g(e,s,"o.id = ANY(?::text[])",[i])).map(a=>[a.id,a]));return await M(e,s,i.map(a=>{const r=d.get(a);if(!r)throw new Error(`document ${a} has no documents row or is not readable`);return r}))}c(X,"deliveryDocsOf");async function ue(e,t,n){return(await X(e,t,[n]))[0]}c(ue,"deliveryDocOf");async function le(e,t){return(await h(e,t)).context.view}c(le,"viewOwners");async function pe(e,t,n){const s=await h(e,t),i=[...new Set(n.map(r=>r.id))],d=new Map(i.map(r=>[r,[]]));if(i.length===0)return d;const a=await M(e,s,await g(e,s,"o.owner = ANY(?::text[]) AND d.unlisted = 0",[i]));for(const r of a)d.get(r.owner.id).push(r);return d}c(pe,"listingCorpora");async function fe(e,t){if(t.class!=="node")throw new Error(`nodeSubject needs a node reader, got ${t.class}`);const n=await K(t.node.id,[...t.repos,...t.projectRepos]);if(n===null)throw new Error(`no node ${t.node.id}`);return n}c(fe,"nodeSubject");export{ue as deliveryDocOf,X as deliveryDocsOf,P as deliveryLimitFor,pe as listingCorpora,de as loadCorpus,fe as nodeSubject,b as ownerHandle,ce as primeBodies,z as profileIdOfObject,re as readRule,J as typedLimitKey,le as viewOwners};
1
+ var B=Object.defineProperty;var s=(e,t)=>B(e,"name",{value:t,configurable:!0});import{permits as C,resolveReader as I}from"../../permissions/evaluator.js";import{get as q,getMany as Y}from"../../graph/bodies.js";import{resolveName as F,viewOf as T,viewResolutions as J}from"../../graph/names.js";import{rulesOn as K,rulesOfMany as U}from"../../graph/rules.js";import{loadExactProfileManifest as P}from"../../profiles/manifest.js";import{assembleNodeSubject as z}from"../subject.js";import{mapAsync as G}from"../../async-array.js";function b(e){return e.type==="node"?e.id:e.name}s(b,"ownerHandle");function Q(e){return`${e.type}:${b(e)}`}s(Q,"typedLimitKey");function V(e,t,n){if(n?.class==="node"&&n.profile!==null&&n.profile.id===t.id)return"content";const o=e?.delivery_limits;return o?o[Q(t)]??o[b(t)]??"content":"content"}s(V,"deliveryLimitFor");async function X(e,t){return(await e.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'profile'").get(t))?.external_id??null}s(X,"profileIdOfObject");async function Z(e,t){if(t.class!=="node"||t.profile===null)return null;const n=await X(e,t.profile.id);if(n===null)throw new Error(`profile object ${t.profile.id} has no profile identity`);return P(n).manifest}s(Z,"readerManifest");const O=new WeakSet,$=new WeakMap;function fe(e){O.add(e)}s(fe,"shareCorpusReads");function g(e,t,n){if(!O.has(e))return n();let o=$.get(e);o===void 0&&$.set(e,o=new Map);const a=JSON.stringify(t);let c=o.get(a);return c===void 0&&(c=n(),o.set(a,c),c.catch(()=>o.delete(a))),c}s(g,"once");const M=new WeakMap;function y(e,t){let n=M.get(t);return n===void 0&&(n=(async()=>{const o=await T(e,t),a=await I(e,t);return{reader:t,context:{view:o,ev:a},read:await C(e,a,"read","o"),manifest:await Z(e,t)}})(),M.set(t,n),n.catch(()=>M.delete(t))),n}s(y,"corpusScope");async function we(e,t){return(await y(e,t)).read}s(we,"readRule");async function v(e,t,n,o){return[...await g(t.reader,["docs",n,o],async()=>await ee(e,t,n,o))]}s(v,"documentRows");async function ee(e,t,n,o){return await e.prepareUncached(`SELECT o.*, d.heads_key, d.unlisted, d.source_path FROM objects o JOIN documents d ON d.object = o.id
2
+ WHERE o.type = 'document' AND o.deleted_at IS NULL AND ${n} AND ${t.read.sql} ORDER BY o.seq`).all(...o,...t.read.params)}s(ee,"documentRowsNow");async function te(e,t,n){return await g(t.reader,["heads",n.map(o=>[o.id,o.heads_key])],async()=>await ne(e,n))}s(te,"headBodyHashes");async function ne(e,t){const n=[...new Set(t.flatMap(r=>r.heads_key.split(",")))],o=n.length===0?[]:await e.prepare("SELECT rev_id, document, number, body_hash FROM revisions WHERE rev_id = ANY(?::text[])").all(n),a=new Map(o.map(r=>[r.rev_id,r])),c=new Map;for(const r of t){let d;for(const p of r.heads_key.split(",")){const l=a.get(p);if(l===void 0||l.document!==r.id)continue;const f=Number(l.number);(d===void 0||f>d.number)&&(d={number:f,body_hash:l.body_hash})}if(d===void 0)throw new Error(`document ${r.id} has no head revision ${r.heads_key}`);c.set(r.id,d.body_hash)}return c}s(ne,"headBodyHashesNow");async function _(e,t,n,o){if(n.length===0)return[];const{reader:a,context:c,manifest:r}=t,{view:d}=c,p=new Map(d.map((i,w)=>[i.id,w])),l=[...new Set(n.map(i=>i.owner).filter(i=>!p.has(i)))],f=new Map(d.map(i=>[i.id,i]));if(l.length>0)for(const i of await e.prepare("SELECT * FROM objects WHERE id = ANY(?::text[])").all(l))f.set(i.id,i);const h=n.map(i=>i.id),u=o??await g(a,["rules",h],async()=>await U(e,h)),m=await te(e,t,n),S=await g(a,["names",n.map(i=>i.name)],async()=>await J(e,c,n.map(i=>i.name)));return await G(n,async i=>{const w=f.get(i.owner);if(w===void 0)throw new Error(`document ${i.id} has no owner row ${i.owner}`);const A=p.get(w.id)??d.length,k=b(w),E=S.get(i.name),R=E===void 0?await F(e,a,i.name,c):E===null?{missing:!0}:{object:{id:E}},j=m.get(i.id),{heads_key:D,unlisted:H,source_path:L,...W}=i,N={object:W,owner:w,ownerHandle:k,viewRank:A,ownNode:a.class==="node"&&i.owner===a.node.id,shipped:L!==null,kind:i.kind==="preference"?"preference":"knowledge",name:i.name,displayName:"object"in R&&R.object.id===i.id?i.name:`${k}/${i.name}`,preview:i.preview,unlisted:H!==0,headsKey:D,bodyHash:j,body:s(async()=>x.get(N)??oe(N,await q(e,j)),"body"),rules:u.get(i.id)??[],limit:V(r,w,a)};return N})}s(_,"toDeliveryDocs");const x=new WeakMap;function oe(e,t){return x.set(e,t),t}s(oe,"remember");async function me(e,t){const n=t.filter(a=>!x.has(a)),o=await Y(e,n.map(a=>a.bodyHash));for(const a of n)x.set(a,o.get(a.bodyHash))}s(me,"primeBodies");async function he(e,t,n){const o=await y(e,t),{view:a}=o.context,c=new Map;if(a.length===0)return[];const r={sql:`${o.read.sql} AND o.owner IN (${a.map(()=>"?").join(",")})`,params:[...o.read.params,...a.map(u=>u.id)]};for(const u of await K(e,n,r))c.set(u.object,[...c.get(u.object)??[],u]);const d=t.class==="node"&&n.includes("boot")?await v(e,o,"o.owner = ?",[t.node.id]):[],p=[...new Set([...c.keys(),...d.map(u=>u.id)])],l=p.length===0?[]:await v(e,o,"o.id = ANY(?::text[])",[p]),f=new Map(a.map((u,m)=>[u.id,m])),h=s(u=>f.get(u.owner)??a.length,"rankOf");return await _(e,o,l.sort((u,m)=>h(u)-h(m)||u.seq-m.seq),c)}s(he,"loadCorpus");async function ae(e,t,n){if(n.length===0)return[];const o=await y(e,t),a=n.map(r=>r.id),c=new Map((await v(e,o,"o.id = ANY(?::text[])",[a])).map(r=>[r.id,r]));return await _(e,o,a.map(r=>{const d=c.get(r);if(!d)throw new Error(`document ${r} has no documents row or is not readable`);return d}))}s(ae,"deliveryDocsOf");async function ye(e,t,n){return(await ae(e,t,[n]))[0]}s(ye,"deliveryDocOf");async function ge(e,t){return(await y(e,t)).context.view}s(ge,"viewOwners");async function ve(e,t,n){const o=await y(e,t),a=[...new Set(n.map(d=>d.id))],c=new Map(a.map(d=>[d,[]]));if(a.length===0)return c;const r=await _(e,o,await v(e,o,"o.owner = ANY(?::text[]) AND d.unlisted = 0",[a]));for(const d of r)c.get(d.owner.id).push(d);return c}s(ve,"listingCorpora");async function xe(e,t){if(t.class!=="node")throw new Error(`nodeSubject needs a node reader, got ${t.class}`);const n=await z(t.node.id,[...t.repos,...t.projectRepos]);if(n===null)throw new Error(`no node ${t.node.id}`);return n}s(xe,"nodeSubject");export{ye as deliveryDocOf,ae as deliveryDocsOf,V as deliveryLimitFor,ve as listingCorpora,he as loadCorpus,xe as nodeSubject,b as ownerHandle,me as primeBodies,X as profileIdOfObject,we as readRule,fe as shareCorpusReads,Q as typedLimitKey,ge as viewOwners};
@@ -5,7 +5,7 @@ import type { StartDataDTO } from '../../../api/dto/execution-start.js';
5
5
  export declare function extensionNode(node: NonNullable<Awaited<ReturnType<typeof getNode>>>): Promise<BrokerExtensionNodeDTO>;
6
6
  /** The node state, names, bearings and first system-prompt block a cycle opens with, and the persona acknowledgement the bearings make. A companion
7
7
  * awaiting its marker may still be shut down by the bind: it gets the state and names only, with no bearings, ledger write, persona acknowledgement
8
- * or system prompt until the bind commits. */
8
+ * or system prompt until the bind commits. The node's repository view is built once and serves both the state's subject and the delivery. */
9
9
  export declare function renderStartData(nodeId: string, bearings: BrokerCycleStartRequest['bearings'], namesOnly: boolean, warmed?: boolean): Promise<{
10
10
  state: BrokerExtensionStateDTO;
11
11
  delivery: Pick<BrokerCycleStartResultDTO, 'names' | 'boot' | 'system_prompt'>;
@@ -1 +1 @@
1
- var X=Object.defineProperty;var s=(t,e)=>X(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as Z,findNodeBySessionFile as I,getNode as g,getNodes as q,isWarmSpare as ee,recordLaunch as te,recordRespawnAttempt as ne,recordSettledTurn as ie,setPresence as x,subscriptionsOf as re,updateNode as _,updateNodeTelemetry as oe}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ae,recordExecutionPid as se}from"../../../core/canvas/executions.js";import{bindSession as ce,readLiveSession as de,transferSession as le}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ue}from"../../../core/canvas/paths.js";import{isPidAlive as pe}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as fe}from"../../../core/substrate/subject.js";import{openDb as C,withCanvasWrite as f}from"../../../core/canvas/db.js";import{runningJobs as me}from"../../../core/graph/jobs.js";import{notFound as R,usage as l}from"../../../core/errors.js";import{hasUnseenWakeMail as F,releaseExecutionMail as we}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as ye}from"../../../core/runtime/kickoff.js";import{readRoadmap as he}from"../../../core/runtime/roadmap.js";import{forkSourceNode as be}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{confirmViewer as T,probeViewer as B,tearDownNode as N}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as _e}from"../viewer-presence.js";import{evaluateStop as ke}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as L}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as ve,recordFault as ge}from"../../../core/canvas/recovery.js";import{updateModelRecipe as xe}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as Se}from"../../review/finish.js";import{emitEvent as D}from"../../../core/events/emit.js";import{consumePendingPark as Pe,recordPendingParkActivity as Re}from"../../park-pending.js";import{shouldParkAfterSummary as Oe}from"../../park-activity.js";import{ownerOnly as Ee}from"../router.js";import{situationalContextEnvelope as Ae}from"../../../core/runtime/situational-context.js";import{recoveryState as Ce,requireCurrentExecution as u}from"./broker-recovery.js";import{runAttachments as Fe}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Be}from"../../../core/graph/reader.js";import{checkoutsForCwd as Ne}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Le}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as De}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Me,writeNodeTelemetryRecord as je}from"./telemetry-record.js";import{mapAsync as Ve}from"../../../core/async-array.js";import{crtrVersion as M}from"../../../shared/crtr-version.js";import{buildPiArgv as $e}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ue}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as We,cycleCompatible as He}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Je,drainBearings as Ge}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Ye}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ke}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as ze}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Qe}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Xe}from"../../../api/errors.js";function p(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`${e} requires a JSON body`);return t}s(p,"objectBody");function j(t){const e=p(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw l("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw l("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw l("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw l("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw l("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw l("reviewBoundaryIds must be an array of strings");return e}s(j,"parseSessionBoundBody");function Ze(t){const e=p(t,"broker settle");if(typeof e.stopReason!="string")throw l("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw l(`${n} must be a boolean`);return e}s(Ze,"parseSettleBody");function Ie(t){const e=p(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw l("brokerVersion must be a non-empty string");return e}s(Ie,"parseCycleBody");function qe(t){const e=p(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw l("outcome must be completed or failed");return e}s(qe,"parseParkCompleteBody");function et(t){const e=p(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw l("expected_execution_id must be a non-empty string");const n=Me(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(et,"parseTelemetryBody");function tt(t){const e=p(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw l("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw l("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw l("userSelected must be a boolean");return e}s(tt,"parseModelCommitBody");async function m(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(m,"requireNode");async function v(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(v,"extensionNode");async function V(t){const e=await m(t),n=[],r=new Set([t]);let i=e.parent??null;for(;i!==null&&i!==""&&!r.has(i);){r.add(i);const d=await g(i);if(d===null)break;n.unshift(await v(d)),i=d.parent??null}const a=await Ve((await q((await re(t)).map(d=>d.node_id))).filter(d=>d.kind!=="human").sort((d,w)=>d.status===w.status?0:d.status==="active"?-1:w.status==="active"?1:0),v),o=typeof e.fork_source_file=="string"?await be(e.fork_source_file):null,c=await fe(t);if(c===null)throw R(`unknown node: ${t}`,{received:t});return{node:await v(e),warm_spare:await ee(t),situational_card:await Ae(t),ancestors:n,children:a,fork_source:o===null?null:await v(o),subject:c,roadmap:await he(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function nt(t){const e=p(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw l("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw l("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw l("recap expected must contain name, description, title, icon, and kind strings");return e}s(nt,"parseGeneratedNameBody");function it(t){const e=p(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw l(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(it,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:Z(e.sessionFile);return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t);if(await se(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await I(n);if(o!==null&&o.node_id!==t){if(pe(o.pi_pid))return await ge(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await de(o.node_id);if(c===null||await le({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await ce(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await ye(t),i.intent==="refresh"&&await k(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function rt(t){return{status:200,body:await $(t.params.id,j(t.body))}}s(rt,"handleSessionBound");function ot(t){const e=j(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw l("bearings must be fresh, inherited or present");return e}s(ot,"parseCycleStartBody");async function at(t,e,n,r,i=!1){const a=e.warm_spare||r,o=!a&&n!=="present";return i||await Be(await C(),t),await f(async c=>{const d=await Te(c,t,async(K,z,Q)=>await Ne(c,K,z,Q)),w=await Le(c,d),y=await O(c,d,{activity:"names"},w),b=o?await O(c,d,{activity:"boot",...n==="inherited"?{inherited:!0}:{}},w):void 0,A=a?void 0:await O(c,d,{activity:"system-prompt"},w);return{names:{refs:y.refs,names:y.names},...b===void 0?{}:{boot:{content:b.content,...b.inherited===!0?{inherited:!0}:{}}},...A===void 0?{}:{system_prompt:A.content}}})}s(at,"startupDelivery");async function U(t,e,n,r=!1){const i=await V(t),a=await at(t,i,e,n,r);if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,d=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(d,o)||await Y(t,d,o)}return{state:i,delivery:a}}s(U,"renderStartData");async function mn(t){const{state:e,delivery:n}=await U(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(mn,"renderCarriedStart");async function st(t){const e=t.params.id,n=ot(t.body),r=await m(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await u(e,n.executionId);else{const{action:y}=await $(e,n);if(y!=="none")return{status:200,body:{action:y}}}const{state:c,delivery:d}=await U(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...d,recovery:await Ce(e),attachments:(await Fe(e)).map(({path:y,sha256:b})=>({path:y,sha256:b})),structured_request:await L(e)}}}s(st,"handleCycleStart");async function W(t,e){return e.live!==null||await _e(t)||await F(t)}s(W,"isHeldAwake");async function H(t,e){return(await S(t))?.runner==="blaxel"&&!await W(t,e)&&(await me(await C(),t)).length===0}s(H,"residentBlaxelCanIdle");function J(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(J,"refreshDirective");async function ct(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ie(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await ne(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await k(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:J(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await ve(t))?.retry.disposition==="fatal"&&await L(t)===null&&await H(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:J(e),closePane:!1};const a=await ke(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await F(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await W(t,n);return(await S(t))?.runner==="blaxel"?{directive:await H(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await k(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ct,"settleBroker");async function dt(t){const e=t.params.id,n=Ie(t.body);await u(e,n.expected_execution_id);const r=await m(e);if(r.intent!=="refresh")throw new Xe(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=$e(r);return n.brokerVersion===M()&&(i.release===null||i.release===M())&&He(i.launchJson,await Ue(e,a,r.cwd))?{status:200,body:await lt(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(dt,"handleCycle");async function lt(t,e,n,r){e.cycles=(e.cycles??0)+1,await we(t,n);const i=await Ge(e,n),a=await Je(e,i);await Ye(t),await Ke(t,e,!1),await ze(t),await h(t,{preserveEpisode:!0}),await te(t,new Date().toISOString()),await _(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of We)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Qe({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(lt,"startCycleRecord");async function ut(t){const e=t.params.id,n=p(t.body,"broker idle");return await u(e,n.expected_execution_id),await ae(n.expected_execution_id),{status:204}}s(ut,"handleIdle");async function pt(t){const e=t.params.id,n=Ze(t.body);await u(e,n.expected_execution_id);const r=await B(e),{directive:i,closePane:a}=await f(async()=>await ct(e,n,await T(r)));return a&&await N(e),i.action!=="reprompt"&&Se(e).catch(o=>D({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(pt,"handleSettle");async function ft(t){const e=t.params.id,n=qe(t.body);await u(e,n.expected_execution_id);const r=await B(e),i=await f(async()=>{const a=await Pe(e);if(a===void 0)return{action:"stay_dormant"};const o=await m(e);return await Oe(e,o,a,await T(r))?(await h(e),await k(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),D({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ue(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await N(e),{status:200,body:i}}s(ft,"handleParkComplete");async function mt(t){const e=t.params.id;return await u(e,p(t.body,"broker park-activity").expected_execution_id),{status:200,body:await f(async()=>({activity:await Re(e)?"recorded":"none"}))}}s(mt,"handleParkActivity");async function wt(t){const e=t.params.id,n=et(t.body);return await u(e,n.expected_execution_id),await f(async()=>{await oe(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),je(e,n)}),{status:204}}s(wt,"handleTelemetry");async function yt(t){const e=t.params.id,n=tt(t.body);return await u(e,n.expected_execution_id),{status:200,body:{modelOverride:(await f(async()=>await xe(await m(e),n.spec,n.intent,n.userSelected))).model_override}}}s(yt,"handleModelCommit");let G=!0;function wn(t){G=t}s(wn,"setRequestsStartRunObservers");async function ht(t){const e=t.params.id,n=await m(e);return n.run_id&&G&&await De(e,n.run_id),{status:200,body:await V(e)}}s(ht,"handleExtensionState");async function bt(t){const e=t.params.id,n=nt(t.body);return await u(e,n.expected_execution_id),{status:200,body:await f(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await m(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const d=await _(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(d),description:d.description??"",title:d.title??"",icon:d.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await _(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(bt,"handleGeneratedName");async function _t(t){const e=t.params.id,n=it(t.body);return await u(e,n.expected_execution_id),{status:200,body:{applied:await Y(e,n.from,n.to)}}}s(_t,"handlePersonaAck");async function Y(t,e,n){return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await _(t,{persona_ack:n}),!0)})}s(Y,"applyPersonaAck");const yn=Ee([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:mt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:bt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:_t}]);export{yn as brokerOperationRoutes,v as extensionNode,mn as renderCarriedStart,U as renderStartData,wn as setRequestsStartRunObservers};
1
+ var K=Object.defineProperty;var s=(t,e)=>K(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as z,findNodeBySessionFile as Q,getNode as g,getNodes as X,isWarmSpare as Z,recordLaunch as I,recordRespawnAttempt as q,recordSettledTurn as ee,setPresence as x,subscriptionsOf as te,updateNode as b,updateNodeTelemetry as ne}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ie,recordExecutionPid as re}from"../../../core/canvas/executions.js";import{bindSession as oe,readLiveSession as ae,transferSession as se}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ce}from"../../../core/canvas/paths.js";import{isPidAlive as de}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as le}from"../../../core/substrate/subject.js";import{shareCorpusReads as ue}from"../../../core/substrate/delivery/corpus.js";import{openDb as A,withCanvasWrite as w}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as R,usage as d}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as fe}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as me}from"../../../core/runtime/kickoff.js";import{readRoadmap as we}from"../../../core/runtime/roadmap.js";import{forkSourceNode as ye}from"../../../core/runtime/nodes.js";import{transition as _}from"../../../core/runtime/lifecycle.js";import{confirmViewer as F,probeViewer as T,tearDownNode as B}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as he}from"../viewer-presence.js";import{evaluateStop as be}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as N}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as _e,recordFault as ke}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ve}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as ge}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as xe,recordPendingParkActivity as Se}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ee,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Ce,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Te}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Be}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as Ne}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Le,writeNodeTelemetryRecord as De}from"./telemetry-record.js";import{mapAsync as Me}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Ve}from"../../../core/runtime/launch.js";import{brokerLaunchJson as $e}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as je,cycleCompatible as Ue}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as We,drainBearings as He}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Je}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ge}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Ye}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Ke}from"../../../core/runtime/stamp/protocol.js";import{ApiError as ze}from"../../../api/errors.js";function m(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} requires a JSON body`);return t}s(m,"objectBody");function M(t){const e=m(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw d("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw d("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw d("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw d("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw d("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw d("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function Qe(t){const e=m(t,"broker settle");if(typeof e.stopReason!="string")throw d("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw d(`${n} must be a boolean`);return e}s(Qe,"parseSettleBody");function Xe(t){const e=m(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw d("brokerVersion must be a non-empty string");return e}s(Xe,"parseCycleBody");function Ze(t){const e=m(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw d("outcome must be completed or failed");return e}s(Ze,"parseParkCompleteBody");function Ie(t){const e=m(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw d("expected_execution_id must be a non-empty string");const n=Le(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(Ie,"parseTelemetryBody");function qe(t){const e=m(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw d("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw d("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw d("userSelected must be a boolean");return e}s(qe,"parseModelCommitBody");async function y(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(y,"requireNode");async function k(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(k,"extensionNode");async function V(t,e){const n=await y(t),r=[],i=new Set([t]);let a=n.parent??null;for(;a!==null&&a!==""&&!i.has(a);){i.add(a);const u=await g(a);if(u===null)break;r.unshift(await k(u)),a=u.parent??null}const o=await Me((await X((await te(t)).map(u=>u.node_id))).filter(u=>u.kind!=="human").sort((u,p)=>u.status===p.status?0:u.status==="active"?-1:p.status==="active"?1:0),k),c=typeof n.fork_source_file=="string"?await ye(n.fork_source_file):null,l=e??await le(t);if(l===null)throw R(`unknown node: ${t}`,{received:t});return{node:await k(n),warm_spare:await Z(t),situational_card:await Oe(t),ancestors:r,children:o,fork_source:c===null?null:await k(c),subject:l,roadmap:await we(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function et(t){const e=m(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw d("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw d("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw d("recap expected must contain name, description, title, icon, and kind strings");return e}s(et,"parseGeneratedNameBody");function tt(t){const e=m(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw d(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(tt,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:z(e.sessionFile);return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t);if(await re(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await Q(n);if(o!==null&&o.node_id!==t){if(de(o.pi_pid))return await ke(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await ae(o.node_id);if(c===null||await se({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await oe(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await me(t),i.intent==="refresh"&&await _(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function nt(t){return{status:200,body:await $(t.params.id,M(t.body))}}s(nt,"handleSessionBound");function it(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw d("bearings must be fresh, inherited or present");return e}s(it,"parseCycleStartBody");async function rt(t,e,n,r,i,a){const o=r.warm_spare||a,c=!o&&i!=="present",l=await O(t,e,{activity:"names"},n),u=c?await O(t,e,{activity:"boot",...i==="inherited"?{inherited:!0}:{}},n):void 0,p=o?void 0:await O(t,e,{activity:"system-prompt"},n);return{names:{refs:l.refs,names:l.names},...u===void 0?{}:{boot:{content:u.content,...u.inherited===!0?{inherited:!0}:{}}},...p===void 0?{}:{system_prompt:p.content}}}s(rt,"startupDelivery");async function j(t,e,n,r=!1){r||await Fe(await A(),t);const{state:i,delivery:a}=await w(async o=>{const c=await Ce(o,t,async(p,v,Y)=>await Te(o,p,v,Y));ue(c);const l=await Be(o,c),u=await V(t,l);return{state:u,delivery:await rt(o,c,l,u,e,n)}});if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,l=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(l,o)||await G(t,l,o)}return{state:i,delivery:a}}s(j,"renderStartData");async function fn(t){const{state:e,delivery:n}=await j(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(fn,"renderCarriedStart");async function ot(t){const e=t.params.id,n=it(t.body),r=await y(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await f(e,n.executionId);else{const{action:p}=await $(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:l}=await j(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...l,recovery:await Ee(e),attachments:(await Ae(e)).map(({path:p,sha256:v})=>({path:p,sha256:v})),structured_request:await N(e)}}}s(ot,"handleCycleStart");async function U(t,e){return e.live!==null||await he(t)||await C(t)}s(U,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await U(t,e)&&(await pe(await A(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function at(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ee(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await q(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await _(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await _e(t))?.retry.disposition==="fatal"&&await N(t)===null&&await W(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:H(e),closePane:!1};const a=await be(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await U(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await _(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(at,"settleBroker");async function st(t){const e=t.params.id,n=Xe(t.body);await f(e,n.expected_execution_id);const r=await y(e);if(r.intent!=="refresh")throw new ze(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=Ve(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&Ue(i.launchJson,await $e(e,a,r.cwd))?{status:200,body:await ct(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(st,"handleCycle");async function ct(t,e,n,r){e.cycles=(e.cycles??0)+1,await fe(t,n);const i=await He(e,n),a=await We(e,i);await Je(t),await Ge(t,e,!1),await Ye(t),await h(t,{preserveEpisode:!0}),await I(t,new Date().toISOString()),await b(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of je)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Ke({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(ct,"startCycleRecord");async function dt(t){const e=t.params.id,n=m(t.body,"broker idle");return await f(e,n.expected_execution_id),await ie(n.expected_execution_id),{status:204}}s(dt,"handleIdle");async function lt(t){const e=t.params.id,n=Qe(t.body);await f(e,n.expected_execution_id);const r=await T(e),{directive:i,closePane:a}=await w(async()=>await at(e,n,await F(r)));return a&&await B(e),i.action!=="reprompt"&&ge(e).catch(o=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(lt,"handleSettle");async function ut(t){const e=t.params.id,n=Ze(t.body);await f(e,n.expected_execution_id);const r=await T(e),i=await w(async()=>{const a=await xe(e);if(a===void 0)return{action:"stay_dormant"};const o=await y(e);return await Pe(e,o,a,await F(r))?(await h(e),await _(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ce(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await B(e),{status:200,body:i}}s(ut,"handleParkComplete");async function pt(t){const e=t.params.id;return await f(e,m(t.body,"broker park-activity").expected_execution_id),{status:200,body:await w(async()=>({activity:await Se(e)?"recorded":"none"}))}}s(pt,"handleParkActivity");async function ft(t){const e=t.params.id,n=Ie(t.body);return await f(e,n.expected_execution_id),await w(async()=>{await ne(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),De(e,n)}),{status:204}}s(ft,"handleTelemetry");async function mt(t){const e=t.params.id,n=qe(t.body);return await f(e,n.expected_execution_id),{status:200,body:{modelOverride:(await w(async()=>await ve(await y(e),n.spec,n.intent,n.userSelected))).model_override}}}s(mt,"handleModelCommit");let J=!0;function mn(t){J=t}s(mn,"setRequestsStartRunObservers");async function wt(t){const e=t.params.id,n=await y(e);return n.run_id&&J&&await Ne(e,n.run_id),{status:200,body:await V(e)}}s(wt,"handleExtensionState");async function yt(t){const e=t.params.id,n=et(t.body);return await f(e,n.expected_execution_id),{status:200,body:await w(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await y(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const l=await b(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(l),description:l.description??"",title:l.title??"",icon:l.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await b(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(yt,"handleGeneratedName");async function ht(t){const e=t.params.id,n=tt(t.body);return await f(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(ht,"handlePersonaAck");async function G(t,e,n){return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await b(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const wn=Re([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:nt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:ot},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:lt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:mt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:yt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:ht}]);export{wn as brokerOperationRoutes,k as extensionNode,fn as renderCarriedStart,j as renderStartData,mn as setRequestsStartRunObservers};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.684",
3
+ "version": "0.3.685",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "license": "UNLICENSED",
158
158
  "dependencies": {
159
- "@north-light/identity": "0.3.684",
160
- "@north-light/plugin": "0.3.684",
159
+ "@north-light/identity": "0.3.685",
160
+ "@north-light/plugin": "0.3.685",
161
161
  "@earendil-works/chord": "1.5.2",
162
162
  "@earendil-works/pi-agent-core": "1.5.2",
163
163
  "@earendil-works/pi-ai": "1.5.2",
@@ -8,6 +8,7 @@ import { publishFileExclusive } from '../fs-utils.js';
8
8
  import { initializeEmptyLayout, runtimeRoot } from '../layout.js';
9
9
  import { translatePlaceholders, translateOnce } from '../statements.js';
10
10
  import { ensureHome } from './paths.js';
11
+ import { addStepTiming, isCollectingStepTimings, statementLabel } from '../step-timings.js';
11
12
  import { emitEvent } from '../events/emit.js';
12
13
  import { ensureSchema } from './schema-chain.js';
13
14
  import { canvasDatabaseSchema, canvasSchemaDatabaseUrl, canvasSearchPathOptions } from './schema-version.js';
@@ -165,7 +166,9 @@ class Handle {
165
166
  return await transaction.client.query(config);
166
167
  }
167
168
  finally {
168
- transaction.statementMs += performance.now() - began;
169
+ const ms = performance.now() - began;
170
+ transaction.statementMs += ms;
171
+ transaction.statements?.push({ text: config.text, ms });
169
172
  }
170
173
  }
171
174
  return await this.connections().query(config);
@@ -382,7 +385,11 @@ export async function withCanvasWrite(body, options = {}) {
382
385
  return result;
383
386
  }
384
387
  const entry = new Error('canvas write transaction entered here');
388
+ const timingName = isCollectingStepTimings() ? options.timingName : undefined;
389
+ const waitStart = performance.now();
385
390
  const client = await handle.checkout();
391
+ if (timingName !== undefined)
392
+ addStepTiming(`${timingName}_checkout_wait`, performance.now() - waitStart);
386
393
  // The pool removes its own 'error' listener while a connection is checked out. A server error or a dropped socket that
387
394
  // arrives between statements (a body awaiting non-database work) has no active query to fail, so without a listener of
388
395
  // ours it is an unhandled 'error' event and kills the process. Record it: the client is no longer queryable, so the
@@ -393,7 +400,7 @@ export async function withCanvasWrite(body, options = {}) {
393
400
  const started = performance.now();
394
401
  let committed = false;
395
402
  let failed = false;
396
- const transaction = { handle, client, open: true, afterCommit: [], statementMs: 0 };
403
+ const transaction = { handle, client, open: true, afterCommit: [], statementMs: 0, ...(timingName === undefined ? {} : { statements: [] }) };
397
404
  try {
398
405
  await client.query('BEGIN');
399
406
  try {
@@ -416,6 +423,12 @@ export async function withCanvasWrite(body, options = {}) {
416
423
  finally {
417
424
  transaction.open = false;
418
425
  const held = performance.now() - started;
426
+ if (timingName !== undefined && transaction.statements !== undefined) {
427
+ addStepTiming(`${timingName}_statements_count`, transaction.statements.length);
428
+ addStepTiming(`${timingName}_statements_ms`, transaction.statementMs);
429
+ addStepTiming(`${timingName}_other_ms`, held - transaction.statementMs);
430
+ [...transaction.statements].sort((a, b) => b.ms - a.ms).slice(0, 3).forEach((st, i) => addStepTiming(`${timingName}_slow${i + 1}_${statementLabel(st.text)}`, st.ms));
431
+ }
419
432
  // A failed transaction rethrows its error to the caller; warning here would print ahead of it and hide the cause.
420
433
  if (!failed && held - transaction.statementMs > SLOW_TRANSACTION_MS) {
421
434
  console.warn(`[canvas db] write transaction held its connection ${Math.round(held)}ms (${Math.round(transaction.statementMs)}ms in its statements); its body did non-db work while holding a pooled connection and its row locks\n${entry.stack}`);
@@ -62,21 +62,37 @@ function chainOf(stored) {
62
62
  /** The chain of `dir` as this process knows it: git here on a Mac or self-hosted install; on a cloud role the row the person's machine reported
63
63
  * most recently, git where nothing is stored (a Mac path is a missing directory there: `not-a-repo`, no git spawned, no error). */
64
64
  export async function checkoutChainOf(db, dir, person) {
65
- if (!isCloudRole())
66
- return await checkoutChain(dir);
67
- // A cloud role's node on a person's machine has no checkout here: its answer is the stored row. A node with no stored row (a profile on no machine) keeps git.
65
+ const resolved = resolve(dir);
66
+ return (await checkoutChainsOf(db, [resolved], person)).get(resolved);
67
+ }
68
+ /** The chains of several directories in one read, keyed by directory (as given; each already resolved). On a cloud role, the newest row the person's
69
+ * machine reported for each; git where none is stored, or where the process has no person (a profile on no machine). Elsewhere, git. */
70
+ export async function checkoutChainsOf(db, dirs, person) {
71
+ const out = new Map();
72
+ const unique = [...new Set(dirs)];
73
+ if (!isCloudRole()) {
74
+ for (const dir of unique)
75
+ out.set(dir, await checkoutChain(dir));
76
+ return out;
77
+ }
68
78
  let who;
69
79
  try {
70
80
  who = await person();
71
81
  }
72
82
  catch (error) {
73
- if (error instanceof PersonOutsideRequestError)
74
- return await checkoutChain(dir);
75
- throw error;
83
+ if (!(error instanceof PersonOutsideRequestError))
84
+ throw error;
85
+ for (const dir of unique)
86
+ out.set(dir, await checkoutChain(dir));
87
+ return out;
76
88
  }
77
- const row = await db.prepare(`SELECT c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
78
- WHERE p.person IN (?, ?) AND c.dir = ? ORDER BY c.observed_at DESC LIMIT 1`).get(who.replace(/^user:/, ''), `user:${who.replace(/^user:/, '')}`, resolve(dir));
79
- return row === undefined ? await checkoutChain(dir) : chainOf(row.chain_json);
89
+ const bare = who.replace(/^user:/, '');
90
+ const rows = unique.length === 0 ? [] : await db.prepare(`SELECT DISTINCT ON (c.dir) c.dir, c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
91
+ WHERE p.person IN (?, ?) AND c.dir = ANY(?::text[]) ORDER BY c.dir, c.observed_at DESC`).all(bare, `user:${bare}`, unique);
92
+ const stored = new Map(rows.map((r) => [r.dir, r.chain_json]));
93
+ for (const dir of unique)
94
+ out.set(dir, stored.has(dir) ? chainOf(stored.get(dir)) : await checkoutChain(dir));
95
+ return out;
80
96
  }
81
97
  /** Run the checkout lookups for `dirs` before a canvas write opens: on the machine environment of `profileId` (cloud role) ask the Mac and store
82
98
  * the answer; otherwise run git here. */
@@ -16,7 +16,7 @@ import { warmCheckoutDirs } from '../checkout-identities.js';
16
16
  import { fillProfileProjectRepo } from '../profiles/manifest.js';
17
17
  import { emitEvent } from '../events/emit.js';
18
18
  import { isCloudRole } from '../canvas/person-state.js';
19
- import { loadReadAccess, mayRead, prefetchRepoReads, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
19
+ import { loadReadAccess, readableAmong, prefetchRepoReads, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
20
20
  /** A node's view of repos: for the checkouts enclosing its cwd, every repo object of their remotes the person may read (own first, then oldest), then
21
21
  * the repos its profile names (an entry's `repo`, and the checkouts of its `path`), in manifest order, each repo once. A repo entry needs no folder or
22
22
  * git; one the person may not read adds nothing. A project path that no longer exists, is not in a repo, or has no work tree contributes nothing. */
@@ -27,6 +27,9 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
27
27
  const access = who === undefined ? undefined : await loadReadAccess(db, who);
28
28
  if (access !== undefined && who !== undefined)
29
29
  await prefetchRepoReads(db, who, [cwd, ...projects.flatMap((p) => p.path !== undefined && (isCloudRole() || existsSync(p.path)) ? [p.path] : [])], access);
30
+ // One read answers whether the person may read every repo the profile's entries name.
31
+ const named = projects.flatMap((p) => p.repo === undefined ? [] : [p.repo]);
32
+ const readable = who === undefined ? new Set() : await readableAmong(db, who, named, access);
30
33
  const checkouts = await reposFn(cwd, person, access);
31
34
  const seen = new Set(checkouts.map((c) => c.repo.id));
32
35
  const projectRepos = [];
@@ -35,7 +38,7 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
35
38
  if (project.repo !== undefined && !seen.has(project.repo)) {
36
39
  const repo = await lookups.object(project.repo);
37
40
  if (repo !== null && repo.type === 'repo' && repo.deleted_at === null
38
- && await mayRead(db, who ?? person ?? await personIdAsync(), repo.id, access)) {
41
+ && readable.has(repo.id)) {
39
42
  seen.add(repo.id);
40
43
  projectRepos.push(repo);
41
44
  }
@@ -6,11 +6,11 @@ import { ExitCode } from '../../../types.js';
6
6
  import { personIdAsync } from '../../canvas/person.js';
7
7
  import { ensureOwner } from '../objects.js';
8
8
  import { checkoutChain, handleHint } from './identity.js';
9
- import { checkoutChainOf } from '../../checkout-identities.js';
9
+ import { checkoutChainOf, checkoutChainsOf } from '../../checkout-identities.js';
10
10
  import { subjectSet } from '../../permissions/evaluator.js';
11
11
  import { loadDefinitions } from '../../permissions/schemas.js';
12
12
  import { compilePermission } from '../../permissions/compile.js';
13
- import { f, raw } from '../../permissions/sql.js';
13
+ import { raw } from '../../permissions/sql.js';
14
14
  import { OBJECT_TYPE } from '../../permissions/builtin.js';
15
15
  export { handleHint };
16
16
  async function existingRepo(db, person, scheme, externalId) {
@@ -36,12 +36,15 @@ export async function ensureRepo(db, id, handle) {
36
36
  export async function loadReadAccess(db, person) {
37
37
  return { defs: await loadDefinitions(db), subjects: await subjectSet(db, person.replace(/^user:/, '')) };
38
38
  }
39
- /** Whether `person` may read the object `id` by permission facts alone (no ceiling): the gate for a repo a profile names. */
40
- export async function mayRead(db, person, id, access) {
39
+ /** The ids among `ids` that `person` may read by permission facts alone (no ceiling), in one read: the gate for the repos a profile names. */
40
+ export async function readableAmong(db, person, ids, access) {
41
+ if (ids.length === 0)
42
+ return new Set();
41
43
  const { defs, subjects } = access ?? await loadReadAccess(db, person);
42
- const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', f `${id}::text`);
43
- const row = await db.prepareUncached(`SELECT ${read.sql} AS ok`).get(...read.params);
44
- return row?.ok === true;
44
+ const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', raw('o.id'));
45
+ const rows = await db.prepareUncached(`SELECT o.id FROM objects o WHERE o.id = ANY(?::text[]) AND ${read.sql}`)
46
+ .all(ids, ...read.params);
47
+ return new Set(rows.map((r) => r.id));
45
48
  }
46
49
  /** The repo objects of one remote identity, any person's, that `person` may read (permission facts only, no ceiling), the person's own first and
47
50
  * then by age, oldest first. `heldByPerson` says whether the person has an identity row for it at all, readable or not. */
@@ -76,16 +79,10 @@ const localPathRepos = async (db) => await db.prepare(`SELECT o.*, i.external_id
76
79
  * repos of every git identity in `dirs`, and the local-path repos) and store it on `access`. */
77
80
  export async function prefetchRepoReads(db, person, dirs, access) {
78
81
  const ids = new Map();
79
- for (const cwd of dirs) {
80
- let chain;
81
- try {
82
- chain = await checkoutChainOf(db, realpathOrSelf(resolve(cwd)), async () => person);
83
- }
84
- catch (e) {
85
- if (e instanceof CrtrError && e.code === 'git-lookup-failed')
86
- continue; // the loop reports it
87
- throw e;
88
- }
82
+ const chains = await checkoutChainsOf(db, dirs.map((cwd) => realpathOrSelf(resolve(cwd))), async () => person);
83
+ // A chain with a failed lookup is not the answer: `checkoutsForCwd` looks that directory up itself, as it did before this prefetch kept chains.
84
+ access.chains = new Map([...chains].filter(([, chain]) => chain.every((id) => id.ok)));
85
+ for (const chain of chains.values()) {
89
86
  for (const id of chain)
90
87
  if (id.ok)
91
88
  ids.set(`${id.scheme}\0${id.externalId}`, { scheme: id.scheme, externalId: id.externalId });
@@ -111,7 +108,7 @@ export async function checkoutsForCwd(db, cwd, person, access) {
111
108
  const dir = realpathOrSelf(resolve(cwd));
112
109
  const found = [];
113
110
  let loaded = access;
114
- for (const id of await checkoutChainOf(db, dir, async () => person ?? await personIdAsync())) {
111
+ for (const id of access?.chains?.get(dir) ?? await checkoutChainOf(db, dir, async () => person ?? await personIdAsync())) {
115
112
  if (!id.ok) {
116
113
  throw new CrtrError('git-lookup-failed', `cannot identify the repo at ${id.dir}: ${id.reason}`, ExitCode.GENERAL, { dir: id.dir });
117
114
  }
@@ -289,6 +289,7 @@ async function recordStartCallTimings(callId, answer) {
289
289
  * 'uncertain': the call was sent and its answer lost, so the Mac may have a broker: the execution stays launching and the node stays active, and the
290
290
  * tick's `status` of that execution decides (the machine runner's rule). 'full': the daemon is drained or at its broker cap, so nothing was begun. */
291
291
  async function startOnMachine(meta, environmentId, inv) {
292
+ const setupStart = performance.now();
292
293
  // Loaded here: the handlers import the runtime that imports this module.
293
294
  const { buildStartBundle } = await import('../../daemon/api/handlers/execution-start.js');
294
295
  const { renderCarriedStart } = await import('../../daemon/api/handlers/broker-ops.js');
@@ -311,9 +312,22 @@ async function startOnMachine(meta, environmentId, inv) {
311
312
  const launchJson = await brokerLaunchJson(meta.node_id, inv, meta.cwd);
312
313
  await setExecutionLaunchJson(executionId, launchJson);
313
314
  const execId = executionId;
314
- await timedStep('warm_repos', async () => await warmNodeRepos(await openDb(), meta.node_id));
315
- const sub = meta.sub ?? await personIdAsync();
316
- const bundle = await timedStep('start_bundle', () => buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' }));
315
+ addStepTiming('execution_setup', performance.now() - setupStart);
316
+ // Warm-up and the bundle are independent (the bundle reads the node, profile metadata, environment and secrets; warm-up writes checkout identities and a
317
+ // profile project's `repo`), so they run together. Both settle before the render transaction opens, and warm-up's error wins if both fail. The
318
+ // `warm_repos` and `start_bundle` marks each measure their own step and overlap; `warm_and_bundle` is the joined interval.
319
+ const [warmed, bundled] = await timedStep('warm_and_bundle', async () => await Promise.allSettled([
320
+ timedStep('warm_repos', async () => await warmNodeRepos(await openDb(), meta.node_id)),
321
+ timedStep('start_bundle', async () => {
322
+ const sub = meta.sub ?? await personIdAsync();
323
+ return await buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' });
324
+ }),
325
+ ]));
326
+ if (warmed.status === 'rejected')
327
+ throw warmed.reason;
328
+ if (bundled.status === 'rejected')
329
+ throw bundled.reason;
330
+ const bundle = bundled.value;
317
331
  callId = await timedStep('render_transaction', () => withCanvasWrite(async (db) => {
318
332
  // The reader is built here, after the goal and every birth write have landed, so the rendered bearings see them.
319
333
  const start = await renderCarriedStart(meta.node_id);
@@ -322,7 +336,7 @@ async function startOnMachine(meta, environmentId, inv) {
322
336
  executionId: execId, nodeId: meta.node_id, attempt: 1, sandboxName: null, release: acceptedRelease(), launchJson, cwd: meta.cwd, resuming: false,
323
337
  nodeToken, bundle, start,
324
338
  });
325
- }));
339
+ }, { timingName: 'render_tx' }));
326
340
  }
327
341
  catch (error) {
328
342
  emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
@@ -5,12 +5,33 @@
5
5
  // `Server-Timing` response header. A request opts in by running inside `collectStepTimings`; `timedStep` / `addStepTiming` record nothing
6
6
  // outside one. Names and durations only: never a token, secret, env value or document body.
7
7
  import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
8
9
  const stepTimings = new AsyncLocalStorage();
9
10
  /** Run `fn`, collecting the steps recorded beneath it. */
10
11
  export async function collectStepTimings(fn) {
11
12
  const steps = [];
12
- const value = await stepTimings.run({ steps, start: performance.now() }, fn);
13
- return { value, steps };
13
+ // How long the event loop was blocked while the request ran: a blocked loop delays every await in it, and shows as time no step explains.
14
+ const loop = monitorEventLoopDelay({ resolution: 5 });
15
+ loop.enable();
16
+ try {
17
+ const value = await stepTimings.run({ steps, start: performance.now() }, fn);
18
+ return { value, steps };
19
+ }
20
+ finally {
21
+ loop.disable();
22
+ if (loop.count > 0)
23
+ steps.push(['event_loop_delay_max', loop.max / 1e6], ['event_loop_delay_p99', loop.percentile(99) / 1e6]);
24
+ }
25
+ }
26
+ /** True when the running request is collecting steps. */
27
+ export function isCollectingStepTimings() {
28
+ return stepTimings.getStore() !== undefined;
29
+ }
30
+ /** A short stable label for a statement: its verb and first table (`select_nodes`, `insert_run_events`), never its parameters or text. */
31
+ export function statementLabel(text) {
32
+ const verb = /^\s*(select|insert|update|delete|with|savepoint|release|rollback)\b/i.exec(text)?.[1]?.toLowerCase() ?? 'other';
33
+ const table = /\b(?:from|into|update)\s+(?:only\s+)?([a-z_][a-z0-9_.]*)/i.exec(text)?.[1]?.toLowerCase().replace(/\W/g, '_');
34
+ return table === undefined ? verb : `${verb}_${table}`;
14
35
  }
15
36
  /** Record a step's duration in ms, when a request is collecting. */
16
37
  export function addStepTiming(name, ms) {
@@ -41,6 +41,27 @@ async function readerManifest(db, reader) {
41
41
  throw new Error(`profile object ${reader.profile.id} has no profile identity`);
42
42
  return loadExactProfileManifest(profileId).manifest;
43
43
  }
44
+ /** Readers whose corpus reads are shared for as long as the reader lives (`shareCorpusReads`). */
45
+ const sharing = new WeakSet();
46
+ const shared = new WeakMap();
47
+ /** Make every document, head, rule, name and body read this reader's deliveries make run once per distinct input. Only for a reader built for one
48
+ * render that writes no documents while it lives: the answers are those of the first read, whatever changes after. */
49
+ export function shareCorpusReads(reader) { sharing.add(reader); }
50
+ function once(reader, key, load) {
51
+ if (!sharing.has(reader))
52
+ return load();
53
+ let reads = shared.get(reader);
54
+ if (reads === undefined)
55
+ shared.set(reader, reads = new Map());
56
+ const id = JSON.stringify(key);
57
+ let hit = reads.get(id);
58
+ if (hit === undefined) {
59
+ hit = load();
60
+ reads.set(id, hit);
61
+ hit.catch(() => reads.delete(id));
62
+ }
63
+ return hit;
64
+ }
44
65
  /** One scope per reader object. A reader is built for one request and its view, subjects and read rule are facts of that reader, so every
45
66
  * corpus of one delivery shares them: the `names` activity loads one corpus per owner in the view and a boot one per linked document, and
46
67
  * rebuilding the scope for each cost about thirty statements a time. */
@@ -64,12 +85,18 @@ export async function readRule(db, reader) {
64
85
  }
65
86
  /** The live documents satisfying `where` that the reader may read. */
66
87
  async function documentRows(db, scope, where, args) {
88
+ return [...await once(scope.reader, ['docs', where, args], async () => await documentRowsNow(db, scope, where, args))];
89
+ }
90
+ async function documentRowsNow(db, scope, where, args) {
67
91
  return await db.prepareUncached(`SELECT o.*, d.heads_key, d.unlisted, d.source_path FROM objects o JOIN documents d ON d.object = o.id
68
92
  WHERE o.type = 'document' AND o.deleted_at IS NULL AND ${where} AND ${scope.read.sql} ORDER BY o.seq`)
69
93
  .all(...args, ...scope.read.params);
70
94
  }
71
95
  /** Each document's current body hash: the highest-numbered of its head revisions, for all of `docs` in one query. */
72
- async function headBodyHashes(db, docs) {
96
+ async function headBodyHashes(db, scope, docs) {
97
+ return await once(scope.reader, ['heads', docs.map((d) => [d.id, d.heads_key])], async () => await headBodyHashesNow(db, docs));
98
+ }
99
+ async function headBodyHashesNow(db, docs) {
73
100
  const heads = [...new Set(docs.flatMap((d) => d.heads_key.split(',')))];
74
101
  const rows = heads.length === 0 ? [] : await db.prepare('SELECT rev_id, document, number, body_hash FROM revisions WHERE rev_id = ANY(?::text[])')
75
102
  .all(heads);
@@ -105,9 +132,10 @@ async function toDeliveryDocs(db, scope, rows, rulesByDoc) {
105
132
  for (const o of await db.prepare('SELECT * FROM objects WHERE id = ANY(?::text[])').all(outside))
106
133
  owners.set(o.id, o);
107
134
  }
108
- const rules = rulesByDoc ?? await rulesOfMany(db, rows.map((r) => r.id));
109
- const hashes = await headBodyHashes(db, rows);
110
- const resolvedNames = await viewResolutions(db, context, rows.map((r) => r.name));
135
+ const ruleIds = rows.map((r) => r.id);
136
+ const rules = rulesByDoc ?? await once(reader, ['rules', ruleIds], async () => await rulesOfMany(db, ruleIds));
137
+ const hashes = await headBodyHashes(db, scope, rows);
138
+ const resolvedNames = await once(reader, ['names', rows.map((r) => r.name)], async () => await viewResolutions(db, context, rows.map((r) => r.name)));
111
139
  return await mapAsync(rows, async (doc) => {
112
140
  const owner = owners.get(doc.owner);
113
141
  if (owner === undefined)
@@ -8,6 +8,7 @@ import { isSafeNodeId } from '../../../core/canvas/paths.js';
8
8
  import { isPidAlive } from '../../../core/canvas/pid.js';
9
9
  import { editorLabel } from '../../../core/canvas/labels.js';
10
10
  import { assembleNodeSubject } from '../../../core/substrate/subject.js';
11
+ import { shareCorpusReads } from '../../../core/substrate/delivery/corpus.js';
11
12
  import { openDb, withCanvasWrite } from '../../../core/canvas/db.js';
12
13
  import { runningJobs } from '../../../core/graph/jobs.js';
13
14
  import { notFound, usage } from '../../../core/errors.js';
@@ -160,7 +161,7 @@ export async function extensionNode(node) {
160
161
  created: node.created,
161
162
  };
162
163
  }
163
- async function extensionState(nodeId) {
164
+ async function extensionState(nodeId, gate) {
164
165
  const node = await requireNode(nodeId);
165
166
  const ancestors = [];
166
167
  const seen = new Set([nodeId]);
@@ -179,7 +180,7 @@ async function extensionState(nodeId) {
179
180
  const source = typeof node.fork_source_file === 'string'
180
181
  ? await forkSourceNode(node.fork_source_file)
181
182
  : null;
182
- const subject = await assembleNodeSubject(nodeId);
183
+ const subject = gate ?? await assembleNodeSubject(nodeId);
183
184
  if (subject === null)
184
185
  throw notFound(`unknown node: ${nodeId}`, { received: nodeId });
185
186
  return {
@@ -295,30 +296,31 @@ function parseCycleStartBody(body) {
295
296
  /** The names, bearings and first system-prompt block a cycle opens with, delivered in one write the way the
296
297
  * delivery route would deliver each. A warm spare is owed no bearings and no system prompt: its claim delivers them.
297
298
  * `namesOnly` gives a node the same treatment while its bind is undecided. */
298
- async function startupDelivery(nodeId, state, bearings, namesOnly, warmed = false) {
299
+ async function startupDelivery(db, reader, subject, state, bearings, namesOnly) {
299
300
  const warm = state.warm_spare || namesOnly;
300
301
  const bootOwed = !warm && bearings !== 'present';
302
+ const names = await deliver(db, reader, { activity: 'names' }, subject);
303
+ const boot = bootOwed ? await deliver(db, reader, { activity: 'boot', ...(bearings === 'inherited' ? { inherited: true } : {}) }, subject) : undefined;
304
+ const system = warm ? undefined : await deliver(db, reader, { activity: 'system-prompt' }, subject);
305
+ return {
306
+ names: { refs: names.refs, names: names.names },
307
+ ...(boot === undefined ? {} : { boot: { content: boot.content, ...(boot.inherited === true ? { inherited: true } : {}) } }),
308
+ ...(system === undefined ? {} : { system_prompt: system.content }),
309
+ };
310
+ }
311
+ /** The node state, names, bearings and first system-prompt block a cycle opens with, and the persona acknowledgement the bearings make. A companion
312
+ * awaiting its marker may still be shut down by the bind: it gets the state and names only, with no bearings, ledger write, persona acknowledgement
313
+ * or system prompt until the bind commits. The node's repository view is built once and serves both the state's subject and the delivery. */
314
+ export async function renderStartData(nodeId, bearings, namesOnly, warmed = false) {
301
315
  if (!warmed)
302
316
  await warmNodeRepos(await openDb(), nodeId);
303
- return await withCanvasWrite(async (db) => {
317
+ const { state, delivery } = await withCanvasWrite(async (db) => {
304
318
  const reader = await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access));
319
+ shareCorpusReads(reader);
305
320
  const subject = await nodeSubject(db, reader);
306
- const names = await deliver(db, reader, { activity: 'names' }, subject);
307
- const boot = bootOwed ? await deliver(db, reader, { activity: 'boot', ...(bearings === 'inherited' ? { inherited: true } : {}) }, subject) : undefined;
308
- const system = warm ? undefined : await deliver(db, reader, { activity: 'system-prompt' }, subject);
309
- return {
310
- names: { refs: names.refs, names: names.names },
311
- ...(boot === undefined ? {} : { boot: { content: boot.content, ...(boot.inherited === true ? { inherited: true } : {}) } }),
312
- ...(system === undefined ? {} : { system_prompt: system.content }),
313
- };
321
+ const state = await extensionState(nodeId, subject);
322
+ return { state, delivery: await startupDelivery(db, reader, subject, state, bearings, namesOnly) };
314
323
  });
315
- }
316
- /** The node state, names, bearings and first system-prompt block a cycle opens with, and the persona acknowledgement the bearings make. A companion
317
- * awaiting its marker may still be shut down by the bind: it gets the state and names only, with no bearings, ledger write, persona acknowledgement
318
- * or system prompt until the bind commits. */
319
- export async function renderStartData(nodeId, bearings, namesOnly, warmed = false) {
320
- const state = await extensionState(nodeId);
321
- const delivery = await startupDelivery(nodeId, state, bearings, namesOnly, warmed);
322
324
  // The bearings just rendered are the persona baseline; the broker does not acknowledge it separately.
323
325
  if (delivery.boot !== undefined) {
324
326
  const current = { kind: state.node.kind, mode: state.node.mode, lifecycle: state.node.lifecycle };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.684",
3
+ "version": "0.3.685",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.684",
3
+ "version": "0.3.685",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.684",
3
+ "version": "0.3.685",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.684",
31
- "@north-light/identity": "0.3.684"
30
+ "@north-light/api": "0.3.685",
31
+ "@north-light/identity": "0.3.685"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.684",
3
+ "version": "0.3.685",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.684",
9
+ "version": "0.3.685",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.684",
32
- "@north-light/plugin": "0.3.684",
31
+ "@north-light/identity": "0.3.685",
32
+ "@north-light/plugin": "0.3.685",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.684",
10670
+ "version": "0.3.685",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.684",
10675
+ "version": "0.3.685",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.684",
10680
+ "version": "0.3.685",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.684",
10688
+ "version": "0.3.685",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.684",
10692
- "@north-light/identity": "0.3.684"
10691
+ "@north-light/api": "0.3.685",
10692
+ "@north-light/identity": "0.3.685"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.684",
10697
+ "version": "0.3.685",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.684",
10701
- "@north-light/identity": "0.3.684",
10702
- "@north-light/plugin": "0.3.684",
10700
+ "@north-light/api": "0.3.685",
10701
+ "@north-light/identity": "0.3.685",
10702
+ "@north-light/plugin": "0.3.685",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {