@north-light/cli 0.3.683 → 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.
Files changed (30) hide show
  1. package/dist/core/canvas/db.d.ts +3 -0
  2. package/dist/core/canvas/db.js +4 -4
  3. package/dist/core/checkout-identities.d.ts +3 -0
  4. package/dist/core/checkout-identities.js +3 -3
  5. package/dist/core/graph/reader.js +3 -3
  6. package/dist/core/graph/repo-sync/repos.d.ts +5 -2
  7. package/dist/core/graph/repo-sync/repos.js +4 -4
  8. package/dist/core/runtime/runner/blaxel/image-build.d.ts +2 -0
  9. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  10. package/dist/core/runtime/spawn.js +2 -2
  11. package/dist/core/step-timings.d.ts +4 -0
  12. package/dist/core/step-timings.js +1 -1
  13. package/dist/core/substrate/delivery/corpus.d.ts +3 -0
  14. package/dist/core/substrate/delivery/corpus.js +2 -2
  15. package/dist/daemon/api/handlers/broker-ops.d.ts +1 -1
  16. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  17. package/package.json +3 -3
  18. package/packages/crouter-api/dist/core/canvas/db.js +15 -2
  19. package/packages/crouter-api/dist/core/checkout-identities.js +25 -9
  20. package/packages/crouter-api/dist/core/graph/reader.js +5 -2
  21. package/packages/crouter-api/dist/core/graph/repo-sync/repos.js +15 -18
  22. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +5 -2
  23. package/packages/crouter-api/dist/core/runtime/spawn.js +18 -4
  24. package/packages/crouter-api/dist/core/step-timings.js +23 -2
  25. package/packages/crouter-api/dist/core/substrate/delivery/corpus.js +32 -4
  26. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +21 -19
  27. package/packages/crouter-api/package.json +1 -1
  28. package/packages/crouter-identity/package.json +1 -1
  29. package/packages/crouter-plugin/package.json +3 -3
  30. package/runtime.lock.json +14 -14
@@ -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};
@@ -83,6 +83,8 @@ interface ImageDoc {
83
83
  export declare function getImage(config: BlaxelConfig, name: string): Promise<ImageDoc | null>;
84
84
  /** Deleting an absent image is not an error; an image a sandbox still uses is refused by Blaxel. */
85
85
  export declare function deleteImage(config: BlaxelConfig, name: string): Promise<void>;
86
+ /** How long a build may stay BUILDING: the crouter-cloud image takes ~30-33 min on Blaxel. */
87
+ export declare const BUILD_TIMEOUT_MS: number;
86
88
  /** Uploads `dir` (Dockerfile and context) as a build of sandbox image `name` and waits for it. A failed build throws with Blaxel's last event message. */
87
89
  export declare function buildImage(config: BlaxelConfig, name: string, dir: string, options?: BuildImageOptions): Promise<BuiltImage>;
88
90
  /** The image name of an environment: every revision is a new tag of it. */
@@ -1,8 +1,8 @@
1
- var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as K}from"node:child_process";import{constants as v,lstatSync as j,mkdirSync as q,readFileSync as z,readdirSync as H,readlinkSync as J,rmSync as W,writeFileSync as b}from"node:fs";import{join as E,relative as X}from"node:path";import{crc32 as V,deflateRawSync as Z}from"node:zlib";import{BlaxelApiError as Q}from"./client.js";const tt="public.ecr.aws/docker/library/node:24-alpine",et="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",A="/var/lib/crtr/recipe-pi-agent",rt="blaxel.toml",nt=`[build]
1
+ var K=Object.defineProperty;var c=(t,r)=>K(t,"name",{value:r,configurable:!0});import{spawn as j}from"node:child_process";import{constants as A,lstatSync as q,mkdirSync as z,readFileSync as H,readdirSync as J,readlinkSync as W,rmSync as X,writeFileSync as b}from"node:fs";import{join as E,relative as V}from"node:path";import{crc32 as Z,deflateRawSync as Q}from"node:zlib";import{BlaxelApiError as tt}from"./client.js";const et="public.ecr.aws/docker/library/node:24-alpine",rt="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",D="/var/lib/crtr/recipe-pi-agent",nt="blaxel.toml",st=`[build]
2
2
  slim = false
3
- `,st="1.1.0",x="recipe-setup.sh",L="repos",D="/work/.crtr/setup.log",P="/work/.crtr/setup-failed",B=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ot=c(t=>(t??"").split(`
4
- `).map(r=>r.trim()).filter(r=>r!==""),"lines"),I=c((t,r)=>`RUN { ${r}; } >> ${D} 2>&1 || echo ${B(t)} "exited $?" >> ${P}`,"guarded");function it(t,r,i=!1){const o=ot(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${tt}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${et} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${A} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${P} ${D}`,I("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),o.length>0&&e.push(I("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${st}`)),a&&e.push(`COPY ${x} /tmp/${x}`),e.push("WORKDIR /work");for(const s of o)e.push(I(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${A} pi install ${B(s)}`));a&&e.push(I("setup script",`bash /tmp/${x}`)),e.push(I("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const s of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${s} ${s}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
- `)}c(it,"recipeDockerfile");const at=c((t,r,i)=>new Promise((o,a)=>{const n=K("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",s=>{e+=s.toString()}),n.on("error",a),n.on("close",s=>{s===0?o():a(new Error(`git ${t[0]} failed (${s}): ${e.slice(0,300)}`))})}),"runGit");async function wt(t){const r=t.git??at,i=t.packagesToken??null,o=t.cloneUrl??(n=>`https://github.com/${n}.git`);q(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),E(L,n.name)],a,t.dir)}b(E(t.dir,rt),nt),b(E(t.dir,"Dockerfile"),it(t.recipe,t.revision,i!==null)),i!==null&&b(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
- `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,x),t.recipe.setup_script.endsWith(`
3
+ `,ot="1.1.0",U="recipe-setup.sh",L="repos",B="/work/.crtr/setup.log",P="/work/.crtr/setup-failed",C=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),it=c(t=>(t??"").split(`
4
+ `).map(r=>r.trim()).filter(r=>r!==""),"lines"),I=c((t,r)=>`RUN { ${r}; } >> ${B} 2>&1 || echo ${C(t)} "exited $?" >> ${P}`,"guarded");function at(t,r,i=!1){const o=it(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${et}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${rt} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${D} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${P} ${B}`,I("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),o.length>0&&e.push(I("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${ot}`)),a&&e.push(`COPY ${U} /tmp/${U}`),e.push("WORKDIR /work");for(const s of o)e.push(I(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${C(s)}`));a&&e.push(I("setup script",`bash /tmp/${U}`)),e.push(I("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const s of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${s} ${s}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
+ `)}c(at,"recipeDockerfile");const ct=c((t,r,i)=>new Promise((o,a)=>{const n=j("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",s=>{e+=s.toString()}),n.on("error",a),n.on("close",s=>{s===0?o():a(new Error(`git ${t[0]} failed (${s}): ${e.slice(0,300)}`))})}),"runGit");async function Et(t){const r=t.git??ct,i=t.packagesToken??null,o=t.cloneUrl??(n=>`https://github.com/${n}.git`);z(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),E(L,n.name)],a,t.dir)}b(E(t.dir,nt),st),b(E(t.dir,"Dockerfile"),at(t.recipe,t.revision,i!==null)),i!==null&&b(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
+ `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,U),t.recipe.setup_script.endsWith(`
7
7
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
8
- `)}c(wt,"prepareBuildDir");function C(t,r,i){for(const o of H(r).sort()){const a=E(r,o),n=j(a),e=X(t,a).split("\\").join("/");n.isDirectory()?C(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(J(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:z(a),mode:v.S_IFREG|n.mode&511})}}c(C,"walk");function ct(t){const r=[];C(t,t,r);const i=[],o=[];let a=0;for(const s of r){const d=Buffer.from(s.name),g=Z(s.data),$=V(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE($,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(d.length,26),i.push(p,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE($,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(s.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,d),a+=p.length+d.length+g.length}const n=Buffer.concat(o),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ct,"zipDirectory");async function O(t,r,i,o,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await e.text();let d=null;if(s!=="")try{d=JSON.parse(s)}catch{d={raw:s}}if(!e.ok&&!a.includes(e.status))throw new Q(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(O,"api");async function G(t,r){const{status:i,json:o}=await O(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(G,"getImage");async function gt(t,r){await O(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(gt,"deleteImage");async function Et(t,r,i,o={}){const a=o.sleep??(h=>new Promise(u=>setTimeout(u,h))),n=o.now??Date.now,e=n(),s=await G(t,r),d=new Set((s?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(u=>Date.parse(u.time??"")).filter(u=>!Number.isNaN(u)),"eventTimes"),$=Math.max(-1/0,...g(s)),l=(await O(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ct(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const M=e+(o.timeoutMs??20*6e4);let R=null;for(;;){const h=await G(t,r),u=h?.metadata?.status,N=g(h).filter(m=>m>$).sort((m,_)=>m-_);if(u==="BUILT"&&N.length>=2){R??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),_=N[0],T=c(w=>Date.parse(w??"")>=_,"touchedSince"),k=m.filter(w=>!d.has(w.name)||T(w.createdAt)||T(w.updatedAt)),y=n()-R>=(o.tagGraceMs??6e4),S=(k.length>0?k:y?m:[]).sort((w,F)=>(F.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(S!==void 0)return{ref:`sandbox/${r}:${S}`,buildMs:n()-e};if(y)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(u==="FAILED"||u==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${u.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>M)throw new Error(`building image ${r} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${u??"none"})`);await a(o.pollMs??3e3)}}c(Et,"buildImage");const It=c(t=>`env-${t}`,"environmentImageName");function $t(t){W(t,{recursive:!0,force:!0})}c($t,"removeBuildDir");export{nt as BLAXEL_TOML,rt as BLAXEL_TOML_FILE,tt as NODE_BASE_IMAGE,A as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,et as SANDBOX_API_IMAGE,P as SETUP_FAILED_FILE,D as SETUP_LOG_FILE,x as SETUP_SCRIPT_FILE,Et as buildImage,gt as deleteImage,It as environmentImageName,G as getImage,wt as prepareBuildDir,it as recipeDockerfile,$t as removeBuildDir,ct as zipDirectory};
8
+ `)}c(Et,"prepareBuildDir");function G(t,r,i){for(const o of J(r).sort()){const a=E(r,o),n=q(a),e=V(t,a).split("\\").join("/");n.isDirectory()?G(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(W(a)),mode:A.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:H(a),mode:A.S_IFREG|n.mode&511})}}c(G,"walk");function lt(t){const r=[];G(t,t,r);const i=[],o=[];let a=0;for(const s of r){const d=Buffer.from(s.name),g=Q(s.data),$=Z(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE($,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(d.length,26),i.push(p,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE($,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(s.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,d),a+=p.length+d.length+g.length}const n=Buffer.concat(o),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(lt,"zipDirectory");async function O(t,r,i,o,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await e.text();let d=null;if(s!=="")try{d=JSON.parse(s)}catch{d={raw:s}}if(!e.ok&&!a.includes(e.status))throw new tt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(O,"api");async function M(t,r){const{status:i,json:o}=await O(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(M,"getImage");async function It(t,r){await O(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(It,"deleteImage");const pt=60*6e4;async function $t(t,r,i,o={}){const a=o.sleep??(h=>new Promise(u=>setTimeout(u,h))),n=o.now??Date.now,e=n(),s=await M(t,r),d=new Set((s?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(u=>Date.parse(u.time??"")).filter(u=>!Number.isNaN(u)),"eventTimes"),$=Math.max(-1/0,...g(s)),l=(await O(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(lt(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const T=o.timeoutMs??pt,F=e+T;let R=null;for(;;){const h=await M(t,r),u=h?.metadata?.status,N=g(h).filter(m=>m>$).sort((m,_)=>m-_);if(u==="BUILT"&&N.length>=2){R??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),_=N[0],k=c(w=>Date.parse(w??"")>=_,"touchedSince"),S=m.filter(w=>!d.has(w.name)||k(w.createdAt)||k(w.updatedAt)),y=n()-R>=(o.tagGraceMs??6e4),v=(S.length>0?S:y?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(v!==void 0)return{ref:`sandbox/${r}:${v}`,buildMs:n()-e};if(y)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(u==="FAILED"||u==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${u.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>F)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${u??"none"})`);await a(o.pollMs??3e3)}}c($t,"buildImage");const bt=c(t=>`env-${t}`,"environmentImageName");function Ut(t){X(t,{recursive:!0,force:!0})}c(Ut,"removeBuildDir");export{st as BLAXEL_TOML,nt as BLAXEL_TOML_FILE,pt as BUILD_TIMEOUT_MS,et as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,rt as SANDBOX_API_IMAGE,P as SETUP_FAILED_FILE,B as SETUP_LOG_FILE,U as SETUP_SCRIPT_FILE,$t as buildImage,It as deleteImage,bt as environmentImageName,M as getImage,Et as prepareBuildDir,at as recipeDockerfile,Ut as removeBuildDir,lt as zipDirectory};
@@ -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'>;