@north-light/cli 0.3.654 → 0.3.656
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/docs.d.ts +6 -3
- package/dist/clients/attach/config.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +2 -3
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/render/chat-view.d.ts +41 -37
- package/dist/clients/attach/render/chat-view.js +3 -3
- package/dist/clients/attach/session/bindings.d.ts +1 -1
- package/dist/clients/attach/session/bindings.js +1 -1
- package/dist/clients/attach/session/document-links.d.ts +3 -2
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/session/input-wiring.d.ts +9 -9
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/slash/dispatch.d.ts +6 -8
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/viewer.js +514 -514
- package/dist/commands/node/create.js +1 -1
- package/dist/commands/sys/panels/prefs-panel.js +1 -1
- package/dist/core/config.js +1 -1
- package/dist/core/graph/documents.js +13 -11
- package/dist/core/graph/edges.js +4 -3
- package/dist/core/graph/events.d.ts +1 -1
- package/dist/core/graph/events.js +8 -8
- package/dist/core/graph/exposures.js +7 -4
- package/dist/core/graph/kinds/document.js +4 -4
- package/dist/core/graph/kinds/dto.d.ts +2 -0
- package/dist/core/graph/kinds/dto.js +1 -1
- package/dist/core/graph/names.d.ts +4 -0
- package/dist/core/graph/names.js +9 -8
- package/dist/core/graph/rules.d.ts +2 -0
- package/dist/core/graph/rules.js +3 -3
- package/dist/core/keybindings/catalog.d.ts +3 -3
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/runtime/broker/tool-groups.js +1 -1
- package/dist/core/runtime/broker/turn-replies.d.ts +1 -4
- package/dist/core/runtime/broker/turn-replies.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +2 -2
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +3 -0
- package/dist/core/substrate/delivery/corpus.js +2 -3
- package/dist/core/substrate/delivery/render-event.js +4 -4
- package/dist/core/user-settings.d.ts +13 -35
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/canvas-host.d.ts +9 -0
- package/dist/daemon/api/canvas-host.js +1 -0
- package/dist/daemon/api/document-listener.js +1 -11
- package/dist/daemon/api/document-page.d.ts +18 -0
- package/dist/daemon/api/document-page.js +11 -0
- package/dist/daemon/api/handlers/document-access.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/broker-signals/bus.d.ts +3 -2
- package/dist/daemon/broker-signals/bus.js +1 -1
- package/dist/doc-editor/editor.js +24 -24
- package/dist/types.d.ts +13 -15
- package/dist/types.js +1 -1
- package/docs/cli/the-viewer.md +16 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
var ze=Object.defineProperty;var n=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as He,importPrincipalFor as Le}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Be}from"node:https";import{chmodSync as xe,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as De}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Fe}from"../../core/canvas/paths.js";import{resolveNodeToken as $e}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Je}from"./principal.js";import{createAppRequestHandler as We}from"./app-listener.js";import{decodeJwt as je}from"jose";import{handleRuntimeSignIn as Ve,isRuntimeSignInPath as Ge}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Ye,vendorStatus as Ke}from"./handlers/vendor-status.js";import{toErrorBody as Xe}from"./map.js";import{CONTROL_BODY_MAX_BYTES as Ze}from"../../core/llm/body-limits.js";import{grantFor as Qe,hasSyncedGrants as qe}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as er}from"../../core/directory/issuer.js";import{peerUid as rr}from"../../native/linux.js";import{findScopedApiToken as tr,getApiToken as nr,listScopedApiTokens as or}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as ir,envCrtrdToken as sr}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as ar,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as lr,machineLinkEnvironment as cr,setApiAddress as ur}from"../machine-link/holder.js";import{handleMachineViewUpgrade as pr,machineViewEnvironment as dr}from"../machine-link/forward.js";import{boundDaemonControl as fr}from"../control.js";import{attachRoutes as mr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as gr}from"../peer/handlers.js";import{bashJobRoutes as hr}from"./handlers/bash-jobs.js";import{bashRoutes as Rr}from"./handlers/bash.js";import{hookExecRoutes as Ar}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as yr,brokerSignalStreams as _r}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as vr}from"./handlers/broker-recovery.js";import{canvasRoutes as wr}from"./handlers/canvas.js";import{conversationRoutes as Er}from"./handlers/conversations.js";import{chatInventoryRoutes as Sr}from"./handlers/chat-inventory.js";import{daemonRoutes as br}from"./handlers/daemon.js";import{fileRoutes as Tr}from"./handlers/files.js";import{focusRoutes as Cr}from"./handlers/focus.js";import{analyticsRoutes as kr}from"./handlers/analytics.js";import{memoryReadsRoutes as Ur}from"./handlers/memory-reads.js";import{memoryRoutes as Or}from"./handlers/memory.js";import{healthRoutes as Pr}from"./handlers/health.js";import{humanRequestRoutes as Nr}from"./handlers/human-requests.js";import{inboxRoutes as Ir}from"./handlers/inbox.js";import{feedbackCommentRoutes as zr}from"./handlers/feedback-comments.js";import{objectRoutes as Hr}from"./handlers/objects.js";import{shareRoutes as Lr}from"./handlers/shares.js";import{customObjectRoutes as Br}from"./handlers/custom-objects.js";import{docRoutes as xr}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as Dr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Mr}from"./handlers/package-docs.js";import{documentAccessRoutes as Fr}from"./handlers/document-access.js";import{pluginAppRoutes as $r}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as Jr}from"./handlers/messages.js";import{modelAuthRoutes as Wr}from"./handlers/modelauth.js";import{llmRoutes as jr}from"./handlers/llm.js";import{providerRoutes as Vr}from"./handlers/providers.js";import{modelConfigRoutes as Gr}from"./handlers/model-config.js";import{settingsRoutes as Yr}from"./handlers/settings.js";import{nodeRoutes as Kr}from"./handlers/nodes.js";import{nodeRecordRoutes as Xr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as Zr}from"./handlers/node-outcomes.js";import{nodeEventRoutes as Qr}from"./handlers/node-events.js";import{profileRoutes as qr}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as et}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as rt}from"./handlers/reports.js";import{runRoutes as tt}from"./handlers/run-routes.js";import{reviewCommentRoutes as nt}from"./handlers/review-comments.js";import{reviewRoutes as ot}from"./handlers/reviews.js";import{subscriptionRoutes as it}from"./handlers/subscriptions.js";import{structuredRequestRoutes as st}from"./handlers/structured-requests.js";import{cronRoutes as at}from"./handlers/crons.js";import{setCronRequestHandler as _e}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as lt,cronPrincipalForRunToken as ct}from"../cron/run-token.js";import{worktreeRoutes as ut}from"./handlers/worktree.js";import{limitsRoutes as pt}from"./handlers/limits.js";import{chargeRoutes as dt,spendLimitRoutes as ft}from"./handlers/charges.js";import{executionStartRoutes as mt}from"./handlers/execution-start.js";import{machineCredentialRoutes as gt}from"./handlers/machine-credential.js";import{importRoutes as ht}from"./handlers/imports.js";import{gitCredentialRoutes as Rt}from"./handlers/git-credential.js";function At(e){return new fe().registerAll(Pr(e)).registerAll(br).registerAll(Lr).registerAll(Kr).registerAll(Xr).registerAll(Zr).registerAll(Dr).registerAll(Qr).registerAll(hr).registerAll(Rr).registerAll(Ar).registerAll(he).registerAll(yr).registerAll(Ae).registerAll(Re).registerAll(vr).registerAll(ut).registerAll(pt).registerAll(dt).registerAll(mt).registerAll(gt).registerAll(ht).registerAll(Rt).registerAll(ft).registerAll(ye).registerAll(Jr).registerAll(rt).registerAll(tt).registerAll(st).registerAll(mr).registerAll(wr).registerAll(Er).registerAll(kr).registerAll(Ur).registerAll(Or).registerAll(Tr).registerAll(Hr).registerAll(Br).registerAll(xr).registerAll(Mr).registerAll(Fr).registerAll($r).registerAll(Cr).registerAll(it).registerAll(at).registerAll(qr).registerAll(Wr).registerAll(jr).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(ot).registerAll(nt).registerAll(Ir).registerAll(Nr).registerAll(Sr).registerAll(et).registerAll(zr).registerAll(gr)}n(At,"buildRouter");function yt(e,r){if(e.toUpperCase()!=="GET")return null;const o=r.split("/").filter(u=>u.length>0);if(o.length!==4||o[0]!=="v1"||o[1]!=="nodes"||o[3]!=="attach")return null;const a=o[2];return a===void 0||a===""?null:decodeURIComponent(a)}n(yt,"attachNodeId");function _t(e){const r=e.trim();if(r==="")return null;const o=r.lastIndexOf(":");if(o<0)return null;const a=r.slice(0,o),u=r.slice(o+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}n(_t,"parseTcp");function vt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}n(vt,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={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"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function F(e){return B.get(e)}n(F,"socketPrincipal");async function ve(e,r){const o=process.platform==="linux"?rr(e.socket):null,a=e.headers.authorization;if(a===void 0)return o===null||r.has(o)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(o===null||r.has(o))?u.principal:"unauthorized"}return we(a.slice(7),o)}n(ve,"resolveSocketPrincipal");async function we(e,r){const o=await $e(e);if(!o||r!==null&&r!==o.uid)return"unauthorized";const a=er();if(a&&!H()&&!await qe(a))return"runtime_starting";const u=o.grant??(await Qe("app:terminal",o.sub))?.id??null;return{class:"broker",...o,grant:u}}n(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}n(Ee,"requestPerson");function Se(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}})}n(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?tr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}n(be,"appBearer");function wt(e){const r=new Map;for(const o of or("user"))r.set(o.token,{principal:{class:"app",app:o.grantee,scopes:o.scopes},ceiling:o.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}n(wt,"resolveBearers");function Et(e){try{return je(e).act!==void 0}catch{return!1}}n(Et,"carriesAct");const St=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}n(k,"deny");async function Te(e,r,o){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(o,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(o,"app_token_unknown");if(u.startsWith(lt)){const w=await ct(u);return w===null?k(o,"run_token_invalid_or_settled"):{principal:w,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Le(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(He))return k(o,"import_token_invalid");if(St.test(u)){if(H()&&Et(u)){const x=j();if(x===null)return"person_bearer";try{const v=await x.verifyCall(a);return v.chain[0]?.sub.startsWith("app:")?{call:v}:k(o,"call_token_presenter_not_an_app")}catch(v){return v instanceof S&&v.status===503?"runtime_starting":k(o,`call_token_${v instanceof S?v.code:"invalid"}`)}}const w=H()?pe():null;if(w===null)return"person_bearer";const U=await w.verify(u);return U===null?k(o,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(o,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}n(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new Je(e,r,async()=>{}),W}n(j,"cloudCallResolver");let Ce;function bt(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=We(e,async()=>!0,async()=>{}),Ce}n(bt,"cloudAppCalls");async function Tt(e,r){N(r),I(r);const o=j();try{if(o===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await Ve(e,r,new URL(e.url??"/","http://runtime.local"),o)}catch(a){if(!(a instanceof S))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"}}))}}n(Tt,"serveRuntimeSignIn");function Ct(){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:se(e),key:se(r)}}n(Ct,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}n(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}n(I,"exposeRuntimeHeaders");function kt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}n(kt,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}n(V,"writeUnauthorized");function Ut(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}n(Ut,"writePersonBearerRefused");const Ot={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Pt(e,r){if(!H())return!1;const o=new URL(e.url??"/","http://runtime.local").pathname,a=Ot[o];if(a===void 0||e.method!==a.method)return!1;const u=n((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const w=a.purpose==="vendor_status"?void 0:await Nt(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ke():await Ye(w)))}catch(d){const{status:R,body:m}=Xe(d);u(R,m)}return!0}n(Pt,"serveCloudVendorRoute");async function Nt(e){const r=[];let o=0;for await(const a of e){if(o+=a.length,o>Ze)throw new S(400,"invalid_request","request body too large");r.push(a)}if(o!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}n(Nt,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}n(ke,"writeRuntimeStarting");function It(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}n(It,"writeStartupBlocked");function Ue(e,r,o){return new Promise(a=>{for(const m of r)m.destroy();if(o===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),o);u.push(d,R),e.closeIdleConnections()})}n(Ue,"closeServer");function vo(e={}){let r=null;const o=At(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=n((t,i)=>{const c=fr()?.startupBlock()??null;return c===null||t==="GET"&&(i==="/healthz"||i==="/v1/status"||i==="/v1/ready")||t==="POST"&&(i==="/v1/daemon/migrate"||i==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,i)!==null?null:c},"startupBlockFor"),d=e.socketPath??Fe(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=n((t,i,c)=>{N(i);const p=n(s=>Array.isArray(s)?s[0]:s,"first"),O=p(t.headers[le.toLowerCase()]),h=De(O,X())??Me(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});if(h!==null){i.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),i.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 E=n(s=>{const l=F(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:s instanceof Error?s:new Error(String(s))});try{i.headersSent||i.writeHead(500,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let T;try{T=new URL(t.url??"/","http://127.0.0.1")}catch{try{i.writeHead(400,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const s=u((t.method??"GET").toUpperCase(),T.pathname);if(s!==null){It(i,s.message);return}const l=F(t)??{class:"person"},f=Ee(l),g=n(()=>o.handle(t,i,c,l),"handled");(f===void 0?g():J(f,n(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(s){E(s)}},"onRequest"),w=n(async(t,i,c)=>{const p=F(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(i,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=n(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),v=n((t,i,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(i,503,"Service Unavailable","startup_blocked",O.message);return}const h=yt(t.method??"GET",p.pathname);if(h===null){i.destroy();return}const E=(()=>{const s=F(t);return s===void 0?void 0:Ee(s)})(),T=n(()=>w(t,i,h).then(s=>s?ar(t,i,c,h,async l=>{const f=F(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{i.destroy()}catch{}})}catch{try{i.destroy()}catch{}}},"onUpgrade"),Oe=n(t=>{t.on("error",i=>{A({event:"api.server.failed",level:"error",error:i})})},"bindErrorHandler"),Pe=n(async(t,i)=>{try{const c=await ve(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(i);return}if(c==="runtime_starting"){ke(i);return}B.set(t,c),Se(t,c),m(t,i,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),V(i)}},"onSocketRequest"),D=ie((t,i)=>{Pe(t,i).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ne=n(async(t,i,c)=>{try{const p=await ve(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(i,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(i,403,"Forbidden",L.code,L.message);return}B.set(t,p),v(t,i,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(i,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,i,c)=>{x(i),Ne(t,i,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),_e((t,i,c)=>{B.set(t,c),m(t,i,null)});let re=!1,te,ne;const Ie=new Promise((t,i)=>{te=t,ne=i});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{xe(d,process.platform==="linux"&&G("/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;const $=e.tcp??ir()??de("user").api.tcp;if($!==void 0&&$!==""){const t=_t($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const i=e.token??sr()??nr("user"),c=wt(i),p=n(async(s,l)=>{if(kt(s,l))return;if(H()&&Ge(new URL(s.url??"/","http://runtime.local").pathname)){await Tt(s,l);return}if(await Pt(s,l))return;const f={},g=await Te(s,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){Ut(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:s.method,listener:"tcp",path:new URL(s.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await bt()(s,l,g.call)});return}B.set(s,g.principal),Se(s,g.principal),I(l),m(s,l,g.ceiling)},"tcpOnRequest"),O=n(async(s,l,f)=>{const g=cr(s);if(g!==null){const _=await lr(s,l,f,g);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const z=dr(s);if(z!==null){const _=pr(s,l,f,z);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const C=await Te(s,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",M.code,M.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(s,C.principal),v(s,l,f)},"tcpOnUpgrade"),h=n(s=>{A({event:"api.principal.failed",level:"error",error:s instanceof Error?s:new Error(String(s))})},"failed"),E=n((s,l)=>{p(s,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Ct();b=T===null?ie(E):Be(T,E),b.on("upgrade",(s,l,f)=>{x(l),O(s,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),Oe(b),b.once("listening",()=>{const s=b?.address();if(s!==null&&typeof s=="object"){const{address:l,port:f}=s;r=vt(l,f),l!=="0.0.0.0"&&l!=="::"&&ur(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ie,tcpAddress:n(()=>r,"tcpAddress"),close:n(async(t={})=>{if(!oe){oe=!0,_e(null),_r.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}n(vo,"createApiServer");export{At as buildRouter,Ue as closeServer,vo as createApiServer,F as socketPrincipal};
|
|
1
|
+
var ze=Object.defineProperty;var o=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as He,importPrincipalFor as Le}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Be}from"node:https";import{chmodSync as xe,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as De}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Fe}from"../../core/canvas/paths.js";import{resolveNodeToken as $e}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{isCanvasRequest as Je,serveCanvas as We}from"./canvas-host.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as je}from"./principal.js";import{createAppRequestHandler as Ve}from"./app-listener.js";import{decodeJwt as Ge}from"jose";import{handleRuntimeSignIn as Ye,isRuntimeSignInPath as Ke}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Xe,vendorStatus as Ze}from"./handlers/vendor-status.js";import{toErrorBody as Qe}from"./map.js";import{CONTROL_BODY_MAX_BYTES as qe}from"../../core/llm/body-limits.js";import{grantFor as er,hasSyncedGrants as rr}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as tr}from"../../core/directory/issuer.js";import{peerUid as nr}from"../../native/linux.js";import{findScopedApiToken as or,getApiToken as ir,listScopedApiTokens as sr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as ar,envCrtrdToken as lr}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as cr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as ur,machineLinkEnvironment as pr,setApiAddress as dr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as fr,machineViewEnvironment as mr}from"../machine-link/forward.js";import{boundDaemonControl as gr}from"../control.js";import{attachRoutes as hr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as Rr}from"../peer/handlers.js";import{bashJobRoutes as Ar}from"./handlers/bash-jobs.js";import{bashRoutes as yr}from"./handlers/bash.js";import{hookExecRoutes as vr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as _r,brokerSignalStreams as wr}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as Er}from"./handlers/broker-recovery.js";import{canvasRoutes as Sr}from"./handlers/canvas.js";import{conversationRoutes as br}from"./handlers/conversations.js";import{chatInventoryRoutes as Tr}from"./handlers/chat-inventory.js";import{daemonRoutes as Cr}from"./handlers/daemon.js";import{fileRoutes as kr}from"./handlers/files.js";import{focusRoutes as Ur}from"./handlers/focus.js";import{analyticsRoutes as Or}from"./handlers/analytics.js";import{memoryReadsRoutes as Pr}from"./handlers/memory-reads.js";import{memoryRoutes as Nr}from"./handlers/memory.js";import{healthRoutes as Ir}from"./handlers/health.js";import{humanRequestRoutes as zr}from"./handlers/human-requests.js";import{inboxRoutes as Hr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Lr}from"./handlers/feedback-comments.js";import{objectRoutes as Br}from"./handlers/objects.js";import{shareRoutes as xr}from"./handlers/shares.js";import{customObjectRoutes as Dr}from"./handlers/custom-objects.js";import{docRoutes as Mr}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as Fr}from"./handlers/delivery-retry.js";import{packageDocRoutes as $r}from"./handlers/package-docs.js";import{documentAccessRoutes as Jr}from"./handlers/document-access.js";import{pluginAppRoutes as Wr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as jr}from"./handlers/messages.js";import{modelAuthRoutes as Vr}from"./handlers/modelauth.js";import{llmRoutes as Gr}from"./handlers/llm.js";import{providerRoutes as Yr}from"./handlers/providers.js";import{modelConfigRoutes as Kr}from"./handlers/model-config.js";import{settingsRoutes as Xr}from"./handlers/settings.js";import{nodeRoutes as Zr}from"./handlers/nodes.js";import{nodeRecordRoutes as Qr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as qr}from"./handlers/node-outcomes.js";import{nodeEventRoutes as et}from"./handlers/node-events.js";import{profileRoutes as rt}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as tt}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as nt}from"./handlers/reports.js";import{runRoutes as ot}from"./handlers/run-routes.js";import{reviewCommentRoutes as it}from"./handlers/review-comments.js";import{reviewRoutes as st}from"./handlers/reviews.js";import{subscriptionRoutes as at}from"./handlers/subscriptions.js";import{structuredRequestRoutes as lt}from"./handlers/structured-requests.js";import{cronRoutes as ct}from"./handlers/crons.js";import{setCronRequestHandler as ve}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as ut,cronPrincipalForRunToken as pt}from"../cron/run-token.js";import{worktreeRoutes as dt}from"./handlers/worktree.js";import{limitsRoutes as ft}from"./handlers/limits.js";import{chargeRoutes as mt,spendLimitRoutes as gt}from"./handlers/charges.js";import{executionStartRoutes as ht}from"./handlers/execution-start.js";import{machineCredentialRoutes as Rt}from"./handlers/machine-credential.js";import{importRoutes as At}from"./handlers/imports.js";import{gitCredentialRoutes as yt}from"./handlers/git-credential.js";function vt(e){return new fe().registerAll(Ir(e)).registerAll(Cr).registerAll(xr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(Fr).registerAll(et).registerAll(Ar).registerAll(yr).registerAll(vr).registerAll(he).registerAll(_r).registerAll(Ae).registerAll(Re).registerAll(Er).registerAll(dt).registerAll(ft).registerAll(mt).registerAll(ht).registerAll(Rt).registerAll(At).registerAll(yt).registerAll(gt).registerAll(ye).registerAll(jr).registerAll(nt).registerAll(ot).registerAll(lt).registerAll(hr).registerAll(Sr).registerAll(br).registerAll(Or).registerAll(Pr).registerAll(Nr).registerAll(kr).registerAll(Br).registerAll(Dr).registerAll(Mr).registerAll($r).registerAll(Jr).registerAll(Wr).registerAll(Ur).registerAll(at).registerAll(ct).registerAll(rt).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(Kr).registerAll(Xr).registerAll(st).registerAll(it).registerAll(Hr).registerAll(zr).registerAll(Tr).registerAll(tt).registerAll(Lr).registerAll(Rr)}o(vt,"buildRouter");function _t(e,r){if(e.toUpperCase()!=="GET")return null;const i=r.split("/").filter(u=>u.length>0);if(i.length!==4||i[0]!=="v1"||i[1]!=="nodes"||i[3]!=="attach")return null;const a=i[2];return a===void 0||a===""?null:decodeURIComponent(a)}o(_t,"attachNodeId");function wt(e){const r=e.trim();if(r==="")return null;const i=r.lastIndexOf(":");if(i<0)return null;const a=r.slice(0,i),u=r.slice(i+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}o(wt,"parseTcp");function Et(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(Et,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={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"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function F(e){return B.get(e)}o(F,"socketPrincipal");async function _e(e,r){const i=process.platform==="linux"?nr(e.socket):null,a=e.headers.authorization;if(a===void 0)return i===null||r.has(i)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(i===null||r.has(i))?u.principal:"unauthorized"}return we(a.slice(7),i)}o(_e,"resolveSocketPrincipal");async function we(e,r){const i=await $e(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const a=tr();if(a&&!H()&&!await rr(a))return"runtime_starting";const u=i.grant??(await er("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:u}}o(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(Ee,"requestPerson");function Se(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}})}o(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?or(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(be,"appBearer");function St(e){const r=new Map;for(const i of sr("user"))r.set(i.token,{principal:{class:"app",app:i.grantee,scopes:i.scopes},ceiling:i.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}o(St,"resolveBearers");function bt(e){try{return Ge(e).act!==void 0}catch{return!1}}o(bt,"carriesAct");const Tt=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(k,"deny");async function Te(e,r,i){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(i,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(i,"app_token_unknown");if(u.startsWith(ut)){const w=await pt(u);return w===null?k(i,"run_token_invalid_or_settled"):{principal:w,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Le(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(He))return k(i,"import_token_invalid");if(Tt.test(u)){if(H()&&bt(u)){const x=j();if(x===null)return"person_bearer";try{const _=await x.verifyCall(a);return _.chain[0]?.sub.startsWith("app:")?{call:_}:k(i,"call_token_presenter_not_an_app")}catch(_){return _ instanceof S&&_.status===503?"runtime_starting":k(i,`call_token_${_ instanceof S?_.code:"invalid"}`)}}const w=H()?pe():null;if(w===null)return"person_bearer";const U=await w.verify(u);return U===null?k(i,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(i,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}o(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new je(e,r,async()=>{}),W}o(j,"cloudCallResolver");let Ce;function Ct(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=Ve(e,async()=>!0,async()=>{}),Ce}o(Ct,"cloudAppCalls");async function kt(e,r){N(r),I(r);const i=j();try{if(i===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await Ye(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(a){if(!(a instanceof S))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"}}))}}o(kt,"serveRuntimeSignIn");function Ut(){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:se(e),key:se(r)}}o(Ut,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}o(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}o(I,"exposeRuntimeHeaders");function Ot(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(Ot,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}o(V,"writeUnauthorized");function Pt(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}o(Pt,"writePersonBearerRefused");const Nt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function It(e,r){if(!H())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,a=Nt[i];if(a===void 0||e.method!==a.method)return!1;const u=o((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const w=a.purpose==="vendor_status"?void 0:await zt(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ze():await Xe(w)))}catch(d){const{status:R,body:m}=Qe(d);u(R,m)}return!0}o(It,"serveCloudVendorRoute");async function zt(e){const r=[];let i=0;for await(const a of e){if(i+=a.length,i>qe)throw new S(400,"invalid_request","request body too large");r.push(a)}if(i!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}o(zt,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}o(ke,"writeRuntimeStarting");function Ht(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}o(Ht,"writeStartupBlocked");function Ue(e,r,i){return new Promise(a=>{for(const m of r)m.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),i);u.push(d,R),e.closeIdleConnections()})}o(Ue,"closeServer");function So(e={}){let r=null;const i=vt(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=o((t,s)=>{const c=gr()?.startupBlock()??null;return c===null||t==="GET"&&(s==="/healthz"||s==="/v1/status"||s==="/v1/ready")||t==="POST"&&(s==="/v1/daemon/migrate"||s==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,s)!==null?null:c},"startupBlockFor"),d=e.socketPath??Fe(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=o((t,s,c)=>{N(s);const p=o(n=>Array.isArray(n)?n[0]:n,"first"),O=p(t.headers[le.toLowerCase()]),h=De(O,X())??Me(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});if(h!==null){s.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),s.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 E=o(n=>{const l=F(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:n instanceof Error?n:new Error(String(n))});try{s.headersSent||s.writeHead(500,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let T;try{T=new URL(t.url??"/","http://127.0.0.1")}catch{try{s.writeHead(400,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const n=u((t.method??"GET").toUpperCase(),T.pathname);if(n!==null){Ht(s,n.message);return}const l=F(t)??{class:"person"},f=Ee(l),g=o(()=>i.handle(t,s,c,l),"handled");(f===void 0?g():J(f,o(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(n){E(n)}},"onRequest"),w=o(async(t,s,c)=>{const p=F(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(s,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=o(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),_=o((t,s,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(s,503,"Service Unavailable","startup_blocked",O.message);return}const h=_t(t.method??"GET",p.pathname);if(h===null){s.destroy();return}const E=(()=>{const n=F(t);return n===void 0?void 0:Ee(n)})(),T=o(()=>w(t,s,h).then(n=>n?cr(t,s,c,h,async l=>{const f=F(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{s.destroy()}catch{}})}catch{try{s.destroy()}catch{}}},"onUpgrade"),Oe=o(t=>{t.on("error",s=>{A({event:"api.server.failed",level:"error",error:s})})},"bindErrorHandler"),Pe=o(async(t,s)=>{try{const c=await _e(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(s);return}if(c==="runtime_starting"){ke(s);return}B.set(t,c),Se(t,c),m(t,s,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),V(s)}},"onSocketRequest"),D=ie((t,s)=>{Pe(t,s).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ne=o(async(t,s,c)=>{try{const p=await _e(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(s,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(s,403,"Forbidden",L.code,L.message);return}B.set(t,p),_(t,s,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(s,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,s,c)=>{x(s),Ne(t,s,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),ve((t,s,c)=>{B.set(t,c),m(t,s,null)});let re=!1,te,ne;const Ie=new Promise((t,s)=>{te=t,ne=s});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{xe(d,process.platform==="linux"&&G("/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;const $=e.tcp??ar()??de("user").api.tcp;if($!==void 0&&$!==""){const t=wt($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const s=e.token??lr()??ir("user"),c=St(s),p=o(async(n,l)=>{if(Je(n)){await We(n,l);return}if(Ot(n,l))return;if(H()&&Ke(new URL(n.url??"/","http://runtime.local").pathname)){await kt(n,l);return}if(await It(n,l))return;const f={},g=await Te(n,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){Pt(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:n.method,listener:"tcp",path:new URL(n.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await Ct()(n,l,g.call)});return}B.set(n,g.principal),Se(n,g.principal),I(l),m(n,l,g.ceiling)},"tcpOnRequest"),O=o(async(n,l,f)=>{const g=pr(n);if(g!==null){const v=await ur(n,l,f,g);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const z=mr(n);if(z!==null){const v=fr(n,l,f,z);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const C=await Te(n,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",M.code,M.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(n,C.principal),_(n,l,f)},"tcpOnUpgrade"),h=o(n=>{A({event:"api.principal.failed",level:"error",error:n instanceof Error?n:new Error(String(n))})},"failed"),E=o((n,l)=>{p(n,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Ut();b=T===null?ie(E):Be(T,E),b.on("upgrade",(n,l,f)=>{x(l),O(n,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),Oe(b),b.once("listening",()=>{const n=b?.address();if(n!==null&&typeof n=="object"){const{address:l,port:f}=n;r=Et(l,f),l!=="0.0.0.0"&&l!=="::"&&dr(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ie,tcpAddress:o(()=>r,"tcpAddress"),close:o(async(t={})=>{if(!oe){oe=!0,ve(null),wr.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}o(So,"createApiServer");export{vt as buildRouter,Ue as closeServer,So as createApiServer,F as socketPrincipal};
|
|
@@ -11,9 +11,10 @@ export declare function cachedBrokerNodeFields(node: BrokerExtensionNodeDTO): Br
|
|
|
11
11
|
* (D39): a grant id, run or node id, structured request, queue, limit, or environment object. `fault_retry` carries a node id: the
|
|
12
12
|
* fault-retry backstop publishes it in the commit that claims the nudge, and the API process holding that node's stream turns it
|
|
13
13
|
* into a `fault-retry` line. `machine` carries a machine environment object id (a call is pending for the API process holding its link);
|
|
14
|
-
* `machine_call` carries a call id (the caller waiting on it re-reads the row).
|
|
14
|
+
* `machine_call` carries a call id (the caller waiting on it re-reads the row). `document` carries a document object id: it was edited or
|
|
15
|
+
* deleted, and a browser document stream re-reads it. The writers fire them (the
|
|
15
16
|
* schema's triggers, or the unit that owns the writer); the bus only delivers. */
|
|
16
|
-
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call"];
|
|
17
|
+
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document"];
|
|
17
18
|
export type BrokerSignalKind = (typeof BROKER_SIGNAL_KINDS)[number];
|
|
18
19
|
export type BrokerSignalSubscriber = (id: string, kind: BrokerSignalKind) => void;
|
|
19
20
|
export interface BrokerSignalSubscription {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|
|
1
|
+
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|