@north-light/cli 0.3.693 → 0.3.695
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/README.md +4 -7
- package/dist/api/command-manifest/result.d.ts +5 -5
- package/dist/api/command-manifest/result.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/run-events.d.ts +1 -0
- package/dist/api/dto/run-events.js +1 -0
- package/dist/api/dto/worktree.d.ts +0 -4
- package/dist/api/errors.js +1 -1
- package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
- package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
- package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
- package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
- package/dist/builtin-memory/crouter-sdk/README.md +14 -42
- package/dist/builtin-memory/crouter-sdk/client.md +5 -7
- package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
- package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
- package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
- package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
- package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
- package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
- package/dist/cli.js +6 -6
- package/dist/clients/attach/session/connection.d.ts +11 -2
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/pane-tag.d.ts +3 -3
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/viewer.js +538 -537
- package/dist/commands/node/inspect.js +9 -9
- package/dist/commands/node-worktree.js +1 -1
- package/dist/commands/pkg/market-manage.js +1 -1
- package/dist/commands/pkg/plugin-manage.js +1 -1
- package/dist/commands/surface/node/placement.d.ts +2 -2
- package/dist/commands/surface/node/placement.js +1 -1
- package/dist/commands/surface.js +1 -1
- package/dist/commands/sys/update.js +1 -1
- package/dist/core/broker-client/client.d.ts +6 -9
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/canvas.js +7 -7
- package/dist/core/canvas/types.d.ts +0 -2
- package/dist/core/config.js +1 -1
- package/dist/core/conversation-store/row-store.js +10 -10
- package/dist/core/graph/exposures.js +1 -1
- package/dist/core/graph/names.js +9 -9
- package/dist/core/graph/watches.js +1 -1
- package/dist/core/installed-plugins.js +1 -1
- package/dist/core/keybindings/attach-control.d.ts +3 -0
- package/dist/core/keybindings/attach-control.js +1 -1
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/ledger/chunks.d.ts +3 -1
- package/dist/core/ledger/chunks.js +2 -2
- package/dist/core/ledger/index.d.ts +1 -1
- package/dist/core/ledger/index.js +1 -1
- package/dist/core/ledger/read.d.ts +4 -0
- package/dist/core/ledger/read.js +2 -2
- package/dist/core/llm/run.js +2 -2
- package/dist/core/logged-step-timings.d.ts +7 -0
- package/dist/core/logged-step-timings.js +1 -0
- package/dist/core/permissions/evaluator.d.ts +2 -1
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/receipts.js +1 -1
- package/dist/core/runs/operations.js +8 -8
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/nodes.d.ts +1 -1
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -7
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/machine/runner.d.ts +0 -2
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/runtime/tmux-driver.d.ts +0 -10
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/scoped-state/imported-mac-installs.d.ts +12 -0
- package/dist/core/scoped-state/imported-mac-installs.js +2 -0
- package/dist/core/spaces/stop.js +1 -1
- package/dist/core/step-timings.d.ts +7 -1
- package/dist/core/step-timings.js +1 -1
- package/dist/core/worktree-close.js +4 -6
- package/dist/core/worktree-landing.d.ts +0 -38
- package/dist/core/worktree-landing.js +2 -3
- package/dist/core/worktree-sweep.d.ts +0 -1
- package/dist/core/worktree-sweep.js +4 -6
- package/dist/core/worktree.d.ts +0 -4
- package/dist/core/worktree.js +13 -15
- package/dist/daemon/api/app-listener.d.ts +1 -0
- package/dist/daemon/api/app-listener.js +10 -10
- package/dist/daemon/api/bridge.js +4 -4
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +3 -3
- package/dist/daemon/api/server.d.ts +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/cron/armed-context.js +1 -1
- package/dist/daemon/crtrd.js +20 -18
- package/dist/daemon/machine-link/client.d.ts +5 -1
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/holder.js +3 -3
- package/dist/daemon/pidfile.js +2 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/dist/daemon/runs/append-section.js +2 -2
- package/dist/daemon/runs/observer.js +3 -3
- package/dist/shared/env.d.ts +8 -3
- package/dist/shared/env.js +2 -2
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/docs/apps/guides/stream-a-run.md +6 -7
- package/docs/concepts/lifecycle-and-wakes.md +1 -1
- package/docs/concepts/nodes-and-the-canvas.md +2 -2
- package/docs/concepts/profiles-kinds-and-modes.md +1 -1
- package/docs/concepts/scopes-and-trust.md +1 -1
- package/docs/concepts/why-a-daemon.md +1 -1
- package/docs/sdk/README.md +13 -41
- package/docs/sdk/client.md +5 -7
- package/docs/sdk/docker.md +1 -1
- package/docs/sdk/errors.md +3 -43
- package/docs/sdk/getting-started.md +11 -83
- package/docs/sdk/release-notes.md +10 -0
- package/docs/sdk/resources.md +11 -44
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
- package/packages/crouter-api/dist/api/errors.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/connection.js +36 -1
- package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
- package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
- package/packages/crouter-api/dist/commands/node/inspect.js +16 -2
- package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
- package/packages/crouter-api/dist/commands/pkg/market-manage.js +22 -19
- package/packages/crouter-api/dist/commands/pkg/plugin-manage.js +2 -1
- package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
- package/packages/crouter-api/dist/commands/surface.js +2 -3
- package/packages/crouter-api/dist/commands/sys/update.js +5 -3
- package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
- package/packages/crouter-api/dist/core/canvas/canvas.js +6 -11
- package/packages/crouter-api/dist/core/config.js +10 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
- package/packages/crouter-api/dist/core/graph/exposures.js +1 -1
- package/packages/crouter-api/dist/core/graph/names.js +7 -20
- package/packages/crouter-api/dist/core/graph/watches.js +1 -1
- package/packages/crouter-api/dist/core/installed-plugins.js +3 -2
- package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
- package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
- package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
- package/packages/crouter-api/dist/core/ledger/index.js +1 -1
- package/packages/crouter-api/dist/core/ledger/read.js +18 -1
- package/packages/crouter-api/dist/core/llm/run.js +1 -1
- package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
- package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
- package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
- package/packages/crouter-api/dist/core/runs/operations.js +5 -4
- package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
- package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
- package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +4 -24
- package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
- package/packages/crouter-api/dist/core/scoped-state/imported-mac-installs.js +94 -0
- package/packages/crouter-api/dist/core/spaces/stop.js +2 -2
- package/packages/crouter-api/dist/core/step-timings.js +7 -2
- package/packages/crouter-api/dist/core/worktree-close.js +5 -51
- package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
- package/packages/crouter-api/dist/core/worktree.js +9 -74
- package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +13 -2
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +2 -0
- package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
- package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
- package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
- package/packages/crouter-api/dist/shared/env.js +15 -4
- package/packages/crouter-api/dist/types.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/serve.js +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
- package/dist/builtin-memory/crouter-sdk/files.md +0 -50
- package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
- package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
- package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
- package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
- package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
- package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
- package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
- package/dist/commands/surface-reload.d.ts +0 -7
- package/dist/commands/surface-reload.js +0 -1
- package/docs/sdk/bash.md +0 -39
- package/docs/sdk/files.md +0 -49
- package/docs/sdk/guides/README.md +0 -17
- package/docs/sdk/guides/event-driven-assistant.md +0 -24
- package/docs/sdk/guides/fan-out-pipeline.md +0 -24
- package/docs/sdk/guides/human-approval.md +0 -24
- package/docs/sdk/guides/typed-extraction.md +0 -24
- package/docs/sdk/nodes.md +0 -194
- package/docs/sdk/streaming.md +0 -149
- package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
|
@@ -1 +1 @@
|
|
|
1
|
-
var He=Object.defineProperty;var o=(e,r)=>He(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as Le,importPrincipalFor as Be}from"./import-auth.js";import{createServer as se}from"node:http";import{createServer as xe}from"node:https";import{chmodSync as De,existsSync as Y,readFileSync as ae,unlinkSync as le}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as ce,RUNTIME_VERSION_HEADER as K,minimumRuntimeRefusal as Fe}from"../../api/runtime-version.js";import{CONTRACT_HEADER as X,CONTRACT_LEVEL as ue,REQUIRED_CONTRACT_HEADER as pe,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as Z}from"../../shared/crtr-version.js";import{apiSocketPath as $e}from"../../core/canvas/paths.js";import{resolveNodeToken as Je}from"../../core/canvas/node-tokens.js";import{isCloudRole as N,runAsPerson as W}from"../../core/canvas/person.js";import{isCanvasRequest as We,serveCanvas as je}from"./canvas-host.js";import{personBearerVerifier as de}from"./auth/person-bearer.js";import{personHasSnapshot as Q}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Ve}from"./principal.js";import{createAppRequestHandler as Ge}from"./app-listener.js";import{decodeJwt as Ye}from"jose";import{handleRuntimeSignIn as Ke,isRuntimeSignInPath as Xe}from"./key-signin.js";import{RunError as b}from"../../core/runs/operations.js";import{createRepoPluginHandler as Ze,isRepoPluginPath as Qe}from"./repo-plugin.js";import{removeVendorAccount as qe,vendorStatus as er}from"./handlers/vendor-status.js";import{toErrorBody as rr}from"./map.js";import{CONTROL_BODY_MAX_BYTES as tr}from"../../core/llm/body-limits.js";import{grantFor as nr,hasSyncedGrants as or}from"../../core/grants/mirror.js";import{readConfig as fe}from"../../core/config.js";import{directoryIssuer as ir}from"../../core/directory/issuer.js";import{peerUid as sr}from"../../native/linux.js";import{findScopedApiToken as ar,getApiToken as lr,listScopedApiTokens as cr}from"../../core/secrets.js";import{emitEvent as y}from"../../core/events/emit.js";import{envCrtrdTcp as ur,envCrtrdToken as pr}from"../../shared/env.js";import{Router as me,actsAsPerson as ge}from"./router.js";import{handleAttachUpgrade as dr,refuseUpgrade as v}from"./bridge.js";import{handleMachineLinkUpgrade as fr,machineLinkEnvironment as mr,setApiAddress as gr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as hr,machineViewEnvironment as Rr}from"../machine-link/forward.js";import{boundDaemonControl as Ar}from"../control.js";import{attachRoutes as yr,mayAttachNode as he}from"./handlers/attach.js";import{peerRoutes as vr}from"../peer/handlers.js";import{bashJobRoutes as _r}from"./handlers/bash-jobs.js";import{nodeFileRoutes as wr}from"./handlers/node-files.js";import{bashRoutes as Er}from"./handlers/bash.js";import{hookExecRoutes as Sr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as Re}from"./handlers/broker-ops.js";import{brokerSignalRoutes as br,brokerSignalStreams as Tr}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Ae,nodeFaultRoutes as Cr}from"./handlers/broker-recovery.js";import{canvasRoutes as kr}from"./handlers/canvas.js";import{conversationRoutes as Pr}from"./handlers/conversations.js";import{chatInventoryRoutes as Ur}from"./handlers/chat-inventory.js";import{daemonRoutes as Or}from"./handlers/daemon.js";import{fileRoutes as Nr}from"./handlers/files.js";import{focusRoutes as Ir}from"./handlers/focus.js";import{analyticsRoutes as zr}from"./handlers/analytics.js";import{memoryReadsRoutes as Hr}from"./handlers/memory-reads.js";import{memoryRoutes as Lr}from"./handlers/memory.js";import{healthRoutes as Br}from"./handlers/health.js";import{humanRequestRoutes as xr}from"./handlers/human-requests.js";import{inboxRoutes as Dr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Fr}from"./handlers/feedback-comments.js";import{objectRoutes as Mr}from"./handlers/objects.js";import{shareRoutes as $r}from"./handlers/shares.js";import{customObjectRoutes as Jr}from"./handlers/custom-objects.js";import{docRoutes as Wr}from"./handlers/docs.js";import{deliveryRoutes as ye}from"./handlers/delivery.js";import{deliveryRetryRoutes as jr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Vr}from"./handlers/package-docs.js";import{documentAccessRoutes as Gr}from"./handlers/document-access.js";import{pluginAppRoutes as Yr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ve,messageRoutes as Kr}from"./handlers/messages.js";import{modelAuthRoutes as Xr}from"./handlers/modelauth.js";import{llmRoutes as Zr}from"./handlers/llm.js";import{providerRoutes as Qr}from"./handlers/providers.js";import{modelConfigRoutes as qr}from"./handlers/model-config.js";import{settingsRoutes as et}from"./handlers/settings.js";import{nodeRoutes as rt}from"./handlers/nodes.js";import{nodeRecordRoutes as tt}from"./handlers/node-records.js";import{nodeOutcomeRoutes as nt}from"./handlers/node-outcomes.js";import{nodeEventRoutes as ot}from"./handlers/node-events.js";import{profileRoutes as it}from"./handlers/profiles.js";import{environmentRoutes as st}from"./handlers/environments.js";import{prospectiveChatInventoryRoutes as at}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as lt}from"./handlers/reports.js";import{runRoutes as ct}from"./handlers/run-routes.js";import{reviewCommentRoutes as ut}from"./handlers/review-comments.js";import{reviewRoutes as pt}from"./handlers/reviews.js";import{subscriptionRoutes as dt}from"./handlers/subscriptions.js";import{structuredRequestRoutes as ft}from"./handlers/structured-requests.js";import{cronRoutes as mt}from"./handlers/crons.js";import{setCronRequestHandler as _e}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as gt,cronPrincipalForRunToken as ht}from"../cron/run-token.js";import{worktreeRoutes as Rt}from"./handlers/worktree.js";import{limitsRoutes as At}from"./handlers/limits.js";import{chargeRoutes as yt,spendLimitRoutes as vt}from"./handlers/charges.js";import{executionStartRoutes as _t}from"./handlers/execution-start.js";import{machineCredentialRoutes as wt}from"./handlers/machine-credential.js";import{importRoutes as Et}from"./handlers/imports.js";import{gitCredentialRoutes as St}from"./handlers/git-credential.js";function bt(e){return new me().registerAll(Br(e)).registerAll(Or).registerAll($r).registerAll(rt).registerAll(tt).registerAll(nt).registerAll(jr).registerAll(ot).registerAll(_r).registerAll(wr).registerAll(Er).registerAll(Sr).registerAll(Re).registerAll(br).registerAll(ye).registerAll(Ae).registerAll(Cr).registerAll(Rt).registerAll(At).registerAll(yt).registerAll(_t).registerAll(wt).registerAll(Et).registerAll(St).registerAll(vt).registerAll(ve).registerAll(Kr).registerAll(lt).registerAll(ct).registerAll(ft).registerAll(yr).registerAll(kr).registerAll(Pr).registerAll(zr).registerAll(Hr).registerAll(Lr).registerAll(Nr).registerAll(Mr).registerAll(Jr).registerAll(Wr).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(Ir).registerAll(dt).registerAll(mt).registerAll(it).registerAll(st).registerAll(Xr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(et).registerAll(pt).registerAll(ut).registerAll(Dr).registerAll(xr).registerAll(Ur).registerAll(at).registerAll(Fr).registerAll(vr)}o(bt,"buildRouter");function Tt(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 s=i[2];return s===void 0||s===""?null:decodeURIComponent(s)}o(Tt,"attachNodeId");function Ct(e){const r=e.trim();if(r==="")return null;const i=r.lastIndexOf(":");if(i<0)return null;const s=r.slice(0,i),u=r.slice(i+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:s===""?"0.0.0.0":s,port:d}}o(Ct,"parseTcp");function kt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(kt,"formatTcpAddress");const I={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"},ee={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function $(e){return B.get(e)}o($,"socketPrincipal");async function we(e,r){const i=process.platform==="linux"?sr(e.socket):null,s=e.headers.authorization;if(s===void 0)return i===null||r.has(i)?{class:"person"}:"unauthorized";if(typeof s!="string"||!s.startsWith("Bearer "))return"unauthorized";if(s.slice(7).startsWith("crtr_pub_"))return ee;if(s.slice(7).startsWith(re)){const u=Te(s.slice(7));return u!==void 0&&(i===null||r.has(i))?u.principal:"unauthorized"}return Ee(s.slice(7),i)}o(we,"resolveSocketPrincipal");async function Ee(e,r){const i=await Je(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const s=ir();if(s&&!N()&&!await or(s))return"runtime_starting";const u=i.grant??(await nr("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:u}}o(Ee,"brokerPrincipal");function Se(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(Se,"requestPerson");function be(e,r){r.class==="broker"&&y({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(be,"noteBrokerRequest");const re="crtr_app_";function Te(e){const r=e.startsWith(re)?ar(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(Te,"appBearer");function Pt(e){const r=new Map;for(const i of cr("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(Pt,"resolveBearers");function Ut(e){try{return Ye(e).act!==void 0}catch{return!1}}o(Ut,"carriesAct");const Ot=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function P(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(P,"deny");async function Ce(e,r,i){const s=e.headers.authorization;if(s===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:ee,ceiling:null};if(typeof s!="string"||!s.startsWith("Bearer "))return P(i,s===void 0?"no_authorization_header":"not_a_bearer");const u=s.slice(7);if(u.startsWith("crtr_pub_"))return{principal:ee,ceiling:null};if(u.startsWith(re))return Te(u)??P(i,"app_token_unknown");if(u.startsWith(gt)){const E=await ht(u);return E===null?P(i,"run_token_invalid_or_settled"):{principal:E,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Be(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(Le))return P(i,"import_token_invalid");if(Ot.test(u)){if(N()&&Ut(u)){const x=V();if(x===null)return"person_bearer";try{const w=await x.verifyCall(s);return w.chain[0]?.sub.startsWith("app:")?{call:w}:P(i,"call_token_presenter_not_an_app")}catch(w){return w instanceof b&&w.status===503?"runtime_starting":P(i,`call_token_${w instanceof b?w.code:"invalid"}`)}}const E=N()?de():null;if(E===null)return"person_bearer";const U=await E.verify(u);return U===null?P(i,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await Ee(u,null);return m==="unauthorized"?P(i,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}o(Ce,"authorizeTcp");let j;function V(){if(j!==void 0)return j;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return j=e===void 0||r===void 0?null:new Ve(e,r,async()=>{}),j}o(V,"cloudCallResolver");let ke;function Nt(){const e=V();if(e===null)throw new b(503,"runtime_starting","app calls are not configured on this listener");return ke??=Ge(e,async()=>!0,async()=>{}),ke}o(Nt,"cloudAppCalls");async function It(e,r){z(r),H(r);const i=V();try{if(i===null)throw new b(503,"runtime_starting","sign-in is not configured on this listener");await Ke(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(s){if(!(s instanceof b))throw s;if(r.headersSent){r.destroy();return}r.writeHead(s.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:s.code,message:s.message,...s.param?{param:s.param}:{},origin:"runtime"}}))}}o(It,"serveRuntimeSignIn");function zt(){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:ae(e),key:ae(r)}}o(zt,"tcpTls");function z(e){e.setHeader(K,Z()),e.setHeader(X,ue)}o(z,"advertiseRuntime");function H(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${K}, ${X}`)}o(H,"exposeRuntimeHeaders");function Ht(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(z(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${K}, ${X}`,"Access-Control-Allow-Headers":`authorization, content-type, ${ce.toLowerCase()}, ${pe.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(Ht,"answerPreflight");function G(e,r=!1){z(e),r&&H(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...I,origin:"runtime"}}))}o(G,"writeUnauthorized");function Lt(e){z(e),H(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}o(Lt,"writePersonBearerRefused");const Bt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function xt(e,r){if(!N())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,s=Bt[i];if(s===void 0||e.method!==s.method)return!1;const u=o((d,R)=>{z(r),H(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=de();if(d===null)throw new b(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),s.purpose):null;if(m===null)throw new b(401,"unauthorized","invalid directory token");const E=s.purpose==="vendor_status"?void 0:await Dt(e);u(200,await W(m,async()=>s.purpose==="vendor_status"?er():await qe(E)))}catch(d){const{status:R,body:m}=rr(d);u(R,m)}return!0}o(xt,"serveCloudVendorRoute");async function Dt(e){const r=[];let i=0;for await(const s of e){if(i+=s.length,i>tr)throw new b(400,"invalid_request","request body too large");r.push(s)}if(i!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new b(400,"invalid_request","invalid JSON body")}}o(Dt,"readVendorBody");function Pe(e){z(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(Pe,"writeRuntimeStarting");function Ft(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(Ft,"writeStartupBlocked");function Ue(e,r,i){return new Promise(s=>{for(const m of r)m.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>s());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);s()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),i);u.push(d,R),e.closeIdleConnections()})}o(Ue,"closeServer");function No(e={}){let r=null;const i=bt(()=>r),s=new me().registerAll(Re).registerAll(ye).registerAll(Ae).registerAll(ve),u=o((t,n)=>{const c=Ar()?.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"&&s.match(t,n)!==null?null:c},"startupBlockFor"),d=e.socketPath??$e(),R=new Set([process.getuid?.()??0,...fe("user").runtime?.person_uids??[]]),m=o((t,n,c)=>{z(n);const p=o(f=>Array.isArray(f)?f[0]:f,"first"),O=p(t.headers[ce.toLowerCase()]),A=Fe(O,Z())??Me(p(t.headers[pe.toLowerCase()]),ue,{legacyMinimum:O,runtimeVersion:Z()});if(A!==null){n.writeHead(A.status,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:A.code,message:A.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in A?{param:A.param}:{details:A.details}}}));return}const S=o(f=>{const l=$(t);y({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:f instanceof Error?f:new Error(String(f))});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 C;try{C=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 f=u((t.method??"GET").toUpperCase(),C.pathname);if(f!==null){Ft(n,f.message);return}const l=$(t)??{class:"person"},a=Se(l),g=o(()=>i.handle(t,n,c,l),"handled");(a===void 0?g():W(a,o(async()=>{Q()||await q(a),await g()},"handledAsPerson"))).catch(S)}catch(f){S(f)}},"onRequest"),E=o(async(t,n,c)=>{const p=$(t);return p===void 0||ge(p)||await he(p,"either",c)?!0:(v(n,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"),w=o((t,n,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){v(n,503,"Service Unavailable","startup_blocked",O.message);return}const A=Tt(t.method??"GET",p.pathname);if(A===null){n.destroy();return}const S=(()=>{const f=$(t);return f===void 0?void 0:Se(f)})(),C=o(()=>E(t,n,A).then(f=>f?dr(t,n,c,A,async l=>{const a=$(t);return a===void 0||ge(a)||await he(a,l,A)}):void 0),"attach");(S===void 0?C():W(S,async()=>{Q()||await q(S),await C()})).catch(()=>{try{n.destroy()}catch{}})}catch{try{n.destroy()}catch{}}},"onUpgrade"),Oe=o(t=>{t.on("error",n=>{y({event:"api.server.failed",level:"error",error:n})})},"bindErrorHandler"),Ne=o(async(t,n)=>{try{const c=await we(t,R);if(c==="unauthorized"){y({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),G(n);return}if(c==="runtime_starting"){Pe(n);return}B.set(t,c),be(t,c),m(t,n,c.class==="app"?c.scopes:null)}catch(c){y({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),G(n)}},"onSocketRequest"),D=se((t,n)=>{Ne(t,n).catch(c=>y({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ie=o(async(t,n,c)=>{try{const p=await we(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&y({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),v(n,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){v(n,403,"Forbidden",L.code,L.message);return}B.set(t,p),w(t,n,c)}catch(p){y({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),v(n,401,"Unauthorized",I.code,I.message)}},"onSocketUpgrade");D.on("upgrade",(t,n,c)=>{x(n),Ie(t,n,c).catch(p=>y({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),_e((t,n,c)=>{B.set(t,c),m(t,n,null)});let te=!1,ne,oe;const ze=new Promise((t,n)=>{ne=t,oe=n});D.once("listening",()=>{te=!0,ne()}),D.on("error",t=>{y({event:"api.server.failed",level:"error",error:t}),te||oe(t)});try{Y(d)&&le(d)}catch{}D.listen(d,()=>{try{De(d,process.platform==="linux"&&Y("/run/crtr/launcher.sock")?438:384)}catch(t){y({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let T;const J=e.tcp??ur()??fe("user").api.tcp;if(J!==void 0&&J!==""){const t=Ct(J);if(t===null)y({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${J}`)});else{N()&&V();const n=N()?Ze():null,c=e.token??pr()??lr("user"),p=Pt(c),O=o(async(l,a)=>{if(We(l)){await je(l,a);return}if(Ht(l,a))return;if(N()&&Xe(new URL(l.url??"/","http://runtime.local").pathname)){await It(l,a);return}if(await xt(l,a))return;if(n!==null&&Qe(new URL(l.url??"/","http://runtime.local").pathname)){await n(l,a);return}const g={},h=await Ce(l,p,g);if(h==="runtime_starting"){H(a),Pe(a);return}if(h==="person_bearer"){Lt(a);return}if(h==="unauthorized"){y({event:"api.principal.denied",level:"warn",fields:{method:l.method,listener:"tcp",path:new URL(l.url??"/","http://runtime.local").pathname,reason:g.reason??"unknown"}}),G(a,!0);return}if("call"in h){H(a);const F=h.call.sub;await W(F,async()=>{Q()||await q(F),await Nt()(l,a,h.call)});return}B.set(l,h.principal),be(l,h.principal),H(a),m(l,a,h.ceiling)},"tcpOnRequest"),A=o(async(l,a,g)=>{const h=mr(l);if(h!==null){const _=await fr(l,a,g,h);_!==null&&v(a,_.status,_.text,_.code,_.message);return}const F=Rr(l);if(F!==null){const _=hr(l,a,g,F);_!==null&&v(a,_.status,_.text,_.code,_.message);return}const k=await Ce(l,p);if(k==="runtime_starting"){v(a,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(k==="person_bearer"){v(a,401,"Unauthorized",M.code,M.message);return}if(k==="unauthorized"){v(a,401,"Unauthorized",I.code,I.message);return}if("call"in k){v(a,403,"Forbidden",L.code,L.message);return}if(k.ceiling!==null||k.principal.class==="anonymous"||k.principal.class==="import"){v(a,403,"Forbidden",L.code,L.message);return}B.set(l,k.principal),w(l,a,g)},"tcpOnUpgrade"),S=o(l=>{y({event:"api.principal.failed",level:"error",error:l instanceof Error?l:new Error(String(l))})},"failed"),C=o((l,a)=>{O(l,a).catch(g=>{S(g),a.headersSent?a.destroy():G(a,!0)})},"listener"),f=zt();T=f===null?se(C):xe(f,C),T.on("upgrade",(l,a,g)=>{x(a),A(l,a,g).catch(h=>{S(h),v(a,401,"Unauthorized",I.code,I.message)})}),Oe(T),T.once("listening",()=>{const l=T?.address();if(l!==null&&typeof l=="object"){const{address:a,port:g}=l;r=kt(a,g),a!=="0.0.0.0"&&a!=="::"&&gr(r)}}),T.listen(t.port,t.host)}}let ie=!1;return{ready:ze,tcpAddress:o(()=>r,"tcpAddress"),close:o(async(t={})=>{if(!ie){ie=!0,_e(null),Tr.close(),await Promise.all([Ue(D,U,t.graceMs),T!==void 0?Ue(T,U,t.graceMs):Promise.resolve()]);try{Y(d)&&le(d)}catch{}}},"close")}}o(No,"createApiServer");export{bt as buildRouter,Ue as closeServer,No as createApiServer,$ 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{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{importRoutes as kt}from"./handlers/imports.js";import{gitCredentialRoutes as Pt}from"./handlers/git-credential.js";function Ut(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(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(Ut,"buildRouter");function Ot(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(Ot,"attachNodeId");function Nt(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(Nt,"parseTcp");function It(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}i(It,"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 Ht(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(Ht,"resolveBearers");function zt(e){try{return qe(e).act!==void 0}catch{return!1}}i(zt,"carriesAct");const Lt=/^[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(Lt.test(u)){if(I()&&zt(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 Bt(){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(Bt,"cloudAppCalls");async function xt(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(xt,"serveRuntimeSignIn");function Dt(){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(Dt,"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 Ft(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(Ft,"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 Mt(e){H(e),z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...$,origin:"runtime"}}))}i(Mt,"writePersonBearerRefused");const $t={"/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=$t[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 Wt(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 Wt(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(Wt,"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 jt(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(jt,"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 Bo(e={}){let r=null;const s=Ut(()=>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){jt(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=Ot(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=Nt(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=Ht(c),N=i(async(o,l)=>{if(V(o),Ke(o)){await Xe(o,l);return}if(Ft(o,l))return;if(I()&&rr(new URL(o.url??"/","http://runtime.local").pathname)){await xt(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"){Mt(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 Bt()(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=Dt();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=It(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(Bo,"createApiServer");export{Ut as buildRouter,He as closeServer,Bo as createApiServer,J as socketPrincipal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var o=(r,e)=>m(r,"name",{value:e,configurable:!0});import{envHomeOverride as _}from"../../shared/env.js";import{loadProfileManifest as v,lookupProfile as h}from"../../core/profiles/manifest.js";import{localEnvironmentSecrets as R}from"../../core/secrets/environment-owner.js";import{ADMITTED_HOST_PATH_ENV as f,buildOperationalEnvBase as g}from"../../core/runtime/spawn-env.js";import{getNode as c}from"../../core/canvas/canvas.js";import{contextDir as w}from"../../core/canvas/paths.js";import{appendRunEvent as y}from"../../core/runs/events.js";import{payerOfGrant as O}from"../../core/grants/mirror.js";import{ZERO_RUN_USAGE as E}from"../../api/dto/run-events.js";import{scopeAllowed as b}from"../../core/scopes.js";import{cronPrincipalOf as x}from"./authority.js";import{personId as C}from"../../core/canvas/person.js";function p(r){if(r.profile==null)return null;let e;try{e=h(r.profile)}catch{return null}if(e.kind==="resolved")return e.entry.profileId;if(e.kind==="absent")return null;throw new l(`the armed profile "${r.profile}" is still on this host but its manifest could not be read (${e.manifestPath}) \u2014 running as root would silently give this cron a different identity, env store, and purview. Repair the manifest, or re-arm the cron under a profile that resolves.`)}o(p,"resolveLiveProfile");function J(r){return{...x(r),cron_id:r.cron_id,origin_run_id:r.origin_run_id,isolated:r.isolated,creator:r.created_by}}o(J,"cronBirthPrincipalOf");async function U(r,e){const n=r.creator===null?null:await c(r.creator);return n!==null&&r.origin_run_id!==null&&n.run_id===r.origin_run_id&&(await c(r.origin_run_id))?.deleting_at==null&&n.grantee===r.grantee&&(n.sub??C())===r.sub&&(n.grant_id??null)===r.grant_id&&(r.scopes===null?n.scopes==null:r.scopes.every(t=>b(n.scopes,t)))?{parent:n.node_id,...r.scopes===null?{}:{scopes:[...r.scopes]}}:{root:!0,rootLifecycle:"terminal",...r.scopes===null?{}:{scopes:[...r.scopes]},run:{grantee:r.grantee,sub:r.sub,grant_id:r.grant_id,client_id:null,metadata_json:JSON.stringify(r.cron_id===null?{exec:!0}:{cron_id:r.cron_id}),run_id:e,event_cursor:1},withinCreate:o(async(t,s)=>{await y(t,e,e,"run.started",{scopes:s.scopes??null,payer:await O(r.grant_id),usage:E})},"withinCreate")}}o(U,"cronBirthPlacement");function G(r){try{return p(r)}catch{return null}}o(G,"resolveLiveProfileOrRoot");function F(r){if(r.profile!=null)try{return v(r.profile).manifest.name}catch{return}}o(F,"resolveLiveProfileName");class l extends Error{static{o(this,"ArmedContextError")}constructor(e){super(e),this.name="ArmedContextError"}}function N(r){if(r==null)return{};let e;try{e=JSON.parse(r)}catch(i){throw new l(`the armed env snapshot is not valid JSON (${i.message}) \u2014 this cron's stored env_json is corrupt, so the run would silently drop every armed variable. Re-arm the cron with a valid --env.`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new l("the armed env snapshot is not a JSON object \u2014 this cron's stored env_json is corrupt. Re-arm the cron with a valid --env.");const n={};for(const[i,t]of Object.entries(e)){if(typeof t!="string")throw new l(`the armed env snapshot's value for "${i}" is not a string \u2014 this cron's stored env_json is corrupt, so the run would silently drop that variable. Re-arm the cron with a valid --env.`);n[i]=t}return n}o(N,"parseArmedEnv");async function V(r,e){const n=N(r.env_json),i=r.grantee==="app:terminal",t=i?p(r):null,s=g({targetCwd:r.cwd,targetProfileId:t,skipSpawnAllow:!i}),a={...s,...await R(t,r.grantee),...n,...t!==null?{CRTR_PROFILE_ID:t}:{},CRTR_CRON_ID:r.cron_id,CRTR_CRON_NAME:r.name,CRTR_RUN_ID:e},u=_();if(u!==void 0&&u!==""&&(a.CRTR_HOME=u),r.anchor_node!=null){a.CRTR_ANCHOR=r.anchor_node;const d=await c(r.anchor_node);d!==null&&(a.CRTR_CONTEXT_DIR=w(d.node_id,d.grantee))}return a[f]=s[f],{profileId:t,env:a}}o(V,"buildArmedRunContext");export{l as ArmedContextError,V as buildArmedRunContext,U as cronBirthPlacement,J as cronBirthPrincipalOf,N as parseArmedEnv,p as resolveLiveProfile,F as resolveLiveProfileName,G as resolveLiveProfileOrRoot};
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
|
-
var cr=Object.defineProperty;var s=(e,c)=>cr(e,"name",{value:c,configurable:!0});import{applyBootSettings as lr}from"./boot-settings.js";import{startPeerOutbox as dr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as pr}from"./peer/relay-service.js";import{writeFileSync as fr,readFileSync as ur,rmSync as hr,mkdirSync as Ee,existsSync as R,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as wr}from"node:path";import{envCrtrdTcp as De,envDocumentPort as vr}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 Te}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 Pr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Er}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Le}from"../core/layout.js";import{migrateLooseKeys as Dr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Tr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Lr,listNodesForSupervision as $e,listParkedResidentsWithWakeMail as $r,setFrozen as Ae}from"../core/canvas/index.js";import{createApiServer as Ar,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{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Gr}from"./api/document-secret.js";import{createAppListener as Fr}from"./api/app-listener.js";import{registerMachineEnvironment as Br}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Hr}from"../core/secrets/blaxel-register.js";import{markCloudRole as jr,resolvePerson as zr,retireLocalPerson as Ur,setPersonId as qr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as Wr}from"../core/permissions/boot.js";import{startRunNotices as Jr}from"./run-notices.js";import{startGrantEffects as Kr}from"./reconcilers/grant-effects.js";import{syncPackages as Vr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Yr}from"../core/model-auth/activations.js";import{createGrantSync as Qr,GRANT_SYNC_INTERVAL_S as Oe}from"../core/grants/sync.js";import{sweepSandboxes as Xr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Zr}from"./cron/run-socket.js";import{hasSyncedGrants as et}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as rt}from"./human/sweep.js";import{resetHandedOffDeliveries as tt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as nt}from"../core/canvas/daemon-actions.js";import{sweepReviews as ot}from"./review/sweep.js";import{pidfilePath as pe}from"./pidfile.js";import{rendererWarning as it}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as at}from"./supervise-cadence.js";import{createResumeDetector as st}from"./resume-detector.js";import{setFatalFaultAnnouncer as ct}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as lt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as dt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as mt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as pt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as yt,migrateLegacyExecutionIdentities as St}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as Pt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Et}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as It}from"../core/ledger/rates.js";import{IdleSandboxReconciler as xt}from"./reconcilers/idle-sandbox.js";import{LedgerSandboxReconciler as Dt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Tt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Ct}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Lt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as $t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as At}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Nt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Mt,subscribeImageBuilt as Ot}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Gt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ge,capturePidCommand as Ft,captureTeardownSnapshot as Fe,isPidAlive as Bt,isAnyPidAlive as Be,killProcessTreePids as He}from"../core/canvas/pid.js";import{bindFleet as Ht,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as jt,clearDaemonControl as zt}from"./control.js";import{execDaemon as Ut,spawnDaemon as qt}from"./manage.js";import{reconcileAndMigrateBoot as Wt}from"../core/canvas/boot.js";import{resolveInstallId as Jt}from"../core/canvas/install-id.js";import{setInstallId as Kt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Vt,daemonOwnershipApplies as Yt,daemonOwnershipClaimed as Qt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Xt,closeAllDbs as ue,openDb as Zt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as en}from"../core/canvas/import-sqlite.js";import{ensurePostgres as rn,ensurePostgresHealthy as tn,stopPostgres as nn,withPostgresStartLock as on}from"./postgres/index.js";import{brokerSignalBus as N}from"./broker-signals/bus.js";import{brokerSignalStreams as an}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as sn}from"./api/handlers/broker-ops.js";import{reconcilePackages as cn}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as ln}from"../core/scoped-state/migrate-app-installs.js";import{publish as dn,readBuiltinSnapshot as mn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as pn,reapStaleSpares as fn}from"../core/runtime/warm-pool.js";import{DaemonFleet as un}from"./fleet.js";import{copyNodeFilesToRows as hn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as wn}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 vn}from"../core/events/source.js";import{activateCanvasImport as gn,MigrationBlockedError as yn,runForcedCanvasImport as Sn}from"../migrations/activation.js";import{adoptInstallPerson as _n,convertLegacyScopedStore as bn,personStoresCopied as kn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Rn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as Ue,installPreludeSnapshot as Pn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as qe}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as la}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const En=5e3,We=150;async function In(e){const c=Ge();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[r,d]of c.processes){const S=d.command;if(d.zombie||!S.includes("broker-cli.js")||!ve(S,f)||ge(S)===e)continue;const P=S.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||p.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of p){const d=Ft(r.pid);if(d===null||!d.includes("broker-cli.js")||!ve(d,f)||ge(d)===e||d.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const S=Fe(r.pid,null);if(!S.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:S})}}const h=Date.now()+En;for(;Date.now()<h&&i.some(r=>Be(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,We));let g=0;for(const r of i){const d=r.snap.tree.length>0?r.snap.tree:[r.pid];Be(d)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):He(d,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,We));const l=Ge();if(l===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[r,d]of l.processes){const S=d.command;d.zombie||!S.includes("broker-cli.js")||ve(S,f)&&ge(S)!==e&&u.push(r)}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:v,sigkilled:g}})}s(In,"reapPriorEpochBrokers");const xn=5e3;async function Dn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Cr(i))?.status;(h==="active"||h==="idle")&&await Ae(i,new Date().toISOString())}const f=c.map(([,i])=>({pid:i.pid,snap:Fe(i.pid,null),exited:i.handle.exited}));for(const i of f)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const p=new Promise(i=>{setTimeout(i,xn).unref()});await Promise.allSettled(f.map(i=>Promise.race([i.exited.then(()=>{}),p])));const v=[];for(const i of f)Bt(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):He(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await vt(i,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:v.length}})}s(Dn,"teardownFleet");function Je(){Ee(wr(pe()),{recursive:!0}),fr(pe(),String(process.pid),"utf8")}s(Je,"writePidfile");function Ke(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ke,"isMissingPathError");function Ve(e){const c=pe();let f;try{f=ur(c,"utf8")}catch(p){if(Ke(p))return;throw p}if(f.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{hr(c)}catch(p){if(Ke(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const Tn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},Q=new lt;ct(e=>Q.handleFatalFault(e,!1));const Cn=new mt,Ln=new dt,Ye=new pt,$n=new ft,An=new ut,Nn=new ht,Mn=new wt,On=new bt,Gn=new kt,Fn=new Rt,Bn=new Et,Hn=new Pt,jn=new Dt,zn=new xt,Un=new Tt,qn=new Ct,Wn=new Lt,Jn=new $t,Kn=new At,Vn=new Nt,Yn=new Mt;async function Qn(e=Date.now(),c=Tn){const f=je(),p=await Q.runFleetPreamble(f);let v,i,h;try{i=await fe();const l=(await $e()).filter(r=>!i.has(r.node_id));v=l.filter(r=>r.status==="active"||r.status==="idle"),h=l.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const u=new Set(h.map(r=>r.node_id));h.push(...(await $r()).filter(r=>!u.has(r.node_id)&&!i.has(r.node_id)))}catch(l){m({level:"error",event:"canvas.node_list.failed",error:l});return}await Q.run(e,{rows:v,fleet:f,lifecycle:c,held:i}),await Cn.run(e,{rows:v,held:i}),await Ln.run(e);const g=await Ye.run(e,{rows:[...v,...h],fleet:f});await $n.run(e,i),await Vn.run(e,i),await Yn.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c,held:i}),await Nn.run(e,{lifecycle:c}),await Mn.run(e,{lifecycle:c}),await On.run(e,{lifecycle:c}),await Gn.run(e,{lifecycle:c,fleet:f,held:i}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),jn.run(e,{lifecycle:c}),zn.run(e,{lifecycle:c}),Un.run(e,{lifecycle:c}),qn.run(e,{lifecycle:c}),Wn.run(e,{lifecycle:c}),await _r(),Kn.run(e,{fleet:f,lifecycle:c}),await Jn.run(e,{rows:v}),Q.warnIfSaturated({fleet:f,lifecycle:c,thresholds:p,frozen:g})}s(Qn,"superviseTick");async function Xn(e,c=Date.now()){if((await fe()).has(e))return;const f=await yt(e);if(f===null||!gt(f))return;const p=await Lr(e);p===null||p.kind==="human"||await Ye.runNode(c,p,je())}s(Xn,"exitedNodePass");function X(e){return e===void 0||e==="reconcile"}s(X,"roleRunsLanes");function M(e){return e===void 0||e==="api"}s(M,"roleServesRequests");const Zn=66e4;function eo(e){const c=new Nr().registerAll(Mr(()=>null).filter(r=>r.pattern==="/healthz")),f=s((r,d)=>{const S=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&S==="/healthz"){c.handle(r,d,null,{class:"person"});return}d.writeHead(404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=Ce();R(p)&&Ie(p);const v=Y(f),i=new Promise((r,d)=>{v.once("error",d),v.listen(p,()=>{v.off("error",d),xe(p,384),r()})});let h,g=null;const l=e.tcp??De()??me("user").api.tcp;if(l!==void 0&&l!==""){const r=/^(.*):(\d+)$/.exec(l.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${l}`);const d=Y(f);d.on("error",S=>m({event:"api.server.failed",level:"error",error:S})),d.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=d}let u=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!u){u=!0,await Promise.all([Ne(v,new Set,r.graceMs),h===void 0?Promise.resolve():Ne(h,new Set,r.graceMs)]);try{R(p)&&Ie(p)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){Ee(Le(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Le(),493);const c=Ce();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Y((l,u)=>{if(l.method==="GET"&&l.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((l,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),l()})});let p;const v=e.tcp??De();if(v){const l=/^(.*):(\d+)$/.exec(v);if(!l||Number(l[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const u=Y(f.listeners("request")[0]);await new Promise((r,d)=>{u.once("error",d),u.listen(Number(l[2]),l[1],()=>{u.off("error",d),r()})}),p=u}Je();let i;const h=s(()=>(i??=(async()=>{f.closeAllConnections(),p?.closeAllConnections(),await Promise.all([f,p].filter(l=>l!==void 0).map(l=>new Promise((u,r)=>l.close(d=>d?r(d):u())))),Ve(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),l=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(l)}
|
|
2
|
-
|
|
3
|
-
`)},"
|
|
4
|
-
`);
|
|
5
|
-
`),
|
|
6
|
-
`);
|
|
7
|
-
`)
|
|
8
|
-
`)
|
|
9
|
-
`);
|
|
10
|
-
`);for(const
|
|
11
|
-
`);for(const
|
|
12
|
-
`);for(const
|
|
13
|
-
`)
|
|
14
|
-
`)
|
|
1
|
+
var cr=Object.defineProperty;var s=(e,l)=>cr(e,"name",{value:l,configurable:!0});import{applyBootSettings as lr}from"./boot-settings.js";import{startPeerOutbox as dr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as pr}from"./peer/relay-service.js";import{writeFileSync as fr,readFileSync as ur,rmSync as hr,mkdirSync as Ie,existsSync as P,unlinkSync as xe,chmodSync as De}from"node:fs";import{createServer as Y}from"node:http";import{dirname as wr}from"node:path";import{envCrtrdTcp as Te,envDocumentPort as vr}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 Le,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Pr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Er}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as $e}from"../core/layout.js";import{migrateLooseKeys as Dr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Tr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Lr,listNodesForSupervision as Ae,listParkedResidentsWithWakeMail as $r,setFrozen as Ne}from"../core/canvas/index.js";import{createApiServer as Ar,closeServer as Me}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Gr}from"./api/document-secret.js";import{createAppListener as Fr}from"./api/app-listener.js";import{registerMachineEnvironment as Br}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Hr}from"../core/secrets/blaxel-register.js";import{markCloudRole as jr,resolvePerson as zr,retireLocalPerson as Ur,setPersonId as qr}from"../core/canvas/person.js";import{backfillNodeApps as Oe,runPermissionsBoot as Wr}from"../core/permissions/boot.js";import{startRunNotices as Jr}from"./run-notices.js";import{startGrantEffects as Kr}from"./reconcilers/grant-effects.js";import{syncPackages as Vr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Yr}from"../core/model-auth/activations.js";import{createGrantSync as Qr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Xr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Zr}from"./cron/run-socket.js";import{hasSyncedGrants as et}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as rt}from"./human/sweep.js";import{resetHandedOffDeliveries as tt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as nt}from"../core/canvas/daemon-actions.js";import{sweepReviews as ot}from"./review/sweep.js";import{pidfilePath as pe}from"./pidfile.js";import{rendererWarning as it}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as at}from"./supervise-cadence.js";import{createResumeDetector as st}from"./resume-detector.js";import{setFatalFaultAnnouncer as ct}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as lt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as dt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as mt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as pt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as yt,migrateLegacyExecutionIdentities as St}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as Pt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Et}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as It}from"../core/ledger/rates.js";import{IdleSandboxReconciler as xt}from"./reconcilers/idle-sandbox.js";import{LedgerSandboxReconciler as Dt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Tt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Ct}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Lt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as $t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as At}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Nt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Mt,subscribeImageBuilt as Ot}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Gt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Ft,captureTeardownSnapshot as Be,isPidAlive as Bt,isAnyPidAlive as He,killProcessTreePids as je}from"../core/canvas/pid.js";import{bindFleet as Ht,boundFleet as ze}from"../core/runtime/fleet.js";import{bindDaemonControl as jt,clearDaemonControl as zt}from"./control.js";import{execDaemon as Ut,spawnDaemon as qt}from"./manage.js";import{reconcileAndMigrateBoot as Wt}from"../core/canvas/boot.js";import{resolveInstallId as Jt}from"../core/canvas/install-id.js";import{setInstallId as Kt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Vt,daemonOwnershipApplies as Yt,daemonOwnershipClaimed as Qt,releaseDaemonOwnership as Ue}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Xt,closeAllDbs as ue,openDb as Zt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as en}from"../core/canvas/import-sqlite.js";import{ensurePostgres as rn,ensurePostgresHealthy as tn,stopPostgres as nn,withPostgresStartLock as on}from"./postgres/index.js";import{brokerSignalBus as N}from"./broker-signals/bus.js";import{brokerSignalStreams as an}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as sn}from"./api/handlers/broker-ops.js";import{reconcilePackages as cn}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as ln}from"../core/scoped-state/migrate-app-installs.js";import{publish as dn,readBuiltinSnapshot as mn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as pn,reapStaleSpares as fn}from"../core/runtime/warm-pool.js";import{DaemonFleet as un}from"./fleet.js";import{copyNodeFilesToRows as hn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as wn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as vn}from"../core/events/source.js";import{activateCanvasImport as gn,MigrationBlockedError as yn,runForcedCanvasImport as Sn}from"../migrations/activation.js";import{adoptInstallPerson as _n,convertLegacyScopedStore as bn,personStoresCopied as kn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Rn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as Pn}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 la}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const En=5e3,Je=150;async function In(e){const l=Fe();if(l===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,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ve(w,f)||ge(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||p.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of p){const c=Ft(i.pid);if(c===null||!c.includes("broker-cli.js")||!ve(c,f)||ge(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=Be(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+En;for(;Date.now()<h&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Je));let y=0;for(const i of o){const c=i.snap.tree.length>0?i.snap.tree:[i.pid];He(c)&&(process.platform==="linux"&&P(C)?await A({operation:"stop",pid:i.pid}):je(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Je));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,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ve(w,f)&&ge(w)!==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(In,"reapPriorEpochBrokers");const xn=5e3;async function Dn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await Cr(o))?.status;(h==="active"||h==="idle")&&await Ne(o,new Date().toISOString())}const f=l.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"&&P(C)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,xn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Bt(o.pid)&&(process.platform==="linux"&&P(C)?await A({operation:"stop",pid:o.pid}):je(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 l)await vt(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Dn,"teardownFleet");function ye(e=null){Ie(wr(pe()),{recursive:!0}),fr(pe(),e===null?String(process.pid):`${process.pid}
|
|
2
|
+
${e}`,"utf8")}s(ye,"writePidfile");function Ke(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ke,"isMissingPathError");function Ve(e){const l=pe();let f;try{f=ur(l,"utf8")}catch(p){if(Ke(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{hr(l)}catch(p){if(Ke(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const Tn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},Q=new lt;ct(e=>Q.handleFatalFault(e,!1));const Cn=new mt,Ln=new dt,Ye=new pt,$n=new ft,An=new ut,Nn=new ht,Mn=new wt,On=new bt,Gn=new kt,Fn=new Rt,Bn=new Et,Hn=new Pt,jn=new Dt,zn=new xt,Un=new Tt,qn=new Ct,Wn=new Lt,Jn=new $t,Kn=new At,Vn=new Nt,Yn=new Mt;async function Qn(e=Date.now(),l=Tn){const f=ze(),p=await Q.runFleetPreamble(f);let g,o,h;try{o=await fe();const d=(await Ae()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),h=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(h.map(i=>i.node_id));h.push(...(await $r()).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 Q.run(e,{rows:g,fleet:f,lifecycle:l,held:o}),await Cn.run(e,{rows:g,held:o}),await Ln.run(e);const y=await Ye.run(e,{rows:[...g,...h],fleet:f});await $n.run(e,o),await Vn.run(e,o),await Yn.run(e,{lifecycle:l}),await An.run(e,{lifecycle:l,held:o}),await Nn.run(e,{lifecycle:l}),await Mn.run(e,{lifecycle:l}),await On.run(e,{lifecycle:l}),await Gn.run(e,{lifecycle:l,fleet:f,held:o}),Fn.run(e,{lifecycle:l}),Bn.run(e,{lifecycle:l}),Hn.run(e,{lifecycle:l}),jn.run(e,{lifecycle:l}),zn.run(e,{lifecycle:l}),Un.run(e,{lifecycle:l}),qn.run(e,{lifecycle:l}),Wn.run(e,{lifecycle:l}),await _r(),Kn.run(e,{fleet:f,lifecycle:l}),await Jn.run(e,{rows:g}),Q.warnIfSaturated({fleet:f,lifecycle:l,thresholds:p,frozen:y})}s(Qn,"superviseTick");async function Xn(e,l=Date.now()){if((await fe()).has(e))return;const f=await yt(e);if(f===null||!gt(f))return;const p=await Lr(e);p===null||p.kind==="human"||await Ye.runNode(l,p,ze())}s(Xn,"exitedNodePass");function X(e){return e===void 0||e==="reconcile"}s(X,"roleRunsLanes");function M(e){return e===void 0||e==="api"}s(M,"roleServesRequests");const Zn=66e4;function eo(e){const l=new Nr().registerAll(Mr(()=>null).filter(c=>c.pattern==="/healthz")),f=s((c,w)=>{const b=(c.url??"/").split("?")[0];if((c.method??"GET").toUpperCase()==="GET"&&b==="/healthz"){l.handle(c,w,null,{class:"person"});return}w.writeHead(404,{"content-type":"application/json; charset=utf-8"}),w.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=Le();P(p)&&xe(p);const g=Y(f),o=new Promise((c,w)=>{g.once("error",w),g.listen(p,()=>{g.off("error",w),De(p,384),c()})});let h,y=null,d=o;const u=e.tcp??Te()??me("user").api.tcp;if(u!==void 0&&u!==""){const c=/^(.*):(\d+)$/.exec(u.trim());if(c===null||Number(c[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const w=Y(f);w.on("error",b=>m({event:"api.server.failed",level:"error",error:b})),d=o.then(()=>new Promise(b=>{w.once("error",()=>b()),w.listen(Number(c[2]),c[1]===""?"0.0.0.0":c[1],()=>{const E=w.address();y=`${E.address}:${E.port}`,b()})})),h=w}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(c={}){if(!i){i=!0,await Promise.all([Me(g,new Set,c.graceMs),h===void 0?Promise.resolve():Me(h,new Set,c.graceMs)]);try{P(p)&&xe(p)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){Ie($e(),{recursive:!0,mode:493}),process.platform==="linux"&&De($e(),493);const l=Le();if(P(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);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(l,()=>{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,c)=>{u.once("error",c),u.listen(Number(d[2]),d[1],()=>{u.off("error",c),i()})}),p=u}ye();let o;const h=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(c=>c?i(c):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{h().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),h}s(to,"serveLayoutRefusal");async function no(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return to(e);Ir();const l=s(t=>{process.stderr.write(`[crtrd] ${t}
|
|
5
|
+
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Yt(e.role);sn(X(e.role));const g=s(async()=>p?await Vt(Ce(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Ce(16).toString("hex")}},"claimOwnership"),{database:o,ownership:h}=f?{database:{url:await Xt()},ownership:await g()}:await on(async()=>({database:await rn({log:l,startLockHeld:!0}),ownership:await g()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
|
|
6
|
+
`);else{const t=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(v=>v!==void 0),a=t.length>0?` (${t.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
|
|
7
|
+
`),h.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"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=h.claim;let d=null,u=null,i=null,c=null,w,b="";try{p&&await In(y.token);for(const r of Tr())process.stderr.write(`[crtrd] ${r}
|
|
8
|
+
`);for(const r of await Dr())process.stderr.write(`[crtrd] ${r}
|
|
9
|
+
`);await Zt(),await en(o.url,l);const t=e.role===void 0&&!await kn();let a=null;t&&(bn({kind:"user",root:We()}),a=Rn(We())),e.role===void 0&&Pn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await N.listen(o.url);const v=s(r=>{we(r).catch(n=>m({level:"error",event:"daemon.settings.reload_failed",error:n}))},"reloadPerson");if(w=await N.subscribe(r=>{qe().includes(r)&&v(r)},{kinds:["settings"],onListenStart:s(()=>{for(const r of qe())v(r)},"onListenStart")}),e.role!==void 0&&jr(),e.role!==void 0){let r;try{r=mn()}catch(_){m({level:"error",event:"daemon.packages.snapshot_failed",error:_})}const n=await he(async _=>(await Oe(_),r===void 0?void 0:await dn(_,r,"release")));c=await he(async _=>await ln(_));for(const _ of n?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${_.path}: ${_.error}
|
|
10
|
+
`)}else{d=await zr(),d!==null&&(qr(d.id),await we(d.id));const r=await he(async n=>(await Oe(n),d===null?null:await cn(n)));if(r!==null){for(const n of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${n.message}
|
|
11
|
+
`);for(const n of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${n.path}: ${n.error}
|
|
12
|
+
`);for(const n of r.quarantined)process.stderr.write(`[crtrd] plugin "${n.name}" has a damaged ${n.file} (${n.reason}); ${n.movedTo!==void 0?`moved to ${n.movedTo}`:"left in place and skipped"}
|
|
13
|
+
`);for(const n of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${n.plugin}" kind ${n.kind} not registered: ${n.message}
|
|
14
|
+
`);for(const n of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${n.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${n.error}
|
|
15
|
+
`)}}if(b=await Jt(),Kt(b),e.role===void 0&&d!==null){if(await _n(d.id),process.platform==="darwin"){const{readConfig:r,updateConfig:n}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:_}=await import("node:os");await n("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=_()})}}u=await Ur(),u.joinedFrom!==null&&await we(u.person),await lr(),i=await Wr()}if(process.platform==="linux"&&P(C)&&(Er(),await A({operation:"users.sync",users:await kr()})),p){await _t(y.token);const r=await hn();Object.values(r).some(n=>n>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
|
|
16
|
+
`)}}catch(t){await N.close();try{if(p){const{released:a}=await Ue(y);if(!a)throw new Error("daemon ownership claim was not released")}await ue()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,Z,j=Promise.resolve(),ee=!1,z,re,te,ne,L;const U=new Set;let oe=!1,Se=!1,I,x,ie,q=!1,W,O,G,F,B,ae,se,ce,le;const Qe=st();let D,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 R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const er={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function rr(){try{E=!1,an.close(),re?.(),re=void 0,te?.(),w?.(),te=void 0,ne?.(),ne=void 0,ce?.(),ce=void 0,await N.close(),z!==void 0&&(clearInterval(z),z=void 0),G!==void 0&&(clearInterval(G),G=void 0),F!==void 0&&(clearInterval(F),F=void 0),le?.(),le=void 0;let t;do t=j,await t;while(t!==j);for(;U.size>0;)await Promise.allSettled([...U]);if(L!==void 0&&(p&&await Dn(L),await L.exitsSettled(),L.dispose()),ie!==void 0&&await ie.close(),x!==void 0&&!q&&(q=!0,await x.close()),ae?.(),ae=void 0,se?.(),se=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if(O!==void 0){const a=O;O=void 0,await a.close()}if(W!==void 0){const a=W;W=void 0,await a.close()}if(oe||(Ve(process.pid),oe=!0),oe&&!Se){if(p){const{released:a}=await Ue(y);if(!a)throw new Error("daemon ownership claim was not released")}Se=!0,await ue()}}finally{zt(),process.off("SIGINT",ke),process.off("SIGTERM",Re),process.off("exit",Pe)}}s(rr,"cleanupAttempt");const J=1e3;let _e=!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 _e?{graceMs:J}:(_e=!0,k.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:J}})}),setTimeout(()=>{nr()},J),{graceMs:J})}s(tr,"requestHandover");async function nr(){try{await T()}catch(t){const a=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
15
17
|
${a}
|
|
16
|
-
`),process.exit(1)}try{process.platform==="linux"&&
|
|
17
|
-
`),process.exit(1)}process.exit(0)}s(nr,"performHandover");function
|
|
18
|
-
${
|
|
19
|
-
`),process.exit(1)}}s(
|
|
18
|
+
`),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ut();const t=await qt({waitForJoinLock:!0});k.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){k.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:t})});const a=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
|
|
19
|
+
`),process.exit(1)}process.exit(0)}s(nr,"performHandover");function T(){if(I!==void 0)return I;const t=rr();return I=t,t.then(()=>{I===t&&(I=void 0)},()=>{I===t&&(I=void 0)}),t}s(T,"requestCleanup");async function or(){S={phase:"initializing",message:ro,blockerPaths:[]},x!==void 0&&!q&&(q=!0,await x.close({graceMs:Zn}))}s(or,"drainApi");async function be(t){try{t==="SIGTERM"&&e.role==="api"&&await or(),await T(),await nn({claimed:s(async()=>{try{return p&&await Qt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const v=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${t} cleanup failed:
|
|
20
|
+
${v}
|
|
21
|
+
`),process.exit(1)}}s(be,"handleSignal");function ke(){be("SIGINT")}s(ke,"onSigint");function Re(){be("SIGTERM")}s(Re,"onSigterm");function Pe(){T().catch(()=>{})}s(Pe,"onExit");async function K(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(K,"enqueue");async function V(){!E||ee||(Qe.check()&&D&&(m({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),ee=!0,await K(async()=>{if(ee=!1,!!E)try{f||await tn({log:l}),await Qn(Date.now(),er)}catch(t){k.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:t})})}}))}s(V,"enqueueTick");let H=null;async function ir(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};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 t=S.phase==="prepared";try{return await de(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ir,"admitStartup");async function ar(t){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await Sn({dryRun:t.dryRun});if(t.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await de(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(v){const r=v instanceof Error?v.message:String(v);return setTimeout(()=>{T().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:r}}}finally{$=null}}s(ar,"repairMigrations");async function sr(){Z=e.intervalMs??at;const t=y.token;L=new un({epoch:t,enqueue:K}),Ht(L),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},k.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Z}})});const a=b;k.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const v=await Br(a);if(k.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:v.environmentId,created:v.created}})}),k.fresh(()=>{let r;try{r=it()}catch{return}r!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),It(),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): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Hr(),!X(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await k.fresh(async()=>{await ot(),await rt(),await tt(Date.now()),await nt(Date.now())}),e.role===void 0&&await k.fresh(async()=>{const{reconcile:r,migrated:n}=await Wt(St);r.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),n.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await k.fresh(async()=>{const r=await fe();for(const n of await Ae())r.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await Ne(n.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await k.fresh(async()=>{await Gt();for(const r of wn){const n=await r.apply();n.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...n.summary}})}}),R(Zr()),D){const r=s(()=>{R(D().catch(()=>{})),R(mr().then(n=>B?.observe(n)).then(()=>{},n=>{m({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");R(Xr().then(({completion:n})=>n).catch(n=>{m({level:"error",event:"daemon.grants.sweep_failed",error:n})})),r(),G=setInterval(r,Ge*1e3),G.unref(),le=dr({joined:!0,register:R})}await K(async()=>{await fn(),await pn()}),z=setInterval(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},Z),re=await Ot(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))}),te=await N.subscribe(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),ne=await N.subscribe(r=>{K(()=>k.fresh(()=>Xn(r)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!E,n=>m({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(r=>m({level:"warn",event:"daemon.move.settle_failed",error:r}))}s(sr,"completeStartup");function de(){return Xe??=sr().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}s(de,"resumeStartup");try{process.on("SIGINT",ke),process.on("SIGTERM",Re),process.on("exit",Pe),vn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),c!==null&&!c.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:c.moved,discarded:c.discarded,people:c.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}}),M(e.role)?W=await yr():Sr(gr());const t=y.token;jt({epoch:t,requestHandover:tr,registerDetached:R,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),ye(),x=M(e.role)?Ar({tcp:e.tcp}):eo(e),await x.ready,ye(x.tcpAddress());const a=vr()??me("user").document_port;if(M(e.role)){const r=Or(a,Gr());try{await r.ready,ie=r}catch(n){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:n instanceof Error?n.message:String(n)}})}}const v=me("user").runtime;if(v?.issuer&&(D=Qr(v.issuer,R),v.unsandboxed===!0&&(B=pr({syncGrants:D}))),e.role==="api"){const r=s(()=>R(import("../core/providers/bundles.js").then(_=>_.syncProviderBundles()).catch(_=>{m({level:"error",event:"daemon.providers.bundle_sync_failed",error:_})})),"bundleTick"),n=s(()=>{R(Vr().catch(_=>{m({level:"error",event:"daemon.packages.sync_failed",error:_})})),r()},"packageTick");n(),F=setInterval(n,Ge*1e3),F.unref()}if(M(e.role)&&(ae=await Jr()),X(e.role)&&(se=Yr()),ce=await Kr({serves:M(e.role),runsLanes:X(e.role)}),v?.unsandboxed===!0&&v.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),M(e.role)&&v!==void 0&&v.listener!==void 0&&v.unsandboxed!==!0&&(O=await Fr(v,async()=>await et(v.issuer.replace(/\/$/,"")),D),await O.ready),e.role===void 0)try{await gn()}catch(r){if($=null,r instanceof yn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},T;throw r}process.platform==="linux"&&P(C)&&(Pr(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await de(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return T}catch(t){try{await T()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}}s(no,"runDaemon");var aa=no;export{Zn as API_DRAIN_GRACE_MS,la as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,aa as default,Xn as exitedNodePass,X as roleRunsLanes,M as roleServesRequests,no as runDaemon,Qn as superviseTick,Dn as teardownFleet};
|
|
@@ -56,10 +56,14 @@ export interface ViewSource {
|
|
|
56
56
|
resume(): void;
|
|
57
57
|
}
|
|
58
58
|
/** Viewer frames, in order (a channel's view.close stays behind its data), fed into the link only while it holds fewer than
|
|
59
|
-
* VIEW_SEND_LOW_WATER unsent bytes; anything sent on the sink directly (a call result) therefore goes ahead of the queue. A source is
|
|
59
|
+
* VIEW_SEND_LOW_WATER unsent bytes; anything sent on the sink directly (a call result, a view.ready) therefore goes ahead of the queue. A source is
|
|
60
60
|
* paused while the queue is deep, so a slow link never buffers a pane stream in memory. */
|
|
61
61
|
export declare function createViewQueue(sink: ViewSink): {
|
|
62
62
|
push(data: string, source?: ViewSource): void;
|
|
63
|
+
waiting(): {
|
|
64
|
+
bytes: number;
|
|
65
|
+
frames: number;
|
|
66
|
+
};
|
|
63
67
|
forget(source: ViewSource): void;
|
|
64
68
|
};
|
|
65
69
|
export declare function linkUrl(apiUrl: string, environmentId: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty;var o=(t,l)=>j(t,"name",{value:l,configurable:!0});import{randomUUID as W}from"node:crypto";import{WebSocket as v}from"ws";import{APIError as O}from"../../api/errors.js";import{emitEvent as N}from"../../core/events/emit.js";import{connectViewSocket as J}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as K,LINK_MAX_PAYLOAD_BYTES as q,parseFrame as F}from"./frames.js";const Y=1e3,D=6e4,X=64*1024,$=4*1024*1024,z=1024*1024,Q=8*1024*1024,G=15e3,H=75e3;function Z(t){const l=[];let i=0;const p=new Set,M=o(()=>{for(;l.length>0&&t.open()&&t.bufferedAmount<X;){const c=l.shift();i-=c.length,t.send(c,M)}if(i<z&&p.size>0){for(const c of p)c.resume();p.clear()}},"pump");return{push(c,a){t.open()&&(l.push(c),i+=c.length,a!==void 0&&i>$&&(a.pause(),p.add(a)),M())},waiting:o(()=>({bytes:i,frames:l.length}),"waiting"),forget(c){p.delete(c)}}}o(Z,"createViewQueue");function ee(t,l){const i=new URL(`/v1/machines/${encodeURIComponent(l)}/link`,t);return i.protocol=i.protocol==="https:"?"wss:":i.protocol==="http:"?"ws:":i.protocol,i.toString()}o(ee,"linkUrl");function le(t){const l=t.backoffMinMs??Y,i=t.backoffMaxMs??D,p=t.openView??J,M=t.silenceMs??H;let c=!1,a,_=l,k;const g=new Map,R=200,b=[],P=o(()=>{const d=a;for(;b.length>0&&d?.readyState===v.OPEN;)d.send(JSON.stringify({type:"exit",...b.shift()}))},"flushExits"),C=o((d,r)=>{N({level:"error",event:d,fields:{environment:t.environmentId},error:r})},"fault");let T;const x=o(()=>{if(c)return;if(T!==void 0){if(t.credential()===T){k=setTimeout(x,_),_=Math.min(_*2,i);return}T=void 0}const d=t.credential(),r=new v(ee(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${d}`},maxPayload:q});a=r;const u=new Map,h=new Map,m=o(e=>{r.readyState===v.OPEN&&r.send(JSON.stringify(e))},"send"),y=Z({get bufferedAmount(){return r.bufferedAmount},open:o(()=>r.readyState===v.OPEN,"open"),send:o((e,n)=>r.send(e,n),"send")}),w=o((e,n)=>y.push(JSON.stringify(e),n),"sendView"),I=o(e=>Math.round(e*10)/10,"round"),A=o(async e=>{const n=t.handlers[e.op];if(n===void 0){m({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const s=new AbortController,f=o(()=>s.abort(new Error("the machine link closed")),"onClose");r.once("close",f);try{m({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,s.signal)??null})}catch(E){m({type:"result",call_id:e.call_id,ok:!1,error:E instanceof Error?E.message:String(E)})}finally{r.off("close",f)}},"runCall"),U=o(e=>{const n=p(e.node);u.set(e.channel,n);const s=performance.now();n.once("connect",()=>{const f=performance.now(),E=y.waiting(),B=r.bufferedAmount;m({type:"view.ready",channel:e.channel}),N({level:"info",event:"daemon.timing.view_ready_sent",fields:{channel:e.channel,node:e.node,open_to_connect_ms:I(f-s),queued_bytes:E.bytes,queued_frames:E.frames,link_buffered_bytes_before:B,link_buffered_bytes_after:r.bufferedAmount}})}),n.on("data",f=>w({type:"view.data",channel:e.channel,bytes:f.toString("base64")},n)),n.once("error",f=>{y.forget(n),u.delete(e.channel)&&w({type:"view.close",channel:e.channel,error:f.message})}),n.once("close",()=>{y.forget(n),u.delete(e.channel)&&w({type:"view.close",channel:e.channel})})},"openChannel"),V=o((e,n)=>{const s=u.get(e);if(s===void 0||s.write(n))return;const f=(h.get(e)??0)+n.length;if(f>Q){u.delete(e),h.delete(e),s.destroy(),w({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}h.has(e)||s.once("drain",()=>h.delete(e)),h.set(e,f)},"writeToChannel");let S;const L=o(()=>{S!==void 0&&clearTimeout(S),S=setTimeout(()=>{N({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),r.terminate()},M)},"heard");r.on("open",()=>{_=l,L(),P(),t.onOpen?.()}),r.on("ping",L),r.on("message",e=>{L();const n=F(e);if(n!==null)try{switch(n.type){case"call":A(n);return;case"job.reported":{const s=g.get(n.id);g.delete(n.id),n.error===void 0?s?.resolve():s?.reject(new O(n.error.status,n.error.code,n.error.message));return}case"view.open":U(n);return;case"view.data":V(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const s=u.get(n.channel);u.delete(n.channel),s?.destroy();return}default:return}}catch(s){C("daemon.machine_link.frame_failed",s)}}),r.on("error",e=>C("daemon.machine_link.client_error",e)),r.on("close",e=>{S!==void 0&&clearTimeout(S);for(const n of u.values())n.destroy();u.clear(),a===r&&(a=void 0);for(const[n,s]of g)g.delete(n),s.reject(new O(503,"machine_offline","the machine link closed before the job report was answered"));c||(e===K&&(N({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),T=d),k=setTimeout(x,_),_=Math.min(_*2,i))})},"connect");return x(),{stop(){c=!0,k!==void 0&&clearTimeout(k),a?.close()},connected:o(()=>a?.readyState===v.OPEN,"connected"),reportJob(d,r,u){const h=a;if(h?.readyState!==v.OPEN)return Promise.reject(new O(503,"machine_offline","the machine link is not open"));const m=W();return new Promise((y,w)=>{const I=setTimeout(()=>{g.delete(m),w(new O(504,"request_timeout","the control plane did not answer the job report"))},t.jobReportTimeoutMs??G);g.set(m,{resolve:o(()=>{clearTimeout(I),y()},"resolve"),reject:o(A=>{clearTimeout(I),w(A)},"reject")}),h.send(JSON.stringify({type:"job.report",id:m,node:d,job:r,request:u}))})},reportExit(d){b.push(d),b.length>R&&b.shift(),P()}}}o(le,"startMachineLink");export{G as JOB_REPORT_TIMEOUT_MS,D as LINK_BACKOFF_MAX_MS,Y as LINK_BACKOFF_MIN_MS,H as LINK_SILENCE_MS,Q as VIEW_WRITE_LIMIT_BYTES,Z as createViewQueue,ee as linkUrl,le as startMachineLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});import{EventEmitter as x}from"node:events";import{createHmac as I,timingSafeEqual as A}from"node:crypto";import{WebSocket as u,WebSocketServer as P}from"ws";import{markAt as R}from"../../core/logged-step-timings.js";import{addStepTiming as k}from"../../core/step-timings.js";import{emitEvent as B}from"../../core/events/emit.js";import{openDb as O}from"../../core/canvas/db.js";import{loadSecretsKey as T}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as _,parseFrame as v}from"./frames.js";import{apiAddress as D,heldLinkOf as g,MachineViewLink as E,UNROUTABLE_PREFIX as L}from"./holder.js";const y=8*1024*1024,$=1013,M=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,q=new P({noServer:!0,maxPayload:_}),S=a(i=>I("sha256",T().key).update(`machine-view:${i}`).digest("hex"),"forwardToken");function N(i,e){const r=g(i);return r!==null?new E(r,e):new U(i,e)}a(N,"openMachineView");class U extends x{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,r){super(),this.environmentId=e,this.nodeId=r;const s=performance.now();this.once("connect",()=>B({level:"info",event:"daemon.timing.forwarded_view_ready",fields:{environment:this.environmentId,node:this.nodeId,open_to_ready_ms:Math.round((performance.now()-s)*10)/10}})),this.dial().catch(t=>this.finish(t instanceof Error?t.message:String(t)))}get destroyed(){return this.ended}write(e){return this.ended?!1:this.ws?.readyState!==u.OPEN?(this.queuedBytes+=e.length,this.queuedBytes>y?(this.finish("machine view: the holder did not accept the channel before its queue filled"),!1):(this.queued.push(e),!0)):this.ws.bufferedAmount>y?(this.finish("machine view: the holder is not draining the channel"),!1):(this.sendData(e),!0)}destroy(){return this.ended||(this.ws?.readyState===u.OPEN&&this.ws.send(JSON.stringify({type:"view.close",channel:""})),this.finish(void 0)),this}sendData(e){this.ws?.send(JSON.stringify({type:"view.data",channel:"",bytes:Buffer.from(e).toString("base64")}))}async dial(){const e=await(await O()).prepare("SELECT api_address, lease_expires_at FROM machine_links WHERE environment = ?").get(this.environmentId);if(e===void 0||Date.parse(e.lease_expires_at)<=Date.now())throw new Error(`machine_offline: machine ${this.environmentId} has no live link`);if(e.api_address.startsWith(L))throw new Error(`machine_unreachable: the API process holding the link wrote ${e.api_address}; set CRTR_API_ADDRESS or listen on TCP`);if(e.api_address===D())throw new Error(`machine_offline: the link row names this API process (${e.api_address}) but it holds no link`);if(this.ended)return;const r=new URL(`/v1/machines/${encodeURIComponent(this.environmentId)}/view`,e.api_address.includes("://")?e.api_address:`ws://${e.api_address}`);r.protocol=r.protocol==="https:"?"wss:":r.protocol==="http:"?"ws:":r.protocol,r.searchParams.set("node",this.nodeId);const s=new u(r.toString(),{headers:{authorization:`Bearer ${S(this.environmentId)}`},maxPayload:_});this.ws=s,s.on("open",()=>{for(const t of this.queued.splice(0))this.sendData(t)}),s.on("unexpected-response",(t,n)=>{n.resume(),this.finish(n.statusCode===409?"machine_offline: the holder no longer holds the link":`machine view refused by ${e.api_address}: ${n.statusCode}`)}),s.on("message",t=>{const n=v(t);n!==null&&(n.type==="view.ready"?this.emit("connect"):n.type==="view.data"?this.emit("data",Buffer.from(n.bytes,"base64")):n.type==="view.close"&&this.finish(n.error))}),s.on("error",t=>this.finish(t.message)),s.on("close",()=>this.finish("machine view forward closed"))}finish(e){this.ended||(this.ended=!0,this.ws?.close(),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}function C(i,e,r){return new Promise(s=>{const t=N(i,e),n=setTimeout(()=>{s(!1),t.destroy()},r);t.on("connect",()=>{clearTimeout(n),s(!0),t.destroy()}),t.on("error",()=>{}),t.on("close",()=>{clearTimeout(n),s(!1)})})}a(C,"probeMachineView");async function G(i,e,r,s){const t=Date.now()+s;let n=!1;r?.then(()=>{n=!0});for(let f=1;Date.now()<=t&&!n;f++){const l=performance.now(),c=await C(i,e,Math.max(1,Math.min(2e3,t-Date.now())));if(k(`probe_${f}_${c?"ready":"failed"}_ms`,performance.now()-l),c)return R("ready_received"),!0;await new Promise(m=>setTimeout(m,250))}return!1}a(G,"waitForMachineView");function Q(i){const e=M.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Q,"machineViewEnvironment");function ee(i,e,r,s){const t=i.headers.authorization,n=/^Bearer (\S+)$/.exec(Array.isArray(t)?t[0]??"":t??"")?.[1]??"",f=Buffer.from(S(s)),l=Buffer.from(n);if(l.length!==f.length||!A(l,f))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const c=new URL(i.url??"/","http://runtime.local").searchParams.get("node");if(c===null||c==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const m=g(s);return m===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(q.handleUpgrade(i,e,r,d=>{const o=new E(m,c),p=a(h=>{d.readyState===u.OPEN&&d.send(JSON.stringify(h))},"send");o.on("connect",()=>p({type:"view.ready",channel:""})),o.on("data",h=>{if(d.bufferedAmount>y){o.destroy(),d.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:h.toString("base64")})}),o.on("error",h=>p({type:"view.close",channel:"",error:h.message})),o.on("close",()=>d.close()),d.on("message",h=>{const w=v(h);w?.type==="view.data"?o.write(Buffer.from(w.bytes,"base64")):w?.type==="view.close"&&o.destroy()}),d.on("close",()=>o.destroy()),d.on("error",()=>o.destroy())}),null)}a(ee,"handleMachineViewUpgrade");export{y as VIEW_BUFFER_LIMIT_BYTES,ee as handleMachineViewUpgrade,Q as machineViewEnvironment,N as openMachineView,C as probeMachineView,G as waitForMachineView};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var R=Object.defineProperty;var s=(i,e)=>R(i,"name",{value:e,configurable:!0});import{importedNodesHeld as
|
|
1
|
+
var R=Object.defineProperty;var s=(i,e)=>R(i,"name",{value:e,configurable:!0});import{importedNodesHeld as y}from"../reconcilers/live-obligation.js";import{EventEmitter as f}from"node:events";import{hostname as T}from"node:os";import{randomUUID as L}from"node:crypto";import{WebSocket as I,WebSocketServer as b}from"ws";import{openDb as r}from"../../core/canvas/db.js";import{emitEvent as h}from"../../core/events/emit.js";import{endExecution as O,recordExecutionExit as x}from"../../core/canvas/executions.js";import{machineEnvironmentOfNode as p}from"../../core/runtime/runner/machine/runner.js";import{storeJobReport as C}from"../api/handlers/bash-jobs.js";import{APIError as E}from"../../api/errors.js";import{brokerSignalBus as M}from"../broker-signals/bus.js";import{verifyMachineCredential as w}from"./credential.js";import{CLOSE_REVOKED as U,CLOSE_SUPERSEDED as g,LINK_MAX_PAYLOAD_BYTES as H,parseFrame as P}from"./frames.js";const W=45e3,j=15e3,F=3e4,$=1e3,v=10,B=new b({noServer:!0,maxPayload:H}),c=new Map,K="unroutable:";let S;const he=s(i=>{S=i},"setApiAddress"),X=s(()=>process.env.CRTR_API_ADDRESS??S??`${K}${T()}:${process.pid}`,"apiAddress"),u=s(()=>new Date(Date.now()+W).toISOString(),"lease");class J extends f{static{s(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;channels=new Map;constructor(e,n,t,a){super(),this.environmentId=e,this.generation=n,this.ws=t,this.token=a}start(){const{ws:e}=this;e.on("message",n=>{this.onMessage(n).catch(t=>this.fault("daemon.machine_link.frame_failed",t))}),e.on("pong",()=>{this.alive=!0}),e.on("close",()=>{this.teardown().catch(n=>this.fault("daemon.machine_link.teardown_failed",n))}),e.on("error",()=>{}),this.timers.push(setInterval(()=>{this.renew().catch(n=>this.fault("daemon.machine_link.renew_failed",n))},j)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},F)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},$)),M.subscribe(n=>{n===this.environmentId&&this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},{kinds:["machine"],onListenStart:s(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},"onListenStart")}).then(n=>{this.closed?n():this.unsubscribe=n})}fault(e,n){h({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==I.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await r(),n=u();if((await e.prepare("UPDATE machine_links SET lease_expires_at = ? WHERE environment = ? AND generation = ?").run(n,this.environmentId,this.generation)).changes===0){this.ws.close(g,"superseded");return}await e.prepare("UPDATE machine_calls SET lease_expires_at = ? WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").run(n,this.environmentId,this.generation),await e.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(new Date().toISOString(),this.environmentId),await this.credentialValid()||this.ws.close(U,"revoked")}async credentialValid(){return await w(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await r()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
|
|
2
2
|
WHERE call_id IN (SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'pending'
|
|
3
3
|
AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)
|
|
4
4
|
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${v})
|
|
5
5
|
RETURNING call_id, op, args_json`).all(this.generation,u(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<v)return}}finally{this.claiming=!1}}}async failCall(e,n,t,a){await this.settle(e,"failed",{code:n,message:t,sent:a},!1)}async isCurrentGeneration(){return await(await r()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await r()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,n,t,a){await G(e,n,t,this.environmentId,this.generation,a)}async onMessage(e){const n=P(e);if(n!==null)switch(n.type){case"result":n.ok?await this.settle(n.call_id,"done",n.value??null,!0):await this.settle(n.call_id,"failed",{code:"machine_call_failed",message:n.error},!0);return;case"exit":await V(this.environmentId,n);return;case"job.report":await this.storeJobReport(n);return;case"view.ready":this.channels.get(n.channel)?.emit("connect");return;case"view.data":this.channels.get(n.channel)?.emit("data",Buffer.from(n.bytes,"base64"));return;case"view.close":this.channels.get(n.channel)?.finish(n.error);return;default:return}}async storeJobReport(e){try{if(await p(e.node)!==this.environmentId)throw new E(404,"unknown_node",`node ${e.node} does not run in this machine environment`);await C(e.node,e.job,e.request),this.send({type:"job.reported",id:e.id})}catch(n){const t=n instanceof E;t||this.fault("daemon.machine_link.job_report_failed",n),this.send({type:"job.reported",id:e.id,error:{status:t?n.status:500,code:t?n.code:"internal_error",message:n.message}})}}async teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),c.get(this.environmentId)===this&&c.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await r(),n=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:t}of n)await this.failCall(t,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function G(i,e,n,t,a,o){const l=await r();(await l.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
|
|
6
6
|
WHERE call_id = ? AND environment = ? AND claimed_generation = ? AND state = 'sent'
|
|
7
|
-
${o?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...o?[t,a]:[])).changes>0&&await l.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(G,"withNotify");async function V(i,e){const n=await r(),t=await n.prepare("SELECT stop_requested_at, stop_reason FROM executions WHERE execution_id = ? AND node_id = ? AND runner = 'machine' AND state != 'exited'").get(e.execution,e.node);return t===void 0||await p(e.node)!==i||(await
|
|
7
|
+
${o?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...o?[t,a]:[])).changes>0&&await l.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(G,"withNotify");async function V(i,e){const n=await r(),t=await n.prepare("SELECT stop_requested_at, stop_reason FROM executions WHERE execution_id = ? AND node_id = ? AND runner = 'machine' AND state != 'exited'").get(e.execution,e.node);return t===void 0||await p(e.node)!==i||(await y()).has(e.node)||(await x(e.execution,{code:e.code,signal:e.signal}),!await O(e.execution,{reason:"exited"}))?!1:(t.stop_requested_at===null&&t.stop_reason===null&&await n.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`execution_exit:${e.node}`),h({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}s(V,"recordMachineBrokerExit");class me extends f{static{s(this,"MachineViewLink")}link;ended=!1;failed=!1;channel=L();constructor(e,n){super(),this.link=e,e.channels.set(this.channel,this);const t=performance.now();this.once("connect",()=>h({level:"info",event:"daemon.timing.machine_view_ready",fields:{channel:this.channel,node:n,open_to_ready_ms:Math.round((performance.now()-t)*10)/10}})),e.send({type:"view.open",channel:this.channel,node:n})||queueMicrotask(()=>this.finish("machine link closed"))}get destroyed(){return this.ended}write(e){return!this.ended&&this.link.send({type:"view.data",channel:this.channel,bytes:Buffer.from(e).toString("base64")})}destroy(){return this.ended||(this.link.send({type:"view.close",channel:this.channel}),this.finish(void 0)),this}finish(e){this.ended||(this.ended=!0,this.link.channels.delete(this.channel),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}const ue=s(i=>c.get(i)??null,"heldLinkOf"),z=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function _e(i){const e=z.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(_e,"machineLinkEnvironment");async function fe(i,e,n,t){const a=i.headers.authorization,o=/^Bearer (\S+)$/.exec(Array.isArray(a)?a[0]??"":a??"")?.[1];if(o===void 0||!await w(t,o))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};const l=new Date().toISOString(),d=await r(),D=await d.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
|
|
8
8
|
ON CONFLICT (environment) DO UPDATE SET generation = machine_links.generation + 1, api_address = EXCLUDED.api_address, connected_at = EXCLUDED.connected_at, lease_expires_at = EXCLUDED.lease_expires_at
|
|
9
|
-
RETURNING generation`).get(t,X(),l,u());await d.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,t);const
|
|
9
|
+
RETURNING generation`).get(t,X(),l,u());await d.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,t);const _=Number(D.generation);return e.destroyed?(await d.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,_),null):(B.handleUpgrade(i,e,n,A=>{const m=new J(t,_,A,o),N=c.get(t);c.set(t,m),N?.ws.close(g,"superseded"),m.start(),m.claim().catch(k=>h({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:k}))}),null)}s(fe,"handleMachineLinkUpgrade");export{J as HeldLink,W as LINK_LEASE_MS,F as LINK_PING_MS,j as LINK_RENEW_MS,me as MachineViewLink,K as UNROUTABLE_PREFIX,X as apiAddress,fe as handleMachineLinkUpgrade,ue as heldLinkOf,_e as machineLinkEnvironment,V as recordMachineBrokerExit,he as setApiAddress};
|
package/dist/daemon/pidfile.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
var o=Object.defineProperty;var i=(r,n)=>o(r,"name",{value:n,configurable:!0});import{existsSync as m,readFileSync as
|
|
1
|
+
var o=Object.defineProperty;var i=(r,n)=>o(r,"name",{value:n,configurable:!0});import{existsSync as m,readFileSync as p}from"node:fs";import{join as u}from"node:path";import{crtrHome as f}from"../core/canvas/paths.js";import{isPidAlive as e}from"../core/canvas/pid.js";import{envPidfileOverride as l}from"../shared/env.js";function c(){return l()??u(f(),"crtrd.pid")}i(c,"pidfilePath");function d(){const r=c();if(!m(r))return null;const n=p(r,"utf8").split(`
|
|
2
|
+
`,1)[0].trim(),t=Number(n);return Number.isFinite(t)&&t>0?t:null}i(d,"readPidfile");function y(){const r=d();return r!==null&&e(r)}i(y,"isDaemonRunning");export{y as isDaemonRunning,e as isPidAlive,c as pidfilePath,d as readPidfile};
|