@north-light/cli 0.3.756 → 0.3.758
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +2 -2
- package/dist/clients/attach/viewer.js +432 -432
- package/dist/commands/profile/new.js +1 -1
- package/dist/commands/profile/project.js +1 -1
- package/dist/commands/sys/import/move.d.ts +5 -0
- package/dist/commands/sys/import/move.js +7 -7
- package/dist/commands/sys/import/retry.d.ts +1 -0
- package/dist/commands/sys/import/retry.js +1 -0
- package/dist/commands/sys/import/start.js +1 -1
- package/dist/core/import/export/cloud.d.ts +1 -0
- package/dist/core/import/export/cloud.js +1 -1
- package/dist/core/import/load/bind.d.ts +5 -4
- package/dist/core/import/load/bind.js +16 -16
- package/dist/core/import/load/blobs.d.ts +6 -0
- package/dist/core/import/load/blobs.js +1 -1
- package/dist/core/import/load/prepare.js +8 -8
- package/dist/core/import/load/run.js +1 -1
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/profiles/project-dir.d.ts +3 -0
- package/dist/core/profiles/project-dir.js +1 -0
- package/dist/daemon/api/handlers/imports.js +1 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/commands/profile/new.js +2 -2
- package/packages/crouter-api/dist/commands/profile/project.js +2 -1
- package/packages/crouter-api/dist/commands/sys/import/move.js +1 -1
- package/packages/crouter-api/dist/commands/sys/import/retry.js +38 -0
- package/packages/crouter-api/dist/commands/sys/import/start.js +2 -1
- package/packages/crouter-api/dist/core/import/export/cloud.js +1 -0
- package/packages/crouter-api/dist/core/import/load/prepare.js +2 -2
- package/packages/crouter-api/dist/core/profiles/manifest.js +12 -18
- package/packages/crouter-api/dist/core/profiles/project-dir.js +20 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- 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/scripts/install-runtime.mjs +1 -30
- package/dist/core/canvas/import-sqlite.d.ts +0 -46
- package/dist/core/canvas/import-sqlite.js +0 -19
- package/dist/core/canvas/migrations.d.ts +0 -16
- package/dist/core/canvas/migrations.js +0 -1073
- package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +0 -6
- package/dist/migrations/004-canvas-documents/legacy-edges.js +0 -18
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var Qe=Object.defineProperty;var a=(e,s)=>Qe(e,"name",{value:s,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as R,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as lr}from"node:path";import{envCrtrdTcp as dr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as le}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as lt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as dt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as de}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Ut}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Ht,ensurePostgresHealthy as zt,stopPostgres as Wt,withPostgresStartLock as qt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as Kt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Vt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Yt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Jt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Qt,readBuiltinSnapshot as Xt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Zt,reapStaleSpares as en}from"../core/runtime/warm-pool.js";import{DaemonFleet as rn}from"./fleet.js";import{copyNodeFilesToRows as tn}from"../core/runtime/first-boot-rows.js";import{emitEvent as d}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as nn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as on}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as $i}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const an=5e3,Ge=150;async function sn(e){const s=Ce();if(s===null)throw d({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 m=wr(),c=[];for(const[i,l]of s.processes){const u=l.command;if(l.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||c.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of c){const l=xt(i.pid);if(l===null||!l.includes("broker-cli.js")||!me(l,m)||fe(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+an;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(l)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):$e(l,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw d({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 v=[];for(const[i,l]of w.processes){const u=l.command;l.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);d({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:c.length,sigtermed:h,sigkilled:S}})}a(sn,"reapPriorEpochBrokers");const ln=5e3;async function dn(e){const s=Array.from(e.entries());if(s.length===0)return;for(const[o]of s){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=s.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const c=new Promise(o=>{setTimeout(o,ln).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),c])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of s)await at(o,{reason:"daemon-teardown"});d({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(lr(le()),{recursive:!0}),nr(le(),[process.pid,...e].join(`
|
|
2
|
-
`),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function
|
|
3
|
-
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(
|
|
4
|
-
`)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,c=Gt(e.role);
|
|
1
|
+
var Qe=Object.defineProperty;var a=(e,d)=>Qe(e,"name",{value:d,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as R,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as dr}from"node:path";import{envCrtrdTcp as lr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as de}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as dt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as lt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as le}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{ensurePostgres as Ut,ensurePostgresHealthy as Ht,stopPostgres as zt,withPostgresStartLock as Wt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Kt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Vt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Yt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Jt,readBuiltinSnapshot as Qt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Xt,reapStaleSpares as Zt}from"../core/runtime/warm-pool.js";import{DaemonFleet as en}from"./fleet.js";import{copyNodeFilesToRows as rn}from"../core/runtime/first-boot-rows.js";import{emitEvent as l}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as tn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as nn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Ai}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const on=5e3,Ge=150;async function an(e){const d=Ce();if(d===null)throw l({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 m=wr(),c=[];for(const[i,s]of d.processes){const u=s.command;if(s.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||c.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of c){const s=xt(i.pid);if(s===null||!s.includes("broker-cli.js")||!me(s,m)||fe(s)===e||s.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+on;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const s=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(s)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):$e(s,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw l({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 v=[];for(const[i,s]of w.processes){const u=s.command;s.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);l({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:c.length,sigtermed:h,sigkilled:S}})}a(an,"reapPriorEpochBrokers");const sn=5e3;async function dn(e){const d=Array.from(e.entries());if(d.length===0)return;for(const[o]of d){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=d.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const c=new Promise(o=>{setTimeout(o,sn).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),c])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of d)await at(o,{reason:"daemon-teardown"});l({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(dr(de()),{recursive:!0}),nr(de(),[process.pid,...e].join(`
|
|
2
|
+
`),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function ln(e){const d=de();let m;try{m=or(d,"utf8")}catch(c){if(Fe(c))return;throw c}if(m.split(`
|
|
3
|
+
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(d)}catch(c){if(Fe(c))return;throw c}}a(ln,"removeOwnedPidfileMirror");const cn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Y=new Xr;Qr(e=>Y.handleFatalFault(e,!1));const pn=new et,mn=new Zr,Be=new rt,fn=new tt,un=new nt,wn=new ot,hn=new it,vn=new ct,gn=new pt,Sn=new mt,_n=new ut,yn=new ft,kn=new ht,bn=new vt,Rn=new gt,En=new St,Pn=new _t,xn=new yt,Dn=new kt;Rt();const In=new bt;async function Tn(e=Date.now(),d=cn){const m=Ne(),c=await Y.runFleetPreamble(m);let h,o,f;try{o=await le();const w=(await Ee()).filter(i=>!o.has(i.node_id));h=w.filter(i=>i.status==="active"||i.status==="idle"),f=w.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const v=new Set(f.map(i=>i.node_id));f.push(...(await Rr()).filter(i=>!v.has(i.node_id)&&!o.has(i.node_id)))}catch(w){l({level:"error",event:"canvas.node_list.failed",error:w});return}await Y.run(e,{rows:h,fleet:m,lifecycle:d,held:o}),await pn.run(e,{rows:h,held:o}),await mn.run(e);const S=await Be.run(e,{rows:[...h,...f],fleet:m});await fn.run(e,o),await Dn.run(e,o),await In.run(e,{lifecycle:d}),await un.run(e,{lifecycle:d,held:o}),await wn.run(e,{lifecycle:d}),await hn.run(e,{lifecycle:d}),await vn.run(e,{lifecycle:d}),await gn.run(e,{lifecycle:d,fleet:m,held:o}),Sn.run(e,{lifecycle:d}),_n.run(e,{lifecycle:d}),yn.run(e,{lifecycle:d}),kn.run(e,{lifecycle:d}),bn.run(e,{lifecycle:d}),Rn.run(e,{lifecycle:d}),En.run(e,{lifecycle:d}),await fr(),xn.run(e,{fleet:m,lifecycle:d}),await Pn.run(e,{rows:h}),Y.warnIfSaturated({fleet:m,lifecycle:d,thresholds:c,frozen:S})}a(Tn,"superviseTick");async function Cn(e,d=Date.now()){if((await le()).has(e))return;const m=await dt(e);if(m===null||!st(m))return;const c=await br(e);c===null||c.kind==="human"||await Be.runNode(d,c,Ne())}a(Cn,"exitedNodePass");function J(e){return e===void 0||e==="reconcile"||e==="all"}a(J,"roleRunsLanes");function F(e){return e===void 0||e==="api"||e==="all"}a(F,"roleServesRequests");const An=66e4;function Ln(e){const d=new Pr().registerAll(xr(()=>null).filter(s=>s.pattern==="/healthz")),m=a((s,u)=>{const _=(s.url??"/").split("?")[0];if((s.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){d.handle(s,u,null,{class:"person"});return}u.writeHead(404,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),c=ur();R(c)&&ke(c);const h=be(m),o=new Promise((s,u)=>{h.once("error",u),h.listen(c,()=>{h.off("error",u),sr(c,384),s()})});let f,S=null,w=o;const v=e.tcp??lr()??Te("user").api.tcp;if(v!==void 0&&v!==""){const s=/^(.*):(\d+)$/.exec(v.trim());if(s===null||Number(s[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${v}`);const u=be(m);u.on("error",_=>l({event:"api.server.failed",level:"error",error:_})),w=o.then(()=>new Promise(_=>{u.once("error",()=>_()),u.listen(Number(s[2]),s[1]===""?"0.0.0.0":s[1],()=>{const b=u.address();S=`${b.address}:${b.port}`,_()})})),f=u}let i=!1;return{ready:w,tcpAddress:a(()=>S,"tcpAddress"),async close(s={}){if(!i){i=!0,await Promise.all([xe(h,new Set,s.graceMs),f===void 0?Promise.resolve():xe(f,new Set,s.graceMs)]);try{R(c)&&ke(c)}catch{}}}}}a(Ln,"createProbeServer");const $n="daemon is draining for shutdown and admits no new work";async function Nn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();_r();const d=a(n=>{process.stderr.write(`[crtrd] ${n}
|
|
4
|
+
`)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,c=Gt(e.role);Kt(J(e.role));const h=a(async()=>c?await Ot(Re(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Re(16).toString("hex")}},"claimOwnership"),{database:o,ownership:f}=e.role!==void 0||m?{database:{url:await Bt()},ownership:await h()}:await Wt(async()=>({database:await Ut({log:d,startLockHeld:!0}),ownership:await h()}));if(!f.claimed){if(f.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${f.incumbentPid??"?"})
|
|
5
5
|
`);else{const n=[f.incumbentPid!==void 0?`pid ${f.incumbentPid}`:void 0,f.verdict!==void 0?`verdict ${f.verdict}`:void 0].filter(t=>t!==void 0),r=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${f.reason}${r}
|
|
6
|
-
`),f.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"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,
|
|
7
|
-
`);await jt(),
|
|
8
|
-
`)}else{w=await Ar(),w!==null&&($r(w.id),await V(w.id));const r=await pe(async t=>(await De(t),w===null?null:await
|
|
6
|
+
`),f.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"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,s=null,u,_="";try{c&&await an(S.token);for(const r of yr())process.stderr.write(`[crtrd] ${r}
|
|
7
|
+
`);await jt(),e.role===void 0&&nn({profiles:[],defaults:{},settings:{},state:{},apps:{}}),await L.listen(o.url);const n=a(r=>{V(r).catch(t=>l({level:"error",event:"daemon.settings.reload_failed",error:t}))},"reloadPerson");if(u=await L.subscribe(r=>{Oe().includes(r)&&n(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of Oe())n(r)},"onListenStart")}),e.role!==void 0&&Cr(),e.role==="all"&&Tr(),e.role!==void 0){let r;try{r=Qt()}catch(p){l({level:"error",event:"daemon.packages.snapshot_failed",error:p})}const t=await pe(async p=>(await De(p),r===void 0?void 0:await Jt(p,r,"release")));s=await pe(async p=>await Yt(p));for(const p of t?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${p.path}: ${p.error}
|
|
8
|
+
`)}else{w=await Ar(),w!==null&&($r(w.id),await V(w.id));const r=await pe(async t=>(await De(t),w===null?null:await Vt(t)));if(r!==null){for(const t of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${t.message}
|
|
9
9
|
`);for(const t of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${t.path}: ${t.error}
|
|
10
10
|
`);for(const t of r.quarantined)process.stderr.write(`[crtrd] plugin "${t.name}" has a damaged ${t.file} (${t.reason}); ${t.movedTo!==void 0?`moved to ${t.movedTo}`:"left in place and skipped"}
|
|
11
11
|
`);for(const t of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${t.plugin}" kind ${t.kind} not registered: ${t.message}
|
|
12
12
|
`);for(const t of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${t.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${t.error}
|
|
13
|
-
`)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&R(I)&&(Sr(),await A({operation:"users.sync",users:await hr()})),c){await
|
|
14
|
-
`)}}catch(n){await L.close();try{if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}await ce()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}let b=!0,Q,B=Promise.resolve(),X=!1,j,Z,ee,re,te,T;const U=new Set;let ne=!1,we=!1,x,E,H=!1,z,C,$,N,M,oe,ie,ae,se;const je=Jr();let D,g={phase:"initializing",message:"daemon startup is running and normal services are unavailable",blockerPaths:[]},Ue=null;function He(){return g.phase==="ready"?null:{phase:g.phase,message:g.message,blockerPaths:g.blockerPaths}}a(He,"startupBlock");function k(n){U.add(n),n.finally(()=>{U.delete(n)}).catch(()=>{})}a(k,"registerDetached");const ze={acceptsDetachedWork:a(()=>b,"acceptsDetachedWork"),registerDetached:k};async function We(){try{b=!1,
|
|
13
|
+
`)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&R(I)&&(Sr(),await A({operation:"users.sync",users:await hr()})),c){await lt(S.token);const r=await rn();Object.values(r).some(t=>t>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
|
|
14
|
+
`)}}catch(n){await L.close();try{if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}await ce()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}let b=!0,Q,B=Promise.resolve(),X=!1,j,Z,ee,re,te,T;const U=new Set;let ne=!1,we=!1,x,E,H=!1,z,C,$,N,M,oe,ie,ae,se;const je=Jr();let D,g={phase:"initializing",message:"daemon startup is running and normal services are unavailable",blockerPaths:[]},Ue=null;function He(){return g.phase==="ready"?null:{phase:g.phase,message:g.message,blockerPaths:g.blockerPaths}}a(He,"startupBlock");function k(n){U.add(n),n.finally(()=>{U.delete(n)}).catch(()=>{})}a(k,"registerDetached");const ze={acceptsDetachedWork:a(()=>b,"acceptsDetachedWork"),registerDetached:k};async function We(){try{b=!1,qt.close(),ee?.(),ee=void 0,re?.(),u?.(),re=void 0,te?.(),te=void 0,ae?.(),ae=void 0,await L.close(),j!==void 0&&(clearInterval(j),j=void 0),Z?.(),Z=void 0,$!==void 0&&(clearInterval($),$=void 0),N!==void 0&&(clearInterval(N),N=void 0),se?.(),se=void 0;let n;do n=B,await n;while(n!==B);for(;U.size>0;)await Promise.allSettled([...U]);if(T!==void 0&&(c&&await dn(T),await T.exitsSettled(),T.dispose()),E!==void 0&&!H&&(H=!0,await E.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,M!==void 0){const r=M;M=void 0,await r.stop()}if(C!==void 0){const r=C;C=void 0,await r.close()}if(z!==void 0){const r=z;z=void 0,await r.close()}if(ne||(ln(process.pid),ne=!0),ne&&!we){if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}we=!0,await ce()}}finally{Ct(),process.off("SIGINT",ge),process.off("SIGTERM",Se),process.off("exit",_e)}}a(We,"cleanupAttempt");const W=1e3;let he=!1;function qe(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return he?{graceMs:W}:(he=!0,y.fresh(()=>{l({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:W}})}),setTimeout(()=>{Ke()},W),{graceMs:W})}a(qe,"requestHandover");async function Ke(){try{await O()}catch(n){const r=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
15
15
|
${r}
|
|
16
|
-
`),process.exit(1)}try{process.platform==="linux"&&R(I)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await At();const n=await Lt();y.fresh(()=>{
|
|
17
|
-
`),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message
|
|
16
|
+
`),process.exit(1)}try{process.platform==="linux"&&R(I)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await At();const n=await Lt();y.fresh(()=>{l({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){y.fresh(()=>{l({level:"error",event:"daemon.handover.successor_failed",error:n})});const r=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${r}
|
|
17
|
+
`),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message:$n,blockerPaths:[]},E!==void 0&&!H&&(H=!0,await E.close({graceMs:An}))}a(Ve,"drainApi");async function ve(n){try{n==="SIGTERM"&&e.role==="api"&&await Ve(),await O(),await zt({claimed:a(async()=>{try{return c&&await Ft()}finally{await ce()}},"claimed")}),process.exit(0)}catch(r){process.exitCode=1;const t=r instanceof Error?r.stack??`${r.name}: ${r.message}`:String(r);process.stderr.write(`[crtrd] ${n} cleanup failed:
|
|
18
18
|
${t}
|
|
19
|
-
`),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){b&&(B=B.then(n).then(()=>{},r=>{y.fresh(()=>{
|
|
19
|
+
`),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){b&&(B=B.then(n).then(()=>{},r=>{y.fresh(()=>{l({level:"error",event:"daemon.lane_job.failed",error:r})})}))}a(q,"enqueue");async function K(){!b||X||(je.check()&&D&&(l({level:"info",event:"daemon.resume.detected"}),k(D().catch(()=>{}))),X=!0,await q(async()=>{if(X=!1,!!b)try{m||await Ht({log:d}),await Tn(Date.now(),ze)}catch(n){y.fresh(()=>{l({level:"error",event:"daemon.tick.failed",error:n})})}}))}a(K,"enqueueTick");let G=null;async function Ye(){if(G!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${G instanceof Error?G.message:String(G)}`};if(g.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(g.phase!=="prepared"&&g.phase!=="recovering")throw{status:409,code:"not_prepared",message:g.message};const n=g.phase==="prepared";try{return await ye(),g={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(r){throw G=r,{status:500,code:"admission_failed",message:`daemon admission failed: ${r instanceof Error?r.message:String(r)}`}}}a(Ye,"admitStartup");async function Je(){Q=e.intervalMs??Yr;const n=S.token;T=new en({epoch:n,enqueue:q}),It(T),g={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},y.fresh(()=>{l({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Q}})});const r=_;if(y.fresh(()=>{l({level:"info",event:"daemon.install_id.resolved",fields:{install_id:r}})}),y.fresh(()=>{let t;try{t=Vr()}catch{return}t!==null&&l({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),wt(),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&&Ir(),!J(e.role)){g={phase:"ready",message:"",blockerPaths:[]};return}if(await y.fresh(async()=>{await Kr(),await zr();const t=e.role!==void 0;await Wr(Date.now(),t),await qr(Date.now(),t)}),e.role===void 0&&await y.fresh(async()=>{const t=await $t();t.changed&&l({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}})}),await y.fresh(async()=>{const t=await le();for(const p of await Ee())t.has(p.node_id)||p.status!=="active"||p.pi_pid!=null||p.frozen_at!=null||p.respawn_not_before!=null||(await Pe(p.node_id,new Date().toISOString()),l({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:p.node_id}))}),await y.fresh(async()=>{await Pt()}),k(Ur()),D){const t=a(()=>{k(D().catch(()=>{})),k(rr().then(p=>M?.observe(p)).then(()=>{},p=>{l({level:"warn",event:"daemon.peer.status_failed",error:p})}))},"refresh");k(jr().then(({completion:p})=>p).catch(p=>{l({level:"error",event:"daemon.grants.sweep_failed",error:p})})),t(),$=setInterval(t,Ie*1e3),$.unref(),se=er({joined:!0,register:k})}await q(async()=>{await Zt(),await Xt()}),Z=Ze(),j=setInterval(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))},Q),ee=await Et(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))}),re=await L.subscribe(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),te=await L.subscribe(t=>{q(()=>y.fresh(()=>Cn(t)))},{kinds:["execution_exit"]}),await K(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!b,p=>l({level:"warn",event:"daemon.move.settle_failed",error:p}))).catch(t=>l({level:"warn",event:"daemon.move.settle_failed",error:t}))}a(Je,"completeStartup");function ye(){return Ue??=Je().catch(n=>{throw g={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}a(ye,"resumeStartup");try{process.on("SIGINT",ge),process.on("SIGTERM",Se),process.on("exit",_e),tn(),w!==null&&l({level:"info",event:"daemon.person.resolved",fields:{person_id:w.id,source:w.source}}),s!==null&&!s.alreadyDone&&l({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:s.moved,discarded:s.discarded,people:s.people}}),i!==null&&l({level:"info",event:"daemon.permissions.boot",fields:{...i}}),v!==null&&l({level:"info",event:"daemon.person.retired",fields:{person_id:v.person,joined_from:v.joinedFrom,retired:v.retired,columns:v.columns}}),F(e.role)?z=await pr():mr(cr());const n=S.token;Tt({epoch:n,requestHandover:qe,registerDetached:k,startupBlock:He,admitStartup:Ye}),ue(),E=F(e.role)?Er({tcp:e.tcp}):Ln(e),await E.ready,ue(E.tcpAddress()??"");const r=Te("user").runtime;if(r?.issuer&&(D=Br(r.issuer,k),r.unsandboxed===!0&&(M=tr({syncGrants:D}))),e.role==="api"||e.role==="all"){const t=a(()=>k(import("../core/providers/bundles.js").then(P=>P.syncProviderBundles()).catch(P=>{l({level:"error",event:"daemon.providers.bundle_sync_failed",error:P})})),"bundleTick"),p=a(()=>{k(Gr().catch(P=>{l({level:"error",event:"daemon.packages.sync_failed",error:P})})),t()},"packageTick");p(),N=setInterval(p,Ie*1e3),N.unref()}return F(e.role)&&(oe=await Mr()),J(e.role)&&(ie=Fr()),ae=await Or({serves:F(e.role),runsLanes:J(e.role)}),r?.unsandboxed===!0&&r.listener!==void 0&&l({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),F(e.role)&&r!==void 0&&r.listener!==void 0&&r.unsandboxed!==!0&&(C=await Dr(r,async()=>await Hr(r.issuer.replace(/\/$/,"")),D),await C.ready,ue(E.tcpAddress()??"",`${r.listener.address}:${C.port()}`)),process.platform==="linux"&&R(I)&&(gr(),await vr("app:terminal")),e.prepare?g={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await ye(),g={phase:"ready",message:"",blockerPaths:[]}),O}catch(n){try{await O()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}}a(Nn,"runDaemon");var Ii=Nn;export{An as API_DRAIN_GRACE_MS,Ai as brokerCommandDeclaresCanvasHome,fe as brokerCommandEpoch,Ii as default,Cn as exitedNodePass,J as roleRunsLanes,F as roleServesRequests,Nn as runDaemon,Tn as superviseTick,dn as teardownFleet};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var u=(y,e)=>A(y,"name",{value:e,configurable:!0});import{rm as N}from"node:fs/promises";import{closeFocusRow as T,getFocusById as P,listFocuses as C,listNodes as D}from"../../core/canvas/index.js";import{pruneExpiredIdempotencyKeys as x}from"../../core/runs/operations.js";import{getNode as g,lastActivityMs as p,listTerminalPlacementResidue as F,pruneExpiredCreateRequests as M,pruneNodes as b}from"../../core/canvas/canvas.js";import{lastContextStripMs as L,stripContextDir as W}from"../../core/canvas/context-strip.js";import{isAppRun as G}from"../../core/canvas/app-run.js";import{isSafeNodeId as l}from"../../core/canvas/paths.js";import{emitEvent as n}from"../../core/events/emit.js";import{operationIdContext as s}from"../../core/events/operation-id.js";import{listLivePanesAsync as V,tearDownNode as k}from"../../core/runtime/placement.js";import{reapStaleSpares as q}from"../../core/runtime/warm-pool.js";import{GroveInstanceSweepReconciler as O}from"./grove-instance-sweep.js";import{ManagedWorktreeSweepReconciler as U}from"./managed-worktree-sweep.js";import{compactRunEvents as H}from"../../core/runs/events.js";import{archiveExpiredRunEvents as Y}from"../../core/events/run-event-chunks.js";import{blobStore as S}from"../../core/blobs/index.js";import{sweepFailedUploads as $}from"../../core/import/load/blobs.js";import{runThrottledLane as d}from"./throttled-lane.js";import{openDb as m}from"../../core/canvas/db.js";import{retentionHold as v}from"./live-obligation.js";import{deleteQuietNodeSandboxes as z}from"../../core/runtime/runner/delete-sandboxes.js";import{pruneMemoryReads as B}from"../../core/canvas/memory-reads.js";import{existsSync as K}from"node:fs";import{launcherRequest as Q}from"../../launcher/client.js";import{LAUNCHER_SOCKET as X}from"../../launcher/spec.js";import{cachePassDue as Z}from"../../launcher/limits/policy.js";const j=10*6e4,h=60*1e3,E=60*1e3,w=5*6e4,R=2,J=1440*6e4,ee=2e3,te=6e4;class Ce{static{u(this,"StorageMaintenanceReconciler")}focusGcInFlight=!1;lastCachePassAt=null;cachePassInFlight=!1;worktreeSweep=new U;groveInstanceSweep=new O;async run(e,r){await this.reapDeadResidue(e,r.held),this.scheduleFocusGc(r),await this.gcWarmPool(e),await this.gcCreateRequests(e),await this.gcViewerAttachments(e);try{await d("run-event-maintenance","",e,ee,te,async t=>{await Y(await S(),e);const a=await H(e,t.state===null?0:Number(t.state));await t.save(String(a.cursor))})}catch(t){console.warn(`run event maintenance failed: ${String(t)}`)}await d("memory-read-prune","",e,60*6e4,10*6e4,async()=>{try{await B(e)}catch(t){console.warn(`memory-read log prune failed: ${String(t)}`)}}),await d("import-failed-upload-sweep","",e,60*6e4,10*6e4,async()=>{try{await $(await m(),await S(),e)}catch(t){console.warn(`failed import upload sweep failed: ${String(t)}`)}}),await d("storage-analyze","",e,1440*6e4,10*6e4,async()=>{await(await m()).exec("ANALYZE")}),await this.sweepRetention(e,r),this.scheduleCachePass(e,r),this.scheduleContextStrip(e,r),this.worktreeSweep.run(e,r),this.groveInstanceSweep.run(e,r)}scheduleCachePass(e,r){this.cachePassInFlight||!Z(this.lastCachePassAt,e)||process.platform!=="linux"||!K(X)||r.lifecycle.acceptsDetachedWork()&&(this.lastCachePassAt=e,this.cachePassInFlight=!0,r.lifecycle.registerDetached(Q({operation:"cache.purge"}).then(()=>{}).catch(t=>{s.fresh(()=>{n({level:"warn",event:"app.cache.pass_failed",error:t})})}).then(()=>{this.cachePassInFlight=!1})))}msSinceTerminalActivity(e,r){const t=p(e);return t===0?Number.POSITIVE_INFINITY:r-t}async sweepRetention(e,r){r.lifecycle.acceptsDetachedWork()&&await d("retention-sweep","",e,w,w,()=>s.fresh(async()=>{try{const t=await b({ttlDays:R,held:await v(r.fleet),removeDirs:u(i=>{r.lifecycle.registerDetached(Promise.all(i.map(c=>N(c,{recursive:!0,force:!0}))).then(()=>{}).catch(c=>{s.fresh(()=>{n({level:"error",event:"canvas.retention.failed",error:c})})}))},"removeDirs")});t.pruned.length>0&&n({level:"info",event:"canvas.retention.pruned",outcome:"succeeded",fields:{pruned_count:t.pruned.length}});const a=await v(r.fleet),o=e-R*24*60*6e4,f=await z({now:e,held:a,quiet:u(async i=>{const c=await g(i);return c!==null&&p(c)<o},"quiet")});f>0&&n({level:"info",event:"canvas.retention.sandboxes_deleted",outcome:"succeeded",fields:{deleted_count:f}})}catch(t){n({level:"error",event:"canvas.retention.failed",error:t})}}))}scheduleContextStrip(e,r){r.lifecycle.acceptsDetachedWork()&&r.lifecycle.registerDetached(d("context-strip","",e,w,10*6e4,()=>this.stripFinishedContexts(e,r)).then(()=>{},t=>{n({level:"error",event:"canvas.context_strip.failed",error:t})}))}async stripFinishedContexts(e,r){const t=await v(r.fleet),a=u(async i=>i!==null&&["done","canceled","dead"].includes(i.status)&&(i.pi_pid??null)===null&&(i.frozen_at??null)===null&&!G(i)&&p(i)<e-J&&!await t(i.node_id),"eligible");let o=0,f=0;try{for(const i of await D({status:["done","canceled","dead"]})){if(!l(i.node_id)||!await a(i))continue;const c=await L(i.node_id);if(c!==null&&c>=p(i)||!await a(await g(i.node_id)))continue;let _;try{_=await W(i.node_id)}catch(I){s.fresh(()=>{n({level:"warn",event:"canvas.context_strip.node_failed",error:I,fields:{node_id:i.node_id}})});continue}_.removed.length>0&&(o+=1,f+=_.bytes)}}catch(i){s.fresh(()=>{n({level:"error",event:"canvas.context_strip.failed",error:i})})}o>0&&s.fresh(()=>{n({level:"info",event:"canvas.context_strip.completed",outcome:"succeeded",fields:{node_count:o,bytes:f}})})}async reapDeadResidue(e,r){let t;try{t=await F()}catch(a){s.fresh(()=>{n({level:"error",event:"residue.reap_scan.failed",error:a})});return}for(const a of t)if(!r.has(a.node_id)){try{if(this.msSinceTerminalActivity(a,e)<j)continue}catch(o){s.fresh(()=>{n({level:"error",event:"residue.reap.failed",...l(a.node_id)?{node_id:a.node_id}:{},error:o,fields:{...l(a.node_id)?{}:{affected_node_id:a.node_id},pane:a.pane,window:a.window,tmux_session:a.tmux_session}})});continue}await s.fresh(async()=>{try{n({level:"info",event:"residue.reaped",...l(a.node_id)?{node_id:a.node_id}:{},fields:{...l(a.node_id)?{}:{affected_node_id:a.node_id},pane:a.pane,window:a.window,tmux_session:a.tmux_session}}),await k(a.node_id)}catch(o){n({level:"error",event:"residue.reap.failed",...l(a.node_id)?{node_id:a.node_id}:{},error:o,fields:{...l(a.node_id)?{}:{affected_node_id:a.node_id},pane:a.pane,window:a.window,tmux_session:a.tmux_session}})}})}}scheduleFocusGc(e){if(this.focusGcInFlight||!e.lifecycle.acceptsDetachedWork())return;this.focusGcInFlight=!0;const r=this.gcStaleFocuses().finally(()=>{this.focusGcInFlight=!1});e.lifecycle.registerDetached(r)}async gcStaleFocuses(){let e;try{e=await C()}catch(t){s.fresh(()=>{n({level:"error",event:"focus.gc.failed",error:t})});return}if(e.length===0)return;let r;try{r=await V()}catch(t){s.fresh(()=>{n({level:"error",event:"focus.gc.failed",error:t})});return}if(r!==null)for(const t of e){if(t.pane===null||r.has(t.pane))continue;if(!await s.fresh(async()=>{try{return(await P(t.focus_id))?.pane!==t.pane||(n({level:"info",event:"focus.gc.removed",...l(t.node_id)?{node_id:t.node_id}:{},fields:{focus_id:t.focus_id,focus_node_id:t.node_id,pane:t.pane}}),await T(t.focus_id)),!0}catch(o){return n({level:"error",event:"focus.gc.failed",error:o}),!1}}))return}}async gcCreateRequests(e){await d("create-request-gc","",e,E,E,()=>s.fresh(async()=>{const r=await M(e),t=await x(e);t>0&&n({level:"info",event:"canvas.idempotency_keys.reaped",outcome:"succeeded",fields:{reaped_count:t}}),r>0&&n({level:"info",event:"canvas.create_requests.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async gcViewerAttachments(e){await d("viewer-attachment-gc","",e,h,h,()=>s.fresh(async()=>{const r=Number((await(await m()).prepare("DELETE FROM viewer_attachments WHERE expires_at <= ?").run(new Date(e).toISOString())).changes);r>0&&n({level:"info",event:"viewer_attachments.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async gcWarmPool(e){await d("warm-pool-gc","",e,h,h,()=>s.fresh(async()=>{const r=await q();r.length>0&&n({level:"info",event:"warm_pool.spares_reaped",outcome:"succeeded",fields:{reaped_count:r.length}})}))}}export{J as CONTEXT_STRIP_GRACE_MS,j as DEAD_REAP_GRACE_MS,w as RETENTION_SWEEP_INTERVAL_MS,R as RETENTION_TTL_DAYS,Ce as StorageMaintenanceReconciler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.758",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.758",
|
|
161
|
+
"@north-light/plugin": "0.3.758",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@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.79';
|
|
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`. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineLeaf } from '../../core/command.js';
|
|
2
2
|
import { usage } from '../../core/errors.js';
|
|
3
|
-
import {
|
|
3
|
+
import { resolveExistingProjectDir } from '../../core/profiles/project-dir.js';
|
|
4
4
|
import { cliClient } from '../api-client.js';
|
|
5
5
|
import { resolveMetaPairs } from './meta.js';
|
|
6
6
|
export const newLeaf = defineLeaf({
|
|
@@ -87,7 +87,7 @@ export const newLeaf = defineLeaf({
|
|
|
87
87
|
throw usage('provide `--name <name>` to create a profile, or `--root` to provision the stable root profile.');
|
|
88
88
|
return newProfileOutput(await cliClient().createProfile({
|
|
89
89
|
name,
|
|
90
|
-
...(project !== undefined ? { projects: [{ path:
|
|
90
|
+
...(project !== undefined ? { projects: [{ path: resolveExistingProjectDir(project) }] } : {}),
|
|
91
91
|
...(repos.length > 0 ? { repositories: repos } : {}),
|
|
92
92
|
...(defaultKind !== undefined ? { default_kind: defaultKind } : {}),
|
|
93
93
|
...(Object.keys(metadata).length > 0 ? { metadata } : {}),
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// `crtr profile project` manages purview relationships and per-owner automatic delivery limits.
|
|
2
2
|
import { defineLeaf, defineBranch } from '../../core/command.js';
|
|
3
3
|
import { resolve } from 'node:path';
|
|
4
|
+
import { resolveExistingProjectDir } from '../../core/profiles/project-dir.js';
|
|
4
5
|
import { usage } from '../../core/errors.js';
|
|
5
6
|
import { cliClient } from '../api-client.js';
|
|
6
7
|
import { resolveProfileViaDaemon } from './daemon-profiles.js';
|
|
@@ -48,7 +49,7 @@ const addLeaf = defineLeaf({
|
|
|
48
49
|
if ((dir === undefined) === (repo === undefined))
|
|
49
50
|
throw usage('pass exactly one of --dir and --repo', { next: 'Use --dir <directory> for a folder or --repo <handle> for a repo with no folder.' });
|
|
50
51
|
const updated = await cliClient().updateProfile(id, {
|
|
51
|
-
add_project: dir !== undefined ? { path:
|
|
52
|
+
add_project: dir !== undefined ? { path: resolveExistingProjectDir(dir) } : { repo: repo },
|
|
52
53
|
});
|
|
53
54
|
return { profile_id: updated.id, projects: updated.projects };
|
|
54
55
|
},
|
|
@@ -57,7 +57,7 @@ const OUTCOME_RETRY_MAX_MS = 30_000;
|
|
|
57
57
|
* while the control plane cannot be reached or answers an error (a lost answer must never read as a failure: the account may hold the records). Only a
|
|
58
58
|
* sign-in that no longer works, or an answer the control plane will repeat, ends the wait with `move_outcome_unknown`, because asking can never succeed again. A `load` that threw while the run
|
|
59
59
|
* never left `uploading` did not start, so its error stands. */
|
|
60
|
-
async function awaitRunOutcome(cloud, runId, loadError) {
|
|
60
|
+
export async function awaitRunOutcome(cloud, runId, loadError) {
|
|
61
61
|
let gap = 2000;
|
|
62
62
|
for (;;) {
|
|
63
63
|
let state;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// `crtr sys import retry <run_id>`: loads a failed import again from the bundle its failure kept.
|
|
2
|
+
import { defineLeaf } from '../../../core/command.js';
|
|
3
|
+
import { usage } from '../../../core/errors.js';
|
|
4
|
+
import { ImportCloud } from '../../../core/import/export/cloud.js';
|
|
5
|
+
import { controlPlaneUrl, personBearer } from '../../../core/directory/person-credential.js';
|
|
6
|
+
import { awaitRunOutcome, defaultDirectoryUrl } from './move.js';
|
|
7
|
+
export const retry = defineLeaf({
|
|
8
|
+
name: 'retry',
|
|
9
|
+
description: 'load a failed import again from the bundle it already uploaded',
|
|
10
|
+
whenToUse: 'an import failed while Northlight was loading it (a refused or conflicting row) and the cause is fixed: no new upload and no new confirm code',
|
|
11
|
+
help: {
|
|
12
|
+
name: 'sys import retry',
|
|
13
|
+
summary: 're-queue a failed run so Northlight loads its kept upload again, then wait for the outcome',
|
|
14
|
+
guide: 'Works for a run that failed before its copy committed and whose upload is under 7 days old (Northlight deletes older ones; run the import again then). The bundle is what was uploaded, so rows this computer changed since are not in it. Prints the final state, or the new failure.',
|
|
15
|
+
params: [
|
|
16
|
+
{ kind: 'positional', name: 'run_id', type: 'string', required: true, constraint: 'The failed import run (`imp_…`).' },
|
|
17
|
+
{ kind: 'flag', name: 'api-url', type: 'string', required: false, constraint: 'Control plane base URL; default is the one the sign-in is for.' },
|
|
18
|
+
],
|
|
19
|
+
output: [
|
|
20
|
+
{ name: 'run_id', type: 'string', required: true, constraint: 'The import run.' },
|
|
21
|
+
{ name: 'state', type: 'string', required: true, constraint: 'Final state of the run, `done`.' },
|
|
22
|
+
],
|
|
23
|
+
outputKind: 'object',
|
|
24
|
+
effects: ['Moves the run from `failed` back to `loading` on the control plane; nothing local changes.'],
|
|
25
|
+
},
|
|
26
|
+
run: async (input) => {
|
|
27
|
+
const runId = String(input['run_id'] ?? '');
|
|
28
|
+
if (runId === '')
|
|
29
|
+
throw usage('name the failed run: crtr sys import retry <run_id>');
|
|
30
|
+
const directoryUrl = defaultDirectoryUrl();
|
|
31
|
+
const apiUrl = input.apiUrl === undefined ? await controlPlaneUrl(directoryUrl) : String(input.apiUrl);
|
|
32
|
+
const cloud = new ImportCloud(apiUrl, () => personBearer(directoryUrl));
|
|
33
|
+
await cloud.retry(runId);
|
|
34
|
+
await awaitRunOutcome(cloud, runId, undefined);
|
|
35
|
+
return { run_id: runId, state: 'done' };
|
|
36
|
+
},
|
|
37
|
+
render: (r) => `<import run="${r['run_id']}" state="${r['state']}"/>`,
|
|
38
|
+
});
|
|
@@ -9,6 +9,7 @@ import { showSignIn } from '../signin.js';
|
|
|
9
9
|
import { insideBroker } from '../join.js';
|
|
10
10
|
import { defaultDirectoryUrl, exportRun, settleEarlierMove, finishMove, runMove } from './move.js';
|
|
11
11
|
import { resume } from './resume.js';
|
|
12
|
+
import { retry } from './retry.js';
|
|
12
13
|
/** Set by `crtr sys signin` on the detached exporter it starts from inside a node: the signin process, which the exporter outlives before it drains,
|
|
13
14
|
* so it is never in a broker's process tree. */
|
|
14
15
|
export const WAIT_FOR_PID_ENV = 'CRTR_IMPORT_WAIT_PID';
|
|
@@ -88,5 +89,5 @@ export const sysImportBranch = defineBranch({
|
|
|
88
89
|
description: 'move this runtime into the person\'s Northlight account',
|
|
89
90
|
whenToUse: 'importing this computer or hosted runtime into Northlight',
|
|
90
91
|
help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database, and on a computer switches it to the machine role.' },
|
|
91
|
-
children: [start, resume],
|
|
92
|
+
children: [start, resume, retry],
|
|
92
93
|
});
|
|
@@ -101,6 +101,7 @@ export class ImportCloud {
|
|
|
101
101
|
uploadUrls(run, keys) { return this.call('POST', `/v1/imports/${run}/upload-urls`, { keys }, true); }
|
|
102
102
|
putStore(run, name, body) { return this.call('PUT', `/v1/imports/${run}/stores/${name}`, body, true); }
|
|
103
103
|
load(run) { return this.call('POST', `/v1/imports/${run}/load`, {}); }
|
|
104
|
+
retry(run) { return this.call('POST', `/v1/imports/${run}/retry`, {}); }
|
|
104
105
|
get(run) { return this.call('GET', `/v1/imports/${run}`); }
|
|
105
106
|
/** `rotate` replaces a credential already issued for this run's machine (without it a second call answers 409 `credential_exists`). */
|
|
106
107
|
machineCredential(run, rotate = false) { return this.call('POST', `/v1/imports/${run}/machine-credential${rotate ? '?rotate=1' : ''}`, {}); }
|
|
@@ -211,8 +211,8 @@ export async function takeRepoSyncedDocuments(db, schema, target) {
|
|
|
211
211
|
}
|
|
212
212
|
/** Columns that record when a fact was written, not what it says. A fact row (an edge, a relation) the target already holds under the same key is present
|
|
213
213
|
* whatever its `created_at`: shipped documents, their links and readers, and the person's `acts_for` are written by the target's own publication and sign-in
|
|
214
|
-
* at another time. The copy step skips the held key (`ON CONFLICT DO NOTHING`); `written_as`
|
|
215
|
-
const WRITTEN_AT = { edges: ['created_at'], relations: ['created_at'] };
|
|
214
|
+
* at another time. The copy step skips the held key (`ON CONFLICT DO NOTHING`); `written_as` still has to agree. A relation's key is the whole fact, so its `written_by` is not compared: the target's row stands (the person's `acts_for` is written by sign-in, a bundle's by the source). */
|
|
215
|
+
const WRITTEN_AT = { edges: ['created_at'], relations: ['created_at', 'written_by'] };
|
|
216
216
|
/** A `charges` id is the idempotency key (`receipt:<provider>:<receipt id>`: "a repeat of an existing id adds nothing", ledger/types.ts): when the target already holds
|
|
217
217
|
* it, the charge is the same one and the copy step skips it (`ON CONFLICT DO NOTHING`; the target's row stands). What the charge says is who paid, what it
|
|
218
218
|
* metered and what it cost; when and how each side recorded or priced it (`at`, `billed_usd`, `priced_at`, `node`, `account`, `price_id`, the admission and cost
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Profile definitions live in scoped state; memory and environment have separate roots.
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import {
|
|
4
|
-
import { resolve as resolvePath } from 'node:path';
|
|
3
|
+
import { realpathSync, rmSync } from 'node:fs';
|
|
4
|
+
import { isAbsolute, resolve as resolvePath } from 'node:path';
|
|
5
|
+
import { resolveExistingProjectDir } from './project-dir.js';
|
|
5
6
|
import { SCHEMA_VERSION } from '../../types.js';
|
|
6
7
|
import { profileSpace } from '../layout.js';
|
|
7
8
|
import { PROFILE_PROJECT_MEMORY_VALUES } from '../../api/dto/profiles.js';
|
|
@@ -165,20 +166,13 @@ export function matchProfileOperand(all, operand, key) {
|
|
|
165
166
|
}
|
|
166
167
|
// Project dirs — resolved to absolute real paths, must exist + be a directory
|
|
167
168
|
// on add/create, deduped by real path, stored in manifest order.
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
if (!
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
}
|
|
176
|
-
try {
|
|
177
|
-
return realpathSync(abs);
|
|
178
|
-
}
|
|
179
|
-
catch {
|
|
180
|
-
return abs;
|
|
181
|
-
}
|
|
169
|
+
/** A cloud role cannot see the caller's disk: the caller's CLI already resolved the path on its own machine, so it is stored as sent. */
|
|
170
|
+
function storedProjectDir(dir) {
|
|
171
|
+
if (!isCloudRole())
|
|
172
|
+
return resolveExistingProjectDir(dir);
|
|
173
|
+
if (!isAbsolute(dir))
|
|
174
|
+
throw usage(`project directory must be an absolute path: ${dir}`, { received: dir });
|
|
175
|
+
return dir;
|
|
182
176
|
}
|
|
183
177
|
/** First-wins by resolved path; by repo only among entries with no path. A folder entry for a repo that has a repo-only entry merges into it
|
|
184
178
|
* (one entry, both fields, the repo-only entry's position). */
|
|
@@ -342,7 +336,7 @@ export async function createProfile(name, projects = [], opts = {}) {
|
|
|
342
336
|
if (opts.metadata !== undefined)
|
|
343
337
|
assertProfileMetadata(opts.metadata);
|
|
344
338
|
assertProfileProjects(projects);
|
|
345
|
-
const resolvedProjects = dedupeProjects(projects.map((p) => ({ ...(p.repo === undefined ? {} : { repo: p.repo }), ...(p.path === undefined ? {} : { path:
|
|
339
|
+
const resolvedProjects = dedupeProjects(projects.map((p) => ({ ...(p.repo === undefined ? {} : { repo: p.repo }), ...(p.path === undefined ? {} : { path: storedProjectDir(p.path) }) })));
|
|
346
340
|
const profileId = generateProfileId(trimmed);
|
|
347
341
|
const manifest = {
|
|
348
342
|
schema_version: SCHEMA_VERSION,
|
|
@@ -505,7 +499,7 @@ export async function renameProfile(profileId, name) {
|
|
|
505
499
|
* a folder no repo identifies keeps `path` only. A listed entry with that path but no repo gains the repo in place. */
|
|
506
500
|
export async function addProfileProject(profileId, dir, repo) {
|
|
507
501
|
assertProfileProjects([{ path: dir, ...(repo === undefined ? {} : { repo }) }]);
|
|
508
|
-
const resolved =
|
|
502
|
+
const resolved = storedProjectDir(dir);
|
|
509
503
|
return await mutateManifest(profileId, (m) => ({
|
|
510
504
|
...m,
|
|
511
505
|
projects: dedupeProjects(m.projects.some((p) => p.path === resolved)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { resolve as resolvePath } from 'node:path';
|
|
3
|
+
import { usage } from '../errors.js';
|
|
4
|
+
/** A project directory as an absolute real path; it must exist and be a directory on THIS machine's disk.
|
|
5
|
+
* The CLI runs this on the caller's machine before sending a path to a canvas that may live in the cloud. */
|
|
6
|
+
export function resolveExistingProjectDir(dir) {
|
|
7
|
+
const abs = resolvePath(dir);
|
|
8
|
+
if (!existsSync(abs) || !statSync(abs).isDirectory()) {
|
|
9
|
+
throw usage(`project directory does not exist or is not a directory: ${dir}`, {
|
|
10
|
+
received: dir,
|
|
11
|
+
next: 'Pass an existing directory path.',
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
return realpathSync(abs);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return abs;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -207,6 +207,7 @@ export const OPERATIONS = [
|
|
|
207
207
|
{ name: 'import.store', method: 'PUT', path: '/v1/imports/:run_id/stores/:name', classes: ['person', 'import'], resource: 'none' },
|
|
208
208
|
{ name: 'import.load', method: 'POST', path: '/v1/imports/:run_id/load', classes: ['person', 'import'], resource: 'none' },
|
|
209
209
|
{ name: 'import.get', method: 'GET', path: '/v1/imports/:run_id', classes: ['person', 'import'], resource: 'none' },
|
|
210
|
+
{ name: 'import.retry', method: 'POST', path: '/v1/imports/:run_id/retry', classes: ['person'], resource: 'none' },
|
|
210
211
|
{ name: 'import.rollback', method: 'POST', path: '/v1/imports/:run_id/rollback', classes: ['person'], resource: 'none' },
|
|
211
212
|
{ name: 'machine.register', method: 'POST', path: '/v1/machines', classes: ['person'], resource: 'none' },
|
|
212
213
|
{ name: 'machine.revoke', method: 'DELETE', path: '/v1/machines/:environment_id', classes: ['person'], resource: 'none' },
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.758",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.758",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.758",
|
|
31
|
+
"@north-light/identity": "0.3.758"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.758",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.758",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.758",
|
|
32
|
+
"@north-light/plugin": "0.3.758",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.758",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.758",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.758",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.758",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.758",
|
|
11927
|
+
"@north-light/identity": "0.3.758"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.758",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.758",
|
|
11936
|
+
"@north-light/identity": "0.3.758",
|
|
11937
|
+
"@north-light/plugin": "0.3.758",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|