@north-light/cli 0.3.751 → 0.3.752
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/environments.d.ts +37 -0
- package/dist/api/routes.d.ts +2 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/core/environments.js +1 -1
- package/dist/core/graph/objects.d.ts +3 -1
- package/dist/core/graph/objects.js +10 -10
- package/dist/core/profiles/manifest.d.ts +5 -0
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +10 -11
- package/dist/core/runtime/runner/blaxel/image-build.js +7 -6
- package/dist/daemon/api/handlers/app-environments.d.ts +2 -0
- package/dist/daemon/api/handlers/app-environments.js +1 -0
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/reconcilers/recipe-image.d.ts +2 -0
- package/dist/daemon/reconcilers/recipe-image.js +5 -5
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +2 -0
- package/packages/crouter-api/dist/core/environments.js +3 -2
- package/packages/crouter-api/dist/core/graph/objects.js +2 -2
- package/packages/crouter-api/dist/core/profiles/manifest.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +42 -44
- package/packages/crouter-api/dist/daemon/api/operations.js +4 -0
- package/packages/crouter-api/dist/daemon/reconcilers/recipe-image.js +9 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
var Fe=Object.defineProperty;var i=(e,r)=>Fe(e,"name",{value:r,configurable:!0});import{markAuthenticated as j,markReceived as V}from"../../core/step-timings.js";import{IMPORT_TOKEN_PREFIX as Me,importPrincipalFor as $e}from"./import-auth.js";import{createServer as pe}from"node:http";import{createServer as Je}from"node:https";import{chmodSync as We,existsSync as X,readFileSync as de,unlinkSync as me}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as fe,RUNTIME_VERSION_HEADER as Z,minimumRuntimeRefusal as je}from"../../api/runtime-version.js";import{CONTRACT_HEADER as Q,CONTRACT_LEVEL as ge,REQUIRED_CONTRACT_HEADER as he,contractRefusal as Ve}from"../../api/contract.js";import{crtrVersion as q}from"../../shared/crtr-version.js";import{apiSocketPath as Ge}from"../../core/canvas/paths.js";import{resolveNodeToken as Ye}from"../../core/canvas/node-tokens.js";import{isCloudRole as I,runAsPerson as G}from"../../core/canvas/person.js";import{isCanvasRequest as Ke,serveCanvas as Xe}from"./canvas-host.js";import{personBearerVerifier as Re}from"./auth/person-bearer.js";import{personHasSnapshot as ee}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as re}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Ze}from"./principal.js";import{createAppRequestHandler as Qe}from"./app-listener.js";import{decodeJwt as qe}from"jose";import{handleRuntimeSignIn as er,isRuntimeSignInPath as rr}from"./key-signin.js";import{RunError as C}from"../../core/runs/operations.js";import{createRepoPluginHandler as tr,isRepoPluginPath as nr}from"./repo-plugin.js";import{removeVendorAccount as or,vendorStatus as ir}from"./handlers/vendor-status.js";import{toErrorBody as sr}from"./map.js";import{CONTROL_BODY_MAX_BYTES as ar}from"../../core/llm/body-limits.js";import{grantFor as lr,hasSyncedGrants as cr}from"../../core/grants/mirror.js";import{readConfig as Ae}from"../../core/config.js";import{directoryIssuer as ur}from"../../core/directory/issuer.js";import{peerUid as pr}from"../../native/linux.js";import{findScopedApiToken as dr,getApiToken as mr,listScopedApiTokens as fr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as gr,envCrtrdToken as hr}from"../../shared/env.js";import{Router as ve,actsAsPerson as ye}from"./router.js";import{handleAttachUpgrade as Rr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as Ar,machineLinkEnvironment as vr,setApiAddress as yr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as _r,machineViewEnvironment as wr}from"../machine-link/forward.js";import{boundDaemonControl as Er}from"../control.js";import{attachRoutes as Sr,mayAttachNode as _e}from"./handlers/attach.js";import{peerRoutes as br}from"../peer/handlers.js";import{bashJobRoutes as Tr}from"./handlers/bash-jobs.js";import{nodeFileRoutes as Cr}from"./handlers/node-files.js";import{bashRoutes as kr}from"./handlers/bash.js";import{hookExecRoutes as Pr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as we}from"./handlers/broker-ops.js";import{brokerSignalRoutes as Ur,brokerSignalStreams as Or}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Ee,nodeFaultRoutes as Nr}from"./handlers/broker-recovery.js";import{canvasRoutes as Ir}from"./handlers/canvas.js";import{conversationRoutes as Hr}from"./handlers/conversations.js";import{chatInventoryRoutes as zr}from"./handlers/chat-inventory.js";import{daemonRoutes as Lr}from"./handlers/daemon.js";import{fileRoutes as Br}from"./handlers/files.js";import{focusRoutes as xr}from"./handlers/focus.js";import{analyticsRoutes as Dr}from"./handlers/analytics.js";import{memoryReadsRoutes as Fr}from"./handlers/memory-reads.js";import{memoryRoutes as Mr}from"./handlers/memory.js";import{healthRoutes as $r}from"./handlers/health.js";import{humanRequestRoutes as Jr}from"./handlers/human-requests.js";import{inboxRoutes as Wr}from"./handlers/inbox.js";import{feedbackCommentRoutes as jr}from"./handlers/feedback-comments.js";import{objectRoutes as Vr}from"./handlers/objects.js";import{shareRoutes as Gr}from"./handlers/shares.js";import{customObjectRoutes as Yr}from"./handlers/custom-objects.js";import{docRoutes as Kr}from"./handlers/docs.js";import{deliveryRoutes as Se}from"./handlers/delivery.js";import{deliveryRetryRoutes as Xr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Zr}from"./handlers/package-docs.js";import{documentAccessRoutes as Qr}from"./handlers/document-access.js";import{pluginAppRoutes as qr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as be,messageRoutes as et}from"./handlers/messages.js";import{modelAuthRoutes as rt}from"./handlers/modelauth.js";import{llmRoutes as tt}from"./handlers/llm.js";import{providerRoutes as nt}from"./handlers/providers.js";import{modelConfigRoutes as ot}from"./handlers/model-config.js";import{settingsRoutes as it}from"./handlers/settings.js";import{nodeRoutes as st}from"./handlers/nodes.js";import{nodeRecordRoutes as at}from"./handlers/node-records.js";import{nodeOutcomeRoutes as lt}from"./handlers/node-outcomes.js";import{nodeEventRoutes as ct}from"./handlers/node-events.js";import{profileRoutes as ut}from"./handlers/profiles.js";import{environmentRoutes as pt}from"./handlers/environments.js";import{prospectiveChatInventoryRoutes as dt}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as mt}from"./handlers/reports.js";import{runRoutes as ft}from"./handlers/run-routes.js";import{reviewCommentRoutes as gt}from"./handlers/review-comments.js";import{reviewRoutes as ht}from"./handlers/reviews.js";import{subscriptionRoutes as Rt}from"./handlers/subscriptions.js";import{structuredRequestRoutes as At}from"./handlers/structured-requests.js";import{cronRoutes as vt}from"./handlers/crons.js";import{setCronRequestHandler as Te}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as yt,cronPrincipalForRunToken as _t}from"../cron/run-token.js";import{worktreeRoutes as wt}from"./handlers/worktree.js";import{limitsRoutes as Et}from"./handlers/limits.js";import{chargeRoutes as St,spendLimitRoutes as bt}from"./handlers/charges.js";import{executionStartRoutes as Tt}from"./handlers/execution-start.js";import{machineCredentialRoutes as Ct}from"./handlers/machine-credential.js";import{machineRoutes as kt}from"./handlers/machines.js";import{importRoutes as Pt}from"./handlers/imports.js";import{gitCredentialRoutes as Ut}from"./handlers/git-credential.js";import{feedbackRoutes as Ot}from"./handlers/feedback.js";function Nt(e){return new ve().registerAll($r(e)).registerAll(Lr).registerAll(Gr).registerAll(st).registerAll(at).registerAll(lt).registerAll(Xr).registerAll(ct).registerAll(Tr).registerAll(Cr).registerAll(kr).registerAll(Pr).registerAll(we).registerAll(Ur).registerAll(Se).registerAll(Ee).registerAll(Nr).registerAll(wt).registerAll(Et).registerAll(St).registerAll(Tt).registerAll(Ct).registerAll(kt).registerAll(Pt).registerAll(Ut).registerAll(Ot).registerAll(bt).registerAll(be).registerAll(et).registerAll(mt).registerAll(ft).registerAll(At).registerAll(Sr).registerAll(Ir).registerAll(Hr).registerAll(Dr).registerAll(Fr).registerAll(Mr).registerAll(Br).registerAll(Vr).registerAll(Yr).registerAll(Kr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(xr).registerAll(Rt).registerAll(vt).registerAll(ut).registerAll(pt).registerAll(rt).registerAll(tt).registerAll(nt).registerAll(ot).registerAll(it).registerAll(ht).registerAll(gt).registerAll(Wr).registerAll(Jr).registerAll(zr).registerAll(dt).registerAll(jr).registerAll(br)}i(Nt,"buildRouter");function It(e,r){if(e.toUpperCase()!=="GET")return null;const s=r.split("/").filter(u=>u.length>0);if(s.length!==4||s[0]!=="v1"||s[1]!=="nodes"||s[3]!=="attach")return null;const a=s[2];return a===void 0||a===""?null:decodeURIComponent(a)}i(It,"attachNodeId");function Ht(e){const r=e.trim();if(r==="")return null;const s=r.lastIndexOf(":");if(s<0)return null;const a=r.slice(0,s),u=r.slice(s+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}i(Ht,"parseTcp");function zt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}i(zt,"formatTcpAddress");const M={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},$={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},te={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function J(e){return B.get(e)}i(J,"socketPrincipal");async function Ce(e,r){const s=process.platform==="linux"?pr(e.socket):null,a=e.headers.authorization;if(a===void 0)return s===null||r.has(s)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return te;if(a.slice(7).startsWith(ne)){const u=Oe(a.slice(7));return u!==void 0&&(s===null||r.has(s))?u.principal:"unauthorized"}return ke(a.slice(7),s)}i(Ce,"resolveSocketPrincipal");async function ke(e,r){const s=await Ye(e);if(!s||r!==null&&r!==s.uid)return"unauthorized";const a=ur();if(a&&!I()&&!await cr(a))return"runtime_starting";const u=s.grant??(await lr("app:terminal",s.sub))?.id??null;return{class:"broker",...s,grant:u}}i(ke,"brokerPrincipal");function Pe(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}i(Pe,"requestPerson");function Ue(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}i(Ue,"noteBrokerRequest");const ne="crtr_app_";function Oe(e){const r=e.startsWith(ne)?dr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}i(Oe,"appBearer");function Lt(e){const r=new Map;for(const s of fr("user"))r.set(s.token,{principal:{class:"app",app:s.grantee,scopes:s.scopes},ceiling:s.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}i(Lt,"resolveBearers");function Bt(e){try{return qe(e).act!==void 0}catch{return!1}}i(Bt,"carriesAct");const xt=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function U(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}i(U,"deny");async function Ne(e,r,s){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:te,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return U(s,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:te,ceiling:null};if(u.startsWith(ne))return Oe(u)??U(s,"app_token_unknown");if(u.startsWith(yt)){const S=await _t(u);return S===null?U(s,"run_token_invalid_or_settled"):{principal:S,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const g=$e(u);if(g!==null)return{principal:g,ceiling:null};if(u.startsWith(Me))return U(s,"import_token_invalid");if(xt.test(u)){if(I()&&Bt(u)){const x=K();if(x===null)return"person_bearer";try{const w=await x.verifyCall(a);return w.chain[0]?.sub.startsWith("app:")?{call:w}:U(s,"call_token_presenter_not_an_app")}catch(w){return w instanceof C&&w.status===503?"runtime_starting":U(s,`call_token_${w instanceof C?w.code:"invalid"}`)}}const S=I()?Re():null;if(S===null)return"person_bearer";const O=await S.verify(u);return O===null?U(s,"person_bearer_not_verified"):{principal:{class:"person",sub:O},ceiling:null}}const f=await ke(u,null);return f==="unauthorized"?U(s,"node_token_unknown"):typeof f=="string"?f:{principal:f,ceiling:null}}i(Ne,"authorizeTcp");let Y;function K(){if(Y!==void 0)return Y;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return Y=e===void 0||r===void 0?null:new Ze(e,r,async()=>{}),Y}i(K,"cloudCallResolver");let Ie;function Dt(){const e=K();if(e===null)throw new C(503,"runtime_starting","app calls are not configured on this listener");return Ie??=Qe(e,async()=>!0,async()=>{}),Ie}i(Dt,"cloudAppCalls");async function Ft(e,r){H(r),z(r);const s=K();try{if(s===null)throw new C(503,"runtime_starting","sign-in is not configured on this listener");await er(e,r,new URL(e.url??"/","http://runtime.local"),s)}catch(a){if(!(a instanceof C))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}i(Ft,"serveRuntimeSignIn");function Mt(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:de(e),key:de(r)}}i(Mt,"tcpTls");function H(e){e.setHeader(Z,q()),e.setHeader(Q,ge)}i(H,"advertiseRuntime");function z(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Z}, ${Q}`)}i(z,"exposeRuntimeHeaders");function $t(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(H(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Z}, ${Q}`,"Access-Control-Allow-Headers":`authorization, content-type, ${fe.toLowerCase()}, ${he.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}i($t,"answerPreflight");function oe(e,r=!1){H(e),r&&z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}i(oe,"writeUnauthorized");function Jt(e){H(e),z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...$,origin:"runtime"}}))}i(Jt,"writePersonBearerRefused");const Wt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function jt(e,r){if(!I())return!1;const s=new URL(e.url??"/","http://runtime.local").pathname,a=Wt[s];if(a===void 0||e.method!==a.method)return!1;const u=i((d,g)=>{H(r),z(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(g))},"answer");try{const d=Re();if(d===null)throw new C(401,$.code,$.message);const g=e.headers.authorization,f=g?.startsWith("Bearer ")?await d.verifyPurpose(g.slice(7),a.purpose):null;if(f===null)throw new C(401,"unauthorized","invalid directory token");const S=a.purpose==="vendor_status"?void 0:await Vt(e);u(200,await G(f,async()=>a.purpose==="vendor_status"?ir():await or(S)))}catch(d){const{status:g,body:f}=sr(d);u(g,f)}return!0}i(jt,"serveCloudVendorRoute");async function Vt(e){const r=[];let s=0;for await(const a of e){if(s+=a.length,s>ar)throw new C(400,"invalid_request","request body too large");r.push(a)}if(s!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new C(400,"invalid_request","invalid JSON body")}}i(Vt,"readVendorBody");function ie(e){H(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"runtime is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}i(ie,"writeRuntimeStarting");function Gt(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}i(Gt,"writeStartupBlocked");function He(e,r,s){return new Promise(a=>{for(const f of r)f.destroy();if(s===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const f of u)clearTimeout(f);a()});const d=setInterval(()=>e.closeIdleConnections(),250),g=setTimeout(()=>e.closeAllConnections(),s);u.push(d,g),e.closeIdleConnections()})}i(He,"closeServer");function Mo(e={}){let r=null;const s=Nt(()=>r),a=new ve().registerAll(we).registerAll(Se).registerAll(Ee).registerAll(be),u=i((t,n)=>{const c=Er()?.startupBlock()??null;return c===null||t==="GET"&&(n==="/healthz"||n==="/v1/status"||n==="/v1/ready")||t==="POST"&&(n==="/v1/daemon/migrate"||n==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,n)!==null?null:c},"startupBlockFor"),d=e.socketPath??Ge(),g=new Set([process.getuid?.()??0,...Ae("user").runtime?.person_uids??[]]),f=i((t,n,c)=>{H(n);const p=i(m=>Array.isArray(m)?m[0]:m,"first"),N=p(t.headers[fe.toLowerCase()]),h=je(N,q())??Ve(p(t.headers[he.toLowerCase()]),ge,{legacyMinimum:N,runtimeVersion:q()});if(h!==null){n.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:h.code,message:h.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in h?{param:h.param}:{details:h.details}}}));return}const T=i(m=>{const E=J(t);A({event:"api.request.failed",level:"error",...E?.class==="broker"?{node_id:E.node}:{},error:m instanceof Error?m:new Error(String(m))});try{n.headersSent||n.writeHead(500,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let k;try{k=new URL(t.url??"/","http://127.0.0.1")}catch{try{n.writeHead(400,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const m=u((t.method??"GET").toUpperCase(),k.pathname);if(m!==null){Gt(n,m.message);return}const E=J(t)??{class:"person"},o=Pe(E),l=i(()=>s.handle(t,n,c,E),"handled");(o===void 0?l():G(o,i(async()=>{ee()||await re(o),await l()},"handledAsPerson"))).catch(T)}catch(m){T(m)}},"onRequest"),S=i(async(t,n,c)=>{const p=J(t);return p===void 0||ye(p)||await _e(p,"either",c)?!0:(y(n,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),O=new Set,x=i(t=>{O.add(t),t.once("close",()=>O.delete(t)),t.on("error",()=>{})},"trackUpgrade"),w=i((t,n,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),N=u((t.method??"GET").toUpperCase(),p.pathname);if(N!==null){y(n,503,"Service Unavailable","startup_blocked",N.message);return}const h=It(t.method??"GET",p.pathname);if(h===null){n.destroy();return}const T=(()=>{const m=J(t);return m===void 0?void 0:Pe(m)})(),k=i(()=>S(t,n,h).then(m=>m?Rr(t,n,c,h,async E=>{const o=J(t);return o===void 0||ye(o)||await _e(o,E,h)}):void 0),"attach");(T===void 0?k():G(T,async()=>{ee()||await re(T),await k()})).catch(()=>{try{n.destroy()}catch{}})}catch{try{n.destroy()}catch{}}},"onUpgrade"),ze=i(t=>{t.on("error",n=>{A({event:"api.server.failed",level:"error",error:n})})},"bindErrorHandler"),Le=i(async(t,n)=>{V(t);try{const c=await Ce(t,g);if(j(t),c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),oe(n);return}if(c==="runtime_starting"){ie(n);return}B.set(t,c),Ue(t,c),f(t,n,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),ie(n)}},"onSocketRequest"),D=pe((t,n)=>{Le(t,n).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Be=i(async(t,n,c)=>{V(t);try{const p=await Ce(t,g);if(j(t),p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(n,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(n,403,"Forbidden",L.code,L.message);return}B.set(t,p),w(t,n,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(n,503,"Service Unavailable","runtime_starting","socket principal unavailable")}},"onSocketUpgrade");D.on("upgrade",(t,n,c)=>{x(n),Be(t,n,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),Te((t,n,c)=>{B.set(t,c),f(t,n,null)});let se=!1,ae,le;const xe=new Promise((t,n)=>{ae=t,le=n});D.once("listening",()=>{se=!0,ae()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),se||le(t)});try{X(d)&&me(d)}catch{}D.listen(d,()=>{try{We(d,process.platform==="linux"&&X("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b,ce=Promise.resolve();const W=e.tcp??gr()??Ae("user").api.tcp;if(W!==void 0&&W!==""){const t=Ht(W);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${W}`)});else{I()&&K();const n=I()?tr():null,c=e.token??hr()??mr("user"),p=Lt(c),N=i(async(o,l)=>{if(V(o),Ke(o)){await Xe(o,l);return}if($t(o,l))return;if(I()&&rr(new URL(o.url??"/","http://runtime.local").pathname)){await Ft(o,l);return}if(await jt(o,l))return;if(n!==null&&nr(new URL(o.url??"/","http://runtime.local").pathname)){await n(o,l);return}const v={},R=await Ne(o,p,v);if(j(o),R==="runtime_starting"){z(l),ie(l);return}if(R==="person_bearer"){Jt(l);return}if(R==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:o.method,listener:"tcp",path:new URL(o.url??"/","http://runtime.local").pathname,reason:v.reason??"unknown"}}),oe(l,!0);return}if("call"in R){z(l);const F=R.call.sub;await G(F,async()=>{ee()||await re(F),await Dt()(o,l,R.call)});return}B.set(o,R.principal),Ue(o,R.principal),z(l),f(o,l,R.ceiling)},"tcpOnRequest"),h=i(async(o,l,v)=>{V(o);const R=vr(o);if(R!==null){const _=await Ar(o,l,v,R);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const F=wr(o);if(F!==null){const _=_r(o,l,v,F);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const P=await Ne(o,p);if(j(o),P==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(P==="person_bearer"){y(l,401,"Unauthorized",$.code,$.message);return}if(P==="unauthorized"){y(l,401,"Unauthorized",M.code,M.message);return}if("call"in P){y(l,403,"Forbidden",L.code,L.message);return}if(P.ceiling!==null||P.principal.class==="anonymous"||P.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(o,P.principal),w(o,l,v)},"tcpOnUpgrade"),T=i(o=>{A({event:"api.principal.failed",level:"error",error:o instanceof Error?o:new Error(String(o))})},"failed"),k=i((o,l)=>{N(o,l).catch(v=>{T(v),l.headersSent?l.destroy():oe(l,!0)})},"listener"),m=Mt();b=m===null?pe(k):Je(m,k),b.on("upgrade",(o,l,v)=>{x(l),h(o,l,v).catch(R=>{T(R),y(l,401,"Unauthorized",M.code,M.message)})}),ze(b),b.once("listening",()=>{const o=b?.address();if(o!==null&&typeof o=="object"){const{address:l,port:v}=o;r=zt(l,v),l!=="0.0.0.0"&&l!=="::"&&yr(r)}});const E=b;ce=new Promise(o=>{E.once("listening",o),E.once("error",()=>o())}),b.listen(t.port,t.host)}}let ue=!1;const De=i(async(t={})=>{if(!ue){ue=!0,Te(null),Or.close(),await Promise.all([He(D,O,t.graceMs),b!==void 0?He(b,O,t.graceMs):Promise.resolve()]);try{X(d)&&me(d)}catch{}}},"close");return{ready:xe.then(()=>ce),tcpAddress:i(()=>r,"tcpAddress"),close:De}}i(Mo,"createApiServer");export{Nt as buildRouter,He as closeServer,Mo as createApiServer,J as socketPrincipal};
|
|
1
|
+
var Fe=Object.defineProperty;var i=(e,r)=>Fe(e,"name",{value:r,configurable:!0});import{markAuthenticated as j,markReceived as V}from"../../core/step-timings.js";import{IMPORT_TOKEN_PREFIX as Me,importPrincipalFor as $e}from"./import-auth.js";import{createServer as pe}from"node:http";import{createServer as Je}from"node:https";import{chmodSync as We,existsSync as X,readFileSync as de,unlinkSync as me}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as fe,RUNTIME_VERSION_HEADER as Z,minimumRuntimeRefusal as je}from"../../api/runtime-version.js";import{CONTRACT_HEADER as Q,CONTRACT_LEVEL as ge,REQUIRED_CONTRACT_HEADER as he,contractRefusal as Ve}from"../../api/contract.js";import{crtrVersion as q}from"../../shared/crtr-version.js";import{apiSocketPath as Ge}from"../../core/canvas/paths.js";import{resolveNodeToken as Ye}from"../../core/canvas/node-tokens.js";import{isCloudRole as I,runAsPerson as G}from"../../core/canvas/person.js";import{isCanvasRequest as Ke,serveCanvas as Xe}from"./canvas-host.js";import{personBearerVerifier as Re}from"./auth/person-bearer.js";import{personHasSnapshot as ee}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as re}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Ze}from"./principal.js";import{createAppRequestHandler as Qe}from"./app-listener.js";import{decodeJwt as qe}from"jose";import{handleRuntimeSignIn as er,isRuntimeSignInPath as rr}from"./key-signin.js";import{RunError as C}from"../../core/runs/operations.js";import{createRepoPluginHandler as tr,isRepoPluginPath as nr}from"./repo-plugin.js";import{removeVendorAccount as or,vendorStatus as ir}from"./handlers/vendor-status.js";import{toErrorBody as sr}from"./map.js";import{CONTROL_BODY_MAX_BYTES as ar}from"../../core/llm/body-limits.js";import{grantFor as lr,hasSyncedGrants as cr}from"../../core/grants/mirror.js";import{readConfig as Ae}from"../../core/config.js";import{directoryIssuer as ur}from"../../core/directory/issuer.js";import{peerUid as pr}from"../../native/linux.js";import{findScopedApiToken as dr,getApiToken as mr,listScopedApiTokens as fr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as gr,envCrtrdToken as hr}from"../../shared/env.js";import{Router as ve,actsAsPerson as ye}from"./router.js";import{handleAttachUpgrade as Rr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as Ar,machineLinkEnvironment as vr,setApiAddress as yr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as _r,machineViewEnvironment as wr}from"../machine-link/forward.js";import{boundDaemonControl as Er}from"../control.js";import{attachRoutes as Sr,mayAttachNode as _e}from"./handlers/attach.js";import{peerRoutes as br}from"../peer/handlers.js";import{bashJobRoutes as Tr}from"./handlers/bash-jobs.js";import{nodeFileRoutes as Cr}from"./handlers/node-files.js";import{bashRoutes as kr}from"./handlers/bash.js";import{hookExecRoutes as Pr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as we}from"./handlers/broker-ops.js";import{brokerSignalRoutes as Ur,brokerSignalStreams as Or}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Ee,nodeFaultRoutes as Nr}from"./handlers/broker-recovery.js";import{canvasRoutes as Ir}from"./handlers/canvas.js";import{conversationRoutes as Hr}from"./handlers/conversations.js";import{chatInventoryRoutes as zr}from"./handlers/chat-inventory.js";import{daemonRoutes as Lr}from"./handlers/daemon.js";import{fileRoutes as Br}from"./handlers/files.js";import{focusRoutes as xr}from"./handlers/focus.js";import{analyticsRoutes as Dr}from"./handlers/analytics.js";import{memoryReadsRoutes as Fr}from"./handlers/memory-reads.js";import{memoryRoutes as Mr}from"./handlers/memory.js";import{healthRoutes as $r}from"./handlers/health.js";import{humanRequestRoutes as Jr}from"./handlers/human-requests.js";import{inboxRoutes as Wr}from"./handlers/inbox.js";import{feedbackCommentRoutes as jr}from"./handlers/feedback-comments.js";import{objectRoutes as Vr}from"./handlers/objects.js";import{shareRoutes as Gr}from"./handlers/shares.js";import{customObjectRoutes as Yr}from"./handlers/custom-objects.js";import{docRoutes as Kr}from"./handlers/docs.js";import{deliveryRoutes as Se}from"./handlers/delivery.js";import{deliveryRetryRoutes as Xr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Zr}from"./handlers/package-docs.js";import{documentAccessRoutes as Qr}from"./handlers/document-access.js";import{pluginAppRoutes as qr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as be,messageRoutes as et}from"./handlers/messages.js";import{modelAuthRoutes as rt}from"./handlers/modelauth.js";import{llmRoutes as tt}from"./handlers/llm.js";import{providerRoutes as nt}from"./handlers/providers.js";import{modelConfigRoutes as ot}from"./handlers/model-config.js";import{settingsRoutes as it}from"./handlers/settings.js";import{nodeRoutes as st}from"./handlers/nodes.js";import{nodeRecordRoutes as at}from"./handlers/node-records.js";import{nodeOutcomeRoutes as lt}from"./handlers/node-outcomes.js";import{nodeEventRoutes as ct}from"./handlers/node-events.js";import{profileRoutes as ut}from"./handlers/profiles.js";import{environmentRoutes as pt}from"./handlers/environments.js";import{appEnvironmentRoutes as dt}from"./handlers/app-environments.js";import{prospectiveChatInventoryRoutes as mt}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as ft}from"./handlers/reports.js";import{runRoutes as gt}from"./handlers/run-routes.js";import{reviewCommentRoutes as ht}from"./handlers/review-comments.js";import{reviewRoutes as Rt}from"./handlers/reviews.js";import{subscriptionRoutes as At}from"./handlers/subscriptions.js";import{structuredRequestRoutes as vt}from"./handlers/structured-requests.js";import{cronRoutes as yt}from"./handlers/crons.js";import{setCronRequestHandler as Te}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as _t,cronPrincipalForRunToken as wt}from"../cron/run-token.js";import{worktreeRoutes as Et}from"./handlers/worktree.js";import{limitsRoutes as St}from"./handlers/limits.js";import{chargeRoutes as bt,spendLimitRoutes as Tt}from"./handlers/charges.js";import{executionStartRoutes as Ct}from"./handlers/execution-start.js";import{machineCredentialRoutes as kt}from"./handlers/machine-credential.js";import{machineRoutes as Pt}from"./handlers/machines.js";import{importRoutes as Ut}from"./handlers/imports.js";import{gitCredentialRoutes as Ot}from"./handlers/git-credential.js";import{feedbackRoutes as Nt}from"./handlers/feedback.js";function It(e){return new ve().registerAll($r(e)).registerAll(Lr).registerAll(Gr).registerAll(st).registerAll(at).registerAll(lt).registerAll(Xr).registerAll(ct).registerAll(Tr).registerAll(Cr).registerAll(kr).registerAll(Pr).registerAll(we).registerAll(Ur).registerAll(Se).registerAll(Ee).registerAll(Nr).registerAll(Et).registerAll(St).registerAll(bt).registerAll(Ct).registerAll(kt).registerAll(Pt).registerAll(Ut).registerAll(Ot).registerAll(Nt).registerAll(Tt).registerAll(be).registerAll(et).registerAll(ft).registerAll(gt).registerAll(vt).registerAll(Sr).registerAll(Ir).registerAll(Hr).registerAll(Dr).registerAll(Fr).registerAll(Mr).registerAll(Br).registerAll(Vr).registerAll(Yr).registerAll(Kr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(xr).registerAll(At).registerAll(yt).registerAll(ut).registerAll(pt).registerAll(dt).registerAll(rt).registerAll(tt).registerAll(nt).registerAll(ot).registerAll(it).registerAll(Rt).registerAll(ht).registerAll(Wr).registerAll(Jr).registerAll(zr).registerAll(mt).registerAll(jr).registerAll(br)}i(It,"buildRouter");function Ht(e,r){if(e.toUpperCase()!=="GET")return null;const s=r.split("/").filter(u=>u.length>0);if(s.length!==4||s[0]!=="v1"||s[1]!=="nodes"||s[3]!=="attach")return null;const a=s[2];return a===void 0||a===""?null:decodeURIComponent(a)}i(Ht,"attachNodeId");function zt(e){const r=e.trim();if(r==="")return null;const s=r.lastIndexOf(":");if(s<0)return null;const a=r.slice(0,s),u=r.slice(s+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}i(zt,"parseTcp");function Lt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}i(Lt,"formatTcpAddress");const M={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},$={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},te={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function J(e){return B.get(e)}i(J,"socketPrincipal");async function Ce(e,r){const s=process.platform==="linux"?pr(e.socket):null,a=e.headers.authorization;if(a===void 0)return s===null||r.has(s)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return te;if(a.slice(7).startsWith(ne)){const u=Oe(a.slice(7));return u!==void 0&&(s===null||r.has(s))?u.principal:"unauthorized"}return ke(a.slice(7),s)}i(Ce,"resolveSocketPrincipal");async function ke(e,r){const s=await Ye(e);if(!s||r!==null&&r!==s.uid)return"unauthorized";const a=ur();if(a&&!I()&&!await cr(a))return"runtime_starting";const u=s.grant??(await lr("app:terminal",s.sub))?.id??null;return{class:"broker",...s,grant:u}}i(ke,"brokerPrincipal");function Pe(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}i(Pe,"requestPerson");function Ue(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}i(Ue,"noteBrokerRequest");const ne="crtr_app_";function Oe(e){const r=e.startsWith(ne)?dr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}i(Oe,"appBearer");function Bt(e){const r=new Map;for(const s of fr("user"))r.set(s.token,{principal:{class:"app",app:s.grantee,scopes:s.scopes},ceiling:s.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}i(Bt,"resolveBearers");function xt(e){try{return qe(e).act!==void 0}catch{return!1}}i(xt,"carriesAct");const Dt=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function U(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}i(U,"deny");async function Ne(e,r,s){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:te,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return U(s,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:te,ceiling:null};if(u.startsWith(ne))return Oe(u)??U(s,"app_token_unknown");if(u.startsWith(_t)){const S=await wt(u);return S===null?U(s,"run_token_invalid_or_settled"):{principal:S,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const g=$e(u);if(g!==null)return{principal:g,ceiling:null};if(u.startsWith(Me))return U(s,"import_token_invalid");if(Dt.test(u)){if(I()&&xt(u)){const x=K();if(x===null)return"person_bearer";try{const w=await x.verifyCall(a);return w.chain[0]?.sub.startsWith("app:")?{call:w}:U(s,"call_token_presenter_not_an_app")}catch(w){return w instanceof C&&w.status===503?"runtime_starting":U(s,`call_token_${w instanceof C?w.code:"invalid"}`)}}const S=I()?Re():null;if(S===null)return"person_bearer";const O=await S.verify(u);return O===null?U(s,"person_bearer_not_verified"):{principal:{class:"person",sub:O},ceiling:null}}const f=await ke(u,null);return f==="unauthorized"?U(s,"node_token_unknown"):typeof f=="string"?f:{principal:f,ceiling:null}}i(Ne,"authorizeTcp");let Y;function K(){if(Y!==void 0)return Y;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return Y=e===void 0||r===void 0?null:new Ze(e,r,async()=>{}),Y}i(K,"cloudCallResolver");let Ie;function Ft(){const e=K();if(e===null)throw new C(503,"runtime_starting","app calls are not configured on this listener");return Ie??=Qe(e,async()=>!0,async()=>{}),Ie}i(Ft,"cloudAppCalls");async function Mt(e,r){H(r),z(r);const s=K();try{if(s===null)throw new C(503,"runtime_starting","sign-in is not configured on this listener");await er(e,r,new URL(e.url??"/","http://runtime.local"),s)}catch(a){if(!(a instanceof C))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}i(Mt,"serveRuntimeSignIn");function $t(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:de(e),key:de(r)}}i($t,"tcpTls");function H(e){e.setHeader(Z,q()),e.setHeader(Q,ge)}i(H,"advertiseRuntime");function z(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Z}, ${Q}`)}i(z,"exposeRuntimeHeaders");function Jt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(H(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Z}, ${Q}`,"Access-Control-Allow-Headers":`authorization, content-type, ${fe.toLowerCase()}, ${he.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}i(Jt,"answerPreflight");function oe(e,r=!1){H(e),r&&z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}i(oe,"writeUnauthorized");function Wt(e){H(e),z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...$,origin:"runtime"}}))}i(Wt,"writePersonBearerRefused");const jt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Vt(e,r){if(!I())return!1;const s=new URL(e.url??"/","http://runtime.local").pathname,a=jt[s];if(a===void 0||e.method!==a.method)return!1;const u=i((d,g)=>{H(r),z(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(g))},"answer");try{const d=Re();if(d===null)throw new C(401,$.code,$.message);const g=e.headers.authorization,f=g?.startsWith("Bearer ")?await d.verifyPurpose(g.slice(7),a.purpose):null;if(f===null)throw new C(401,"unauthorized","invalid directory token");const S=a.purpose==="vendor_status"?void 0:await Gt(e);u(200,await G(f,async()=>a.purpose==="vendor_status"?ir():await or(S)))}catch(d){const{status:g,body:f}=sr(d);u(g,f)}return!0}i(Vt,"serveCloudVendorRoute");async function Gt(e){const r=[];let s=0;for await(const a of e){if(s+=a.length,s>ar)throw new C(400,"invalid_request","request body too large");r.push(a)}if(s!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new C(400,"invalid_request","invalid JSON body")}}i(Gt,"readVendorBody");function ie(e){H(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"runtime is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}i(ie,"writeRuntimeStarting");function Yt(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}i(Yt,"writeStartupBlocked");function He(e,r,s){return new Promise(a=>{for(const f of r)f.destroy();if(s===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const f of u)clearTimeout(f);a()});const d=setInterval(()=>e.closeIdleConnections(),250),g=setTimeout(()=>e.closeAllConnections(),s);u.push(d,g),e.closeIdleConnections()})}i(He,"closeServer");function Jo(e={}){let r=null;const s=It(()=>r),a=new ve().registerAll(we).registerAll(Se).registerAll(Ee).registerAll(be),u=i((t,n)=>{const c=Er()?.startupBlock()??null;return c===null||t==="GET"&&(n==="/healthz"||n==="/v1/status"||n==="/v1/ready")||t==="POST"&&(n==="/v1/daemon/migrate"||n==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,n)!==null?null:c},"startupBlockFor"),d=e.socketPath??Ge(),g=new Set([process.getuid?.()??0,...Ae("user").runtime?.person_uids??[]]),f=i((t,n,c)=>{H(n);const p=i(m=>Array.isArray(m)?m[0]:m,"first"),N=p(t.headers[fe.toLowerCase()]),h=je(N,q())??Ve(p(t.headers[he.toLowerCase()]),ge,{legacyMinimum:N,runtimeVersion:q()});if(h!==null){n.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:h.code,message:h.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in h?{param:h.param}:{details:h.details}}}));return}const T=i(m=>{const E=J(t);A({event:"api.request.failed",level:"error",...E?.class==="broker"?{node_id:E.node}:{},error:m instanceof Error?m:new Error(String(m))});try{n.headersSent||n.writeHead(500,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let k;try{k=new URL(t.url??"/","http://127.0.0.1")}catch{try{n.writeHead(400,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const m=u((t.method??"GET").toUpperCase(),k.pathname);if(m!==null){Yt(n,m.message);return}const E=J(t)??{class:"person"},o=Pe(E),l=i(()=>s.handle(t,n,c,E),"handled");(o===void 0?l():G(o,i(async()=>{ee()||await re(o),await l()},"handledAsPerson"))).catch(T)}catch(m){T(m)}},"onRequest"),S=i(async(t,n,c)=>{const p=J(t);return p===void 0||ye(p)||await _e(p,"either",c)?!0:(y(n,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),O=new Set,x=i(t=>{O.add(t),t.once("close",()=>O.delete(t)),t.on("error",()=>{})},"trackUpgrade"),w=i((t,n,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),N=u((t.method??"GET").toUpperCase(),p.pathname);if(N!==null){y(n,503,"Service Unavailable","startup_blocked",N.message);return}const h=Ht(t.method??"GET",p.pathname);if(h===null){n.destroy();return}const T=(()=>{const m=J(t);return m===void 0?void 0:Pe(m)})(),k=i(()=>S(t,n,h).then(m=>m?Rr(t,n,c,h,async E=>{const o=J(t);return o===void 0||ye(o)||await _e(o,E,h)}):void 0),"attach");(T===void 0?k():G(T,async()=>{ee()||await re(T),await k()})).catch(()=>{try{n.destroy()}catch{}})}catch{try{n.destroy()}catch{}}},"onUpgrade"),ze=i(t=>{t.on("error",n=>{A({event:"api.server.failed",level:"error",error:n})})},"bindErrorHandler"),Le=i(async(t,n)=>{V(t);try{const c=await Ce(t,g);if(j(t),c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),oe(n);return}if(c==="runtime_starting"){ie(n);return}B.set(t,c),Ue(t,c),f(t,n,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),ie(n)}},"onSocketRequest"),D=pe((t,n)=>{Le(t,n).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Be=i(async(t,n,c)=>{V(t);try{const p=await Ce(t,g);if(j(t),p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(n,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(n,403,"Forbidden",L.code,L.message);return}B.set(t,p),w(t,n,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(n,503,"Service Unavailable","runtime_starting","socket principal unavailable")}},"onSocketUpgrade");D.on("upgrade",(t,n,c)=>{x(n),Be(t,n,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),Te((t,n,c)=>{B.set(t,c),f(t,n,null)});let se=!1,ae,le;const xe=new Promise((t,n)=>{ae=t,le=n});D.once("listening",()=>{se=!0,ae()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),se||le(t)});try{X(d)&&me(d)}catch{}D.listen(d,()=>{try{We(d,process.platform==="linux"&&X("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b,ce=Promise.resolve();const W=e.tcp??gr()??Ae("user").api.tcp;if(W!==void 0&&W!==""){const t=zt(W);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${W}`)});else{I()&&K();const n=I()?tr():null,c=e.token??hr()??mr("user"),p=Bt(c),N=i(async(o,l)=>{if(V(o),Ke(o)){await Xe(o,l);return}if(Jt(o,l))return;if(I()&&rr(new URL(o.url??"/","http://runtime.local").pathname)){await Mt(o,l);return}if(await Vt(o,l))return;if(n!==null&&nr(new URL(o.url??"/","http://runtime.local").pathname)){await n(o,l);return}const v={},R=await Ne(o,p,v);if(j(o),R==="runtime_starting"){z(l),ie(l);return}if(R==="person_bearer"){Wt(l);return}if(R==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:o.method,listener:"tcp",path:new URL(o.url??"/","http://runtime.local").pathname,reason:v.reason??"unknown"}}),oe(l,!0);return}if("call"in R){z(l);const F=R.call.sub;await G(F,async()=>{ee()||await re(F),await Ft()(o,l,R.call)});return}B.set(o,R.principal),Ue(o,R.principal),z(l),f(o,l,R.ceiling)},"tcpOnRequest"),h=i(async(o,l,v)=>{V(o);const R=vr(o);if(R!==null){const _=await Ar(o,l,v,R);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const F=wr(o);if(F!==null){const _=_r(o,l,v,F);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const P=await Ne(o,p);if(j(o),P==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(P==="person_bearer"){y(l,401,"Unauthorized",$.code,$.message);return}if(P==="unauthorized"){y(l,401,"Unauthorized",M.code,M.message);return}if("call"in P){y(l,403,"Forbidden",L.code,L.message);return}if(P.ceiling!==null||P.principal.class==="anonymous"||P.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(o,P.principal),w(o,l,v)},"tcpOnUpgrade"),T=i(o=>{A({event:"api.principal.failed",level:"error",error:o instanceof Error?o:new Error(String(o))})},"failed"),k=i((o,l)=>{N(o,l).catch(v=>{T(v),l.headersSent?l.destroy():oe(l,!0)})},"listener"),m=$t();b=m===null?pe(k):Je(m,k),b.on("upgrade",(o,l,v)=>{x(l),h(o,l,v).catch(R=>{T(R),y(l,401,"Unauthorized",M.code,M.message)})}),ze(b),b.once("listening",()=>{const o=b?.address();if(o!==null&&typeof o=="object"){const{address:l,port:v}=o;r=Lt(l,v),l!=="0.0.0.0"&&l!=="::"&&yr(r)}});const E=b;ce=new Promise(o=>{E.once("listening",o),E.once("error",()=>o())}),b.listen(t.port,t.host)}}let ue=!1;const De=i(async(t={})=>{if(!ue){ue=!0,Te(null),Or.close(),await Promise.all([He(D,O,t.graceMs),b!==void 0?He(b,O,t.graceMs):Promise.resolve()]);try{X(d)&&me(d)}catch{}}},"close");return{ready:xe.then(()=>ce),tcpAddress:i(()=>r,"tcpAddress"),close:De}}i(Jo,"createApiServer");export{It as buildRouter,He as closeServer,Jo as createApiServer,J as socketPrincipal};
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as cr}from"./boot-settings.js";import{startBrokerMemoryCap as dr}from"./broker-memory-cap.js";import{startPeerOutbox as pr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Pe,existsSync as E,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as Te}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as Ce}from"node:crypto";import{apiSocketPath as De,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Pr}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Cr}from"../core/profiles/relocate.js";import{getNode as Dr,getRow as Ar,listNodesForSupervision as Le,listParkedResidentsWithWakeMail as Lr,setFrozen as $e}from"../core/canvas/index.js";import{createApiServer as $r,closeServer as Ne}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createAppListener as Gr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Fr}from"../core/canvas/person-state.js";import{markCloudRole as Br,resolvePerson as Hr,retireLocalPerson as Ur,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as qr}from"./run-notices.js";import{startGrantEffects as Wr}from"./reconcilers/grant-effects.js";import{syncPackages as Kr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Vr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Yr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Qr}from"./cron/run-socket.js";import{hasSyncedGrants as Xr}from"../core/grants/mirror.js";import{readConfig as Oe}from"../core/config.js";import{reconcileUndeliveredTickets as Zr}from"./human/sweep.js";import{resetHandedOffDeliveries as et}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as rt}from"../core/canvas/daemon-actions.js";import{sweepReviews as tt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as nt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ot}from"./supervise-cadence.js";import{createResumeDetector as it}from"./resume-detector.js";import{setFatalFaultAnnouncer as at}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as st}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as lt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ct}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as dt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as pt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as mt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ft}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as ut}from"./reconcilers/action-lane.js";import{endLiveExecution as ht,hasObservedExit as wt,latestExecutionForNode as vt,migrateLegacyExecutionIdentities as gt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as yt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as St}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as _t}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as bt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as kt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Rt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Pt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as It}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as xt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Ct}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Dt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,subscribeImageBuilt as $t}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Nt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Mt,captureTeardownSnapshot as Be,isPidAlive as Gt,isAnyPidAlive as He,killProcessTreePids as Ue}from"../core/canvas/pid.js";import{bindFleet as Ot,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Ft,clearDaemonControl as Bt}from"./control.js";import{execDaemon as Ht,spawnDaemon as Ut}from"./manage.js";import{reconcileAndMigrateBoot as jt}from"../core/canvas/boot.js";import{resolveInstallId as zt}from"../core/canvas/install-id.js";import{setInstallId as qt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Wt,daemonOwnershipApplies as Kt,daemonOwnershipClaimed as Jt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Vt,closeAllDbs as ue,openDb as Yt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Xt,ensurePostgresHealthy as Zt,stopPostgres as en,withPostgresStartLock as rn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as tn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as nn}from"./api/handlers/broker-ops.js";import{reconcilePackages as on}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as an}from"../core/scoped-state/migrate-app-installs.js";import{publish as sn,readBuiltinSnapshot as ln}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as cn,reapStaleSpares as dn}from"../core/runtime/warm-pool.js";import{DaemonFleet as pn}from"./fleet.js";import{copyNodeFilesToRows as mn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as fn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as b}from"../core/events/operation-id.js";import{bindDaemonEventSource as un}from"../core/events/source.js";import{activateCanvasImport as hn,MigrationBlockedError as wn,runForcedCanvasImport as vn}from"../migrations/activation.js";import{adoptInstallPerson as gn,convertLegacyScopedStore as yn,personStoresCopied as Sn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as _n}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as bn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as na}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const kn=5e3,Ke=150;async function Rn(e){const c=Fe();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),p=[];for(const[i,l]of c.processes){const v=l.command;if(l.zombie||!v.includes("broker-cli.js")||!ve(v,f)||ge(v)===e)continue;const _=v.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||p.push({pid:i,nodeId:_})}let g=0;const o=[];for(const i of p){const l=Mt(i.pid);if(l===null||!l.includes("broker-cli.js")||!ve(l,f)||ge(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const v=Be(i.pid,null);if(!v.reused){try{process.platform==="linux"&&E(D)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:v})}}const w=Date.now()+kn;for(;Date.now()<w&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];He(l)&&(process.platform==="linux"&&E(D)?await N({operation:"stop",pid:i.pid}):Ue(l,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Fe();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,l]of d.processes){const v=l.command;l.zombie||!v.includes("broker-cli.js")||ve(v,f)&&ge(v)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(Rn,"reapPriorEpochBrokers");const En=5e3;async function Pn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Dr(o))?.status;(w==="active"||w==="idle")&&await $e(o,new Date().toISOString())}const f=c.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&E(D)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,En).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Gt(o.pid)&&(process.platform==="linux"&&E(D)?await N({operation:"stop",pid:o.pid}):Ue(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of c)await ht(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Pn,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
|
|
1
|
+
var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as cr}from"./boot-settings.js";import{startBrokerMemoryCap as dr}from"./broker-memory-cap.js";import{startPeerOutbox as pr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Pe,existsSync as E,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as Te}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as De}from"node:crypto";import{apiSocketPath as Ce,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Pr}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Dr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Ar,listNodesForSupervision as Le,listParkedResidentsWithWakeMail as Lr,setFrozen as $e}from"../core/canvas/index.js";import{createApiServer as $r,closeServer as Ne}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createAppListener as Gr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Fr}from"../core/canvas/person-state.js";import{markCloudRole as Br,resolvePerson as Hr,retireLocalPerson as Ur,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as qr}from"./run-notices.js";import{startGrantEffects as Wr}from"./reconcilers/grant-effects.js";import{syncPackages as Kr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Vr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Yr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Qr}from"./cron/run-socket.js";import{hasSyncedGrants as Xr}from"../core/grants/mirror.js";import{readConfig as Oe}from"../core/config.js";import{reconcileUndeliveredTickets as Zr}from"./human/sweep.js";import{resetHandedOffDeliveries as et}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as rt}from"../core/canvas/daemon-actions.js";import{sweepReviews as tt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as nt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ot}from"./supervise-cadence.js";import{createResumeDetector as it}from"./resume-detector.js";import{setFatalFaultAnnouncer as at}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as st}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as lt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ct}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as dt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as pt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as mt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ft}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as ut}from"./reconcilers/action-lane.js";import{endLiveExecution as ht,hasObservedExit as wt,latestExecutionForNode as vt,migrateLegacyExecutionIdentities as gt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as yt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as St}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as _t}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as bt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as kt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Rt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Pt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as It}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as xt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Dt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Ct}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,removeLeftoverBuildDirs as $t,subscribeImageBuilt as Nt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Mt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Gt,captureTeardownSnapshot as Be,isPidAlive as Ot,isAnyPidAlive as He,killProcessTreePids as Ue}from"../core/canvas/pid.js";import{bindFleet as Ft,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Bt,clearDaemonControl as Ht}from"./control.js";import{execDaemon as Ut,spawnDaemon as jt}from"./manage.js";import{reconcileAndMigrateBoot as zt}from"../core/canvas/boot.js";import{resolveInstallId as qt}from"../core/canvas/install-id.js";import{setInstallId as Wt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Kt,daemonOwnershipApplies as Jt,daemonOwnershipClaimed as Vt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Yt,closeAllDbs as ue,openDb as Qt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Xt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Zt,ensurePostgresHealthy as en,stopPostgres as rn,withPostgresStartLock as tn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as nn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as on}from"./api/handlers/broker-ops.js";import{reconcilePackages as an}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as sn}from"../core/scoped-state/migrate-app-installs.js";import{publish as ln,readBuiltinSnapshot as cn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as dn,reapStaleSpares as pn}from"../core/runtime/warm-pool.js";import{DaemonFleet as mn}from"./fleet.js";import{copyNodeFilesToRows as fn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as un}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as b}from"../core/events/operation-id.js";import{bindDaemonEventSource as hn}from"../core/events/source.js";import{activateCanvasImport as wn,MigrationBlockedError as vn,runForcedCanvasImport as gn}from"../migrations/activation.js";import{adoptInstallPerson as yn,convertLegacyScopedStore as Sn,personStoresCopied as _n}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as bn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as kn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as oa}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const Rn=5e3,Ke=150;async function En(e){const c=Fe();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),p=[];for(const[i,l]of c.processes){const v=l.command;if(l.zombie||!v.includes("broker-cli.js")||!ve(v,f)||ge(v)===e)continue;const _=v.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||p.push({pid:i,nodeId:_})}let g=0;const o=[];for(const i of p){const l=Gt(i.pid);if(l===null||!l.includes("broker-cli.js")||!ve(l,f)||ge(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const v=Be(i.pid,null);if(!v.reused){try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:v})}}const w=Date.now()+Rn;for(;Date.now()<w&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];He(l)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):Ue(l,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Fe();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,l]of d.processes){const v=l.command;l.zombie||!v.includes("broker-cli.js")||ve(v,f)&&ge(v)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(En,"reapPriorEpochBrokers");const Pn=5e3;async function In(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Cr(o))?.status;(w==="active"||w==="idle")&&await $e(o,new Date().toISOString())}const f=c.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,Pn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Ot(o.pid)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):Ue(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of c)await ht(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(In,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
|
|
2
2
|
`),"utf8")}s(Q,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Je,"isMissingPathError");function Ve(e){const c=me();let f;try{f=hr(c,"utf8")}catch(p){if(Je(p))return;throw p}if(f.split(`
|
|
3
|
-
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(p){if(Je(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const
|
|
4
|
-
`),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),w}s(
|
|
5
|
-
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=
|
|
3
|
+
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(p){if(Je(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const xn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new st;at(e=>X.handleFatalFault(e,!1));const Tn=new ct,Dn=new lt,Ye=new dt,Cn=new pt,An=new mt,Ln=new ft,$n=new ut,Nn=new St,Mn=new _t,Gn=new bt,On=new Rt,Fn=new kt,Bn=new Pt,Hn=new It,Un=new xt,jn=new Tt,zn=new Dt,qn=new Ct,Wn=new At;$t();const Kn=new Lt;async function Jn(e=Date.now(),c=xn){const f=je(),p=await X.runFleetPreamble(f);let g,o,w;try{o=await fe();const d=(await Le()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),w=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(w.map(i=>i.node_id));w.push(...(await Lr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:c,held:o}),await Tn.run(e,{rows:g,held:o}),await Dn.run(e);const y=await Ye.run(e,{rows:[...g,...w],fleet:f});await Cn.run(e,o),await Wn.run(e,o),await Kn.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c,held:o}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c}),await Mn.run(e,{lifecycle:c,fleet:f,held:o}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),Un.run(e,{lifecycle:c}),jn.run(e,{lifecycle:c}),await _r(),qn.run(e,{fleet:f,lifecycle:c}),await zn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:p,frozen:y})}s(Jn,"superviseTick");async function Vn(e,c=Date.now()){if((await fe()).has(e))return;const f=await vt(e);if(f===null||!wt(f))return;const p=await Ar(e);p===null||p.kind==="human"||await Ye.runNode(c,p,je())}s(Vn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"||e==="all"}s(Z,"roleRunsLanes");function H(e){return e===void 0||e==="api"||e==="all"}s(H,"roleServesRequests");const Yn=66e4;function Qn(e){const c=new Nr().registerAll(Mr(()=>null).filter(l=>l.pattern==="/healthz")),f=s((l,v)=>{const _=(l.url??"/").split("?")[0];if((l.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){c.handle(l,v,null,{class:"person"});return}v.writeHead(404,{"content-type":"application/json; charset=utf-8"}),v.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=Ce();E(p)&&Ie(p);const g=Y(f),o=new Promise((l,v)=>{g.once("error",v),g.listen(p,()=>{g.off("error",v),xe(p,384),l()})});let w,y=null,d=o;const u=e.tcp??Te()??Oe("user").api.tcp;if(u!==void 0&&u!==""){const l=/^(.*):(\d+)$/.exec(u.trim());if(l===null||Number(l[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const v=Y(f);v.on("error",_=>m({event:"api.server.failed",level:"error",error:_})),d=o.then(()=>new Promise(_=>{v.once("error",()=>_()),v.listen(Number(l[2]),l[1]===""?"0.0.0.0":l[1],()=>{const P=v.address();y=`${P.address}:${P.port}`,_()})})),w=v}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(l={}){if(!i){i=!0,await Promise.all([Ne(g,new Set,l.graceMs),w===void 0?Promise.resolve():Ne(w,new Set,l.graceMs)]);try{E(p)&&Ie(p)}catch{}}}}}s(Qn,"createProbeServer");const Xn="daemon is draining for shutdown and admits no new work";async function Zn(e){Pe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Ae(),493);const c=Ce();if(E(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),d()})});let p;const g=e.tcp??Te();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,l)=>{u.once("error",l),u.listen(Number(d[2]),d[1],()=>{u.off("error",l),i()})}),p=u}Q();let o;const w=s(()=>(o??=(async()=>{f.closeAllConnections(),p?.closeAllConnections(),await Promise.all([f,p].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(l=>l?i(l):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{w().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
|
|
4
|
+
`),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),w}s(Zn,"serveLayoutRefusal");async function eo(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return Zn(e);Ir();const c=s(r=>{process.stderr.write(`[crtrd] ${r}
|
|
5
|
+
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Jt(e.role);on(Z(e.role));const g=s(async()=>p?await Kt(De(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:De(16).toString("hex")}},"claimOwnership"),{database:o,ownership:w}=e.role!==void 0||f?{database:{url:await Yt()},ownership:await g()}:await tn(async()=>({database:await Zt({log:c,startLockHeld:!0}),ownership:await g()}));if(!w.claimed){if(w.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${w.incumbentPid??"?"})
|
|
6
6
|
`);else{const r=[w.incumbentPid!==void 0?`pid ${w.incumbentPid}`:void 0,w.verdict!==void 0?`verdict ${w.verdict}`:void 0].filter(a=>a!==void 0),t=r.length>0?` (${r.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${w.reason}${t}
|
|
7
|
-
`),w.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(w.reason==="own_identity_indeterminate"||w.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=w.claim;let d=null,u=null,i=null,l=null,v,_="";try{p&&await
|
|
7
|
+
`),w.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(w.reason==="own_identity_indeterminate"||w.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=w.claim;let d=null,u=null,i=null,l=null,v,_="";try{p&&await En(y.token);for(const n of Dr())process.stderr.write(`[crtrd] ${n}
|
|
8
8
|
`);for(const n of await Tr())process.stderr.write(`[crtrd] ${n}
|
|
9
|
-
`);await
|
|
10
|
-
`)}else{d=await Hr(),d!==null&&(jr(d.id),await we(d.id));const n=await he(async h=>(await Me(h),d===null?null:await
|
|
9
|
+
`);await Qt(),await Xt(o.url,c);const r=e.role===void 0&&!await _n();let t=null;r&&(Sn({kind:"user",root:We()}),t=bn(We())),e.role===void 0&&kn(t??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const a=s(n=>{we(n).catch(h=>m({level:"error",event:"daemon.settings.reload_failed",error:h}))},"reloadPerson");if(v=await M.subscribe(n=>{qe().includes(n)&&a(n)},{kinds:["settings"],onListenStart:s(()=>{for(const n of qe())a(n)},"onListenStart")}),e.role!==void 0&&Br(),e.role==="all"&&Fr(),e.role!==void 0){let n;try{n=cn()}catch(R){m({level:"error",event:"daemon.packages.snapshot_failed",error:R})}const h=await he(async R=>(await Me(R),n===void 0?void 0:await ln(R,n,"release")));l=await he(async R=>await sn(R));for(const R of h?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${R.path}: ${R.error}
|
|
10
|
+
`)}else{d=await Hr(),d!==null&&(jr(d.id),await we(d.id));const n=await he(async h=>(await Me(h),d===null?null:await an(h)));if(n!==null){for(const h of n.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${h.message}
|
|
11
11
|
`);for(const h of n.invalid)process.stderr.write(`[crtrd] package file is not a document: ${h.path}: ${h.error}
|
|
12
12
|
`);for(const h of n.quarantined)process.stderr.write(`[crtrd] plugin "${h.name}" has a damaged ${h.file} (${h.reason}); ${h.movedTo!==void 0?`moved to ${h.movedTo}`:"left in place and skipped"}
|
|
13
13
|
`);for(const h of n.kinds.refused)process.stderr.write(`[crtrd] plugin "${h.plugin}" kind ${h.kind} not registered: ${h.message}
|
|
14
14
|
`);for(const h of n.kinds.invalid)process.stderr.write(`[crtrd] plugin "${h.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${h.error}
|
|
15
|
-
`)}}if(_=await
|
|
16
|
-
`)}}catch(r){await M.close();try{if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}await ue()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}let P=!0,ee,U=Promise.resolve(),re=!1,j,te,ne,oe,ie,A;const z=new Set;let ae=!1,ye=!1,x,I,q=!1,W,L,G,O,F,se,le,ce,de;const Qe=it();let T,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function k(r){z.add(r),r.finally(()=>{z.delete(r)}).catch(()=>{})}s(k,"registerDetached");const er={acceptsDetachedWork:s(()=>P,"acceptsDetachedWork"),registerDetached:k};async function rr(){try{P=!1,
|
|
15
|
+
`)}}if(_=await qt(),Wt(_),e.role===void 0&&d!==null){if(await yn(d.id),process.platform==="darwin"){const{readConfig:n,updateConfig:h}=await import("../core/config.js");if(n("user").paths?.user_files===void 0){const{homedir:R}=await import("node:os");await h("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=R()})}}u=await Ur(),u.joinedFrom!==null&&await we(u.person),await cr(),i=await zr()}if(process.platform==="linux"&&E(C)&&(Pr(),await N({operation:"users.sync",users:await kr()})),p){await yt(y.token);const n=await fn();Object.values(n).some(h=>h>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(n)}
|
|
16
|
+
`)}}catch(r){await M.close();try{if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}await ue()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}let P=!0,ee,U=Promise.resolve(),re=!1,j,te,ne,oe,ie,A;const z=new Set;let ae=!1,ye=!1,x,I,q=!1,W,L,G,O,F,se,le,ce,de;const Qe=it();let T,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function k(r){z.add(r),r.finally(()=>{z.delete(r)}).catch(()=>{})}s(k,"registerDetached");const er={acceptsDetachedWork:s(()=>P,"acceptsDetachedWork"),registerDetached:k};async function rr(){try{P=!1,nn.close(),ne?.(),ne=void 0,oe?.(),v?.(),oe=void 0,ie?.(),ie=void 0,ce?.(),ce=void 0,await M.close(),j!==void 0&&(clearInterval(j),j=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),de?.(),de=void 0;let r;do r=U,await r;while(r!==U);for(;z.size>0;)await Promise.allSettled([...z]);if(A!==void 0&&(p&&await In(A),await A.exitsSettled(),A.dispose()),I!==void 0&&!q&&(q=!0,await I.close()),se?.(),se=void 0,le?.(),le=void 0,F!==void 0){const t=F;F=void 0,await t.stop()}if(L!==void 0){const t=L;L=void 0,await t.close()}if(W!==void 0){const t=W;W=void 0,await t.close()}if(ae||(Ve(process.pid),ae=!0),ae&&!ye){if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}ye=!0,await ue()}}finally{Ht(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(rr,"cleanupAttempt");const K=1e3;let Se=!1;function tr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return Se?{graceMs:K}:(Se=!0,b.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{nr()},K),{graceMs:K})}s(tr,"requestHandover");async function nr(){try{await D()}catch(r){const t=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
17
17
|
${t}
|
|
18
|
-
`),process.exit(1)}try{process.platform==="linux"&&E(
|
|
19
|
-
`),process.exit(1)}process.exit(0)}s(nr,"performHandover");function
|
|
18
|
+
`),process.exit(1)}try{process.platform==="linux"&&E(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ut();const r=await jt();b.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:r.pid??r.existing_pid??null,spawned:r.started}})})}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:r})});const t=r instanceof Error?r.message:String(r);process.stderr.write(`[crtrd] handover successor failed to start: ${t}
|
|
19
|
+
`),process.exit(1)}process.exit(0)}s(nr,"performHandover");function D(){if(x!==void 0)return x;const r=rr();return x=r,r.then(()=>{x===r&&(x=void 0)},()=>{x===r&&(x=void 0)}),r}s(D,"requestCleanup");async function or(){S={phase:"initializing",message:Xn,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Yn}))}s(or,"drainApi");async function _e(r){try{r==="SIGTERM"&&e.role==="api"&&await or(),await D(),await rn({claimed:s(async()=>{try{return p&&await Vt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(t){process.exitCode=1;const a=t instanceof Error?t.stack??`${t.name}: ${t.message}`:String(t);process.stderr.write(`[crtrd] ${r} cleanup failed:
|
|
20
20
|
${a}
|
|
21
|
-
`),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){
|
|
21
|
+
`),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){D().catch(()=>{})}s(Re,"onExit");async function J(r){P&&(U=U.then(r).then(()=>{},t=>{b.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:t})})}))}s(J,"enqueue");async function V(){!P||re||(Qe.check()&&T&&(m({level:"info",event:"daemon.resume.detected"}),k(T().catch(()=>{}))),re=!0,await J(async()=>{if(re=!1,!!P)try{f||await en({log:c}),await Jn(Date.now(),er)}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:r})})}}))}s(V,"enqueueTick");let B=null;async function ir(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const r=S.phase==="prepared";try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},r?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(t){throw B=t,{status:500,code:"admission_failed",message:`daemon admission failed: ${t instanceof Error?t.message:String(t)}`}}}s(ir,"admitStartup");async function ar(r){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const t=await gn({dryRun:r.dryRun});if(r.dryRun||t.pending||S.phase!=="blocked")return{result:t,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:t,resumed:!1};try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},{result:t,resumed:!0}}catch(a){const n=a instanceof Error?a.message:String(a);return setTimeout(()=>{D().catch(()=>{})},1e3),{result:t,resumed:!1,resumeError:n}}}finally{$=null}}s(ar,"repairMigrations");async function sr(){ee=e.intervalMs??ot;const r=y.token;A=new mn({epoch:r,enqueue:J}),Ft(A),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},b.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const t=_;if(b.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:t}})}),b.fresh(()=>{let a;try{a=nt()}catch{return}a!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:a.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Or(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await b.fresh(async()=>{await tt(),await Zr();const a=e.role!==void 0;await et(Date.now(),a),await rt(Date.now(),a)}),e.role===void 0&&await b.fresh(async()=>{const{reconcile:a,migrated:n}=await zt(gt);a.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:a.cleared.length,same_boot_proven:a.sameBootProven}}),n.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await b.fresh(async()=>{const a=await fe();for(const n of await Le())a.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await $e(n.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await b.fresh(async()=>{await Mt();for(const a of un){const n=await a.apply();n.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:a.id,...n.summary}})}}),k(Qr()),T){const a=s(()=>{k(T().catch(()=>{})),k(mr().then(n=>F?.observe(n)).then(()=>{},n=>{m({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");k(Yr().then(({completion:n})=>n).catch(n=>{m({level:"error",event:"daemon.grants.sweep_failed",error:n})})),a(),G=setInterval(a,Ge*1e3),G.unref(),de=pr({joined:!0,register:k})}await J(async()=>{await pn(),await dn()}),te=dr(),j=setInterval(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},ee),ne=await Nt(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))}),oe=await M.subscribe(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},{kinds:["spend_limits"]}),ie=await M.subscribe(a=>{J(()=>b.fresh(()=>Vn(a)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:a})=>a(()=>!P,n=>m({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(a=>m({level:"warn",event:"daemon.move.settle_failed",error:a}))}s(sr,"completeStartup");function pe(){return Xe??=sr().catch(r=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},r})}s(pe,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),hn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),i!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),H(e.role)?W=await yr():Sr(gr());const r=y.token;Bt({epoch:r,requestHandover:tr,registerDetached:k,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),Q(),I=H(e.role)?$r({tcp:e.tcp}):Qn(e),await I.ready,Q(I.tcpAddress()??"");const t=Oe("user").runtime;if(t?.issuer&&(T=Vr(t.issuer,k),t.unsandboxed===!0&&(F=fr({syncGrants:T}))),e.role==="api"||e.role==="all"){const a=s(()=>k(import("../core/providers/bundles.js").then(h=>h.syncProviderBundles()).catch(h=>{m({level:"error",event:"daemon.providers.bundle_sync_failed",error:h})})),"bundleTick"),n=s(()=>{k(Kr().catch(h=>{m({level:"error",event:"daemon.packages.sync_failed",error:h})})),a()},"packageTick");n(),O=setInterval(n,Ge*1e3),O.unref()}if(H(e.role)&&(se=await qr()),Z(e.role)&&(le=Jr()),ce=await Wr({serves:H(e.role),runsLanes:Z(e.role)}),t?.unsandboxed===!0&&t.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),H(e.role)&&t!==void 0&&t.listener!==void 0&&t.unsandboxed!==!0&&(L=await Gr(t,async()=>await Xr(t.issuer.replace(/\/$/,"")),T),await L.ready,Q(I.tcpAddress()??"",`${t.listener.address}:${L.port()}`)),e.role===void 0)try{await wn()}catch(a){if($=null,a instanceof vn)return S={phase:"blocked",message:a.message,blockerPaths:a.blockerPaths},D;throw a}process.platform==="linux"&&E(C)&&(Er(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await pe(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return D}catch(r){try{await D()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}}s(eo,"runDaemon");var ra=eo;export{Yn as API_DRAIN_GRACE_MS,oa as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,ra as default,Vn as exitedNodePass,Z as roleRunsLanes,H as roleServesRequests,eo as runDaemon,Jn as superviseTick,In as teardownFleet};
|
|
@@ -40,6 +40,8 @@ export interface RecipeImageDeps {
|
|
|
40
40
|
deleteImage?: (name: string) => Promise<void>;
|
|
41
41
|
now?: () => number;
|
|
42
42
|
}
|
|
43
|
+
/** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
|
|
44
|
+
export declare function removeLeftoverBuildDirs(root?: string): void;
|
|
43
45
|
export declare class RecipeImageReconciler {
|
|
44
46
|
private readonly deps;
|
|
45
47
|
constructor(deps?: RecipeImageDeps);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE object = ? AND ${
|
|
3
|
-
RETURNING ${
|
|
4
|
-
WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${
|
|
1
|
+
var h=Object.defineProperty;var _=(r,e)=>h(r,"name",{value:e,configurable:!0});import{mkdtempSync as R,readdirSync as O,rmSync as y}from"node:fs";import{tmpdir as u}from"node:os";import{join as f}from"node:path";import{hasUnseenWakeMail as U}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as I}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as W}from"../../core/runs/events.js";import{blaxelConfigFromEnv as w}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as C,deleteImage as j,environmentImageName as b,prepareBuildDir as H,removeBuildDir as k}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as x}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as N,packagesTokenFor as $,recipeOf as F}from"../api/environment-of.js";import{brokerSignalBus as M}from"../broker-signals/bus.js";const p=3*6e4,S=10*6e4,E="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",D=`NOT ${E}`,L=`(kind = 'blaxel' AND ${D} AND recipe_revision > COALESCE(image_revision, 0) AND ${N})`,v=`(kind = 'blaxel' AND ${E} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function re(r){const e=await(await l()).prepare(`SELECT ${N} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(r);if(e===void 0)throw new Error(`no environment ${r}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}_(re,"resolveEnvironmentImage");async function ae(r){return await M.subscribe(e=>{r(e)},{kinds:["environment_image"]})}_(ae,"subscribeImageBuilt");async function P(r,e){const i=r.recipe.repositories.map(a=>a.github_full_name),t=i.length===0?null:await x(r.person,i),n=R(f(u(),"crtr-recipe-image-"));try{return await H({recipe:r.recipe,revision:r.revision,token:t?.token??null,packagesToken:await $(r.environmentId),dir:n}),await C(e,b(r.environmentId),n)}finally{k(n)}}_(P,"defaultBuild");function ne(r=u()){for(const e of O(r))e.startsWith("crtr-recipe-image-")&&y(f(r,e),{recursive:!0,force:!0})}_(ne,"removeLeftoverBuildDirs");class oe{static{_(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,i){if(i.lifecycle.acceptsDetachedWork())try{const t=new Date(e).toISOString(),n=await l(),a=await n.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(t);for(const{object:o}of a){const s=await this.claim(o,e,L,"recipe_revision");s!==null&&i.lifecycle.registerDetached(this.buildClaimed(o,Number(s.recipe_revision),s.lease).catch(m=>{g({level:"error",event:"recipe_image.failed",error:m})}))}const c=await n.prepare(`SELECT object FROM environments WHERE ${v} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(t);for(const{object:o}of c){const s=await this.claim(o,e,v,"object");s!==null&&i.lifecycle.registerDetached(this.withLease(o,s.lease,m=>this.deleteClaimed(o,m)).catch(m=>{g({level:"error",event:"recipe_image.delete_failed",error:m})}))}}catch(t){g({level:"error",event:"recipe_image.reconcile_failed",error:t})}}async claim(e,i,t,n){const a=new Date(i+p).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
|
|
2
|
+
WHERE object = ? AND ${t} AND (image_building_at IS NULL OR image_building_at <= ?)
|
|
3
|
+
RETURNING ${n} AS recipe_revision`).get(a,e,new Date(i).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:a}}async withLease(e,i,t){const n=this.deps.now??Date.now;let a=i;const c=setInterval(()=>{const o=new Date(n()+p).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(o,e,a)).changes===1&&(a=o)})().catch(()=>{})},p/3);c.unref();try{await t(()=>a)}finally{clearInterval(c)}}async deleteClaimed(e,i){try{await(this.deps.deleteImage??(t=>j(w(),t)))(b(e))}catch(t){const n=t instanceof Error?t.message:String(t),a=new Date((this.deps.now??Date.now)()+S).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${n}`,a,e,i())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:n}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,i())}async buildClaimed(e,i,t){const n=this.deps.now??Date.now;await this.withLease(e,t,async a=>{const c=await F(e);if(c===null||c.revision!==i){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,a());return}let o;try{const d=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(d===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);await(await l()).prepare("UPDATE environments SET image_error = ? WHERE object = ? AND image_building_at = ?").run(`the build of revision ${i} started and its process exited before it finished`,e,a());const T={environmentId:e,revision:i,recipe:c,person:d.person};o=await(this.deps.build??(A=>P(A,w())))(T)}catch(d){await this.recordFailure(e,a(),d instanceof Error?d.message:String(d),n());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
|
|
4
|
+
WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${D}`).run(i,o.ref,e,a(),i)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${E}`).run(o.ref,e)})}async recordFailure(e,i,t,n){const a=new Date(n+S).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(t,a,e,i)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:t}});for(const o of await B(e))try{await I(async s=>{await W(s,o.run_id,o.node_id,"environment.image_failed",{environment_id:e,error:t})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:o.node_id,error:s})}}}}async function B(r){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
|
|
5
5
|
WHERE p.environment_id = ? AND n.status IN ('active', 'idle') AND n.run_id IS NOT NULL
|
|
6
|
-
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(
|
|
6
|
+
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(r),i=[];for(const t of e)await U(t.node_id)&&i.push(t);return i}_(B,"nodesWaitingOnImage");export{E as ENVIRONMENT_DELETED_SQL,D as ENVIRONMENT_LIVE_SQL,L as IMAGE_BUILD_OWED_SQL,v as IMAGE_DELETE_OWED_SQL,p as LEASE_MS,S as RETRY_AFTER_FAILURE_MS,oe as RecipeImageReconciler,B as nodesWaitingOnImage,ne as removeLeftoverBuildDirs,re as resolveEnvironmentImage,ae as subscribeImageBuilt};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.752",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.752",
|
|
162
|
+
"@north-light/plugin": "0.3.752",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.76';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -188,6 +188,8 @@ export const routes = {
|
|
|
188
188
|
appEnvVar: (variable) => `${V}/apps/self/env/${encodeURIComponent(variable)}`,
|
|
189
189
|
profileEnv: (name) => `${V}/profiles/${name}/env`,
|
|
190
190
|
profileEnvVar: (name, variable) => `${V}/profiles/${name}/env/${variable}`,
|
|
191
|
+
environments: () => `${V}/environments`,
|
|
192
|
+
environment: (name) => `${V}/environments/${name}`,
|
|
191
193
|
profileEnvironment: (name) => `${V}/profiles/${name}/environment`,
|
|
192
194
|
// Person settings
|
|
193
195
|
settings: () => `${V}/settings`,
|
|
@@ -11,9 +11,10 @@ import { setCloudProfileWriter } from './profiles/manifest.js';
|
|
|
11
11
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
12
12
|
export async function createProfileBlaxelEnvironment(db, spec) {
|
|
13
13
|
const app = await ownerForGrantee(db, spec.grantee);
|
|
14
|
-
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
|
|
14
|
+
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app, { noActsFor: spec.person.startsWith('app:') });
|
|
15
15
|
const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
|
|
16
|
-
|
|
16
|
+
if (!spec.person.startsWith('app:'))
|
|
17
|
+
await writeActsFor(db, object.id, spec.person); // an app environment is kept for no person
|
|
17
18
|
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, spec.payer ?? null, new Date().toISOString());
|
|
18
19
|
if (spec.recipe !== undefined)
|
|
19
20
|
await writeEnvironmentRecipe(db, object.id, spec.recipe);
|
|
@@ -26,7 +26,7 @@ export const ownerLockKey = (scheme, externalId, person = '') => `owner:${person
|
|
|
26
26
|
* holding the same remote or path each get their own repo. Handles are unique per owner type: a handle already held
|
|
27
27
|
* by a different identity of the same type throws `conflict` naming both; it is
|
|
28
28
|
* never renamed silently. */
|
|
29
|
-
export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
|
|
29
|
+
export async function ensureOwner(db, type, scheme, externalId, handle, owner, options = {}) {
|
|
30
30
|
if (!OWNER_TYPES.has(type))
|
|
31
31
|
throw new Error(`ensureOwner: ${type} is not an owner type`);
|
|
32
32
|
// An owner that exists needs no lock: taking one here would acquire it outside the order a peer ingest locked its keys in.
|
|
@@ -57,7 +57,7 @@ export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
|
|
|
57
57
|
await writeActsFor(db, created.id, userSubject(externalId).id);
|
|
58
58
|
else if (type === 'repo')
|
|
59
59
|
await writeActsFor(db, created.id, userSubject(person).id);
|
|
60
|
-
else if (type === 'profile')
|
|
60
|
+
else if (type === 'profile' && options.noActsFor !== true)
|
|
61
61
|
await writeActsFor(db, created.id, userSubject(await personIdAsync()).id);
|
|
62
62
|
return created;
|
|
63
63
|
}
|
|
@@ -367,7 +367,7 @@ export async function createProfile(name, projects = [], opts = {}) {
|
|
|
367
367
|
else if (cloudProfileWriter === null)
|
|
368
368
|
throw new Error('a cloud role has no profile environment writer registered');
|
|
369
369
|
else
|
|
370
|
-
await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: personId(), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
|
|
370
|
+
await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: opts.appEnvironment === true ? profileApp(manifest) : personId(), ...(opts.appEnvironment === true ? { payer: opts.payer ?? profileApp(manifest) } : {}), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
|
|
371
371
|
return { profileId, manifest };
|
|
372
372
|
}
|
|
373
373
|
export async function ensureAppProfile(grantee) {
|