@north-light/cli 0.3.680 → 0.3.682

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.
@@ -1 +1 @@
1
- var W=Object.defineProperty;var a=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as G,realpathSync as O,rmSync as R,statSync as V}from"node:fs";import{resolve as M}from"node:path";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as g}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as h}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as p,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as c,notFound as d,ambiguous as N,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as D,personId as te}from"../canvas/person-state.js";const P=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,m="root-00000000",j="root";function y(e){return e.grantee??"app:terminal"}a(y,"profileApp");function x(e,t){Y(g(y(t),e).dir)}a(x,"scaffoldProfile");function $(e){if(!P.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a($,"assertSafeProfileId");function $e(e){$(e);const t=p(e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return g(y(t.manifest),e).dir}a($e,"profileDir");function _(e){if(!Array.isArray(e))throw c("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:r}=t;for(const[o,i]of[["path",n],["repo",r]])if(i!==void 0&&(typeof i!="string"||i.trim()===""))throw c(`project entry has an invalid ${o}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${o} a non-empty string, or leave it out.`});if(n===void 0&&r===void 0)throw c(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(_,"assertProfileProjects");function ne(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw c("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,r]of Object.entries(e)){if(n.trim()==="")throw c("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!C.includes(r))throw c(`invalid delivery limit for ${n}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(ne,"assertDeliveryLimits");function re(){return{entries:X(),unreadableIds:[]}}a(re,"enumerateProfiles");function v(){return re().entries}a(v,"listProfiles");function oe(e){const t=v(),n=z(t,e,b);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){$(e);const t=p(e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const b=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if(P.test(t)){const o=e.find(i=>n(i).profileId===t);if(o!==void 0)return o}const r=e.filter(o=>n(o).name===t);if(r.length===1)return r[0];if(r.length>1){const o=r.map(i=>n(i).profileId);throw N(`profile name "${t}" matches ${o.length} profiles: ${o.join(", ")}`,{received:t,candidates:o,next:`Re-run with one exact profile id: ${o.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const r=e.map(o=>`${n(o).profileId} (${n(o).name})`);return d(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ie(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(v(),e,b)}a(ie,"loadProfileManifest");function _e(e){return ae(v(),e,b)}a(_e,"resolveProfileOperand");function ae(e,t,n){const r=z(e,t,n);if(r!==null)return r;const{match:o,tied:i}=ee(t,e.map(n));if(o!==null){const s=e.find(f=>n(f).profileId===o.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(i.length>1){const s=i.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${i.length} profiles: ${s.join(", ")}`,{received:t,candidates:i.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(ae,"matchProfileOperand");function T(e){const t=M(e);if(!G(t)||!V(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return O(t)}catch{return t}}a(T,"resolveExistingProjectDir");function A(e){const t=new Set,n=new Map,r=[];for(const o of e)if(o.path!==void 0){if(t.has(o.path))continue;t.add(o.path);const i=o.repo===void 0?void 0:n.get(o.repo);if(i!==void 0&&r[i].path===void 0){r[i]={...r[i],path:o.path};continue}r.push(o)}else if(o.repo!==void 0){if(n.has(o.repo))continue;n.set(o.repo,r.length),r.push(o)}else r.push(o);return r}a(A,"dedupeProjects");function se(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(se,"slugify");function fe(e){const t=se(e);for(let n=0;n<20;n++){const r=Z().replace(/-/g,"").slice(0,8),o=`${t}-${r}`;if(p(o)===null)return o}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(fe,"generateProfileId");let E=null;function be(e){E=e}a(be,"setCloudProfileWriter");async function Ae(){if(D()){const n=v().find(r=>r.manifest.name===j&&y(r.manifest)==="app:terminal");return n!==void 0?(x(n.profileId,n.manifest),n):await q(j,[],{grantee:"app:terminal"})}const e=p(m);if(e!==null)return x(m,e.manifest),e;const t={schema_version:k,name:j,projects:[],grantee:"app:terminal",paused_at:null,created_at:h(),last_used_at:h()};return x(m,t),await w(n=>n.profiles.some(r=>r.profileId===m)?[]:[{op:"profile.insert",profile:{profileId:m,manifest:t}}]),p(m)}a(Ae,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,r]of Object.entries(e)){if(!U.test(n))throw c(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw c(`metadata value for ${n} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw c(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const o=F(n),i=t.get(o);if(i!==void 0)throw c(`metadata keys ${JSON.stringify(i)} and ${JSON.stringify(n)} both surface as ${o}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(o,n)}}a(S,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[r,o]of Object.entries(e)){if(typeof o!="string"||!U.test(r)||o.includes("\0"))continue;const i=F(r);n.has(i)||(n.add(i),t[r]=o)}return t}a(K,"sanitizeProfileMetadata");async function q(e,t=[],n={}){const r=e.trim();if(r==="")throw c("profile name must not be empty");n.metadata!==void 0&&S(n.metadata),_(t);const o=A(t.map(u=>({...u.repo===void 0?{}:{repo:u.repo},...u.path===void 0?{}:{path:T(u.path)}}))),i=fe(r),s={schema_version:k,name:r,projects:o,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:h(),last_used_at:null};x(i,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:i,manifest:s}}])},"insert");if(!D())await f();else{if(E===null)throw new Error("a cloud role has no profile environment writer registered");await E({profileId:i,grantee:y(s),person:te(),...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async u=>{s.environment_id=u,await f()})}return{profileId:i,manifest:s}}a(q,"createProfile");async function Ee(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,n=v().filter(r=>r.manifest.name===t&&r.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await q(t,[],{grantee:e})}a(Ee,"ensureAppProfile");function H(e){if($(e),p(e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(H,"requireExistingProfile");async function l(e,t){H(e);let n;return await w(r=>{const o=r.profiles.find(i=>i.profileId===e);if(o===void 0)throw d(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(o.manifest))},[{op:"profile.update",profile:n}]}),n}a(l,"mutateManifest");async function Se(e){return await l(e,t=>({...t,last_used_at:h()}))}a(Se,"updateProfileLastUsed");function ce(e){if(e==null||e==="")return null;try{return ie(e)}catch{return null}}a(ce,"loadProfileManifestOrNull");function Oe(e){return e==null||e===""||!P.test(e)?!1:Q(e)}a(Oe,"isProfilePaused");function Re(){return B()}a(Re,"pausedCanvasProfiles");function le(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(le,"assertProfileEntryActive");function Me(e){const t=ce(e);return t===null?null:(le(t),t)}a(Me,"assertProfileActive");async function ke(e){return await l(e,t=>({...t,paused_at:t.paused_at??h()}))}a(ke,"pauseProfile");async function Ce(e){let t=null;return{...await l(e,r=>(t=r.paused_at,{...r,paused_at:null})),pausedAt:t}}a(Ce,"resumeProfile");async function Ne(e,t){return await l(e,n=>({...n,default_kind:t}))}a(Ne,"setProfileDefaultKind");async function De(e,t,n=[]){return S(t),await l(e,r=>{const o={...K(r.metadata),...t};for(const f of n)delete o[f];S(o);const{metadata:i,...s}=r;return{...s,...Object.keys(o).length>0?{metadata:o}:{}}})}a(De,"updateProfileMetadata");function Le(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Le,"readProfileMetadata");async function ze(e,t){const n=t.trim();if(n==="")throw c("profile name must not be empty");return await l(e,o=>({...o,name:n}))}a(ze,"renameProfile");async function Je(e,t,n){_([{path:t,...n===void 0?{}:{repo:n}}]);const r=T(t);return await l(e,o=>({...o,projects:A(o.projects.some(i=>i.path===r)?o.projects.map(i=>i.path===r&&i.repo===void 0&&n!==void 0?{...i,repo:n}:i):[...o.projects,{path:r,...n===void 0?{}:{repo:n}}])}))}a(Je,"addProfileProject");async function Te(e,t){return _([{repo:t}]),await l(e,n=>({...n,projects:n.projects.some(r=>r.repo===t)?n.projects:A([...n.projects,{repo:t}])}))}a(Te,"addProfileRepo");async function Ue(e,t,n){let r=!1;return await l(e,o=>{if(o.projects.some(s=>s.repo===n))return o;const i=o.projects.map(s=>s.path!==t||s.repo!==void 0?s:(r=!0,{...s,repo:n}));return r?{...o,projects:i}:o}),r}a(Ue,"fillProfileProjectRepo");async function Fe(e,t,n){return ne({[t]:n}),await l(e,r=>{const{[t]:o,...i}=r.delivery_limits??{},s=n==="content"?i:{...i,[t]:n},{delivery_limits:f,...u}=r;return Object.keys(s).length===0?u:{...u,delivery_limits:s}})}a(Fe,"setProfileDeliveryLimit");async function Ke(e,t){const n=M(t);let r=n;try{r=O(n)}catch{}return await l(e,i=>{const s=i.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==n);if(s.length===i.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${i.projects.length>0?i.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...i,projects:s}})}a(Ke,"removeProfileProject");async function qe(e){H(e);const t=g(y(L(e).manifest),e);await w(n=>{if(!n.profiles.some(r=>r.profileId===e))throw d(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),R(t.dir,{recursive:!0,force:!0}),R(t.env,{force:!0})}a(qe,"deleteProfile");export{m as ROOT_PROFILE_ID,Je as addProfileProject,Te as addProfileRepo,ne as assertDeliveryLimits,Me as assertProfileActive,le as assertProfileEntryActive,S as assertProfileMetadata,_ as assertProfileProjects,q as createProfile,qe as deleteProfile,Ee as ensureAppProfile,Ae as ensureRootProfile,Ue as fillProfileProjectRepo,Oe as isProfilePaused,v as listProfiles,L as loadExactProfileManifest,ie as loadProfileManifest,oe as lookupProfile,ae as matchProfileOperand,F as metadataEnvName,ke as pauseProfile,Re as pausedCanvasProfiles,$e as profileDir,Le as readProfileMetadata,Ke as removeProfileProject,ze as renameProfile,_e as resolveProfileOperand,Ce as resumeProfile,K as sanitizeProfileMetadata,be as setCloudProfileWriter,Ne as setProfileDefaultKind,Fe as setProfileDeliveryLimit,Se as updateProfileLastUsed,De as updateProfileMetadata};
1
+ var W=Object.defineProperty;var a=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as G,realpathSync as O,rmSync as R,statSync as V}from"node:fs";import{resolve as M}from"node:path";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as g}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as h}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as p,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as c,notFound as d,ambiguous as N,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as D,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const P=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,m="root-00000000",j="root";function y(e){return e.grantee??"app:terminal"}a(y,"profileApp");function x(e,t){Y(g(y(t),e).dir)}a(x,"scaffoldProfile");function $(e){if(!P.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a($,"assertSafeProfileId");function be(e){$(e);const t=p(e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return g(y(t.manifest),e).dir}a(be,"profileDir");function _(e){if(!Array.isArray(e))throw c("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:r}=t;for(const[i,o]of[["path",n],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw c(`project entry has an invalid ${i}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(n===void 0&&r===void 0)throw c(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(_,"assertProfileProjects");function re(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw c("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,r]of Object.entries(e)){if(n.trim()==="")throw c("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!C.includes(r))throw c(`invalid delivery limit for ${n}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function v(){return ie().entries}a(v,"listProfiles");function oe(e){const t=v(),n=z(t,e,b);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){$(e);const t=p(e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const b=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if(P.test(t)){const i=e.find(o=>n(o).profileId===t);if(i!==void 0)return i}const r=e.filter(i=>n(i).name===t);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>n(o).profileId);throw N(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const r=e.map(i=>`${n(i).profileId} (${n(i).name})`);return d(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ae(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(v(),e,b)}a(ae,"loadProfileManifest");function Ae(e){return se(v(),e,b)}a(Ae,"resolveProfileOperand");function se(e,t,n){const r=z(e,t,n);if(r!==null)return r;const{match:i,tied:o}=ee(t,e.map(n));if(i!==null){const s=e.find(f=>n(f).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:t,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(se,"matchProfileOperand");function T(e){const t=M(e);if(!G(t)||!V(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return O(t)}catch{return t}}a(T,"resolveExistingProjectDir");function A(e){const t=new Set,n=new Map,r=[];for(const i of e)if(i.path!==void 0){if(t.has(i.path))continue;t.add(i.path);const o=i.repo===void 0?void 0:n.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(n.has(i.repo))continue;n.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(A,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(fe,"slugify");function ce(e){const t=fe(e);for(let n=0;n<20;n++){const r=Z().replace(/-/g,"").slice(0,8),i=`${t}-${r}`;if(p(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(ce,"generateProfileId");let E=null;function Ee(e){E=e}a(Ee,"setCloudProfileWriter");async function Se(){if(D()){const n=v().find(r=>r.manifest.name===j&&y(r.manifest)==="app:terminal");return n!==void 0?(x(n.profileId,n.manifest),n):await q(j,[],{grantee:"app:terminal"})}const e=p(m);if(e!==null)return x(m,e.manifest),e;const t={schema_version:k,name:j,projects:[],grantee:"app:terminal",paused_at:null,created_at:h(),last_used_at:h()};return x(m,t),await w(n=>n.profiles.some(r=>r.profileId===m)?[]:[{op:"profile.insert",profile:{profileId:m,manifest:t}}]),p(m)}a(Se,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,r]of Object.entries(e)){if(!U.test(n))throw c(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw c(`metadata value for ${n} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw c(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=F(n),o=t.get(i);if(o!==void 0)throw c(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(n)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,n)}}a(S,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!U.test(r)||i.includes("\0"))continue;const o=F(r);n.has(o)||(n.add(o),t[r]=i)}return t}a(K,"sanitizeProfileMetadata");async function q(e,t=[],n={}){const r=e.trim();if(r==="")throw c("profile name must not be empty");n.metadata!==void 0&&S(n.metadata),_(t);const i=A(t.map(l=>({...l.repo===void 0?{}:{repo:l.repo},...l.path===void 0?{}:{path:T(l.path)}}))),o=ce(r),s={schema_version:k,name:r,projects:i,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:h(),last_used_at:null};x(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(D()){if(E===null)throw new Error("a cloud role has no profile environment writer registered");await E({profileId:o,grantee:y(s),person:te(),...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async l=>{s.environment_id=l,await f()})}else{const l=ne();l!==void 0&&(s.environment_id=l.environmentId),await f()}return{profileId:o,manifest:s}}a(q,"createProfile");async function Oe(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,n=v().filter(r=>r.manifest.name===t&&r.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await q(t,[],{grantee:e})}a(Oe,"ensureAppProfile");function H(e){if($(e),p(e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(H,"requireExistingProfile");async function u(e,t){H(e);let n;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw d(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(i.manifest))},[{op:"profile.update",profile:n}]}),n}a(u,"mutateManifest");async function Re(e){return await u(e,t=>({...t,last_used_at:h()}))}a(Re,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(le,"loadProfileManifestOrNull");function Me(e){return e==null||e===""||!P.test(e)?!1:Q(e)}a(Me,"isProfilePaused");function ke(){return B()}a(ke,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ce(e){const t=le(e);return t===null?null:(ue(t),t)}a(Ce,"assertProfileActive");async function Ne(e){return await u(e,t=>({...t,paused_at:t.paused_at??h()}))}a(Ne,"pauseProfile");async function De(e){let t=null;return{...await u(e,r=>(t=r.paused_at,{...r,paused_at:null})),pausedAt:t}}a(De,"resumeProfile");async function Le(e,t){return await u(e,n=>({...n,default_kind:t}))}a(Le,"setProfileDefaultKind");async function ze(e,t,n=[]){return S(t),await u(e,r=>{const i={...K(r.metadata),...t};for(const f of n)delete i[f];S(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(ze,"updateProfileMetadata");function Je(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Je,"readProfileMetadata");async function Te(e,t){const n=t.trim();if(n==="")throw c("profile name must not be empty");return await u(e,i=>({...i,name:n}))}a(Te,"renameProfile");async function Ue(e,t,n){_([{path:t,...n===void 0?{}:{repo:n}}]);const r=T(t);return await u(e,i=>({...i,projects:A(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&n!==void 0?{...o,repo:n}:o):[...i.projects,{path:r,...n===void 0?{}:{repo:n}}])}))}a(Ue,"addProfileProject");async function Fe(e,t){return _([{repo:t}]),await u(e,n=>({...n,projects:n.projects.some(r=>r.repo===t)?n.projects:A([...n.projects,{repo:t}])}))}a(Fe,"addProfileRepo");async function Ke(e,t,n){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===n))return i;const o=i.projects.map(s=>s.path!==t||s.repo!==void 0?s:(r=!0,{...s,repo:n}));return r?{...i,projects:o}:i}),r}a(Ke,"fillProfileProjectRepo");async function qe(e,t,n){return re({[t]:n}),await u(e,r=>{const{[t]:i,...o}=r.delivery_limits??{},s=n==="content"?o:{...o,[t]:n},{delivery_limits:f,...l}=r;return Object.keys(s).length===0?l:{...l,delivery_limits:s}})}a(qe,"setProfileDeliveryLimit");async function He(e,t){const n=M(t);let r=n;try{r=O(n)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==n);if(s.length===o.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(He,"removeProfileProject");async function We(e){H(e);const t=g(y(L(e).manifest),e);await w(n=>{if(!n.profiles.some(r=>r.profileId===e))throw d(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),R(t.dir,{recursive:!0,force:!0}),R(t.env,{force:!0})}a(We,"deleteProfile");export{m as ROOT_PROFILE_ID,Ue as addProfileProject,Fe as addProfileRepo,re as assertDeliveryLimits,Ce as assertProfileActive,ue as assertProfileEntryActive,S as assertProfileMetadata,_ as assertProfileProjects,q as createProfile,We as deleteProfile,Oe as ensureAppProfile,Se as ensureRootProfile,Ke as fillProfileProjectRepo,Me as isProfilePaused,v as listProfiles,L as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,F as metadataEnvName,Ne as pauseProfile,ke as pausedCanvasProfiles,be as profileDir,Je as readProfileMetadata,He as removeProfileProject,Te as renameProfile,Ae as resolveProfileOperand,De as resumeProfile,K as sanitizeProfileMetadata,Ee as setCloudProfileWriter,Le as setProfileDefaultKind,qe as setProfileDeliveryLimit,Re as updateProfileLastUsed,ze as updateProfileMetadata};
@@ -1,3 +1,3 @@
1
- var Ne=Object.defineProperty;var c=(e,r)=>Ne(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as De}from"./unsandboxed.js";import{spawn as Ce}from"node:child_process";import{mkdirSync as fe,existsSync as j,unlinkSync as de,openSync as G,closeSync as L,writeSync as Le,chmodSync as Ae,lstatSync as Be}from"node:fs";import{ensureAppSpace as $e}from"../spaces/space.js";import{sandboxCacheEnv as je}from"../spaces/cache-env.js";import{compileLaunch as Ge,launchStillGranted as Fe}from"../spaces/mounts.js";import{grantsGeneration as me}from"../grants/mirror.js";import{LAUNCHER_SOCKET as X}from"../../launcher/spec.js";import{launcherRequest as F}from"../../launcher/client.js";import{piAgentDir as he}from"./package-health.js";import{existsBeneath as z,readFileBeneath as Me,readTextBeneathIfExists as Ke,setModeBeneath as b,withDirBeneath as V,writeFileBeneath as M}from"../spaces/open-beneath.js";import{dirname as Q,join as m,resolve as Je,isAbsolute as Ue}from"node:path";import{fileURLToPath as pe}from"node:url";import{connectViewSocket as He}from"./view-socket.js";import{appSpace as K}from"../layout.js";import{readConfig as We,readMergedLaunchConfig as qe}from"../config.js";import{loadRotationConfig as Xe}from"../subscription-state.js";import{getNode as E}from"../canvas/index.js";import{withCanvasWrite as ze}from"../canvas/db.js";import{requestExecutionStop as Ve,setExecutionLaunchJson as Qe}from"../canvas/executions.js";import{scopesFilePath as Y,crtrHome as we,nodeRunDir as Z,nodeRunJobDir as Ye,jobDir as Ze,viewSocketPath as Ie,nodeAgentDir as er,contextDir as rr,nodeHome as tr}from"../canvas/paths.js";import{encodeFrame as ge}from"./broker-protocol.js";import{buildBrokerEnv as nr}from"./spawn-env-rows.js";import{hostExecPathFresh as or}from"./branded-host.js";import{isPidAlive as I,killProcessTreePids as Ee,isAnyPidAlive as ir,captureTeardownSnapshot as sr}from"../canvas/pid.js";import{assertMandatoryCanvasExtensions as ar}from"./canvas-extensions.js";import{appMemoryFull as cr,appMemoryTooSmall as lr,boundFleet as ur,brokerCapReached as fr,brokerThresholdsForDaemon as dr}from"./fleet.js";import{admitBrokerMemory as mr}from"./memory-admission.js";import{emitEvent as _}from"../events/emit.js";import{bindBrokerEventSource as hr,eventSource as pr}from"../events/source.js";import{envBrokerEngine as wr}from"../../shared/env.js";import{conversationIdFromPath as gr,conversationStore as Er,ConversationNotFoundError as _e}from"../conversation-store/index.js";import{mintNodeToken as _r}from"../canvas/node-tokens.js";import{personId as kr}from"../canvas/person.js";function J(){const e=Q(pe(import.meta.url));return m(e,"broker-cli.js")}c(J,"resolveBrokerEntry");const vr="@earendil-works/pi-coding-agent";function ke(){const e=m(he(),"models.json"),r=Ke(Q(e),e);if(r===null)return null;const n=JSON.parse(r),o=c(t=>Array.isArray(t)?t.map(o):t===null||typeof t!="object"?t:Object.fromEntries(Object.entries(t).filter(([i])=>!/^(apiKey|authorization|headers|token|secret)$/i.test(i)).map(([i,s])=>[i,o(s)])),"scrub");return{text:r,clean:`${JSON.stringify(o(n),null,2)}
2
- `,credentialed:JSON.stringify(n)!==JSON.stringify(o(n))}}c(ke,"scrubbedBrokerModels");function yr(e,r){const n=m(he(),"models.json"),o=m(r,"models.json"),t=ke();if(t!==null){if(n===o&&t.text!==t.clean){if(t.credentialed)throw new Error("terminal models.json contains credentials; move them into daemon secrets");b(e,o,432);return}M(e,o,t.clean,{atomic:!0,mode:432}),b(e,o,432)}}c(yr,"writeBrokerModels");function ve(e){return e.env.CRTR_BROKER_ENGINE??wr()}c(ve,"resolveEngineSpec");function ye(e){return e.includes("/")||e.endsWith(".jsonl")}c(ye,"isPlainLaunchSessionPath");function Sr(e,r){return Ue(e)?e:Je(r,e)}c(Sr,"resolvePlainLaunchPath");async function br(e,r,n,o){if(n==="--session"&&!ye(o))throw new Error(`[broker] refusing to launch ${e}: launch recipe passes bare --session id '${o}' \u2014 the broker fatally rejects bare ids; pass the .jsonl path instead.`);if(!ye(o))return;const t=Sr(o,r),i=gr(t);try{if(i===null)throw new _e(t);await Er().header(i)}catch(s){if(!(s instanceof _e))throw s;const u=n==="--session"?"session file":"fork source";throw new Error(`[broker] refusing to launch ${e}: launch recipe references missing ${u} '${o}' (${t})`)}}c(br,"preflightLaunchSessionArg");async function Se(e,r,n){const o=ke();return JSON.stringify({...r,configSnapshot:{user:We("user"),launch:qe(n,r.env.CRTR_PROFILE_ID||null),rotation:await Xe()},scopes:(await E(e))?.scopes??null,models:o===null?null:JSON.parse(o.clean)})}c(Se,"brokerLaunchJson");async function Rr(e,r,n,o){const t=Z(e);fe(t,{recursive:!0}),process.platform==="linux"&&j(X)&&Be(t).uid===process.getuid()&&Ae(t,504);const i=m(t,"broker-launch.json");M(t,i,o??await Se(e,r,n),{atomic:!0}),r.env.CRTR_SCOPES_FILE!==void 0&&M(t,Y(e),JSON.stringify((await E(e))?.scopes??[]),{atomic:!0});const s=Me(t,i).toString("utf8"),u=JSON.parse(s);if(!Array.isArray(u.argv))throw new Error(`[broker] refusing to launch ${e}: broker-launch.json is missing the argv array`);const w=ve(r);try{const l=import.meta.resolve(w);if(l.startsWith("file:")&&!j(pe(l)))throw new Error(`resolved to missing file ${l}`)}catch(l){throw new Error(`[broker] refusing to launch ${e}: cannot resolve broker engine '${w}' from ${J()} \u2014 ${l.message}`)}const h=u.argv,N=[];for(let l=0;l<h.length;l++){const x=h[l];if(x==="-e"){const D=h[++l];D!==void 0&&N.push(D);continue}if(x!=="--session"&&x!=="--fork")continue;const R=h[++l];R!==void 0&&await br(e,n,x,R)}try{ar(N)}catch(l){throw new Error(`[broker] refusing to launch ${e}: ${l.message}`)}}c(Rr,"preflightBrokerLaunch");const Pr=2e3,xr=2e3,Tr=150;async function U(e,r){const n=Date.now()+r;for(;ir(e);){const o=n-Date.now();if(o<=0)return!1;await new Promise(t=>setTimeout(t,Math.min(Tr,o)))}return!0}c(U,"waitForTreeExit");async function Or(e,r,n){return e.length===0?{confirmed:!0}:n&&await U(e,Pr)?{confirmed:!0}:(Ee(e,"SIGTERM",r),await U(e,xr)?{confirmed:!0}:(Ee(e,"SIGKILL",r),await U(e,5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`broker process tree for ${e.join(", ")} remained alive after SIGKILL`)}))}c(Or,"terminateBrokerTree");async function be(e,r){const n=await E(e),o=n?.pi_pid,t=o!=null?sr(o,n?.pi_pid_identity??null,r.excludePid):null;return t?.reused===!0&&_({level:"warn",event:"broker.teardown.pid_reuse_refused",node_id:e,fields:{recorded_pid:o,expected_identity:n?.pi_pid_identity??null}}),{tree:t?.tree??[],identities:t?.identities??null,nodeId:e,launcherPid:j(X)&&t?.tree.includes(o)?o:null}}c(be,"prepareBrokerTeardown");async function Re(e){if(e.launcherPid!==null){try{await F({operation:"stop",pid:e.launcherPid})}catch(r){return I(e.launcherPid)?{confirmed:!1,error:r instanceof Error?r:new Error(String(r))}:{confirmed:!0}}return await U([e.launcherPid],5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`launcher pid ${e.launcherPid} remained alive`)}}return new Promise(r=>{let n=!1,o=!1;const t=c(w=>{o||(o=!0,r(w))},"settle"),i=c(()=>{try{de(Ie(e.nodeId))}catch{}},"cleanupSocket"),s=c(w=>{Or(e.tree,e.identities,w).then(t,h=>t({confirmed:!1,error:h instanceof Error?h:new Error(String(h))}))},"finish"),u=He(e.nodeId);u.once("error",()=>{n||(i(),s(!1))}),u.once("connect",()=>{n=!0;try{u.write(ge({type:"hello",role:"controller",client_id:`daemon-shutdown-${process.pid}`})),u.write(ge({type:"shutdown"}))}catch{}u.end(),i(),s(!0)})})}c(Re,"runPreparedBrokerTeardown");async function ft(e,r={},n){let o;try{await Ve(e,{afterTurn:r.startAfter!==void 0,reason:r.reason??"teardown"}),o=await be(e,r)}catch(t){const i={confirmed:!1,error:t instanceof Error?t:new Error(String(t))};return _({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:i.error}),i}return await new Promise(t=>{const i=c(()=>{Re(o).then(async s=>{if(s.confirmed){if(n!==void 0)try{await n()}catch(u){_({level:"error",event:"broker.teardown.after_failed",node_id:e,error:u})}}else _({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:s.error});t(s)},s=>{const u={confirmed:!1,error:s instanceof Error?s:new Error(String(s))};_({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:u.error}),t(u)})},"run");r.startAfter===void 0?setImmediate(i):r.startAfter.then(i,i)})}c(ft,"requestBrokerTeardown");function Pe(){return process.platform==="linux"&&j(X)}c(Pe,"isolatedBrokerLauncherAvailable");const dt={async launch(e,r,n){if(De((await E(e))?.grantee),(await E(e))?.isolated===!0&&!Pe())throw new Error("isolated broker requires the Linux root launcher");const o=n.launchJson??await Se(e,r,n.cwd);await Rr(e,r,n.cwd,o);const t=r.env.CRTR_EXECUTION_ID;n.launchJson===void 0&&t!==void 0&&await Qe(t,o);const i=ur();if(!await i.reserveSlot(e))throw fr(dr().automaticReviveCap,await i.occupancy());let s=null,u,w=!1;try{const h=Ze(e);fe(h,{recursive:!0}),s=G(m(h,"broker.log"),"a");const N=ve(r),l={...await nr(r),CRTR_BROKER_ENGINE:N};if(N!==vr){const a=r.env.NODE_OPTIONS??process.env.NODE_OPTIONS;a!==void 0&&(l.NODE_OPTIONS=a);const f=r.env.CRTR_TEST_PG_URL??process.env.CRTR_TEST_PG_URL;f!==void 0&&(l.CRTR_TEST_PG_URL=f)}pr()===void 0&&hr(e);const x=(await E(e))?.run_id;if(x){const a=await E(x);if(!a||a.deleting_at)throw new Error("run is deleting")}const R=r.env.CRTR_EXECUTION_ID;if(!R)throw new Error("broker launch has no execution id");const D=await ze(a=>_r(a,R,e,new Date().toISOString())),H=Pe();if((await E(e))?.isolated===!0&&!H)throw new Error("isolated broker requires the Linux root launcher");if(process.platform==="linux"&&process.env.CRTR_LAUNCHER_SOCKET&&!H)throw new Error("root launcher socket is unavailable; refusing an unsandboxed broker");if(H){const a=await E(e);if(!a)throw new Error(`missing node ${e}`);const f=a.grantee??"app:terminal",T=await mr(e,{useMemo:!1});if(T.verdict==="denied")throw cr(T);if(T.verdict==="too_small")throw lr(T);const v=await $e(f);Object.assign(l,je(f));const y={uid:process.getuid(),gid:v.gid},g=Z(e);for(const[d,k]of[[K(f).nodes,er(e,f)],[K(f).nodes,rr(e,f)],[g,Ye(e)]])V(d,k,()=>{},!0),b(d,k,1528,y);b(g,m(g,"broker-launch.json"),416,y),z(g,Y(e))&&b(g,Y(e),416,y);const te=m(g,"system-prompt.md");z(g,te)&&b(g,te,432,y);for(const d of["output-schema.json","situational-context.md"]){const k=m(g,d);z(g,k)&&b(g,k,432,y)}const ne=a.isolated===!0,S=tr(e,f,ne);ne&&(V(K(f).nodes,S,()=>{},!0),b(K(f).nodes,S,1528,y),l.HOME=S,l.PI_CODING_AGENT_DIR=m(S,".pi","agent"));const q=m(S,".pi","agent");V(S,q,()=>{},!0),yr(S,q);const oe=m(q,"settings.json"),Te=m(Q(J()),"../../builtin-pi-packages/pi-crtr-extensions");M(S,oe,`${JSON.stringify({packages:[Te]})}
3
- `,{atomic:!0,mode:432}),b(S,oe,432);const ie=m(Z(e),`token-${R}`),B=G(ie,"wx+",384);de(ie),Le(B,D);const se=[G(`/proc/self/fd/${B}`,"r"),G(`/proc/self/fd/${B}`,"r")];L(B);const ae={nodeId:e,app:f,sub:a.sub??kr(),grantId:a.grant_id??null,scopes:a.scopes??null,isolated:a.isolated===!0,...a.isolated===!0?{cwd:a.cwd}:{},command:[process.execPath,J(),"--canvas-home",we(),"--epoch",i.epoch(),e],env:Object.fromEntries(Object.entries({...l,...a.isolated===!0?{PWD:a.cwd}:{}}).filter(d=>d[1]!==void 0)),auditMissing:c(d=>_({level:"warn",event:"broker.mount.missing",node_id:e,fields:{source:d}}),"auditMissing")};try{let d;for(const C of se){const $=await me(),p=await Ge(ae);p.broker=!0;const P=await F({operation:"launch",spec:p},[C]);if(!("pid"in P))throw new Error("launcher did not return a pid");if(await me()===$||await Fe(ae,p)){d=P.pid;break}_({level:"info",event:"broker.launch.regranted",node_id:e,fields:{pid:P.pid}}),await F({operation:"stop",pid:P.pid,signal:"SIGKILL"}).catch(()=>{})}if(d===void 0)throw new Error("grant changed during every launch attempt");const k=d,Oe=Date.now(),ce=new Promise(C=>{const $=setInterval(()=>{I(k)||(clearInterval($),F({operation:"exit.status",pid:k}).then(p=>"oomKilled"in p?{oomKilled:p.oomKilled,code:p.code??null,signal:p.signal??null}:{oomKilled:!1,code:null,signal:null},()=>({oomKilled:!1,code:null,signal:null})).then(({oomKilled:p,code:P,signal:ue})=>{_({level:p||P!==0?"warn":"info",event:"broker.exited",node_id:e,fields:{pid:k,code:P,signal:ue,uptime_ms:Date.now()-Oe,oom_killed:p}}),C({code:P,signal:ue,...p?{oomKilled:!0}:{}})}))},250);$.unref()});L(s),s=null;const le={pid:k,exited:ce};return i.register(e,le),w=!0,ce.then(async C=>await i.onChildExit(e,C,R)),le}finally{for(const d of se)L(d)}}const xe=await or(),O=Ce(xe,[J(),"--canvas-home",we(),"--epoch",i.epoch(),e],{cwd:n.cwd,detached:!0,stdio:["ignore",s,s,"pipe"],env:l});u=O;const A=O.stdio[3];if(!A||!("end"in A))throw new Error("broker token pipe did not open");A.on("error",a=>_({event:"broker.token_pipe.failed",level:"error",node_id:e,error:a})),A.end(D),L(s),s=null;const ee=Date.now(),re=new Promise(a=>{let f=!1;const T=c(v=>{f||(f=!0,a(v))},"finish");O.once("exit",(v,y)=>{_({level:v===0?"info":"warn",event:"broker.exited",node_id:e,fields:{code:v,signal:y,uptime_ms:Date.now()-ee}}),T({code:v,signal:y})}),O.once("error",v=>{_({level:"error",event:"broker.launch.failed",node_id:e,error:v,fields:{uptime_ms:Date.now()-ee}}),T({code:null,signal:null})})});O.unref();const W={pid:O.pid??null,exited:re};return W.pid!==null&&(i.register(e,W),w=!0,re.then(async a=>await i.onChildExit(e,a,R))),W}catch(h){if(!w&&u?.pid!=null)try{u.kill("SIGTERM")}catch{}throw h}finally{w||i.releaseReservation(e),s!==null&&L(s)}},async isAlive(e){return I((typeof e=="string"?await E(e):e)?.pi_pid)},async teardown(e,r={}){try{return Re(await be(e,r))}catch(n){return Promise.resolve({confirmed:!1,error:n instanceof Error?n:new Error(String(n))})}},async signal(e,r){const n=(await E(e))?.pi_pid;if(n!=null)try{process.kill(n,r)}catch{}}};export{Se as brokerLaunchJson,dt as headlessBrokerHost,Pe as isolatedBrokerLauncherAvailable,Rr as preflightBrokerLaunch,ft as requestBrokerTeardown};
1
+ var Ne=Object.defineProperty;var c=(e,r)=>Ne(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as De}from"./unsandboxed.js";import{spawn as Ce}from"node:child_process";import{mkdirSync as de,existsSync as j,unlinkSync as me,openSync as G,closeSync as L,writeSync as Le,chmodSync as $e,lstatSync as Ae}from"node:fs";import{ensureAppSpace as Be}from"../spaces/space.js";import{sandboxCacheEnv as je}from"../spaces/cache-env.js";import{compileLaunch as Ge,launchStillGranted as Fe}from"../spaces/mounts.js";import{grantsGeneration as he}from"../grants/mirror.js";import{LAUNCHER_SOCKET as z}from"../../launcher/spec.js";import{launcherRequest as F}from"../../launcher/client.js";import{piAgentDir as pe}from"./package-health.js";import{existsBeneath as V,readFileBeneath as Me,readTextBeneathIfExists as Ke,setModeBeneath as S,withDirBeneath as Q,writeFileBeneath as M}from"../spaces/open-beneath.js";import{dirname as Y,join as m,resolve as Je,isAbsolute as Ue}from"node:path";import{fileURLToPath as we}from"node:url";import{connectViewSocket as He}from"./view-socket.js";import{appSpace as K}from"../layout.js";import{readConfig as We,readMergedLaunchConfig as qe}from"../config.js";import{loadRotationConfig as Xe}from"../subscription-state.js";import{getNode as _}from"../canvas/index.js";import{withCanvasWrite as ze}from"../canvas/db.js";import{requestExecutionStop as Ve,setExecutionLaunchJson as Qe}from"../canvas/executions.js";import{scopesFilePath as Z,crtrHome as ge,nodeRunDir as I,nodeRunJobDir as Ye,jobDir as Ze,viewSocketPath as Ie,nodeAgentDir as er,contextDir as rr,nodeHome as nr}from"../canvas/paths.js";import{encodeFrame as Ee}from"./broker-protocol.js";import{buildBrokerEnv as tr}from"./spawn-env-rows.js";import{hostExecPathFresh as or}from"./branded-host.js";import{isPidAlive as ee,killProcessTreePids as _e,isAnyPidAlive as ir,captureTeardownSnapshot as sr}from"../canvas/pid.js";import{assertMandatoryCanvasExtensions as ar}from"./canvas-extensions.js";import{appMemoryFull as cr,appMemoryTooSmall as lr,boundFleet as ur,brokerCapReached as fr,brokerThresholdsForDaemon as dr}from"./fleet.js";import{admitBrokerMemory as mr}from"./memory-admission.js";import{emitEvent as w}from"../events/emit.js";import{bindBrokerEventSource as hr,eventSource as pr}from"../events/source.js";import{envBrokerEngine as wr}from"../../shared/env.js";import{conversationIdFromPath as gr,conversationStore as Er,ConversationNotFoundError as ke}from"../conversation-store/index.js";import{mintNodeToken as _r}from"../canvas/node-tokens.js";import{personId as kr}from"../canvas/person.js";function J(){const e=Y(we(import.meta.url));return m(e,"broker-cli.js")}c(J,"resolveBrokerEntry");const vr="@earendil-works/pi-coding-agent";function ve(){const e=m(pe(),"models.json"),r=Ke(Y(e),e);if(r===null)return null;const t=JSON.parse(r),o=c(n=>Array.isArray(n)?n.map(o):n===null||typeof n!="object"?n:Object.fromEntries(Object.entries(n).filter(([s])=>!/^(apiKey|authorization|headers|token|secret)$/i.test(s)).map(([s,a])=>[s,o(a)])),"scrub");return{text:r,clean:`${JSON.stringify(o(t),null,2)}
2
+ `,credentialed:JSON.stringify(t)!==JSON.stringify(o(t))}}c(ve,"scrubbedBrokerModels");function yr(e,r){const t=m(pe(),"models.json"),o=m(r,"models.json"),n=ve();if(n!==null){if(t===o&&n.text!==n.clean){if(n.credentialed)throw new Error("terminal models.json contains credentials; move them into daemon secrets");S(e,o,432);return}M(e,o,n.clean,{atomic:!0,mode:432}),S(e,o,432)}}c(yr,"writeBrokerModels");function ye(e){return e.env.CRTR_BROKER_ENGINE??wr()}c(ye,"resolveEngineSpec");function be(e){return e.includes("/")||e.endsWith(".jsonl")}c(be,"isPlainLaunchSessionPath");function br(e,r){return Ue(e)?e:Je(r,e)}c(br,"resolvePlainLaunchPath");async function Sr(e,r,t,o){if(t==="--session"&&!be(o))throw new Error(`[broker] refusing to launch ${e}: launch recipe passes bare --session id '${o}' \u2014 the broker fatally rejects bare ids; pass the .jsonl path instead.`);if(!be(o))return;const n=br(o,r),s=gr(n);try{if(s===null)throw new ke(n);await Er().header(s)}catch(a){if(!(a instanceof ke))throw a;const u=t==="--session"?"session file":"fork source";throw new Error(`[broker] refusing to launch ${e}: launch recipe references missing ${u} '${o}' (${n})`)}}c(Sr,"preflightLaunchSessionArg");async function Se(e,r,t){const o=ve();return JSON.stringify({...r,configSnapshot:{user:We("user"),launch:qe(t,r.env.CRTR_PROFILE_ID||null),rotation:await Xe()},scopes:(await _(e))?.scopes??null,models:o===null?null:JSON.parse(o.clean)})}c(Se,"brokerLaunchJson");async function Rr(e,r,t,o){const n=I(e);de(n,{recursive:!0}),process.platform==="linux"&&j(z)&&Ae(n).uid===process.getuid()&&$e(n,504);const s=m(n,"broker-launch.json");M(n,s,o??await Se(e,r,t),{atomic:!0}),r.env.CRTR_SCOPES_FILE!==void 0&&M(n,Z(e),JSON.stringify((await _(e))?.scopes??[]),{atomic:!0});const a=Me(n,s).toString("utf8"),u=JSON.parse(a);if(!Array.isArray(u.argv))throw new Error(`[broker] refusing to launch ${e}: broker-launch.json is missing the argv array`);const g=ye(r);try{const l=import.meta.resolve(g);if(l.startsWith("file:")&&!j(we(l)))throw new Error(`resolved to missing file ${l}`)}catch(l){throw new Error(`[broker] refusing to launch ${e}: cannot resolve broker engine '${g}' from ${J()} \u2014 ${l.message}`)}const h=u.argv,N=[];for(let l=0;l<h.length;l++){const T=h[l];if(T==="-e"){const D=h[++l];D!==void 0&&N.push(D);continue}if(T!=="--session"&&T!=="--fork")continue;const R=h[++l];R!==void 0&&await Sr(e,t,T,R)}try{ar(N)}catch(l){throw new Error(`[broker] refusing to launch ${e}: ${l.message}`)}}c(Rr,"preflightBrokerLaunch");const Pr=2e3,xr=2e3,Tr=150;async function U(e,r){const t=Date.now()+r;for(;ir(e);){const o=t-Date.now();if(o<=0)return!1;await new Promise(n=>setTimeout(n,Math.min(Tr,o)))}return!0}c(U,"waitForTreeExit");async function Or(e,r,t){return e.length===0?{confirmed:!0}:t&&await U(e,Pr)?{confirmed:!0}:(_e(e,"SIGTERM",r),await U(e,xr)?{confirmed:!0}:(_e(e,"SIGKILL",r),await U(e,5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`broker process tree for ${e.join(", ")} remained alive after SIGKILL`)}))}c(Or,"terminateBrokerTree");async function Re(e,r){const t=await _(e),o=t?.pi_pid,n=o!=null?sr(o,t?.pi_pid_identity??null,r.excludePid):null;return n?.reused===!0&&w({level:"warn",event:"broker.teardown.pid_reuse_refused",node_id:e,fields:{recorded_pid:o,expected_identity:t?.pi_pid_identity??null}}),{tree:n?.tree??[],identities:n?.identities??null,nodeId:e,launcherPid:j(z)&&n?.tree.includes(o)?o:null}}c(Re,"prepareBrokerTeardown");async function Pe(e){if(e.launcherPid!==null){try{await F({operation:"stop",pid:e.launcherPid})}catch(r){return ee(e.launcherPid)?{confirmed:!1,error:r instanceof Error?r:new Error(String(r))}:{confirmed:!0}}return await U([e.launcherPid],5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`launcher pid ${e.launcherPid} remained alive`)}}return new Promise(r=>{let t=!1,o=!1;const n=c(g=>{o||(o=!0,r(g))},"settle"),s=c(()=>{try{me(Ie(e.nodeId))}catch{}},"cleanupSocket"),a=c(g=>{Or(e.tree,e.identities,g).then(n,h=>n({confirmed:!1,error:h instanceof Error?h:new Error(String(h))}))},"finish"),u=He(e.nodeId);u.once("error",()=>{t||(s(),a(!1))}),u.once("connect",()=>{t=!0;try{u.write(Ee({type:"hello",role:"controller",client_id:`daemon-shutdown-${process.pid}`})),u.write(Ee({type:"shutdown"}))}catch{}u.end(),s(),a(!0)})})}c(Pe,"runPreparedBrokerTeardown");async function dn(e,r={},t){let o;try{await Ve(e,{afterTurn:r.startAfter!==void 0,reason:r.reason??"teardown"}),o=await Re(e,r)}catch(n){const s={confirmed:!1,error:n instanceof Error?n:new Error(String(n))};return w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:s.error}),s}return await new Promise(n=>{const s=c(()=>{Pe(o).then(async a=>{if(a.confirmed){if(t!==void 0)try{await t()}catch(u){w({level:"error",event:"broker.teardown.after_failed",node_id:e,error:u})}}else w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:a.error});n(a)},a=>{const u={confirmed:!1,error:a instanceof Error?a:new Error(String(a))};w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:u.error}),n(u)})},"run");r.startAfter===void 0?setImmediate(s):r.startAfter.then(s,s)})}c(dn,"requestBrokerTeardown");function xe(){return process.platform==="linux"&&j(z)}c(xe,"isolatedBrokerLauncherAvailable");const mn={async launch(e,r,t){if(De((await _(e))?.grantee),(await _(e))?.isolated===!0&&!xe())throw new Error("isolated broker requires the Linux root launcher");const o=t.launchJson??await Se(e,r,t.cwd);await Rr(e,r,t.cwd,o);const n=r.env.CRTR_EXECUTION_ID;t.launchJson===void 0&&n!==void 0&&await Qe(n,o);const s=ur();if(!await s.reserveSlot(e))throw fr(dr().automaticReviveCap,await s.occupancy());let a=null,u,g=!1;try{const h=Ze(e);de(h,{recursive:!0}),a=G(m(h,"broker.log"),"a");const N=ye(r),l={...await tr(r),CRTR_BROKER_ENGINE:N};if(N!==vr){const i=r.env.NODE_OPTIONS??process.env.NODE_OPTIONS;i!==void 0&&(l.NODE_OPTIONS=i);const f=r.env.CRTR_TEST_PG_URL??process.env.CRTR_TEST_PG_URL;f!==void 0&&(l.CRTR_TEST_PG_URL=f)}pr()===void 0&&hr(e);const T=(await _(e))?.run_id;if(T){const i=await _(T);if(!i||i.deleting_at)throw new Error("run is deleting")}const R=r.env.CRTR_EXECUTION_ID;if(!R)throw new Error("broker launch has no execution id");const D=await ze(i=>_r(i,R,e,new Date().toISOString())),H=xe();if((await _(e))?.isolated===!0&&!H)throw new Error("isolated broker requires the Linux root launcher");if(process.platform==="linux"&&process.env.CRTR_LAUNCHER_SOCKET&&!H)throw new Error("root launcher socket is unavailable; refusing an unsandboxed broker");if(H){const i=await _(e);if(!i)throw new Error(`missing node ${e}`);const f=i.grantee??"app:terminal",O=await mr(e,{useMemo:!1});if(O.verdict==="denied")throw cr(O);if(O.verdict==="too_small")throw lr(O);const v=await Be(f);Object.assign(l,je(f));const y={uid:process.getuid(),gid:v.gid},E=I(e);for(const[d,k]of[[K(f).nodes,er(e,f)],[K(f).nodes,rr(e,f)],[E,Ye(e)]])Q(d,k,()=>{},!0),S(d,k,1528,y);S(E,m(E,"broker-launch.json"),416,y),V(E,Z(e))&&S(E,Z(e),416,y);const te=m(E,"system-prompt.md");V(E,te)&&S(E,te,432,y);for(const d of["output-schema.json","situational-context.md"]){const k=m(E,d);V(E,k)&&S(E,k,432,y)}const oe=i.isolated===!0,b=nr(e,f,oe);oe&&(Q(K(f).nodes,b,()=>{},!0),S(K(f).nodes,b,1528,y),l.HOME=b,l.PI_CODING_AGENT_DIR=m(b,".pi","agent"));const X=m(b,".pi","agent");Q(b,X,()=>{},!0),yr(b,X);const ie=m(X,"settings.json"),Te=m(Y(J()),"../../builtin-pi-packages/pi-crtr-extensions");M(b,ie,`${JSON.stringify({packages:[Te]})}
3
+ `,{atomic:!0,mode:432}),S(b,ie,432);const se=m(I(e),`token-${R}`),A=G(se,"wx+",384);me(se),Le(A,D);const ae=[G(`/proc/self/fd/${A}`,"r"),G(`/proc/self/fd/${A}`,"r")];L(A);const ce={nodeId:e,app:f,sub:i.sub??kr(),grantId:i.grant_id??null,scopes:i.scopes??null,isolated:i.isolated===!0,...i.isolated===!0?{cwd:i.cwd}:{},command:[process.execPath,J(),"--canvas-home",ge(),"--epoch",s.epoch(),e],env:Object.fromEntries(Object.entries({...l,...i.isolated===!0?{PWD:i.cwd}:{}}).filter(d=>d[1]!==void 0)),auditMissing:c(d=>w({level:"warn",event:"broker.mount.missing",node_id:e,fields:{source:d}}),"auditMissing")};try{let d;for(const C of ae){const B=await he(),p=await Ge(ce);p.broker=!0;const x=await F({operation:"launch",spec:p},[C]);if(!("pid"in x))throw new Error("launcher did not return a pid");if(await he()===B||await Fe(ce,p)){d=x.pid;break}w({level:"info",event:"broker.launch.regranted",node_id:e,fields:{pid:x.pid}}),await F({operation:"stop",pid:x.pid,signal:"SIGKILL"}).catch(()=>{})}if(d===void 0)throw new Error("grant changed during every launch attempt");const k=d,Oe=Date.now(),le=new Promise(C=>{const B=setInterval(()=>{ee(k)||(clearInterval(B),F({operation:"exit.status",pid:k}).then(p=>"oomKilled"in p?{oomKilled:p.oomKilled,code:p.code??null,signal:p.signal??null}:{oomKilled:!1,code:null,signal:null},()=>({oomKilled:!1,code:null,signal:null})).then(({oomKilled:p,code:x,signal:fe})=>{w({level:p||x!==0?"warn":"info",event:"broker.exited",node_id:e,fields:{pid:k,code:x,signal:fe,uptime_ms:Date.now()-Oe,oom_killed:p}}),C({code:x,signal:fe,...p?{oomKilled:!0}:{}})}))},250);B.unref()});L(a),a=null;const ue={pid:k,exited:le};return s.register(e,ue),g=!0,le.then(async C=>await s.onChildExit(e,C,R)),ue}finally{for(const d of ae)L(d)}}const W=await or(),P=Ce(W,[J(),"--canvas-home",ge(),"--epoch",s.epoch(),e],{cwd:t.cwd,detached:!0,stdio:["ignore",a,a,"pipe"],env:l});u=P;try{await new Promise((i,f)=>{P.once("spawn",i),P.once("error",f)})}catch(i){throw w({level:"error",event:"broker.launch.failed",node_id:e,error:i,fields:{cwd:t.cwd,executable:W}}),new Error(`could not spawn the broker (executable ${W}, cwd ${t.cwd}): ${i.message}`,{cause:i})}const $=P.stdio[3];if(!$||!("end"in $))throw new Error("broker token pipe did not open");$.on("error",i=>w({event:"broker.token_pipe.failed",level:"error",node_id:e,error:i})),$.end(D),L(a),a=null;const re=Date.now(),ne=new Promise(i=>{let f=!1;const O=c(v=>{f||(f=!0,i(v))},"finish");P.once("exit",(v,y)=>{w({level:v===0?"info":"warn",event:"broker.exited",node_id:e,fields:{code:v,signal:y,uptime_ms:Date.now()-re}}),O({code:v,signal:y})}),P.once("error",v=>{w({level:"error",event:"broker.launch.failed",node_id:e,error:v,fields:{uptime_ms:Date.now()-re}}),O({code:null,signal:null})})});P.unref();const q={pid:P.pid??null,exited:ne};return q.pid!==null&&(s.register(e,q),g=!0,ne.then(async i=>await s.onChildExit(e,i,R))),q}catch(h){if(!g&&u?.pid!=null)try{u.kill("SIGTERM")}catch{}throw h}finally{g||s.releaseReservation(e),a!==null&&L(a)}},async isAlive(e){return ee((typeof e=="string"?await _(e):e)?.pi_pid)},async teardown(e,r={}){try{return Pe(await Re(e,r))}catch(t){return Promise.resolve({confirmed:!1,error:t instanceof Error?t:new Error(String(t))})}},async signal(e,r){const t=(await _(e))?.pi_pid;if(t!=null)try{process.kill(t,r)}catch{}}};export{Se as brokerLaunchJson,mn as headlessBrokerHost,xe as isolatedBrokerLauncherAvailable,Rr as preflightBrokerLaunch,dn as requestBrokerTeardown};
@@ -17,6 +17,10 @@ export declare const RUN_USER = "crtr";
17
17
  /** Where the image installs the recipe's pi packages: one pi agent dir of its own, not any app's. The start script (`sandbox-start.mjs`) links its
18
18
  * `npm`/`git` trees into, and merges its `packages` setting with, the agent dir of whichever app the node runs in. Keep the two in step. */
19
19
  export declare const RECIPE_PI_AGENT_DIR = "/var/lib/crtr/recipe-pi-agent";
20
+ /** Blaxel runs a slimming pass after the Docker build that deletes `make`, `gcc`, `g++`, headers and static libraries from the image, so a recipe's apk-installed
21
+ * toolchain compiled in the build stage and was gone in the running sandbox. `slim = false` in the uploaded `blaxel.toml` keeps them. */
22
+ export declare const BLAXEL_TOML_FILE = "blaxel.toml";
23
+ export declare const BLAXEL_TOML = "[build]\nslim = false\n";
20
24
  export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
21
25
  export declare const REPOS_DIR = "repos";
22
26
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
@@ -1,6 +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 _}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 X}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="1.1.0",b="recipe-setup.sh",L="repos",D="/work/.crtr/setup.log",P="/work/.crtr/setup-failed",B=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),nt=c(t=>(t??"").split(`
2
- `).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${D} 2>&1 || echo ${B(t)} "exited $?" >> ${P}`,"guarded");function st(t,r,i=!1){const o=nt(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}`,$("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($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${rt}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work");for(const s of o)e.push($(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${A} pi install ${B(s)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("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(`
3
- `)}c(st,"recipeDockerfile");const ot=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 ht(t){const r=t.git??ot,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)}_(E(t.dir,"Dockerfile"),st(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
4
- `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
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]
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(`
5
7
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
6
- `)}c(ht,"prepareBuildDir");function C(t,r,i){for(const o of H(r).sort()){const a=E(r,o),n=j(a),e=V(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 it(t){const r=[];C(t,t,r);const i=[],o=[];let a=0;for(const s of r){const u=Buffer.from(s.name),g=Q(s.data),I=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(I,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),i.push(p,u,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(s.data.length,24),l.writeUInt16LE(u.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,u),a+=p.length+u.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(it,"zipDirectory");async function R(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 u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!e.ok&&!a.includes(e.status))throw new X(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:u}}c(R,"api");async function G(t,r){const{status:i,json:o}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(G,"getImage");async function mt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(mt,"deleteImage");async function wt(t,r,i,o={}){const a=o.sleep??(h=>new Promise(d=>setTimeout(d,h))),n=o.now??Date.now,e=n(),s=await G(t,r),u=new Set((s?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(d=>Date.parse(d.time??"")).filter(d=>!Number.isNaN(d)),"eventTimes"),I=Math.max(-1/0,...g(s)),l=(await R(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(it(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const F=e+(o.timeoutMs??20*6e4);let N=null;for(;;){const h=await G(t,r),d=h?.metadata?.status,k=g(h).filter(m=>m>I).sort((m,x)=>m-x);if(d==="BUILT"&&k.length>=2){N??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],O=c(w=>Date.parse(w??"")>=x,"touchedSince"),T=m.filter(w=>!u.has(w.name)||O(w.createdAt)||O(w.updatedAt)),y=n()-N>=(o.tagGraceMs??6e4),S=(T.length>0?T:y?m:[]).sort((w,M)=>(M.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(d==="FAILED"||d==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${d.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>F)throw new Error(`building image ${r} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${d??"none"})`);await a(o.pollMs??3e3)}}c(wt,"buildImage");const gt=c(t=>`env-${t}`,"environmentImageName");function Et(t){W(t,{recursive:!0,force:!0})}c(Et,"removeBuildDir");export{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,b as SETUP_SCRIPT_FILE,wt as buildImage,mt as deleteImage,gt as environmentImageName,G as getImage,ht as prepareBuildDir,st as recipeDockerfile,Et as removeBuildDir,it as zipDirectory};
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};
@@ -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}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as $e}from"node:path";import{appSpace as Re}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Me,forkSourceNode as Fe,currentNodeContext as De,rootOfSpine as Ne,newNodeId as le,preflightNodeId as Be}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Pe,selectProfileForCwdReadOnly as Le}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as Ae}from"./launch.js";import{devEnvironmentCwd as We,runsOnBlaxel as je,sandboxWorktreeRequest as ze}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as He,rollbackManagedWorktreeAsync as Ke}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Ue,rollbackManagedWorktreeOnMachine as Xe,worktreeMachineOf as qe}from"../worktree-machine.js";import{usage as _,brokerLaunchFailed as K}from"../errors.js";import{writeGoal as Ge}from"./kickoff.js";import{appendSituationalContext as Ve,formatSituationalProse as Je}from"./situational-context.js";import{ensureRoadmap as Ye}from"./roadmap.js";import{buildWakeBearings as Qe}from"./bearings.js";import{encodeKickoffOrigin as Ze,KICKOFF_ORIGIN_ENV as en}from"./stamp/protocol.js";import{carryInitialInput as nn}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as rn,getNode as w,fullName as we,jobDir as tn,recordExecutionPid as on,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 an}from"../spaces/open-beneath.js";import{conversationIdFromPath as U,conversationStore as R}from"../conversation-store/index.js";import{appMemoryTooSmall as dn,boundFleet as me,brokerThresholdsForDaemon as Y}from"./fleet.js";import{admitBrokerMemory as sn}from"./memory-admission.js";import{emitEvent as k}from"../events/emit.js";import{remoteEnvironmentOf as ln}from"./blaxel-environment.js";import{openViewerWindow as cn,focusOf as un,windowOfPane as fn}from"./placement.js";import{awaitBrokerViewSocket as wn}from"./view-socket.js";import{readLogSnapshot as mn}from"../events/read.js";import{transition as S}from"./lifecycle.js";import{beginBootFaultAttempt as hn}from"../canvas/recovery.js";import{headlessBrokerHost as Q,brokerLaunchJson as pn}from"./host.js";import{openDb as _n,withCanvasWrite as kn}from"../canvas/db.js";import{warmNodeRepos as vn}from"../graph/reader.js";import{mintNodeToken as gn}from"../canvas/node-tokens.js";import{personIdAsync as yn}from"../canvas/person.js";import{recordLaunch as bn}from"../canvas/canvas.js";import{setExecutionLaunchJson as xn}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as Cn}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as Sn,awaitMachineCall as En,callTimes as On}from"./runner/machine/call.js";import{addStepTiming as Z,timedStep as X}from"../step-timings.js";import{MachineLostError as In,MachineOfflineError as $n}from"./runner/machine/ops.js";import{isDrained as Rn}from"../../daemon/drain.js";import{ensureDaemon as Mn}from"../../daemon/manage.js";import{readConfig as Fn}from"../config.js";import{modelRequestFromConfig as Dn,unregisteredConcreteModel as Nn,unroutableConcreteModel as Bn}from"../model-routes.js";import{openModelRegistry as Tn}from"./model-registry.js";import{MODEL_SPEC_NEXT as Pn}from"./model-selection.js";import{forkNodeLedger as Ln}from"./ledger.js";import{appRungForGrant as An}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Wn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as jn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as zn}from"../async-array.js";import{checkStart as Hn}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 Kn(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, fix the launch recipe or environment, then retry.")}}l(Kn,"launchBrokerOrCrash");function Un(e){return mn({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(Un,"lastStartupStep");function Xn(e,r){const o=Un(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(Xn,"notReadyDescription");async function qn(e,r){try{await S(e,"crash",{reason:"launch_failed",outcome:E(r)})}catch{}try{Q.teardown(e)}catch{}}l(qn,"crashAndTearDown");async function Gn(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(Gn,"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 Gn(r)}l(pe,"resolveForkSource");async function Vn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await w(r))?.profile_id??null:t.readOnlySelection===!0?Le(o):Pe(o)}l(Vn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Dn(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 An(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 Nn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await Tn(),r);if(t!==void 0)throw _(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Pn});const a=await Bn(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 Jn(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(Jn,"resolveSpawner");async function Yn(e,r){const o=await On(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(Yn,"recordStartCallTimings");async function Qn(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 Rn())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 pn(e.node_id,o,e.cwd);await xn(d,s);const P=d;await X("warm_repos",async()=>await vn(await _n(),e.node_id));const O=e.sub??await yn(),L=await X("start_bundle",()=>t({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:O,launchJson:s,runner:"machine"}));c=await X("render_transaction",()=>kn(async v=>{const M=await a(e.node_id),F=await gn(v,P,e.node_id,new Date().toISOString());return await Sn(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 En(r,"start",c)}catch(s){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),s instanceof In||s instanceof $n&&s.sent?"uncertain":(await T(d,{reason:"launch_failed"}),"failed")}try{await Yn(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",()=>bn(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(Qn,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Mn()}catch{}const a=De(),d=e.root===!0,c=Jn(e.parent,a.nodeId??null,d),m=e.mode??"base",s=e.rootLifecycle??(d?"resident":"terminal"),P=d&&s==="resident",O=c===null?null:await w(c),L=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Be(e.nodeId);const v=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,M=v===void 0?null:await Fe(v),F=await zn([O,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,I=D?e.run!==void 0&&d&&!F?e.cwd:$e(Re(e.run?.grantee??O?.grantee??"app:terminal").nodes,h):e.cwd;const p=await Vn(e.profile,c,I),A=D?null:await We(p,e.worktreeCwd??I);A!==null&&(I=A,h??=await le());const N=e.worktree===!0||A!==null,ne=e.run?.grant_id??O?.grant_id??null,B=e.run??L??O??M,re=await ke((await ce(e.kind,m,{lifecycle:s,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:I,profileId:p,app:B?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:I,profileId:p}),await Hn({grantee:B?.grantee??"app:terminal",sub:B?.sub,grant_id:B?.grant_id});const te=M?.node_id??null;let y,W=I;const j=N&&await je(p)?await ze(p,A??e.worktreeCwd??e.cwd,h,e.worktreeBase):void 0,z=N&&j===void 0?await qe(p):null;try{N&&j===void 0&&(y=z!==null?await Ue(z,e.worktreeCwd??e.cwd,h,e.worktreeBase):await He(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 Me({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 Ln(n.node_id,te??null)}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}if(await Ge(n.node_id,e.prompt),e.situationalContext!==void 0&&await Ve(n.node_id,Je(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?`${Qe(e.wakeOrigin)}
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)}
2
2
 
3
- `:""}${e.prompt}`;m==="orchestrator"&&await Ye(n.node_id,{goal:e.prompt.trim()}),await Zn(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=Ae(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Ne(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[en]=Ze(i),await nn(g,n)}const b=me();if(await ln(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await Cn(n.profile_id??null):null;if(u!==null){Z("birth",performance.now()-t);const C=await Qn(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}}const ie=await b.reserveSlot(n.node_id),x=ie?await sn(n.node_id):null;if(x?.verdict==="too_small"){b.releaseReservation(n.node_id);const i=dn(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 hn(n.node_id),{automaticReviveCap:xe}=Y();let $;try{$=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:$};let H;try{H=await Kn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await T($,{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($,{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 on($,n.node_id,H.pid)==="shutdown")throw await T($,{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 wn(n.node_id,H.exited);if(!i.ready){const u=Xn(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 qn(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&&Fn("user").auto_open_child_viewers)try{const i=await un(c);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await cn(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=fn(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 Xe(z,y):await Ke(y)),f}}l(ge,"spawnChildPrepared");async function it(e){return ge(e)}l(it,"spawnChild");async function Zn(e){const r=Wn(e.cwd,e.profile_id).plans.get("node:start")??[];await jn(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:tn(e.node_id)},runtime:{isBirth:!0,canvasHome:rn(),profile:e.profile_id??null}})}l(Zn,"invokeBirthLifecycleHooks");const er=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function at(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);an(await J(e),d,await J(c),m,er)})}l(at,"forkNode");export{ke as appPaidLaunch,ve as assertLaunchModelRegistered,at as forkNode,Zn as invokeBirthLifecycleHooks,pe as resolveForkSource,Vn as resolveProfileId,Jn as resolveSpawner,it as spawnChild,ge as spawnChildPrepared};
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};
@@ -56,7 +56,7 @@ export declare const CONFIG_SETTINGS_COVERAGE: {
56
56
  applies: string;
57
57
  group: "updates";
58
58
  order: number;
59
- format: (config: ScopeConfig) => "off" | "notify" | "apply";
59
+ format: (config: ScopeConfig) => "notify" | "off" | "apply";
60
60
  cycle: (config: ScopeConfig, delta: number) => void;
61
61
  setFromString: (config: ScopeConfig, raw: string) => "auto_update.crtr must be notify, apply, or false" | null;
62
62
  };
@@ -68,7 +68,7 @@ export declare const CONFIG_SETTINGS_COVERAGE: {
68
68
  applies: string;
69
69
  group: "updates";
70
70
  order: number;
71
- format: (config: ScopeConfig) => "off" | "notify" | "apply";
71
+ format: (config: ScopeConfig) => "notify" | "off" | "apply";
72
72
  cycle: (config: ScopeConfig, delta: number) => void;
73
73
  setFromString: (config: ScopeConfig, raw: string) => "auto_update.content must be notify, apply, or false" | null;
74
74
  };
@@ -1 +1 @@
1
- var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{openDb as N}from"../../../core/canvas/db.js";import{assertLaunchKind as v}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as M}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as $}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as F}from"../../../core/graph/jobs.js";import{boundFleet as S}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as V}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as C}from"../reader.js";import{canRead as B}from"../../../core/graph/access.js";import{ownersByHandle as G}from"../../../core/graph/names.js";import{reposForCwd as H,warmCheckoutIdentities as K}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as U}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as I}from"../../../core/scopes.js";import{validateEnvVarName as W}from"../../../core/env-name.js";import{listProfileEnvNames as J,removeProfileEnvVar as Y,setProfileEnvVar as z}from"../../../core/profiles/env-store.js";import{isDeploymentName as Q,listAppEnvNames as X,removeAppEnvVar as Z,setAppEnvVar as x}from"../../../core/profiles/app-env-store.js";import{addProfileProject as ee,addProfileRepo as te,assertDeliveryLimits as ae,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as E,pauseProfile as ie,removeProfileProject as ne,renameProfile as oe,resumeProfile as se,setProfileDefaultKind as de,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as fe}from"../../profile-delete.js";import{brokerSignalBus as le}from"../../broker-signals/bus.js";import{toProfileDTO as me}from"../map.js";import{isCloudRole as ue,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as T}from"../../../core/environment-repos.js";import{machineEnvironmentId as he}from"../../../core/environments.js";import{actsAsPerson as g,appOf as j,resolvedScopes as ve}from"../router.js";const A="root",ye=4096;function h(t,e=[]){return{...me(t),environment_id:t.manifest.environment_id??he(),repositories:e}}o(h,"toProfileDTO");async function l(t){return h(t,(await T()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function k(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new p(400,"invalid_request",`${t} already has a profile named ${e}`)}o(k,"assertNameFree");async function m(t,e){const r=await q(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new p(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();k(r,a),e.default_kind!==void 0&&await v(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const f=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:h(f)}}if(!ue())throw new p(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new p(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await U(a,t,r),await oe(t,r)))}o(be,"renameProfileAndHandle");async function Pe(t,e,r){await K(r);const i=(await w(async n=>await H(n,r)))[0];await ee(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function Ee(t,e,r,a){const i=await w(async n=>{const s=await C(n,t);for(const f of await G(n,a,"repo"))if(await B(n,s,f))return f;return null});if(i===null)throw new p(404,"not_found",`no repo you can read is named ${a}`);await te(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Ee,"addRepoWithDefaultLimit");async function ge(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&k(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await v(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&ae({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await de(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Ee(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await ne(e,a.remove_project),{status:200,body:await l(E(e))}}o(ge,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await J(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,r=W(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function O(t){const e=D(t);if(Q(e)&&!g(t.principal))throw new p(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(O,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await z(e,r,a)}}}o(De,"handleEnvSet");async function Ie(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Y(e,r)}}}o(Ie,"handleEnvRemove");async function Te(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===A&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===A)throw new p(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await v(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:h(n)}}o(Te,"handleEnsure");async function Ae(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ae,"handleSetMetadata");async function ke(t){const e=E(t.params.name),r=await ie(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=S();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&V(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=E(t.params.name),r=await se(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await $(a.node_id)!==null)&&le.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await M(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>F(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Oe,"handleResume");async function R(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await N(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await ve(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return I(r,s)&&(e.class!=="broker"||I(e.scopes,s))})}o(R,"visibleProfiles");async function q(t,e){const r=await R(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new p(404,"not_found","profile not found");if(i.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(q,"requireUsableProfile");async function Re(t){const e=await T();return{status:200,body:(await R(t)).map(r=>h(r,e.get(r.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await q(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return fe((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const dt=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await X(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=O(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await x(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await Z(c(t),O(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Te},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ae},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:ge},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Ie},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,dt as profileRoutes,be as renameProfileAndHandle,q as requireUsableProfile};
1
+ var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{openDb as N}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as M}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as $}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as F}from"../../../core/graph/jobs.js";import{boundFleet as S}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as V}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as C}from"../reader.js";import{canRead as B}from"../../../core/graph/access.js";import{ownersByHandle as G}from"../../../core/graph/names.js";import{reposForCwd as H,warmCheckoutIdentities as K}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as U}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as W}from"../../../core/env-name.js";import{listProfileEnvNames as J,removeProfileEnvVar as Y,setProfileEnvVar as z}from"../../../core/profiles/env-store.js";import{isDeploymentName as Q,listAppEnvNames as X,removeAppEnvVar as Z,setAppEnvVar as x}from"../../../core/profiles/app-env-store.js";import{addProfileProject as ee,addProfileRepo as te,assertDeliveryLimits as ae,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as E,pauseProfile as ie,removeProfileProject as ne,renameProfile as oe,resumeProfile as se,setProfileDefaultKind as de,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as fe}from"../../profile-delete.js";import{brokerSignalBus as le}from"../../broker-signals/bus.js";import{toProfileDTO as me}from"../map.js";import{isCloudRole as ue,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as A}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,resolvedScopes as ve}from"../router.js";const I="root",he=4096;function v(t,e=[]){return{...me(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await A()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function k(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new p(400,"invalid_request",`${t} already has a profile named ${e}`)}o(k,"assertNameFree");async function m(t,e){const r=await q(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new p(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function ye(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();k(r,a),e.default_kind!==void 0&&await h(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const f=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(f)}}if(!ue())throw new p(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new p(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:he,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(ye,"handleCreate");async function _e(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await U(a,t,r),await oe(t,r)))}o(_e,"renameProfileAndHandle");async function be(t,e,r){await K(r);const i=(await w(async n=>await H(n,r)))[0];await ee(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(be,"addProjectWithDefaultLimit");async function Pe(t,e,r,a){const i=await w(async n=>{const s=await C(n,t);for(const f of await G(n,a,"repo"))if(await B(n,s,f))return f;return null});if(i===null)throw new p(404,"not_found",`no repo you can read is named ${a}`);await te(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Pe,"addRepoWithDefaultLimit");async function Ee(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&k(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&ae({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await _e(e,a.name),a.default_kind!==void 0&&await de(e,a.default_kind),a.add_project?.path!==void 0?await be(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Pe(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await ne(e,a.remove_project),{status:200,body:await l(E(e))}}o(Ee,"handleUpdate");async function ge(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await J(e)}}}o(ge,"handleEnvList");function D(t){const e=t.params.var,r=W(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function O(t){const e=D(t);if(Q(e)&&!g(t.principal))throw new p(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(O,"requireSelfEnvVarName");async function je(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await z(e,r,a)}}}o(je,"handleEnvSet");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Y(e,r)}}}o(De,"handleEnvRemove");async function Te(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===I&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===I)throw new p(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await h(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:v(n)}}o(Te,"handleEnsure");async function Ae(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ae,"handleSetMetadata");async function Ie(t){const e=E(t.params.name),r=await ie(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=S();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&V(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Ie,"handlePause");async function ke(t){const e=E(t.params.name),r=await se(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await $(a.node_id)!==null)&&le.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await M(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>F(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handleResume");async function R(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await N(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await ve(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(r,s)&&(e.class!=="broker"||T(e.scopes,s))})}o(R,"visibleProfiles");async function q(t,e){const r=await R(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new p(404,"not_found","profile not found");if(i.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(q,"requireUsableProfile");async function Oe(t){const e=await A();return{status:200,body:(await R(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Oe,"handleList");async function Re(t){return{status:200,body:await l(await q(t,t.params.name))}}o(Re,"handleGet");async function qe(t){return fe((await m(t,t.params.name)).profileId,t.body)}o(qe,"handleDelete");const ot=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await X(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=O(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await x(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await Z(c(t),O(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Te},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:Ie},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:ke},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ae},{method:"POST",pattern:"/v1/profiles",handler:ye},{method:"PATCH",pattern:"/v1/profiles/:name",handler:Ee},{method:"GET",pattern:"/v1/profiles/:name/env",handler:ge},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:je},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name",handler:qe},{method:"GET",pattern:"/v1/profiles",handler:Oe},{method:"GET",pattern:"/v1/profiles/:name",handler:Re}];export{be as addProjectWithDefaultLimit,ot as profileRoutes,_e as renameProfileAndHandle,q as requireUsableProfile};