@north-light/cli 0.3.751 → 0.3.753
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 +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/environments.d.ts +37 -0
- package/dist/api/dto/health.d.ts +3 -0
- package/dist/api/routes.d.ts +2 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
- package/dist/clients/attach/viewer.js +342 -342
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/core/audit.d.ts +2 -0
- package/dist/core/audit.js +2 -2
- package/dist/core/canvas/canvas.d.ts +1 -1
- package/dist/core/canvas/canvas.js +26 -19
- package/dist/core/canvas/schema-pg/038-actor.sql +4 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/environments.js +1 -1
- package/dist/core/graph/objects.d.ts +3 -1
- package/dist/core/graph/objects.js +10 -10
- package/dist/core/import/load/copy.js +9 -9
- package/dist/core/import/load/keys.d.ts +5 -0
- package/dist/core/import/load/keys.js +8 -0
- package/dist/core/import/load/rollback.js +7 -7
- package/dist/core/import/load/run.js +2 -3
- package/dist/core/import/load/verify.js +8 -8
- package/dist/core/ledger/charges.js +1 -1
- package/dist/core/ledger/chunks.js +1 -1
- package/dist/core/ledger/read.js +1 -1
- package/dist/core/ledger/types.d.ts +4 -0
- package/dist/core/profiles/manifest.d.ts +5 -0
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/providers/audit.js +3 -3
- package/dist/core/providers/call.d.ts +2 -0
- package/dist/core/providers/call.js +1 -1
- package/dist/core/providers/receipts.d.ts +2 -0
- package/dist/core/providers/receipts.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +10 -11
- package/dist/core/runtime/runner/blaxel/image-build.js +7 -6
- package/dist/daemon/api/handlers/app-environments.d.ts +2 -0
- package/dist/daemon/api/handlers/app-environments.js +1 -0
- package/dist/daemon/api/handlers/providers.d.ts +2 -0
- package/dist/daemon/api/handlers/providers.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/manage.js +3 -3
- package/dist/daemon/peer/ingress.js +1 -1
- package/dist/daemon/reconcilers/recipe-image.d.ts +2 -0
- package/dist/daemon/reconcilers/recipe-image.js +5 -5
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +2 -0
- package/packages/crouter-api/dist/commands/sys/daemon.js +8 -3
- package/packages/crouter-api/dist/core/canvas/canvas.js +14 -4
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/environments.js +3 -2
- package/packages/crouter-api/dist/core/graph/objects.js +2 -2
- package/packages/crouter-api/dist/core/import/load/copy.js +47 -23
- package/packages/crouter-api/dist/core/import/load/keys.js +77 -0
- package/packages/crouter-api/dist/core/ledger/charges.js +3 -3
- package/packages/crouter-api/dist/core/ledger/chunks.js +1 -1
- package/packages/crouter-api/dist/core/ledger/read.js +1 -1
- package/packages/crouter-api/dist/core/profiles/manifest.js +1 -1
- package/packages/crouter-api/dist/core/providers/audit.js +2 -2
- package/packages/crouter-api/dist/core/providers/call.js +2 -2
- package/packages/crouter-api/dist/core/providers/receipts.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +42 -44
- package/packages/crouter-api/dist/daemon/api/handlers/providers.js +1 -1
- package/packages/crouter-api/dist/daemon/api/operations.js +4 -0
- package/packages/crouter-api/dist/daemon/manage.js +3 -2
- package/packages/crouter-api/dist/daemon/reconcilers/recipe-image.js +9 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as cr}from"./boot-settings.js";import{startBrokerMemoryCap as dr}from"./broker-memory-cap.js";import{startPeerOutbox as pr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Pe,existsSync as E,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as Te}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as Ce}from"node:crypto";import{apiSocketPath as De,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Pr}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Cr}from"../core/profiles/relocate.js";import{getNode as Dr,getRow as Ar,listNodesForSupervision as Le,listParkedResidentsWithWakeMail as Lr,setFrozen as $e}from"../core/canvas/index.js";import{createApiServer as $r,closeServer as Ne}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createAppListener as Gr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Fr}from"../core/canvas/person-state.js";import{markCloudRole as Br,resolvePerson as Hr,retireLocalPerson as Ur,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as qr}from"./run-notices.js";import{startGrantEffects as Wr}from"./reconcilers/grant-effects.js";import{syncPackages as Kr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Vr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Yr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Qr}from"./cron/run-socket.js";import{hasSyncedGrants as Xr}from"../core/grants/mirror.js";import{readConfig as Oe}from"../core/config.js";import{reconcileUndeliveredTickets as Zr}from"./human/sweep.js";import{resetHandedOffDeliveries as et}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as rt}from"../core/canvas/daemon-actions.js";import{sweepReviews as tt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as nt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ot}from"./supervise-cadence.js";import{createResumeDetector as it}from"./resume-detector.js";import{setFatalFaultAnnouncer as at}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as st}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as lt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ct}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as dt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as pt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as mt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ft}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as ut}from"./reconcilers/action-lane.js";import{endLiveExecution as ht,hasObservedExit as wt,latestExecutionForNode as vt,migrateLegacyExecutionIdentities as gt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as yt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as St}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as _t}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as bt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as kt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Rt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Pt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as It}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as xt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Ct}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Dt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,subscribeImageBuilt as $t}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Nt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Mt,captureTeardownSnapshot as Be,isPidAlive as Gt,isAnyPidAlive as He,killProcessTreePids as Ue}from"../core/canvas/pid.js";import{bindFleet as Ot,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Ft,clearDaemonControl as Bt}from"./control.js";import{execDaemon as Ht,spawnDaemon as Ut}from"./manage.js";import{reconcileAndMigrateBoot as jt}from"../core/canvas/boot.js";import{resolveInstallId as zt}from"../core/canvas/install-id.js";import{setInstallId as qt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Wt,daemonOwnershipApplies as Kt,daemonOwnershipClaimed as Jt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Vt,closeAllDbs as ue,openDb as Yt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Xt,ensurePostgresHealthy as Zt,stopPostgres as en,withPostgresStartLock as rn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as tn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as nn}from"./api/handlers/broker-ops.js";import{reconcilePackages as on}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as an}from"../core/scoped-state/migrate-app-installs.js";import{publish as sn,readBuiltinSnapshot as ln}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as cn,reapStaleSpares as dn}from"../core/runtime/warm-pool.js";import{DaemonFleet as pn}from"./fleet.js";import{copyNodeFilesToRows as mn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as fn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as b}from"../core/events/operation-id.js";import{bindDaemonEventSource as un}from"../core/events/source.js";import{activateCanvasImport as hn,MigrationBlockedError as wn,runForcedCanvasImport as vn}from"../migrations/activation.js";import{adoptInstallPerson as gn,convertLegacyScopedStore as yn,personStoresCopied as Sn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as _n}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as bn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as na}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const kn=5e3,Ke=150;async function Rn(e){const c=Fe();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),p=[];for(const[i,l]of c.processes){const v=l.command;if(l.zombie||!v.includes("broker-cli.js")||!ve(v,f)||ge(v)===e)continue;const _=v.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||p.push({pid:i,nodeId:_})}let g=0;const o=[];for(const i of p){const l=Mt(i.pid);if(l===null||!l.includes("broker-cli.js")||!ve(l,f)||ge(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const v=Be(i.pid,null);if(!v.reused){try{process.platform==="linux"&&E(D)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:v})}}const w=Date.now()+kn;for(;Date.now()<w&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];He(l)&&(process.platform==="linux"&&E(D)?await N({operation:"stop",pid:i.pid}):Ue(l,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Fe();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,l]of d.processes){const v=l.command;l.zombie||!v.includes("broker-cli.js")||ve(v,f)&&ge(v)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(Rn,"reapPriorEpochBrokers");const En=5e3;async function Pn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Dr(o))?.status;(w==="active"||w==="idle")&&await $e(o,new Date().toISOString())}const f=c.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&E(D)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,En).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Gt(o.pid)&&(process.platform==="linux"&&E(D)?await N({operation:"stop",pid:o.pid}):Ue(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of c)await ht(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Pn,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
|
|
1
|
+
var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as cr}from"./boot-settings.js";import{startBrokerMemoryCap as dr}from"./broker-memory-cap.js";import{startPeerOutbox as pr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Pe,existsSync as E,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as Te}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as De}from"node:crypto";import{apiSocketPath as Ce,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Pr}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Dr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Ar,listNodesForSupervision as Le,listParkedResidentsWithWakeMail as Lr,setFrozen as $e}from"../core/canvas/index.js";import{createApiServer as $r,closeServer as Ne}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createAppListener as Gr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Fr}from"../core/canvas/person-state.js";import{markCloudRole as Br,resolvePerson as Hr,retireLocalPerson as Ur,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as qr}from"./run-notices.js";import{startGrantEffects as Wr}from"./reconcilers/grant-effects.js";import{syncPackages as Kr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Vr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Yr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Qr}from"./cron/run-socket.js";import{hasSyncedGrants as Xr}from"../core/grants/mirror.js";import{readConfig as Oe}from"../core/config.js";import{reconcileUndeliveredTickets as Zr}from"./human/sweep.js";import{resetHandedOffDeliveries as et}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as rt}from"../core/canvas/daemon-actions.js";import{sweepReviews as tt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as nt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ot}from"./supervise-cadence.js";import{createResumeDetector as it}from"./resume-detector.js";import{setFatalFaultAnnouncer as at}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as st}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as lt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ct}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as dt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as pt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as mt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ft}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as ut}from"./reconcilers/action-lane.js";import{endLiveExecution as ht,hasObservedExit as wt,latestExecutionForNode as vt,migrateLegacyExecutionIdentities as gt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as yt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as St}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as _t}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as bt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as kt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Rt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Pt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as It}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as xt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Dt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Ct}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,removeLeftoverBuildDirs as $t,subscribeImageBuilt as Nt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Mt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Gt,captureTeardownSnapshot as Be,isPidAlive as Ot,isAnyPidAlive as He,killProcessTreePids as Ue}from"../core/canvas/pid.js";import{bindFleet as Ft,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Bt,clearDaemonControl as Ht}from"./control.js";import{execDaemon as Ut,spawnDaemon as jt}from"./manage.js";import{reconcileAndMigrateBoot as zt}from"../core/canvas/boot.js";import{resolveInstallId as qt}from"../core/canvas/install-id.js";import{setInstallId as Wt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Kt,daemonOwnershipApplies as Jt,daemonOwnershipClaimed as Vt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Yt,closeAllDbs as ue,openDb as Qt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Xt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Zt,ensurePostgresHealthy as en,stopPostgres as rn,withPostgresStartLock as tn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as nn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as on}from"./api/handlers/broker-ops.js";import{reconcilePackages as an}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as sn}from"../core/scoped-state/migrate-app-installs.js";import{publish as ln,readBuiltinSnapshot as cn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as dn,reapStaleSpares as pn}from"../core/runtime/warm-pool.js";import{DaemonFleet as mn}from"./fleet.js";import{copyNodeFilesToRows as fn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as un}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as b}from"../core/events/operation-id.js";import{bindDaemonEventSource as hn}from"../core/events/source.js";import{activateCanvasImport as wn,MigrationBlockedError as vn,runForcedCanvasImport as gn}from"../migrations/activation.js";import{adoptInstallPerson as yn,convertLegacyScopedStore as Sn,personStoresCopied as _n}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as bn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as kn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as oa}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const Rn=5e3,Ke=150;async function En(e){const c=Fe();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),p=[];for(const[i,l]of c.processes){const v=l.command;if(l.zombie||!v.includes("broker-cli.js")||!ve(v,f)||ge(v)===e)continue;const _=v.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||p.push({pid:i,nodeId:_})}let g=0;const o=[];for(const i of p){const l=Gt(i.pid);if(l===null||!l.includes("broker-cli.js")||!ve(l,f)||ge(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const v=Be(i.pid,null);if(!v.reused){try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:v})}}const w=Date.now()+Rn;for(;Date.now()<w&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];He(l)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):Ue(l,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Fe();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,l]of d.processes){const v=l.command;l.zombie||!v.includes("broker-cli.js")||ve(v,f)&&ge(v)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(En,"reapPriorEpochBrokers");const Pn=5e3;async function In(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Cr(o))?.status;(w==="active"||w==="idle")&&await $e(o,new Date().toISOString())}const f=c.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,Pn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Ot(o.pid)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):Ue(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of c)await ht(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(In,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
|
|
2
2
|
`),"utf8")}s(Q,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Je,"isMissingPathError");function Ve(e){const c=me();let f;try{f=hr(c,"utf8")}catch(p){if(Je(p))return;throw p}if(f.split(`
|
|
3
|
-
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(p){if(Je(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const
|
|
4
|
-
`),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),w}s(
|
|
5
|
-
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=
|
|
3
|
+
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(p){if(Je(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const xn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new st;at(e=>X.handleFatalFault(e,!1));const Tn=new ct,Dn=new lt,Ye=new dt,Cn=new pt,An=new mt,Ln=new ft,$n=new ut,Nn=new St,Mn=new _t,Gn=new bt,On=new Rt,Fn=new kt,Bn=new Pt,Hn=new It,Un=new xt,jn=new Tt,zn=new Dt,qn=new Ct,Wn=new At;$t();const Kn=new Lt;async function Jn(e=Date.now(),c=xn){const f=je(),p=await X.runFleetPreamble(f);let g,o,w;try{o=await fe();const d=(await Le()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),w=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(w.map(i=>i.node_id));w.push(...(await Lr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:c,held:o}),await Tn.run(e,{rows:g,held:o}),await Dn.run(e);const y=await Ye.run(e,{rows:[...g,...w],fleet:f});await Cn.run(e,o),await Wn.run(e,o),await Kn.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c,held:o}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c}),await Mn.run(e,{lifecycle:c,fleet:f,held:o}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),Un.run(e,{lifecycle:c}),jn.run(e,{lifecycle:c}),await _r(),qn.run(e,{fleet:f,lifecycle:c}),await zn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:p,frozen:y})}s(Jn,"superviseTick");async function Vn(e,c=Date.now()){if((await fe()).has(e))return;const f=await vt(e);if(f===null||!wt(f))return;const p=await Ar(e);p===null||p.kind==="human"||await Ye.runNode(c,p,je())}s(Vn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"||e==="all"}s(Z,"roleRunsLanes");function H(e){return e===void 0||e==="api"||e==="all"}s(H,"roleServesRequests");const Yn=66e4;function Qn(e){const c=new Nr().registerAll(Mr(()=>null).filter(l=>l.pattern==="/healthz")),f=s((l,v)=>{const _=(l.url??"/").split("?")[0];if((l.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){c.handle(l,v,null,{class:"person"});return}v.writeHead(404,{"content-type":"application/json; charset=utf-8"}),v.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=Ce();E(p)&&Ie(p);const g=Y(f),o=new Promise((l,v)=>{g.once("error",v),g.listen(p,()=>{g.off("error",v),xe(p,384),l()})});let w,y=null,d=o;const u=e.tcp??Te()??Oe("user").api.tcp;if(u!==void 0&&u!==""){const l=/^(.*):(\d+)$/.exec(u.trim());if(l===null||Number(l[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const v=Y(f);v.on("error",_=>m({event:"api.server.failed",level:"error",error:_})),d=o.then(()=>new Promise(_=>{v.once("error",()=>_()),v.listen(Number(l[2]),l[1]===""?"0.0.0.0":l[1],()=>{const P=v.address();y=`${P.address}:${P.port}`,_()})})),w=v}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(l={}){if(!i){i=!0,await Promise.all([Ne(g,new Set,l.graceMs),w===void 0?Promise.resolve():Ne(w,new Set,l.graceMs)]);try{E(p)&&Ie(p)}catch{}}}}}s(Qn,"createProbeServer");const Xn="daemon is draining for shutdown and admits no new work";async function Zn(e){Pe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Ae(),493);const c=Ce();if(E(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),d()})});let p;const g=e.tcp??Te();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,l)=>{u.once("error",l),u.listen(Number(d[2]),d[1],()=>{u.off("error",l),i()})}),p=u}Q();let o;const w=s(()=>(o??=(async()=>{f.closeAllConnections(),p?.closeAllConnections(),await Promise.all([f,p].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(l=>l?i(l):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{w().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
|
|
4
|
+
`),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),w}s(Zn,"serveLayoutRefusal");async function eo(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return Zn(e);Ir();const c=s(r=>{process.stderr.write(`[crtrd] ${r}
|
|
5
|
+
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Jt(e.role);on(Z(e.role));const g=s(async()=>p?await Kt(De(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:De(16).toString("hex")}},"claimOwnership"),{database:o,ownership:w}=e.role!==void 0||f?{database:{url:await Yt()},ownership:await g()}:await tn(async()=>({database:await Zt({log:c,startLockHeld:!0}),ownership:await g()}));if(!w.claimed){if(w.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${w.incumbentPid??"?"})
|
|
6
6
|
`);else{const r=[w.incumbentPid!==void 0?`pid ${w.incumbentPid}`:void 0,w.verdict!==void 0?`verdict ${w.verdict}`:void 0].filter(a=>a!==void 0),t=r.length>0?` (${r.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${w.reason}${t}
|
|
7
|
-
`),w.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(w.reason==="own_identity_indeterminate"||w.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=w.claim;let d=null,u=null,i=null,l=null,v,_="";try{p&&await
|
|
7
|
+
`),w.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(w.reason==="own_identity_indeterminate"||w.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=w.claim;let d=null,u=null,i=null,l=null,v,_="";try{p&&await En(y.token);for(const n of Dr())process.stderr.write(`[crtrd] ${n}
|
|
8
8
|
`);for(const n of await Tr())process.stderr.write(`[crtrd] ${n}
|
|
9
|
-
`);await
|
|
10
|
-
`)}else{d=await Hr(),d!==null&&(jr(d.id),await we(d.id));const n=await he(async h=>(await Me(h),d===null?null:await
|
|
9
|
+
`);await Qt(),await Xt(o.url,c);const r=e.role===void 0&&!await _n();let t=null;r&&(Sn({kind:"user",root:We()}),t=bn(We())),e.role===void 0&&kn(t??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const a=s(n=>{we(n).catch(h=>m({level:"error",event:"daemon.settings.reload_failed",error:h}))},"reloadPerson");if(v=await M.subscribe(n=>{qe().includes(n)&&a(n)},{kinds:["settings"],onListenStart:s(()=>{for(const n of qe())a(n)},"onListenStart")}),e.role!==void 0&&Br(),e.role==="all"&&Fr(),e.role!==void 0){let n;try{n=cn()}catch(R){m({level:"error",event:"daemon.packages.snapshot_failed",error:R})}const h=await he(async R=>(await Me(R),n===void 0?void 0:await ln(R,n,"release")));l=await he(async R=>await sn(R));for(const R of h?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${R.path}: ${R.error}
|
|
10
|
+
`)}else{d=await Hr(),d!==null&&(jr(d.id),await we(d.id));const n=await he(async h=>(await Me(h),d===null?null:await an(h)));if(n!==null){for(const h of n.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${h.message}
|
|
11
11
|
`);for(const h of n.invalid)process.stderr.write(`[crtrd] package file is not a document: ${h.path}: ${h.error}
|
|
12
12
|
`);for(const h of n.quarantined)process.stderr.write(`[crtrd] plugin "${h.name}" has a damaged ${h.file} (${h.reason}); ${h.movedTo!==void 0?`moved to ${h.movedTo}`:"left in place and skipped"}
|
|
13
13
|
`);for(const h of n.kinds.refused)process.stderr.write(`[crtrd] plugin "${h.plugin}" kind ${h.kind} not registered: ${h.message}
|
|
14
14
|
`);for(const h of n.kinds.invalid)process.stderr.write(`[crtrd] plugin "${h.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${h.error}
|
|
15
|
-
`)}}if(_=await
|
|
16
|
-
`)}}catch(r){await M.close();try{if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}await ue()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}let P=!0,ee,U=Promise.resolve(),re=!1,j,te,ne,oe,ie,A;const z=new Set;let ae=!1,ye=!1,x,I,q=!1,W,L,G,O,F,se,le,ce,de;const Qe=it();let T,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function k(r){z.add(r),r.finally(()=>{z.delete(r)}).catch(()=>{})}s(k,"registerDetached");const er={acceptsDetachedWork:s(()=>P,"acceptsDetachedWork"),registerDetached:k};async function rr(){try{P=!1,
|
|
15
|
+
`)}}if(_=await qt(),Wt(_),e.role===void 0&&d!==null){if(await yn(d.id),process.platform==="darwin"){const{readConfig:n,updateConfig:h}=await import("../core/config.js");if(n("user").paths?.user_files===void 0){const{homedir:R}=await import("node:os");await h("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=R()})}}u=await Ur(),u.joinedFrom!==null&&await we(u.person),await cr(),i=await zr()}if(process.platform==="linux"&&E(C)&&(Pr(),await N({operation:"users.sync",users:await kr()})),p){await yt(y.token);const n=await fn();Object.values(n).some(h=>h>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(n)}
|
|
16
|
+
`)}}catch(r){await M.close();try{if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}await ue()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}let P=!0,ee,U=Promise.resolve(),re=!1,j,te,ne,oe,ie,A;const z=new Set;let ae=!1,ye=!1,x,I,q=!1,W,L,G,O,F,se,le,ce,de;const Qe=it();let T,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function k(r){z.add(r),r.finally(()=>{z.delete(r)}).catch(()=>{})}s(k,"registerDetached");const er={acceptsDetachedWork:s(()=>P,"acceptsDetachedWork"),registerDetached:k};async function rr(){try{P=!1,nn.close(),ne?.(),ne=void 0,oe?.(),v?.(),oe=void 0,ie?.(),ie=void 0,ce?.(),ce=void 0,await M.close(),j!==void 0&&(clearInterval(j),j=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),de?.(),de=void 0;let r;do r=U,await r;while(r!==U);for(;z.size>0;)await Promise.allSettled([...z]);if(A!==void 0&&(p&&await In(A),await A.exitsSettled(),A.dispose()),I!==void 0&&!q&&(q=!0,await I.close()),se?.(),se=void 0,le?.(),le=void 0,F!==void 0){const t=F;F=void 0,await t.stop()}if(L!==void 0){const t=L;L=void 0,await t.close()}if(W!==void 0){const t=W;W=void 0,await t.close()}if(ae||(Ve(process.pid),ae=!0),ae&&!ye){if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}ye=!0,await ue()}}finally{Ht(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(rr,"cleanupAttempt");const K=1e3;let Se=!1;function tr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return Se?{graceMs:K}:(Se=!0,b.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{nr()},K),{graceMs:K})}s(tr,"requestHandover");async function nr(){try{await D()}catch(r){const t=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
17
17
|
${t}
|
|
18
|
-
`),process.exit(1)}try{process.platform==="linux"&&E(
|
|
19
|
-
`),process.exit(1)}process.exit(0)}s(nr,"performHandover");function
|
|
18
|
+
`),process.exit(1)}try{process.platform==="linux"&&E(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ut();const r=await jt();b.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:r.pid??r.existing_pid??null,spawned:r.started}})})}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:r})});const t=r instanceof Error?r.message:String(r);process.stderr.write(`[crtrd] handover successor failed to start: ${t}
|
|
19
|
+
`),process.exit(1)}process.exit(0)}s(nr,"performHandover");function D(){if(x!==void 0)return x;const r=rr();return x=r,r.then(()=>{x===r&&(x=void 0)},()=>{x===r&&(x=void 0)}),r}s(D,"requestCleanup");async function or(){S={phase:"initializing",message:Xn,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Yn}))}s(or,"drainApi");async function _e(r){try{r==="SIGTERM"&&e.role==="api"&&await or(),await D(),await rn({claimed:s(async()=>{try{return p&&await Vt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(t){process.exitCode=1;const a=t instanceof Error?t.stack??`${t.name}: ${t.message}`:String(t);process.stderr.write(`[crtrd] ${r} cleanup failed:
|
|
20
20
|
${a}
|
|
21
|
-
`),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){
|
|
21
|
+
`),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){D().catch(()=>{})}s(Re,"onExit");async function J(r){P&&(U=U.then(r).then(()=>{},t=>{b.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:t})})}))}s(J,"enqueue");async function V(){!P||re||(Qe.check()&&T&&(m({level:"info",event:"daemon.resume.detected"}),k(T().catch(()=>{}))),re=!0,await J(async()=>{if(re=!1,!!P)try{f||await en({log:c}),await Jn(Date.now(),er)}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:r})})}}))}s(V,"enqueueTick");let B=null;async function ir(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const r=S.phase==="prepared";try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},r?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(t){throw B=t,{status:500,code:"admission_failed",message:`daemon admission failed: ${t instanceof Error?t.message:String(t)}`}}}s(ir,"admitStartup");async function ar(r){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const t=await gn({dryRun:r.dryRun});if(r.dryRun||t.pending||S.phase!=="blocked")return{result:t,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:t,resumed:!1};try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},{result:t,resumed:!0}}catch(a){const n=a instanceof Error?a.message:String(a);return setTimeout(()=>{D().catch(()=>{})},1e3),{result:t,resumed:!1,resumeError:n}}}finally{$=null}}s(ar,"repairMigrations");async function sr(){ee=e.intervalMs??ot;const r=y.token;A=new mn({epoch:r,enqueue:J}),Ft(A),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},b.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const t=_;if(b.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:t}})}),b.fresh(()=>{let a;try{a=nt()}catch{return}a!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:a.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Or(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await b.fresh(async()=>{await tt(),await Zr();const a=e.role!==void 0;await et(Date.now(),a),await rt(Date.now(),a)}),e.role===void 0&&await b.fresh(async()=>{const{reconcile:a,migrated:n}=await zt(gt);a.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:a.cleared.length,same_boot_proven:a.sameBootProven}}),n.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await b.fresh(async()=>{const a=await fe();for(const n of await Le())a.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await $e(n.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await b.fresh(async()=>{await Mt();for(const a of un){const n=await a.apply();n.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:a.id,...n.summary}})}}),k(Qr()),T){const a=s(()=>{k(T().catch(()=>{})),k(mr().then(n=>F?.observe(n)).then(()=>{},n=>{m({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");k(Yr().then(({completion:n})=>n).catch(n=>{m({level:"error",event:"daemon.grants.sweep_failed",error:n})})),a(),G=setInterval(a,Ge*1e3),G.unref(),de=pr({joined:!0,register:k})}await J(async()=>{await pn(),await dn()}),te=dr(),j=setInterval(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},ee),ne=await Nt(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))}),oe=await M.subscribe(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},{kinds:["spend_limits"]}),ie=await M.subscribe(a=>{J(()=>b.fresh(()=>Vn(a)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:a})=>a(()=>!P,n=>m({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(a=>m({level:"warn",event:"daemon.move.settle_failed",error:a}))}s(sr,"completeStartup");function pe(){return Xe??=sr().catch(r=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},r})}s(pe,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),hn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),i!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),H(e.role)?W=await yr():Sr(gr());const r=y.token;Bt({epoch:r,requestHandover:tr,registerDetached:k,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),Q(),I=H(e.role)?$r({tcp:e.tcp}):Qn(e),await I.ready,Q(I.tcpAddress()??"");const t=Oe("user").runtime;if(t?.issuer&&(T=Vr(t.issuer,k),t.unsandboxed===!0&&(F=fr({syncGrants:T}))),e.role==="api"||e.role==="all"){const a=s(()=>k(import("../core/providers/bundles.js").then(h=>h.syncProviderBundles()).catch(h=>{m({level:"error",event:"daemon.providers.bundle_sync_failed",error:h})})),"bundleTick"),n=s(()=>{k(Kr().catch(h=>{m({level:"error",event:"daemon.packages.sync_failed",error:h})})),a()},"packageTick");n(),O=setInterval(n,Ge*1e3),O.unref()}if(H(e.role)&&(se=await qr()),Z(e.role)&&(le=Jr()),ce=await Wr({serves:H(e.role),runsLanes:Z(e.role)}),t?.unsandboxed===!0&&t.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),H(e.role)&&t!==void 0&&t.listener!==void 0&&t.unsandboxed!==!0&&(L=await Gr(t,async()=>await Xr(t.issuer.replace(/\/$/,"")),T),await L.ready,Q(I.tcpAddress()??"",`${t.listener.address}:${L.port()}`)),e.role===void 0)try{await wn()}catch(a){if($=null,a instanceof vn)return S={phase:"blocked",message:a.message,blockerPaths:a.blockerPaths},D;throw a}process.platform==="linux"&&E(C)&&(Er(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await pe(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return D}catch(r){try{await D()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}}s(eo,"runDaemon");var ra=eo;export{Yn as API_DRAIN_GRACE_MS,oa as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,ra as default,Vn as exitedNodePass,Z as roleRunsLanes,H as roleServesRequests,eo as runDaemon,Jn as superviseTick,In as teardownFleet};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var A=Object.defineProperty;var r=(t,i)=>A(t,"name",{value:i,configurable:!0});import{chmodSync as N,closeSync as Y,existsSync as F,mkdirSync as k,openSync as
|
|
1
|
+
var A=Object.defineProperty;var r=(t,i)=>A(t,"name",{value:i,configurable:!0});import{chmodSync as N,closeSync as Y,existsSync as F,mkdirSync as k,openSync as G,unlinkSync as L,writeFileSync as J,rmSync as R}from"node:fs";import{createServer as X}from"node:http";import{dirname as K,join as z}from"node:path";import{spawn as V}from"node:child_process";import{SELF_UPDATE_SCRIPT as W}from"../core/self-update.js";import{apiSocketPath as $,crtrHome as b}from"../core/canvas/paths.js";import{bindDaemonEventSource as Q}from"../core/events/source.js";import{emitEvent as d}from"../core/events/emit.js";import{brokerCommandDeclaresCanvasHome as Z}from"../core/runtime/broker-ownership.js";import{createMachineExecutor as q,findBrokers as ee,stopAllBrokers as ne}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as te}from"../core/checkout-identities.js";import{machineWorktreeHandlers as oe}from"../core/worktree-machine.js";import{readPersonCredential as re}from"../core/directory/person-credential.js";import{socketDir as ie}from"../core/layout.js";import{isDaemonRunning as ae,pidfilePath as I,readPidfile as se}from"./pidfile.js";import{spawnDaemon as ce}from"./manage.js";import{processGeneration as de}from"../commands/sys/shared.js";import{cancelMachineCron as me,runMachineCron as le,stopOrphanedMachineCrons as fe}from"./cron/machine-exec.js";import{startMachineLink as pe}from"./machine-link/client.js";import{deleteMoveRecord as P,readMachineConfig as ue,readMachineCredential as C,readMoveRecord as he,writeMoveRecord as ve}from"./machine-link/config.js";import{jobExitReporting as _e,stopMachineJob as we}from"./machine-link/job-sweep.js";import{notifyMoveFinished as ye}from"./machine-link/move-notify.js";import{machineSupervision as Se,SUPERVISION_TICK_MS as Ie}from"./machine-supervision.js";import{startBrokerMemoryCap as ge}from"./broker-memory-cap.js";const D=10*6e4,Ee=3e4,Me=75;let g=0;function Te(t,i){if(Date.now()-g<D||!/^\d+\.\d+\.\d+$/.test(t))return;g=Date.now(),d({level:"warn",event:"daemon.machine.updating",fields:{release:t}});const s=G(z(b(),"crtrd.err"),"a"),n=V(process.execPath,[W,"--version",t],{stdio:["ignore",s,s]});Y(s),n.on("error",a=>d({level:"error",event:"daemon.machine.update_failed",fields:{release:t},error:a})),n.on("exit",a=>{if(a===Me){g=Date.now()-D+Ee;return}if(a!==0){d({level:"error",event:"daemon.machine.update_failed",fields:{release:t,exit_code:a}});return}i()})}r(Te,"updateToRelease");const O=1024;function xe(t,i){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:t,signed_in:i,generation_id:de()?.id??null,startup_phase:t?"ready":"recovering"}}r(xe,"machineHealth");async function tn(){const t=ue();if(t===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const i=re()!==void 0;if(i&&C(),ae())throw new Error("a crtrd is already running for this home");Q(),i||(await ne(),await fe(),d({level:"info",event:"daemon.machine.signed_out",fields:{environment:t.environmentId}})),k(ie(),{recursive:!0,mode:493});const s=$();F(s)&&L(s);let n;const a=_e(()=>n),c=X((e,o)=>{const m=(e.url??"").split("?")[0];if(e.method==="POST"&&(m==="/job-exit"||m==="/job-activity")){const T=[];let S=0;e.on("data",l=>{S+=l.length,S<=O&&T.push(l)}),e.on("end",()=>{if(S>O){o.writeHead(413),o.end();return}let l={};try{l=JSON.parse(Buffer.concat(T).toString("utf8"))}catch{}const x=typeof l.node=="string"&&typeof l.job=="string";o.writeHead(x?202:400,{"content-type":"application/json; charset=utf-8"}),o.end("{}"),x&&(m==="/job-exit"?a.notice:a.activity)(l.node,l.job)});return}const M=(e.method??"GET")==="GET"&&(e.url??"/").split("?")[0]==="/healthz";o.writeHead(M?200:404,{"content-type":"application/json; charset=utf-8"}),o.end(JSON.stringify(M?xe(n?.connected()===!0,i):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((e,o)=>{c.once("error",o),c.listen(s,()=>{c.off("error",o),N(s,384),e()})}),k(K(I()),{recursive:!0}),J(I(),String(process.pid),"utf8");let f;t.runId!==void 0&&await be(t.runId,i,()=>f!==void 0);const u=new Set,v=new Set;let _=!1;const p=q({apiUrl:t.apiUrl,environmentId:t.environmentId,onExit:r(e=>n?.reportExit(e),"onExit")}),j=r(async(e,o)=>{u.add(e.executionId);for(const m of v)m.add(e.executionId);try{return await p.start(e,o)}finally{u.delete(e.executionId)}},"start");n=i?pe({apiUrl:t.apiUrl,environmentId:t.environmentId,credential:C,onOpen:r(()=>{a.onOpen(),_=!0},"onOpen"),onBehind:r(e=>Te(e,U),"onBehind"),handlers:{start:j,wake:p.wake,stop:p.stop,status:p.status,delete:p.delete,viewer:p.viewer,"cron.run":le,"cron.cancel":me,"job.stop":r(e=>we(e),"job.stop"),...oe,...te}}):void 0;const E=n===void 0?void 0:Se({link:n,brokers:r(async()=>{const e=new Set(u);v.add(e);const o=await ee().finally(()=>v.delete(e));return _&&(_=!1,n?.reportRunning([...new Set([...e,...o.filter(m=>Z(m.command,b())).map(m=>m.execution)])])),o},"brokers"),stop:r((e,o)=>p.stop({execution:{executionId:e,nodeId:o,attempt:0},options:{reason:"yield_stall"}}),"stop")});let w=!1;const B=E===void 0?void 0:setInterval(()=>{w||(w=!0,E(Date.now()).catch(e=>d({level:"error",event:"daemon.machine.supervision_failed",error:e})).finally(()=>{w=!1}))},Ie),H=ge();d({level:"info",event:"daemon.machine.started",fields:{environment:t.environmentId}});const y=r(()=>f??=(async()=>{n?.stop(),clearInterval(B),H(),await new Promise(e=>{c.close(()=>e()),c.closeAllConnections()}),se()===process.pid&&(R(s,{force:!0}),R(I(),{force:!0})),process.off("SIGINT",h),process.off("SIGTERM",h)})(),"teardown"),U=r(async()=>{if(f===void 0){await y();try{const e=await ce();d({level:"info",event:"daemon.machine.replaced",fields:{successor_pid:e.pid??e.existing_pid??null}}),process.exit(0)}catch(e){d({level:"error",event:"daemon.machine.successor_failed",error:e}),process.exit(1)}}},"replaceSelf"),h=r(()=>{y().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",h),process.on("SIGTERM",h),y}r(tn,"runMachineDaemon");const ke=5e3,Re=3e5;async function be(t,i,s){let n;try{n=he()}catch(c){d({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:c.message}});return}if(n===void 0||n.state==="running"||n.runId!==t)return;if(n.notified||n.notify===null){P();return}if(n.state==="committed"&&(n={...n,state:"activated"},ve(n)),!i)return;const a=n;(async()=>{let c=ke;for(;;){try{await ye(a),P();return}catch(f){d({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:a.notify??"",error:f.message}})}if(await new Promise(f=>{setTimeout(f,c).unref()}),s())return;c=Math.min(c*2,Re)}})()}r(be,"settleFinishedMove");export{xe as machineHealth,tn as runMachineDaemon};
|
package/dist/daemon/manage.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var J=Object.defineProperty;var o=(e
|
|
2
|
-
`).at(-1)??"";return JSON.parse(u)}o(P,"runDaemonEntry");function
|
|
3
|
-
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(
|
|
1
|
+
var J=Object.defineProperty;var o=(t,e)=>J(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as q}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as x,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as N}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{apiSocketPath as nt,crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as ot}from"../core/canvas/pid.js";import{bindDaemonEventSource as at,eventSource as it}from"../core/events/source.js";import{hostExecPath as I}from"../core/runtime/branded-host.js";import{isDaemonRunning as st,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as ct,readMachineConfig as ut}from"./machine-link/config.js";import{exclusiveLockOwnerPid as lt}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as _t}from"../core/canvas/paths.js";import{envNoDaemonAutostart as dt}from"../shared/env.js";import{waitForDaemonAvailability as pt}from"../api/index.js";import{localClient as Rt}from"../api/node-transport.js";const ft=["TMUX","TMUX_PANE","NODE_OPTIONS"],mt=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_LAYOUT_REFUSE","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),ht=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function Et(t){return ft.includes(t)?!1:t.startsWith("CRTR_")?mt.has(t)||ht.some(e=>t.startsWith(e)):!0}o(Et,"daemonKeepsEnv");function y(){const t={};for(const[e,r]of Object.entries(process.env))Et(e)&&(t[e]=r);return t}o(y,"sanitizedDaemonEnv");function Tt(){for(let t=x(Z(import.meta.url));;t=x(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(x(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Tt,"generationRoot");async function g(){const t=Tt(),e=N(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",N(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=N(T(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(g,"resolveDaemonLaunch");function wt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(wt,"daemonCommandDeclaresCanvasHome");function Dt(){const t=ot();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&wt(a,e)&&n!==process.pid&&r.push(n);return r}o(Dt,"findDaemonPids");function St(t){const e=Dt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)q("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(St,"sweepStrayDaemons");async function Zt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=I(),r=await g();return t(e,[e,...r,"--canvas-home",S()],y())}o(Zt,"execDaemon");async function P(t){const e=await g(),r=K(I(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:y()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
|
|
2
|
+
`).at(-1)??"";return JSON.parse(u)}o(P,"runDaemonEntry");function te(t,e){return P(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return P(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return P(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return Rt({autostart:!1,timeoutMs:e,socketPath:nt()}).probeHealthz(e)}o(b,"probeDaemonHealth");function At(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(At,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new C(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function U(t){return new Promise(e=>{setTimeout(e,t)})}o(U,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
|
|
3
|
+
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ct(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??U,i=r.now??Date.now;let p=null,l=null;return await pt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${t} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${t} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof C&&(l=_),_}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new C(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(Ct,"verifyDaemonStartup");async function Ot(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??U,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ot,"waitForDaemonExit");const Mt=2e3,xt=5e3;async function z(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??U,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ot(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Mt;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await z(t)==="killed",n=St(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Nt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Nt,"readLogTailFrom");async function It(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ut()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:At(i)}}et(S(),{recursive:!0});const n=await g().catch(i=>{throw new Y(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();it()===void 0&&at();const c=K(I(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:y()});G(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await Ct(d,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Nt(a,u),"childStderrTail")},e)}catch(i){const p=lt(_t())===d;if(f===null&&!p&&!(i instanceof C))try{await z(d,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:d,startup_phase:e}}o(It,"spawnDaemon");function yt(){return dt()||process.argv.includes("--no-autostart")}o(yt,"autostartDisabled");const gt=5e3,Pt=6e4;let $=!1,A,O=0,M=0;function Lt(t){return Math.min(gt*2**(t-1),Pt)}o(Lt,"autostartBackoffMs");function vt(){A=void 0,O=0,M=0}o(vt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??st,r=t.spawnDaemon??It,n=t.now??Date.now;if(!yt()&&!(!t.spawnDaemon&&ct())&&!$&&!(n()<M)){if(e()){vt();return}A=void 0,$=!0,r().then(()=>{A=void 0,O=0,M=0},a=>{(a instanceof k||a instanceof Y)&&(A=a.message),O+=1,M=n()+Lt(O)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{ft as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,B as DaemonNotPreparedError,C as DaemonStartupBlockedError,yt as autostartDisabled,ae as daemonAutostartStartupFailure,wt as daemonCommandDeclaresCanvasHome,Et as daemonKeepsEnv,ie as ensureDaemon,Zt as execDaemon,Dt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,At as probeErrorMessage,vt as resetDaemonAutostart,ee as runDaemonBodiesDump,te as runDaemonImportDump,re as runDaemonInstallId,y as sanitizedDaemonEnv,It as spawnDaemon,oe as stopAllDaemons,z as stopDaemonProcess,St as sweepStrayDaemons,Ct as verifyDaemonStartup,Ot as waitForDaemonExit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var H=Object.defineProperty;var a=(e,t)=>H(e,"name",{value:t,configurable:!0});import{randomUUID as j}from"node:crypto";import{verifyCallToken as I}from"@north-light/identity";import{ENVELOPE_HEADER as L}from"../../core/peer/envelope.js";import{mirrorGrantLink as U,peerAuthority as q}from"./authority.js";import{peerVersionRefusal as z,PEER_VERSION_HEADER as D}from"../../core/peer/version.js";import{auditOutcome as v,writePeerAudit as P}from"../../core/audit.js";import{emitEvent as C}from"../../core/events/emit.js";import{joinedOwner as G}from"../../core/directory/join.js";import{grantSubs as N}from"../../core/grants/mirror.js";import{errorCodes as T}from"../../api/error-codes.js";let O;function S(){return O??=import("../api/server.js").then(e=>e.buildRouter(()=>null)),O}a(S,"defaultRouter");async function x(e,t){return(await S()).match(e.toUpperCase(),t)!==null}a(x,"isDaemonRoute");function V(e,t,r,o,i,m){if(e.headersSent){e.destroy();return}const l=T[r];e.writeHead(t,{"content-type":"application/json; charset=utf-8","Request-Id":i,"X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify({error:{code:r,message:o,origin:"runtime",...m===void 0?{}:{details:m},...l?{type:l.type}:{},request_id:i}}))}a(V,"refuse");const
|
|
1
|
+
var H=Object.defineProperty;var a=(e,t)=>H(e,"name",{value:t,configurable:!0});import{randomUUID as j}from"node:crypto";import{verifyCallToken as I}from"@north-light/identity";import{ENVELOPE_HEADER as L}from"../../core/peer/envelope.js";import{mirrorGrantLink as U,peerAuthority as q}from"./authority.js";import{peerVersionRefusal as z,PEER_VERSION_HEADER as D}from"../../core/peer/version.js";import{auditOutcome as v,writePeerAudit as P}from"../../core/audit.js";import{emitEvent as C}from"../../core/events/emit.js";import{joinedOwner as G}from"../../core/directory/join.js";import{grantSubs as N}from"../../core/grants/mirror.js";import{errorCodes as T}from"../../api/error-codes.js";let O;function S(){return O??=import("../api/server.js").then(e=>e.buildRouter(()=>null)),O}a(S,"defaultRouter");async function x(e,t){return(await S()).match(e.toUpperCase(),t)!==null}a(x,"isDaemonRoute");function V(e,t,r,o,i,m){if(e.headersSent){e.destroy();return}const l=T[r];e.writeHead(t,{"content-type":"application/json; charset=utf-8","Request-Id":i,"X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify({error:{code:r,message:o,origin:"runtime",...m===void 0?{}:{details:m},...l?{type:l.type}:{},request_id:i}}))}a(V,"refuse");const E=a((e,t)=>{const r=e.headers[t.toLowerCase()];return Array.isArray(r)?r[0]:r},"header");async function ee(){try{const e=G();if(e!==null)return e;const t=await N();return t.length===1?t[0]:null}catch{return null}}a(ee,"runtimeOwner");async function te(e,t,r,o){const i=t.getHeader("Request-Id")?.toString()??j();t.setHeader("Request-Id",i);const m=E(e,L),l=new URL(e.url??"/","http://peer.local"),R=(e.method??"GET").toUpperCase();let d={class:m===void 0?"machine":"forwarded",grantee:null,sub:null,via:"unauthenticated",operation:`${R} ${l.pathname}`,node_id:null},b=!1;const k=a(async(n,c={})=>{if(!b){b=!0;try{await P({request_id:i,resource:l.pathname,...d,...c,outcome:n})}catch(u){C({level:"error",event:"daemon.peer.audit_failed",error:u instanceof Error?u:new Error(String(u)),fields:{request_id:i}})}}},"record"),s=a(async(n,c,u,f)=>{await k(v(n)),V(t,n,c,u,i,f)},"deny");try{if(r.ready&&!await r.ready()){await s(503,"runtime_starting","runtime_starting");return}let n;if(o!==void 0&&!("chain"in o)){await s(o.status,o.code,o.message);return}if(o!==void 0)n=o;else{const y=await r.audience();if(y===null){await s(503,"runtime_starting","this machine does not yet know its own address");return}const _=E(e,"authorization");if(!_?.startsWith("Bearer ")||_.length<=7){await s(401,"unauthorized","a machine token is required");return}try{n=await I({token:_.slice(7),jwks:r.jwks,issuer:r.issuer,audience:y})}catch{await s(401,"unauthorized","invalid machine token");return}}d={...d,grantee:n.sub,sub:n.sub,via:n.chain[0]?.sub??"unauthenticated"};const c=await(r.router??S)(),u=c.match(R,l.pathname);d={...d,operation:u?.operation.name??d.operation,node_id:u?.params.id??null};const f=await r.owner(),p=await q(n,m,{self:r.self,relation:a(y=>f!==null&&y===f?"owner":null,"relation"),grantLink:U(r.syncGrants??(async()=>{}))});if("status"in p){await s(p.status,p.code,p.message);return}const w=z(E(e,D));if(w!==null){await s(426,w.code,w.message,w.details);return}const{principal:h}=p,g=h.class==="forwarded"&&h.actor.kind==="app"?h.actor:null,A={grantee:g?.app??n.sub,node_id:g?.node??d.node_id,actor:g?.app??null};t.once("close",()=>{k(t.writableFinished?v(t.statusCode):"aborted",A)}),await c.handle(e,t,null,h)}catch(n){C({level:"error",event:"daemon.peer.ingress_failed",error:n instanceof Error?n:new Error(String(n)),fields:{request_id:i}}),await s(500,"server_failure","peer request failed")}}a(te,"servePeer");export{x as isDaemonRoute,ee as runtimeOwner,te as servePeer};
|
|
@@ -40,6 +40,8 @@ export interface RecipeImageDeps {
|
|
|
40
40
|
deleteImage?: (name: string) => Promise<void>;
|
|
41
41
|
now?: () => number;
|
|
42
42
|
}
|
|
43
|
+
/** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
|
|
44
|
+
export declare function removeLeftoverBuildDirs(root?: string): void;
|
|
43
45
|
export declare class RecipeImageReconciler {
|
|
44
46
|
private readonly deps;
|
|
45
47
|
constructor(deps?: RecipeImageDeps);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE object = ? AND ${
|
|
3
|
-
RETURNING ${
|
|
4
|
-
WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${
|
|
1
|
+
var h=Object.defineProperty;var _=(r,e)=>h(r,"name",{value:e,configurable:!0});import{mkdtempSync as R,readdirSync as O,rmSync as y}from"node:fs";import{tmpdir as u}from"node:os";import{join as f}from"node:path";import{hasUnseenWakeMail as U}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as I}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as W}from"../../core/runs/events.js";import{blaxelConfigFromEnv as w}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as C,deleteImage as j,environmentImageName as b,prepareBuildDir as H,removeBuildDir as k}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as x}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as N,packagesTokenFor as $,recipeOf as F}from"../api/environment-of.js";import{brokerSignalBus as M}from"../broker-signals/bus.js";const p=3*6e4,S=10*6e4,E="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",D=`NOT ${E}`,L=`(kind = 'blaxel' AND ${D} AND recipe_revision > COALESCE(image_revision, 0) AND ${N})`,v=`(kind = 'blaxel' AND ${E} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function re(r){const e=await(await l()).prepare(`SELECT ${N} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(r);if(e===void 0)throw new Error(`no environment ${r}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}_(re,"resolveEnvironmentImage");async function ae(r){return await M.subscribe(e=>{r(e)},{kinds:["environment_image"]})}_(ae,"subscribeImageBuilt");async function P(r,e){const i=r.recipe.repositories.map(a=>a.github_full_name),t=i.length===0?null:await x(r.person,i),n=R(f(u(),"crtr-recipe-image-"));try{return await H({recipe:r.recipe,revision:r.revision,token:t?.token??null,packagesToken:await $(r.environmentId),dir:n}),await C(e,b(r.environmentId),n)}finally{k(n)}}_(P,"defaultBuild");function ne(r=u()){for(const e of O(r))e.startsWith("crtr-recipe-image-")&&y(f(r,e),{recursive:!0,force:!0})}_(ne,"removeLeftoverBuildDirs");class oe{static{_(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,i){if(i.lifecycle.acceptsDetachedWork())try{const t=new Date(e).toISOString(),n=await l(),a=await n.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(t);for(const{object:o}of a){const s=await this.claim(o,e,L,"recipe_revision");s!==null&&i.lifecycle.registerDetached(this.buildClaimed(o,Number(s.recipe_revision),s.lease).catch(m=>{g({level:"error",event:"recipe_image.failed",error:m})}))}const c=await n.prepare(`SELECT object FROM environments WHERE ${v} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(t);for(const{object:o}of c){const s=await this.claim(o,e,v,"object");s!==null&&i.lifecycle.registerDetached(this.withLease(o,s.lease,m=>this.deleteClaimed(o,m)).catch(m=>{g({level:"error",event:"recipe_image.delete_failed",error:m})}))}}catch(t){g({level:"error",event:"recipe_image.reconcile_failed",error:t})}}async claim(e,i,t,n){const a=new Date(i+p).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
|
|
2
|
+
WHERE object = ? AND ${t} AND (image_building_at IS NULL OR image_building_at <= ?)
|
|
3
|
+
RETURNING ${n} AS recipe_revision`).get(a,e,new Date(i).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:a}}async withLease(e,i,t){const n=this.deps.now??Date.now;let a=i;const c=setInterval(()=>{const o=new Date(n()+p).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(o,e,a)).changes===1&&(a=o)})().catch(()=>{})},p/3);c.unref();try{await t(()=>a)}finally{clearInterval(c)}}async deleteClaimed(e,i){try{await(this.deps.deleteImage??(t=>j(w(),t)))(b(e))}catch(t){const n=t instanceof Error?t.message:String(t),a=new Date((this.deps.now??Date.now)()+S).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${n}`,a,e,i())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:n}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,i())}async buildClaimed(e,i,t){const n=this.deps.now??Date.now;await this.withLease(e,t,async a=>{const c=await F(e);if(c===null||c.revision!==i){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,a());return}let o;try{const d=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(d===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);await(await l()).prepare("UPDATE environments SET image_error = ? WHERE object = ? AND image_building_at = ?").run(`the build of revision ${i} started and its process exited before it finished`,e,a());const T={environmentId:e,revision:i,recipe:c,person:d.person};o=await(this.deps.build??(A=>P(A,w())))(T)}catch(d){await this.recordFailure(e,a(),d instanceof Error?d.message:String(d),n());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
|
|
4
|
+
WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${D}`).run(i,o.ref,e,a(),i)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${E}`).run(o.ref,e)})}async recordFailure(e,i,t,n){const a=new Date(n+S).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(t,a,e,i)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:t}});for(const o of await B(e))try{await I(async s=>{await W(s,o.run_id,o.node_id,"environment.image_failed",{environment_id:e,error:t})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:o.node_id,error:s})}}}}async function B(r){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
|
|
5
5
|
WHERE p.environment_id = ? AND n.status IN ('active', 'idle') AND n.run_id IS NOT NULL
|
|
6
|
-
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(
|
|
6
|
+
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(r),i=[];for(const t of e)await U(t.node_id)&&i.push(t);return i}_(B,"nodesWaitingOnImage");export{E as ENVIRONMENT_DELETED_SQL,D as ENVIRONMENT_LIVE_SQL,L as IMAGE_BUILD_OWED_SQL,v as IMAGE_DELETE_OWED_SQL,p as LEASE_MS,S as RETRY_AFTER_FAILURE_MS,oe as RecipeImageReconciler,B as nodesWaitingOnImage,ne as removeLeftoverBuildDirs,re as resolveEnvironmentImage,ae as subscribeImageBuilt};
|
|
@@ -7,6 +7,12 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
|
|
|
7
7
|
|
|
8
8
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
9
9
|
|
|
10
|
+
## 0.3.753
|
|
11
|
+
|
|
12
|
+
### Charges and audit rows record the actor
|
|
13
|
+
|
|
14
|
+
`charges` and `audit_rows` gain a nullable `actor` column: the principal that presented the call (the token's presenting link, or the envelope's `act`). Rows written earlier hold null. No SDK call or response changes.
|
|
15
|
+
|
|
10
16
|
## 0.3.751
|
|
11
17
|
|
|
12
18
|
### Call tokens may name any principal
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.753",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.753",
|
|
162
|
+
"@north-light/plugin": "0.3.753",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.77';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -188,6 +188,8 @@ export const routes = {
|
|
|
188
188
|
appEnvVar: (variable) => `${V}/apps/self/env/${encodeURIComponent(variable)}`,
|
|
189
189
|
profileEnv: (name) => `${V}/profiles/${name}/env`,
|
|
190
190
|
profileEnvVar: (name, variable) => `${V}/profiles/${name}/env/${variable}`,
|
|
191
|
+
environments: () => `${V}/environments`,
|
|
192
|
+
environment: (name) => `${V}/environments/${name}`,
|
|
191
193
|
profileEnvironment: (name) => `${V}/profiles/${name}/environment`,
|
|
192
194
|
// Person settings
|
|
193
195
|
settings: () => `${V}/settings`,
|
|
@@ -13,6 +13,7 @@ import { DaemonNotPreparedError, probeDaemonHealth, probeErrorMessage, spawnDaem
|
|
|
13
13
|
import { isDaemonRunning, readPidfile, isPidAlive } from '../../daemon/pidfile.js';
|
|
14
14
|
import { cliClient } from '../api-client.js';
|
|
15
15
|
import { readMachineConfig } from '../../daemon/machine-link/config.js';
|
|
16
|
+
import { apiSocketPath } from '../../core/canvas/paths.js';
|
|
16
17
|
import { localClient } from '../../api/node-transport.js';
|
|
17
18
|
import { defineSysBranch } from './branch.js';
|
|
18
19
|
import { selectedGeneration } from './shared.js';
|
|
@@ -156,9 +157,13 @@ const daemonAdmit = defineLeaf({
|
|
|
156
157
|
});
|
|
157
158
|
// daemon status
|
|
158
159
|
/** The generation id the live daemon reports on `/v1/status`; undefined when it reports none or cannot be asked. */
|
|
159
|
-
|
|
160
|
+
/** The generation this computer's daemon runs. It asks this computer's daemon socket, never a node's relay, which on an imported Mac answers
|
|
161
|
+
* for the shared control plane. A machine-role daemon serves no `/v1/status` and reports its generation in `/healthz` instead. */
|
|
162
|
+
async function servingGenerationId(health) {
|
|
163
|
+
if (health.generation_id !== undefined)
|
|
164
|
+
return health.generation_id ?? undefined;
|
|
160
165
|
try {
|
|
161
|
-
const status = await localClient({ autostart: false }).status();
|
|
166
|
+
const status = await localClient({ autostart: false, socketPath: apiSocketPath() }).status();
|
|
162
167
|
return status.generation_id ?? undefined;
|
|
163
168
|
}
|
|
164
169
|
catch {
|
|
@@ -193,7 +198,7 @@ const daemonStatus = defineLeaf({
|
|
|
193
198
|
return { running: false };
|
|
194
199
|
try {
|
|
195
200
|
const health = await probeDaemonHealth();
|
|
196
|
-
const serving = await servingGenerationId();
|
|
201
|
+
const serving = await servingGenerationId(health);
|
|
197
202
|
const selected = selectedGeneration().generation?.id;
|
|
198
203
|
return {
|
|
199
204
|
running: true,
|
|
@@ -80,6 +80,16 @@ const turnOpen = (r) => r['turn_open_at'] != null && r['turn_closed_at'] == null
|
|
|
80
80
|
/** Whether the engine behind an open turn is alive. A cloud role never hosts a broker (it runs on a Mac or in a sandbox),
|
|
81
81
|
* so a pid probe on this host always fails there and the execution row is the only liveness record. */
|
|
82
82
|
const engineLive = (pidPresentHere) => pidPresentHere || isCloudRole();
|
|
83
|
+
/** The `node_rows` columns `rowFrom` reads. Whole-table scans select these, never `*`: the view also carries each node's
|
|
84
|
+
* initial prompt, launch config and tool summaries (about 60 KB per finished node in prod), which no `NodeRow` holds. */
|
|
85
|
+
const NODE_ROW_COLUMNS = `node_id, name, description, cycles, kind, mode, lifecycle, status, cwd, host_kind, profile_id, scopes_json, isolated,
|
|
86
|
+
grantee, sub, grant_id, client_id, metadata_json, run_id, event_cursor, last_activity_at, caused_by, last_turn_error_json, deleting_at,
|
|
87
|
+
parent, created, intent, cycle_pending, frozen_at, respawn_failures, respawn_not_before, launched_at, last_settled_at, terminal_reason,
|
|
88
|
+
final_report, finalized_at, outcome_kind, outcome_reason, outcome_at, outcome_revision, outcome_detail_json, deadline_at,
|
|
89
|
+
telemetry_tokens_in, telemetry_context_tokens, telemetry_last_activity, telemetry_updated_at, pi_pid, pi_pid_identity,
|
|
90
|
+
"window", tmux_session, pane, turn_open_at, turn_closed_at,
|
|
91
|
+
fault_id, fault_link, fault_op, fault_kind, fault_message, fault_since, fault_operation_id, fault_anchor_entry_id,
|
|
92
|
+
fault_retry_disposition, fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at, fault_provider_error_json`;
|
|
83
93
|
function rowFrom(r) {
|
|
84
94
|
const node = {
|
|
85
95
|
node_id: r['node_id'],
|
|
@@ -670,7 +680,7 @@ export async function listNodes(filter) {
|
|
|
670
680
|
if (filter?.withRecordedPidOrFrozen === true)
|
|
671
681
|
clauses.push('(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)');
|
|
672
682
|
const rows = await (await openDb())
|
|
673
|
-
.prepareUncached(`SELECT
|
|
683
|
+
.prepareUncached(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows WHERE ${clauses.join(' AND ')} ORDER BY created`)
|
|
674
684
|
.all(...params);
|
|
675
685
|
return rows.map(rowFrom);
|
|
676
686
|
}
|
|
@@ -702,7 +712,7 @@ export const nodesForSupervisionSql = `WITH candidates AS MATERIALIZED (
|
|
|
702
712
|
SELECT node_id FROM executions
|
|
703
713
|
WHERE state != 'exited' AND state = 'running' AND pid IS NOT NULL
|
|
704
714
|
)
|
|
705
|
-
SELECT v
|
|
715
|
+
SELECT ${NODE_ROW_COLUMNS.split(',').map((c) => `v.${c.trim()}`).join(', ')} FROM candidates c CROSS JOIN node_rows v
|
|
706
716
|
WHERE v.node_id = c.node_id
|
|
707
717
|
AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
708
718
|
AND v.kind != 'human'
|
|
@@ -1109,13 +1119,13 @@ export async function pruneNodes(opts) {
|
|
|
1109
1119
|
const quiet = (row) => lastActivityMs(row) < cutoffMs;
|
|
1110
1120
|
const toPruned = (row) => ({ node_id: row.node_id, status: row.status, created: row.created });
|
|
1111
1121
|
const watchedOwners = await ownersOfWatchedDocuments();
|
|
1112
|
-
const terminal = (await filterAsync((await db.prepare(`SELECT
|
|
1122
|
+
const terminal = (await filterAsync((await db.prepare(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows
|
|
1113
1123
|
WHERE status IN ('dead', 'done', 'canceled') AND created < ?
|
|
1114
1124
|
ORDER BY created`)
|
|
1115
1125
|
.all(cutoff))
|
|
1116
1126
|
.map(rowFrom), async (row) => await isCollectible(row, { pastTtl: true }) && quiet(row) && !watchedOwners.has(row.node_id) && !await opts.held(row.node_id)))
|
|
1117
1127
|
.map(toPruned);
|
|
1118
|
-
const stale = !includeStale ? [] : (await filterAsync((await db.prepare(`SELECT
|
|
1128
|
+
const stale = !includeStale ? [] : (await filterAsync((await db.prepare(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows
|
|
1119
1129
|
WHERE status IN ('active', 'idle') AND created < ?
|
|
1120
1130
|
ORDER BY created`)
|
|
1121
1131
|
.all(cutoff))
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 38;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -11,9 +11,10 @@ import { setCloudProfileWriter } from './profiles/manifest.js';
|
|
|
11
11
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
12
12
|
export async function createProfileBlaxelEnvironment(db, spec) {
|
|
13
13
|
const app = await ownerForGrantee(db, spec.grantee);
|
|
14
|
-
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
|
|
14
|
+
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app, { noActsFor: spec.person.startsWith('app:') });
|
|
15
15
|
const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
|
|
16
|
-
|
|
16
|
+
if (!spec.person.startsWith('app:'))
|
|
17
|
+
await writeActsFor(db, object.id, spec.person); // an app environment is kept for no person
|
|
17
18
|
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, spec.payer ?? null, new Date().toISOString());
|
|
18
19
|
if (spec.recipe !== undefined)
|
|
19
20
|
await writeEnvironmentRecipe(db, object.id, spec.recipe);
|