@north-light/cli 0.3.731 → 0.3.733

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.
Files changed (62) hide show
  1. package/dist/api/client.d.ts +3 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/builtin-memory/northlight-apps/get-started.md +4 -4
  6. package/dist/clients/attach/overlays/graph.d.ts +2 -0
  7. package/dist/clients/attach/overlays/graph.js +1 -1
  8. package/dist/clients/attach/viewer.js +478 -478
  9. package/dist/commands/sys/daemon.js +1 -1
  10. package/dist/commands/sys/import/move.d.ts +2 -0
  11. package/dist/commands/sys/import/move.js +9 -7
  12. package/dist/commands/sys/join.js +1 -1
  13. package/dist/commands/sys/signin.js +2 -2
  14. package/dist/core/canvas/canvas.d.ts +1 -1
  15. package/dist/core/canvas/canvas.js +16 -16
  16. package/dist/core/canvas/schema-pg/034-authz-epoch-triggers.sql +43 -0
  17. package/dist/core/canvas/schema-version.d.ts +1 -1
  18. package/dist/core/canvas/schema-version.js +1 -1
  19. package/dist/core/canvas/tree.d.ts +4 -0
  20. package/dist/core/canvas/tree.js +6 -6
  21. package/dist/core/directory/join.d.ts +6 -26
  22. package/dist/core/directory/join.js +1 -1
  23. package/dist/core/environment-starter-script.d.ts +1 -1
  24. package/dist/core/environment-starter-script.js +1 -1
  25. package/dist/core/grants/sync.js +1 -1
  26. package/dist/core/providers/call.js +1 -1
  27. package/dist/core/runtime/runner/blaxel/image-build.js +3 -3
  28. package/dist/core/runtime/runner/blaxel/release-image.js +2 -2
  29. package/dist/core/storage/client.js +2 -2
  30. package/dist/daemon/api/handlers/canvas.js +5 -5
  31. package/dist/daemon/api/handlers/shares.js +1 -1
  32. package/dist/daemon/crtrd.js +8 -8
  33. package/dist/daemon/manage.d.ts +2 -7
  34. package/dist/daemon/manage.js +3 -3
  35. package/docs/apps/get-started.md +4 -4
  36. package/docs/cli/join-northlight.md +16 -22
  37. package/package.json +3 -3
  38. package/packages/crouter-api/dist/api/client.js +4 -3
  39. package/packages/crouter-api/dist/api/contract.js +1 -1
  40. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +18 -1
  41. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -3
  42. package/packages/crouter-api/dist/commands/sys/import/move.js +12 -0
  43. package/packages/crouter-api/dist/commands/sys/join.js +5 -37
  44. package/packages/crouter-api/dist/commands/sys/signin.js +6 -4
  45. package/packages/crouter-api/dist/core/canvas/canvas.js +7 -3
  46. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  47. package/packages/crouter-api/dist/core/canvas/tree.js +20 -0
  48. package/packages/crouter-api/dist/core/directory/join.js +35 -86
  49. package/packages/crouter-api/dist/core/environment-starter-script.js +1 -1
  50. package/packages/crouter-api/dist/core/grants/sync.js +1 -1
  51. package/packages/crouter-api/dist/core/providers/call.js +1 -1
  52. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +1 -1
  53. package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +1 -1
  54. package/packages/crouter-api/dist/core/storage/client.js +1 -1
  55. package/packages/crouter-api/dist/daemon/manage.js +2 -16
  56. package/packages/crouter-api/package.json +1 -1
  57. package/packages/crouter-identity/package.json +1 -1
  58. package/packages/crouter-plugin/package.json +3 -3
  59. package/runtime.lock.json +14 -14
  60. package/dist/core/directory/join-lock.d.ts +0 -13
  61. package/dist/core/directory/join-lock.js +0 -1
  62. package/packages/crouter-api/dist/core/directory/join-lock.js +0 -61
@@ -1 +1 @@
1
- var _=Object.defineProperty;var i=(t,e)=>_(t,"name",{value:e,configurable:!0});import{SHARE_VERBS as f}from"../../../api/dto/permissions.js";import{ApiError as c}from"../../../api/errors.js";import{openDb as g,withCanvasWrite as v}from"../../../core/canvas/db.js";import{joinedOwner as R}from"../../../core/directory/join.js";import{groupFactId as O}from"../../../core/graph/groups.js";import{actorOf as S}from"../../../core/graph/documents.js";import{publish as T}from"../../../core/graph/events.js";import{GROUP_TYPE as b,OBJECT_TYPE as w,VERB_RELATION as h}from"../../../core/permissions/builtin.js";import{check as y,userOf as $}from"../../../core/permissions/evaluator.js";import{deleteFact as A,EVERYONE as L,formatSubject as p,listFacts as N,parseSubject as B,writeFact as F}from"../../../core/permissions/facts.js";import{readerFor as D,resolveRef as I}from"../reader.js";import{asApiError as k}from"./schemas.js";import{invalidRequest as C,isRecord as P}from"./validate.js";const W={edit:["document","repo"],message:["node","profile"],use:["environment"]};async function q(t,e){if(e.startsWith("group:")){const a=await t.prepare("SELECT id FROM objects WHERE type = 'group' AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(e.slice(6));if(a===void 0)throw new c(404,"not_found",`group ${e.slice(6)} not found`);return{type:b,id:O(a.id),relation:"member"}}if(e.startsWith("team:"))return{type:b,id:e,relation:"member"};const r=B(e);if(r.type!=="user"||r.relation!=="")throw new c(400,"invalid_subject","`subject` must be `user:<id>`, `team:<id>`, `group:<handle>` or `user:*`");return r}i(q,"subjectOf");async function U(t,e,r){return e.principal.class==="broker"?`node:${e.principal.node}`:`user:${await $(t,r)}`}i(U,"writtenBy");async function j(t,e,r){const a=await D(t,e),o=await I(t,a,decodeURIComponent(e.params.ref));if("remote"in o||"deleted"in o)throw new c(404,"not_found","object not found");if(!await y(t,a,"share",o.id))throw await y(t,a,"read",o.id)?new c(403,"not_owner",`only the owner of ${o.name}, or the owner's agents, may share it`):new c(404,"not_found","object not found");const n=r===null?void 0:W[r];if(r!==null&&n!==void 0&&!n.includes(o.type))throw new c(400,"verb_not_applicable",`\`${r}\` applies to ${n.join(" and ")} objects; ${o.name} is a ${o.type}`,{verb:r,type:o.type});return{object:o,reader:a}}i(j,"shareable");async function V(t,e){return e.owner===null?!1:await t.prepare("SELECT 1 AS ok FROM objects WHERE id = ? AND type = 'group'").get(e.owner)!==void 0}i(V,"ownedByGroup");function Y(t,e){const r=[],a=P(t)?t:(r.push({field:"body",problem:"must be an object"}),{}),o=a.verb;return(typeof o!="string"||!f.includes(o))&&r.push({field:"verb",problem:`must be one of ${f.join(", ")}`,received:o}),typeof a.subject!="string"&&r.push({field:"subject",problem:"must be a string"}),r.length>0&&C(e,r),{verb:o,subject:a.subject}}i(Y,"parse");async function E(t,e){const{verb:r,subject:a}=Y(e?t.body:Object.fromEntries(t.query),e?"share request":"share revoke request");if(e&&a===p(L)&&R()===null)throw new c(400,"not_joined","sharing with everyone needs an install that has joined the directory; run `crtr sys join` first");const o=h[r];try{return await v(async n=>{const u=await q(n,a),{object:s,reader:d}=await j(n,t,r);if(e&&r==="edit"&&s.type==="repo"&&!await V(n,s))throw new c(400,"verb_not_applicable",`\`edit\` applies to documents and to repos a group holds; ${s.name} is a personal repo`,{verb:r,type:s.type});const l={resourceType:w,resourceId:s.id,relation:o,subject:u},m=e?await F(n,{...l,writtenBy:await U(n,t,d)}):await A(n,l);return m&&await T(n,{event:e?"relation.written":"relation.deleted",object:s,actor:S(d),attrs:{resource:s.id,relation:o,subject:p(u)}}),{id:s.id,name:s.name,relation:o,subject:p(u),changed:m}})}catch(n){throw k(n)}}i(E,"change");async function G(t){const e=await g(),{object:r}=await j(e,t,null),a=new Map(Object.entries(h).map(([n,u])=>[u,n])),o=(await N(e,w,r.id)).filter(n=>a.has(n.relation)&&n.written_by!=="package").map(n=>({verb:a.get(n.relation),subject:p({type:n.subject_type,id:n.subject_id,relation:n.subject_relation}),written_by:n.written_by,created_at:n.created_at}));return{id:r.id,name:r.name,items:o}}i(G,"list");const ae=[{method:"GET",pattern:"/v1/objects/:ref/shares",handler:i(async t=>({status:200,body:await G(t)}),"handler")},{method:"POST",pattern:"/v1/objects/:ref/shares",handler:i(async t=>({status:200,body:await E(t,!0)}),"handler")},{method:"DELETE",pattern:"/v1/objects/:ref/shares",handler:i(async t=>({status:200,body:await E(t,!1)}),"handler")}];export{ae as shareRoutes};
1
+ var _=Object.defineProperty;var i=(t,e)=>_(t,"name",{value:e,configurable:!0});import{SHARE_VERBS as f}from"../../../api/dto/permissions.js";import{ApiError as c}from"../../../api/errors.js";import{openDb as g,withCanvasWrite as v}from"../../../core/canvas/db.js";import{joinedOwner as R}from"../../../core/directory/join.js";import{groupFactId as O}from"../../../core/graph/groups.js";import{actorOf as S}from"../../../core/graph/documents.js";import{publish as T}from"../../../core/graph/events.js";import{GROUP_TYPE as b,OBJECT_TYPE as w,VERB_RELATION as h}from"../../../core/permissions/builtin.js";import{check as y,userOf as $}from"../../../core/permissions/evaluator.js";import{deleteFact as A,EVERYONE as L,formatSubject as p,listFacts as N,parseSubject as B,writeFact as F}from"../../../core/permissions/facts.js";import{readerFor as D,resolveRef as I}from"../reader.js";import{asApiError as k}from"./schemas.js";import{invalidRequest as C,isRecord as P}from"./validate.js";const W={edit:["document","repo"],message:["node","profile"],use:["environment"]};async function q(t,e){if(e.startsWith("group:")){const a=await t.prepare("SELECT id FROM objects WHERE type = 'group' AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(e.slice(6));if(a===void 0)throw new c(404,"not_found",`group ${e.slice(6)} not found`);return{type:b,id:O(a.id),relation:"member"}}if(e.startsWith("team:"))return{type:b,id:e,relation:"member"};const r=B(e);if(r.type!=="user"||r.relation!=="")throw new c(400,"invalid_subject","`subject` must be `user:<id>`, `team:<id>`, `group:<handle>` or `user:*`");return r}i(q,"subjectOf");async function U(t,e,r){return e.principal.class==="broker"?`node:${e.principal.node}`:`user:${await $(t,r)}`}i(U,"writtenBy");async function j(t,e,r){const a=await D(t,e),o=await I(t,a,decodeURIComponent(e.params.ref));if("remote"in o||"deleted"in o)throw new c(404,"not_found","object not found");if(!await y(t,a,"share",o.id))throw await y(t,a,"read",o.id)?new c(403,"not_owner",`only the owner of ${o.name}, or the owner's agents, may share it`):new c(404,"not_found","object not found");const n=r===null?void 0:W[r];if(r!==null&&n!==void 0&&!n.includes(o.type))throw new c(400,"verb_not_applicable",`\`${r}\` applies to ${n.join(" and ")} objects; ${o.name} is a ${o.type}`,{verb:r,type:o.type});return{object:o,reader:a}}i(j,"shareable");async function V(t,e){return e.owner===null?!1:await t.prepare("SELECT 1 AS ok FROM objects WHERE id = ? AND type = 'group'").get(e.owner)!==void 0}i(V,"ownedByGroup");function Y(t,e){const r=[],a=P(t)?t:(r.push({field:"body",problem:"must be an object"}),{}),o=a.verb;return(typeof o!="string"||!f.includes(o))&&r.push({field:"verb",problem:`must be one of ${f.join(", ")}`,received:o}),typeof a.subject!="string"&&r.push({field:"subject",problem:"must be a string"}),r.length>0&&C(e,r),{verb:o,subject:a.subject}}i(Y,"parse");async function E(t,e){const{verb:r,subject:a}=Y(e?t.body:Object.fromEntries(t.query),e?"share request":"share revoke request");if(e&&a===p(L)&&R()===null)throw new c(400,"not_joined","sharing with everyone needs an install that has joined the directory; run `crtr sys signin` first");const o=h[r];try{return await v(async n=>{const u=await q(n,a),{object:s,reader:d}=await j(n,t,r);if(e&&r==="edit"&&s.type==="repo"&&!await V(n,s))throw new c(400,"verb_not_applicable",`\`edit\` applies to documents and to repos a group holds; ${s.name} is a personal repo`,{verb:r,type:s.type});const l={resourceType:w,resourceId:s.id,relation:o,subject:u},m=e?await F(n,{...l,writtenBy:await U(n,t,d)}):await A(n,l);return m&&await T(n,{event:e?"relation.written":"relation.deleted",object:s,actor:S(d),attrs:{resource:s.id,relation:o,subject:p(u)}}),{id:s.id,name:s.name,relation:o,subject:p(u),changed:m}})}catch(n){throw k(n)}}i(E,"change");async function G(t){const e=await g(),{object:r}=await j(e,t,null),a=new Map(Object.entries(h).map(([n,u])=>[u,n])),o=(await N(e,w,r.id)).filter(n=>a.has(n.relation)&&n.written_by!=="package").map(n=>({verb:a.get(n.relation),subject:p({type:n.subject_type,id:n.subject_id,relation:n.subject_relation}),written_by:n.written_by,created_at:n.created_at}));return{id:r.id,name:r.name,items:o}}i(G,"list");const ae=[{method:"GET",pattern:"/v1/objects/:ref/shares",handler:i(async t=>({status:200,body:await G(t)}),"handler")},{method:"POST",pattern:"/v1/objects/:ref/shares",handler:i(async t=>({status:200,body:await E(t,!0)}),"handler")},{method:"DELETE",pattern:"/v1/objects/:ref/shares",handler:i(async t=>({status:200,body:await E(t,!1)}),"handler")}];export{ae as shareRoutes};
@@ -1,21 +1,21 @@
1
- var lr=Object.defineProperty;var s=(e,l)=>lr(e,"name",{value:l,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startBrokerMemoryCap as pr}from"./broker-memory-cap.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as fr}from"../core/peer/directory.js";import{createPeerRelay as ur}from"./peer/relay-service.js";import{writeFileSync as hr,readFileSync as wr,rmSync as vr,mkdirSync as xe,existsSync as P,unlinkSync as De,chmodSync as Te}from"node:fs";import{createServer as Y}from"node:http";import{dirname as gr}from"node:path";import{envCrtrdTcp as Ce,envDocumentPort as yr}from"../shared/env.js";import{openCanvasConversationStore as Sr,serveCanvasConversationStore as _r}from"../core/canvas/sessions.js";import{installConversationStore as br}from"../core/conversation-store/index.js";import{pollRunObservers as kr}from"./runs/observer.js";import{randomBytes as Le}from"node:crypto";import{apiSocketPath as $e,crtrHome as Rr}from"../core/canvas/paths.js";import{activeAppUsers as Pr}from"../core/spaces/users.js";import{ensureAppSpace as Er,ensureUserFiles as Ir}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 xr}from"./launcher-events.js";import{initializeEmptyLayout as Dr,layoutNeedsMigration as Tr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Cr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Lr}from"../core/profiles/relocate.js";import{getNode as $r,getRow as Ar,listNodesForSupervision as Ne,listParkedResidentsWithWakeMail as Nr,setFrozen as Me}from"../core/canvas/index.js";import{createApiServer as Mr,closeServer as Oe}from"./api/server.js";import{Router as Or}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Fr}from"./api/document-listener.js";import{documentSecret as Br}from"./api/document-secret.js";import{createAppListener as Hr}from"./api/app-listener.js";import{registerMachineEnvironment as jr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as zr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Ur,resolvePerson as qr,retireLocalPerson as Wr,setPersonId as Jr}from"../core/canvas/person.js";import{backfillNodeApps as Ge,runPermissionsBoot as Kr}from"../core/permissions/boot.js";import{startRunNotices as Vr}from"./run-notices.js";import{startGrantEffects as Yr}from"./reconcilers/grant-effects.js";import{syncPackages as Qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Xr}from"../core/model-auth/activations.js";import{createGrantSync as Zr,GRANT_SYNC_INTERVAL_S as Fe}from"../core/grants/sync.js";import{sweepSandboxes as et}from"../core/grants/on-sync.js";import{rebuildCronExecutions as rt}from"./cron/run-socket.js";import{hasSyncedGrants as tt}from"../core/grants/mirror.js";import{readConfig as fe}from"../core/config.js";import{reconcileUndeliveredTickets as nt}from"./human/sweep.js";import{resetHandedOffDeliveries as ot}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as it}from"../core/canvas/daemon-actions.js";import{sweepReviews as at}from"./review/sweep.js";import{pidfilePath as ue}from"./pidfile.js";import{rendererWarning as st}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ct}from"./supervise-cadence.js";import{createResumeDetector as lt}from"./resume-detector.js";import{setFatalFaultAnnouncer as dt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as pt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as mt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ft}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ut}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ht}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as wt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as vt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as gt}from"./reconcilers/action-lane.js";import{endLiveExecution as yt,hasObservedExit as St,latestExecutionForNode as _t,migrateLegacyExecutionIdentities as bt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as kt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as Rt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as Pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Et}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as It}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as xt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Dt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Tt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Ct}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Lt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as he}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as $t}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as At}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Nt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Mt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Ot,subscribeImageBuilt as Gt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Ft}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Be,capturePidCommand as Bt,captureTeardownSnapshot as He,isPidAlive as Ht,isAnyPidAlive as je,killProcessTreePids as ze}from"../core/canvas/pid.js";import{bindFleet as jt,boundFleet as Ue}from"../core/runtime/fleet.js";import{bindDaemonControl as zt,clearDaemonControl as Ut}from"./control.js";import{execDaemon as qt,spawnDaemon as Wt}from"./manage.js";import{reconcileAndMigrateBoot as Jt}from"../core/canvas/boot.js";import{resolveInstallId as Kt}from"../core/canvas/install-id.js";import{setInstallId as Vt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Yt,daemonOwnershipApplies as Qt,daemonOwnershipClaimed as Xt,releaseDaemonOwnership as qe}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Zt,closeAllDbs as we,openDb as en,withCanvasWrite as ve}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as rn}from"../core/canvas/import-sqlite.js";import{ensurePostgres as tn,ensurePostgresHealthy as nn,stopPostgres as on,withPostgresStartLock as an}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as sn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as cn}from"./api/handlers/broker-ops.js";import{reconcilePackages as ln}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as dn}from"../core/scoped-state/migrate-app-installs.js";import{publish as pn,readBuiltinSnapshot as mn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as fn,reapStaleSpares as un}from"../core/runtime/warm-pool.js";import{DaemonFleet as hn}from"./fleet.js";import{copyNodeFilesToRows as wn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as vn}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as gn}from"../core/events/source.js";import{activateCanvasImport as yn,MigrationBlockedError as Sn,runForcedCanvasImport as _n}from"../migrations/activation.js";import{adoptInstallPerson as bn,convertLegacyScopedStore as kn,personStoresCopied as Rn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Pn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as We,installPreludeSnapshot as En}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ge}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Je}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ye}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as la}from"../core/runtime/broker-ownership.js";function Se(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(Se,"brokerCommandEpoch");const In=5e3,Ke=150;async function xn(e){const l=Be();if(l===null)throw p({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=Rr(),m=[];for(const[i,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ye(w,f)||Se(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||m.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of m){const c=Bt(i.pid);if(c===null||!c.includes("broker-cli.js")||!ye(c,f)||Se(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=He(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+In;for(;Date.now()<h&&o.some(i=>je(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 c=i.snap.tree.length>0?i.snap.tree:[i.pid];je(c)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):ze(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Be();if(d===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ye(w,f)&&Se(w)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:g,sigkilled:y}})}s(xn,"reapPriorEpochBrokers");const Dn=5e3;async function Tn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await $r(o))?.status;(h==="active"||h==="idle")&&await Me(o,new Date().toISOString())}const f=l.map(([,o])=>({pid:o.pid,snap:He(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,Dn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),m])));const g=[];for(const o of f)Ht(o.pid)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):ze(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of l)await yt(o,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Tn,"teardownFleet");function Q(...e){xe(gr(ue()),{recursive:!0}),hr(ue(),[process.pid,...e].join(`
1
+ var lr=Object.defineProperty;var s=(e,l)=>lr(e,"name",{value:l,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startBrokerMemoryCap as pr}from"./broker-memory-cap.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as fr}from"../core/peer/directory.js";import{createPeerRelay as ur}from"./peer/relay-service.js";import{writeFileSync as hr,readFileSync as wr,rmSync as vr,mkdirSync as xe,existsSync as P,unlinkSync as De,chmodSync as Te}from"node:fs";import{createServer as Y}from"node:http";import{dirname as gr}from"node:path";import{envCrtrdTcp as Ce,envDocumentPort as yr}from"../shared/env.js";import{openCanvasConversationStore as Sr,serveCanvasConversationStore as _r}from"../core/canvas/sessions.js";import{installConversationStore as br}from"../core/conversation-store/index.js";import{pollRunObservers as kr}from"./runs/observer.js";import{randomBytes as Le}from"node:crypto";import{apiSocketPath as $e,crtrHome as Rr}from"../core/canvas/paths.js";import{activeAppUsers as Pr}from"../core/spaces/users.js";import{ensureAppSpace as Er,ensureUserFiles as Ir}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 xr}from"./launcher-events.js";import{initializeEmptyLayout as Dr,layoutNeedsMigration as Tr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Cr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Lr}from"../core/profiles/relocate.js";import{getNode as $r,getRow as Ar,listNodesForSupervision as Ne,listParkedResidentsWithWakeMail as Nr,setFrozen as Me}from"../core/canvas/index.js";import{createApiServer as Mr,closeServer as Oe}from"./api/server.js";import{Router as Or}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Fr}from"./api/document-listener.js";import{documentSecret as Br}from"./api/document-secret.js";import{createAppListener as Hr}from"./api/app-listener.js";import{registerMachineEnvironment as jr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as zr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Ur,resolvePerson as qr,retireLocalPerson as Wr,setPersonId as Kr}from"../core/canvas/person.js";import{backfillNodeApps as Ge,runPermissionsBoot as Jr}from"../core/permissions/boot.js";import{startRunNotices as Vr}from"./run-notices.js";import{startGrantEffects as Yr}from"./reconcilers/grant-effects.js";import{syncPackages as Qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Xr}from"../core/model-auth/activations.js";import{createGrantSync as Zr,GRANT_SYNC_INTERVAL_S as Fe}from"../core/grants/sync.js";import{sweepSandboxes as et}from"../core/grants/on-sync.js";import{rebuildCronExecutions as rt}from"./cron/run-socket.js";import{hasSyncedGrants as tt}from"../core/grants/mirror.js";import{readConfig as fe}from"../core/config.js";import{reconcileUndeliveredTickets as nt}from"./human/sweep.js";import{resetHandedOffDeliveries as ot}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as it}from"../core/canvas/daemon-actions.js";import{sweepReviews as at}from"./review/sweep.js";import{pidfilePath as ue}from"./pidfile.js";import{rendererWarning as st}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ct}from"./supervise-cadence.js";import{createResumeDetector as lt}from"./resume-detector.js";import{setFatalFaultAnnouncer as dt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as pt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as mt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ft}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ut}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ht}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as wt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as vt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as gt}from"./reconcilers/action-lane.js";import{endLiveExecution as yt,hasObservedExit as St,latestExecutionForNode as _t,migrateLegacyExecutionIdentities as bt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as kt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as Rt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as Pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Et}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as It}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as xt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Dt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Tt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Ct}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Lt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as he}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as $t}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as At}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Nt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Mt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Ot,subscribeImageBuilt as Gt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Ft}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Be,capturePidCommand as Bt,captureTeardownSnapshot as He,isPidAlive as Ht,isAnyPidAlive as je,killProcessTreePids as ze}from"../core/canvas/pid.js";import{bindFleet as jt,boundFleet as Ue}from"../core/runtime/fleet.js";import{bindDaemonControl as zt,clearDaemonControl as Ut}from"./control.js";import{execDaemon as qt,spawnDaemon as Wt}from"./manage.js";import{reconcileAndMigrateBoot as Kt}from"../core/canvas/boot.js";import{resolveInstallId as Jt}from"../core/canvas/install-id.js";import{setInstallId as Vt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Yt,daemonOwnershipApplies as Qt,daemonOwnershipClaimed as Xt,releaseDaemonOwnership as qe}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Zt,closeAllDbs as we,openDb as en,withCanvasWrite as ve}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as rn}from"../core/canvas/import-sqlite.js";import{ensurePostgres as tn,ensurePostgresHealthy as nn,stopPostgres as on,withPostgresStartLock as an}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as sn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as cn}from"./api/handlers/broker-ops.js";import{reconcilePackages as ln}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as dn}from"../core/scoped-state/migrate-app-installs.js";import{publish as pn,readBuiltinSnapshot as mn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as fn,reapStaleSpares as un}from"../core/runtime/warm-pool.js";import{DaemonFleet as hn}from"./fleet.js";import{copyNodeFilesToRows as wn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as vn}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as gn}from"../core/events/source.js";import{activateCanvasImport as yn,MigrationBlockedError as Sn,runForcedCanvasImport as _n}from"../migrations/activation.js";import{adoptInstallPerson as bn,convertLegacyScopedStore as kn,personStoresCopied as Rn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Pn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as We,installPreludeSnapshot as En}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ge}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Ke}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ye}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as la}from"../core/runtime/broker-ownership.js";function Se(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(Se,"brokerCommandEpoch");const In=5e3,Je=150;async function xn(e){const l=Be();if(l===null)throw p({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=Rr(),m=[];for(const[i,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ye(w,f)||Se(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||m.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of m){const c=Bt(i.pid);if(c===null||!c.includes("broker-cli.js")||!ye(c,f)||Se(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=He(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+In;for(;Date.now()<h&&o.some(i=>je(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Je));let y=0;for(const i of o){const c=i.snap.tree.length>0?i.snap.tree:[i.pid];je(c)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):ze(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Je));const d=Be();if(d===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ye(w,f)&&Se(w)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:g,sigkilled:y}})}s(xn,"reapPriorEpochBrokers");const Dn=5e3;async function Tn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await $r(o))?.status;(h==="active"||h==="idle")&&await Me(o,new Date().toISOString())}const f=l.map(([,o])=>({pid:o.pid,snap:He(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,Dn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),m])));const g=[];for(const o of f)Ht(o.pid)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):ze(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of l)await yt(o,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Tn,"teardownFleet");function Q(...e){xe(gr(ue()),{recursive:!0}),hr(ue(),[process.pid,...e].join(`
2
2
  `),"utf8")}s(Q,"writePidfile");function Ve(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ve,"isMissingPathError");function Ye(e){const l=ue();let f;try{f=wr(l,"utf8")}catch(m){if(Ve(m))return;throw m}if(f.split(`
3
- `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{vr(l)}catch(m){if(Ve(m))return;throw m}}s(Ye,"removeOwnedPidfileMirror");const Cn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new pt;dt(e=>X.handleFatalFault(e,!1));const Ln=new ft,$n=new mt,Qe=new ut,An=new ht,Nn=new wt,Mn=new vt,On=new gt,Gn=new Rt,Fn=new Pt,Bn=new Et,Hn=new xt,jn=new It,zn=new Tt,Un=new Ct,qn=new Lt,Wn=new $t,Jn=new At,Kn=new Nt,Vn=new Mt,Yn=new Ot;async function Qn(e=Date.now(),l=Cn){const f=Ue(),m=await X.runFleetPreamble(f);let g,o,h;try{o=await he();const d=(await Ne()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),h=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(h.map(i=>i.node_id));h.push(...(await Nr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){p({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:l,held:o}),await Ln.run(e,{rows:g,held:o}),await $n.run(e);const y=await Qe.run(e,{rows:[...g,...h],fleet:f});await An.run(e,o),await Vn.run(e,o),await Yn.run(e,{lifecycle:l}),await Nn.run(e,{lifecycle:l,held:o}),await Mn.run(e,{lifecycle:l}),await On.run(e,{lifecycle:l}),await Gn.run(e,{lifecycle:l}),await Fn.run(e,{lifecycle:l,fleet:f,held:o}),Bn.run(e,{lifecycle:l}),Hn.run(e,{lifecycle:l}),jn.run(e,{lifecycle:l}),zn.run(e,{lifecycle:l}),Un.run(e,{lifecycle:l}),qn.run(e,{lifecycle:l}),Wn.run(e,{lifecycle:l}),await kr(),Kn.run(e,{fleet:f,lifecycle:l}),await Jn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:l,thresholds:m,frozen:y})}s(Qn,"superviseTick");async function Xn(e,l=Date.now()){if((await he()).has(e))return;const f=await _t(e);if(f===null||!St(f))return;const m=await Ar(e);m===null||m.kind==="human"||await Qe.runNode(l,m,Ue())}s(Xn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"}s(Z,"roleRunsLanes");function O(e){return e===void 0||e==="api"}s(O,"roleServesRequests");const Zn=66e4;function eo(e){const l=new Or().registerAll(Gr(()=>null).filter(c=>c.pattern==="/healthz")),f=s((c,w)=>{const b=(c.url??"/").split("?")[0];if((c.method??"GET").toUpperCase()==="GET"&&b==="/healthz"){l.handle(c,w,null,{class:"person"});return}w.writeHead(404,{"content-type":"application/json; charset=utf-8"}),w.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),m=$e();P(m)&&De(m);const g=Y(f),o=new Promise((c,w)=>{g.once("error",w),g.listen(m,()=>{g.off("error",w),Te(m,384),c()})});let h,y=null,d=o;const u=e.tcp??Ce()??fe("user").api.tcp;if(u!==void 0&&u!==""){const c=/^(.*):(\d+)$/.exec(u.trim());if(c===null||Number(c[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const w=Y(f);w.on("error",b=>p({event:"api.server.failed",level:"error",error:b})),d=o.then(()=>new Promise(b=>{w.once("error",()=>b()),w.listen(Number(c[2]),c[1]===""?"0.0.0.0":c[1],()=>{const E=w.address();y=`${E.address}:${E.port}`,b()})})),h=w}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(c={}){if(!i){i=!0,await Promise.all([Oe(g,new Set,c.graceMs),h===void 0?Promise.resolve():Oe(h,new Set,c.graceMs)]);try{P(m)&&De(m)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){xe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&Te(Ae(),493);const l=$e();if(P(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(l,()=>{f.off("error",u),d()})});let m;const g=e.tcp??Ce();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,c)=>{u.once("error",c),u.listen(Number(d[2]),d[1],()=>{u.off("error",c),i()})}),m=u}Q();let o;const h=s(()=>(o??=(async()=>{f.closeAllConnections(),m?.closeAllConnections(),await Promise.all([f,m].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(c=>c?i(c):u())))),Ye(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
3
+ `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{vr(l)}catch(m){if(Ve(m))return;throw m}}s(Ye,"removeOwnedPidfileMirror");const Cn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new pt;dt(e=>X.handleFatalFault(e,!1));const Ln=new ft,$n=new mt,Qe=new ut,An=new ht,Nn=new wt,Mn=new vt,On=new gt,Gn=new Rt,Fn=new Pt,Bn=new Et,Hn=new xt,jn=new It,zn=new Tt,Un=new Ct,qn=new Lt,Wn=new $t,Kn=new At,Jn=new Nt,Vn=new Mt,Yn=new Ot;async function Qn(e=Date.now(),l=Cn){const f=Ue(),m=await X.runFleetPreamble(f);let g,o,h;try{o=await he();const d=(await Ne()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),h=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(h.map(i=>i.node_id));h.push(...(await Nr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){p({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:l,held:o}),await Ln.run(e,{rows:g,held:o}),await $n.run(e);const y=await Qe.run(e,{rows:[...g,...h],fleet:f});await An.run(e,o),await Vn.run(e,o),await Yn.run(e,{lifecycle:l}),await Nn.run(e,{lifecycle:l,held:o}),await Mn.run(e,{lifecycle:l}),await On.run(e,{lifecycle:l}),await Gn.run(e,{lifecycle:l}),await Fn.run(e,{lifecycle:l,fleet:f,held:o}),Bn.run(e,{lifecycle:l}),Hn.run(e,{lifecycle:l}),jn.run(e,{lifecycle:l}),zn.run(e,{lifecycle:l}),Un.run(e,{lifecycle:l}),qn.run(e,{lifecycle:l}),Wn.run(e,{lifecycle:l}),await kr(),Jn.run(e,{fleet:f,lifecycle:l}),await Kn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:l,thresholds:m,frozen:y})}s(Qn,"superviseTick");async function Xn(e,l=Date.now()){if((await he()).has(e))return;const f=await _t(e);if(f===null||!St(f))return;const m=await Ar(e);m===null||m.kind==="human"||await Qe.runNode(l,m,Ue())}s(Xn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"}s(Z,"roleRunsLanes");function O(e){return e===void 0||e==="api"}s(O,"roleServesRequests");const Zn=66e4;function eo(e){const l=new Or().registerAll(Gr(()=>null).filter(c=>c.pattern==="/healthz")),f=s((c,w)=>{const b=(c.url??"/").split("?")[0];if((c.method??"GET").toUpperCase()==="GET"&&b==="/healthz"){l.handle(c,w,null,{class:"person"});return}w.writeHead(404,{"content-type":"application/json; charset=utf-8"}),w.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),m=$e();P(m)&&De(m);const g=Y(f),o=new Promise((c,w)=>{g.once("error",w),g.listen(m,()=>{g.off("error",w),Te(m,384),c()})});let h,y=null,d=o;const u=e.tcp??Ce()??fe("user").api.tcp;if(u!==void 0&&u!==""){const c=/^(.*):(\d+)$/.exec(u.trim());if(c===null||Number(c[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const w=Y(f);w.on("error",b=>p({event:"api.server.failed",level:"error",error:b})),d=o.then(()=>new Promise(b=>{w.once("error",()=>b()),w.listen(Number(c[2]),c[1]===""?"0.0.0.0":c[1],()=>{const E=w.address();y=`${E.address}:${E.port}`,b()})})),h=w}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(c={}){if(!i){i=!0,await Promise.all([Oe(g,new Set,c.graceMs),h===void 0?Promise.resolve():Oe(h,new Set,c.graceMs)]);try{P(m)&&De(m)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){xe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&Te(Ae(),493);const l=$e();if(P(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(l,()=>{f.off("error",u),d()})});let m;const g=e.tcp??Ce();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,c)=>{u.once("error",c),u.listen(Number(d[2]),d[1],()=>{u.off("error",c),i()})}),m=u}Q();let o;const h=s(()=>(o??=(async()=>{f.closeAllConnections(),m?.closeAllConnections(),await Promise.all([f,m].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(c=>c?i(c):u())))),Ye(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
4
4
  `),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),h}s(to,"serveLayoutRefusal");async function no(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Tr())return to(e);Dr();const l=s(t=>{process.stderr.write(`[crtrd] ${t}
5
5
  `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,m=Qt(e.role);cn(Z(e.role));const g=s(async()=>m?await Yt(Le(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Le(16).toString("hex")}},"claimOwnership"),{database:o,ownership:h}=f?{database:{url:await Zt()},ownership:await g()}:await an(async()=>({database:await tn({log:l,startLockHeld:!0}),ownership:await g()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
6
6
  `);else{const t=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(v=>v!==void 0),a=t.length>0?` (${t.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
7
7
  `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=h.claim;let d=null,u=null,i=null,c=null,w,b="";try{m&&await xn(y.token);for(const r of Lr())process.stderr.write(`[crtrd] ${r}
8
8
  `);for(const r of await Cr())process.stderr.write(`[crtrd] ${r}
9
- `);await en(),await rn(o.url,l);const t=e.role===void 0&&!await Rn();let a=null;t&&(kn({kind:"user",root:Je()}),a=Pn(Je())),e.role===void 0&&En(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const v=s(r=>{ge(r).catch(n=>p({level:"error",event:"daemon.settings.reload_failed",error:n}))},"reloadPerson");if(w=await M.subscribe(r=>{We().includes(r)&&v(r)},{kinds:["settings"],onListenStart:s(()=>{for(const r of We())v(r)},"onListenStart")}),e.role!==void 0&&Ur(),e.role!==void 0){let r;try{r=mn()}catch(_){p({level:"error",event:"daemon.packages.snapshot_failed",error:_})}const n=await ve(async _=>(await Ge(_),r===void 0?void 0:await pn(_,r,"release")));c=await ve(async _=>await dn(_));for(const _ of n?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${_.path}: ${_.error}
10
- `)}else{d=await qr(),d!==null&&(Jr(d.id),await ge(d.id));const r=await ve(async n=>(await Ge(n),d===null?null:await ln(n)));if(r!==null){for(const n of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${n.message}
9
+ `);await en(),await rn(o.url,l);const t=e.role===void 0&&!await Rn();let a=null;t&&(kn({kind:"user",root:Ke()}),a=Pn(Ke())),e.role===void 0&&En(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const v=s(r=>{ge(r).catch(n=>p({level:"error",event:"daemon.settings.reload_failed",error:n}))},"reloadPerson");if(w=await M.subscribe(r=>{We().includes(r)&&v(r)},{kinds:["settings"],onListenStart:s(()=>{for(const r of We())v(r)},"onListenStart")}),e.role!==void 0&&Ur(),e.role!==void 0){let r;try{r=mn()}catch(_){p({level:"error",event:"daemon.packages.snapshot_failed",error:_})}const n=await ve(async _=>(await Ge(_),r===void 0?void 0:await pn(_,r,"release")));c=await ve(async _=>await dn(_));for(const _ of n?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${_.path}: ${_.error}
10
+ `)}else{d=await qr(),d!==null&&(Kr(d.id),await ge(d.id));const r=await ve(async n=>(await Ge(n),d===null?null:await ln(n)));if(r!==null){for(const n of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${n.message}
11
11
  `);for(const n of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${n.path}: ${n.error}
12
12
  `);for(const n of r.quarantined)process.stderr.write(`[crtrd] plugin "${n.name}" has a damaged ${n.file} (${n.reason}); ${n.movedTo!==void 0?`moved to ${n.movedTo}`:"left in place and skipped"}
13
13
  `);for(const n of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${n.plugin}" kind ${n.kind} not registered: ${n.message}
14
14
  `);for(const n of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${n.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${n.error}
15
- `)}}if(b=await Kt(),Vt(b),e.role===void 0&&d!==null){if(await bn(d.id),process.platform==="darwin"){const{readConfig:r,updateConfig:n}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:_}=await import("node:os");await n("user",Ie=>{Ie.paths??={},Ie.paths.user_files??=_()})}}u=await Wr(),u.joinedFrom!==null&&await ge(u.person),await dr(),i=await Kr()}if(process.platform==="linux"&&P(C)&&(xr(),await N({operation:"users.sync",users:await Pr()})),m){await kt(y.token);const r=await wn();Object.values(r).some(n=>n>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
16
- `)}}catch(t){await M.close();try{if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}await we()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,ee,j=Promise.resolve(),re=!1,z,te,ne,oe,ie,L;const U=new Set;let ae=!1,_e=!1,x,I,se,q=!1,W,$,G,F,B,ce,le,de,pe;const Xe=lt();let D,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},A="initial startup activation",Ze=null;function er(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(er,"startupBlock");function R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const rr={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function tr(){try{E=!1,sn.close(),ne?.(),ne=void 0,oe?.(),w?.(),oe=void 0,ie?.(),ie=void 0,de?.(),de=void 0,await M.close(),z!==void 0&&(clearInterval(z),z=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),F!==void 0&&(clearInterval(F),F=void 0),pe?.(),pe=void 0;let t;do t=j,await t;while(t!==j);for(;U.size>0;)await Promise.allSettled([...U]);if(L!==void 0&&(m&&await Tn(L),await L.exitsSettled(),L.dispose()),se!==void 0&&await se.close(),I!==void 0&&!q&&(q=!0,await I.close()),ce?.(),ce=void 0,le?.(),le=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if($!==void 0){const a=$;$=void 0,await a.close()}if(W!==void 0){const a=W;W=void 0,await a.close()}if(ae||(Ye(process.pid),ae=!0),ae&&!_e){if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}_e=!0,await we()}}finally{Ut(),process.off("SIGINT",Re),process.off("SIGTERM",Pe),process.off("exit",Ee)}}s(tr,"cleanupAttempt");const J=1e3;let be=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return be?{graceMs:J}:(be=!0,k.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:J}})}),setTimeout(()=>{or()},J),{graceMs:J})}s(nr,"requestHandover");async function or(){try{await T()}catch(t){const a=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
15
+ `)}}if(b=await Jt(),Vt(b),e.role===void 0&&d!==null){if(await bn(d.id),process.platform==="darwin"){const{readConfig:r,updateConfig:n}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:_}=await import("node:os");await n("user",Ie=>{Ie.paths??={},Ie.paths.user_files??=_()})}}u=await Wr(),u.joinedFrom!==null&&await ge(u.person),await dr(),i=await Jr()}if(process.platform==="linux"&&P(C)&&(xr(),await N({operation:"users.sync",users:await Pr()})),m){await kt(y.token);const r=await wn();Object.values(r).some(n=>n>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
16
+ `)}}catch(t){await M.close();try{if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}await we()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,ee,j=Promise.resolve(),re=!1,z,te,ne,oe,ie,L;const U=new Set;let ae=!1,_e=!1,x,I,se,q=!1,W,$,G,F,B,ce,le,de,pe;const Xe=lt();let D,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},A="initial startup activation",Ze=null;function er(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(er,"startupBlock");function R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const rr={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function tr(){try{E=!1,sn.close(),ne?.(),ne=void 0,oe?.(),w?.(),oe=void 0,ie?.(),ie=void 0,de?.(),de=void 0,await M.close(),z!==void 0&&(clearInterval(z),z=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),F!==void 0&&(clearInterval(F),F=void 0),pe?.(),pe=void 0;let t;do t=j,await t;while(t!==j);for(;U.size>0;)await Promise.allSettled([...U]);if(L!==void 0&&(m&&await Tn(L),await L.exitsSettled(),L.dispose()),se!==void 0&&await se.close(),I!==void 0&&!q&&(q=!0,await I.close()),ce?.(),ce=void 0,le?.(),le=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if($!==void 0){const a=$;$=void 0,await a.close()}if(W!==void 0){const a=W;W=void 0,await a.close()}if(ae||(Ye(process.pid),ae=!0),ae&&!_e){if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}_e=!0,await we()}}finally{Ut(),process.off("SIGINT",Re),process.off("SIGTERM",Pe),process.off("exit",Ee)}}s(tr,"cleanupAttempt");const K=1e3;let be=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return be?{graceMs:K}:(be=!0,k.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{or()},K),{graceMs:K})}s(nr,"requestHandover");async function or(){try{await T()}catch(t){const a=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
17
17
  ${a}
18
- `),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await qt();const t=await Wt({waitForJoinLock:!0});k.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:t})});const a=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
18
+ `),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await qt();const t=await Wt();k.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:t})});const a=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
19
19
  `),process.exit(1)}process.exit(0)}s(or,"performHandover");function T(){if(x!==void 0)return x;const t=tr();return x=t,t.then(()=>{x===t&&(x=void 0)},()=>{x===t&&(x=void 0)}),t}s(T,"requestCleanup");async function ir(){S={phase:"initializing",message:ro,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Zn}))}s(ir,"drainApi");async function ke(t){try{t==="SIGTERM"&&e.role==="api"&&await ir(),await T(),await on({claimed:s(async()=>{try{return m&&await Xt()}finally{await we()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const v=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${t} cleanup failed:
20
20
  ${v}
21
- `),process.exit(1)}}s(ke,"handleSignal");function Re(){ke("SIGINT")}s(Re,"onSigint");function Pe(){ke("SIGTERM")}s(Pe,"onSigterm");function Ee(){T().catch(()=>{})}s(Ee,"onExit");async function K(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(K,"enqueue");async function V(){!E||re||(Xe.check()&&D&&(p({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),re=!0,await K(async()=>{if(re=!1,!!E)try{f||await nn({log:l}),await Qn(Date.now(),rr)}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:t})})}}))}s(V,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const t=S.phase==="prepared";try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(t){if(A!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${A})`};A="repair";try{const a=await _n({dryRun:t.dryRun});if(t.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(v){const r=v instanceof Error?v.message:String(v);return setTimeout(()=>{T().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:r}}}finally{A=null}}s(sr,"repairMigrations");async function cr(){ee=e.intervalMs??ct;const t=y.token;L=new hn({epoch:t,enqueue:K}),jt(L),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},k.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const a=b;k.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const v=await jr(a);if(k.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:v.environmentId,created:v.created}})}),k.fresh(()=>{let r;try{r=st()}catch{return}r!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),Dt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&zr(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await k.fresh(async()=>{await at(),await nt();const r=e.role!==void 0;await ot(Date.now(),r),await it(Date.now(),r)}),e.role===void 0&&await k.fresh(async()=>{const{reconcile:r,migrated:n}=await Jt(bt);r.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),n.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await k.fresh(async()=>{const r=await he();for(const n of await Ne())r.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await Me(n.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await k.fresh(async()=>{await Ft();for(const r of vn){const n=await r.apply();n.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...n.summary}})}}),R(rt()),D){const r=s(()=>{R(D().catch(()=>{})),R(fr().then(n=>B?.observe(n)).then(()=>{},n=>{p({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");R(et().then(({completion:n})=>n).catch(n=>{p({level:"error",event:"daemon.grants.sweep_failed",error:n})})),r(),G=setInterval(r,Fe*1e3),G.unref(),pe=mr({joined:!0,register:R})}await K(async()=>{await un(),await fn()}),te=pr(),z=setInterval(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},ee),ne=await Gt(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))}),oe=await M.subscribe(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),ie=await M.subscribe(r=>{K(()=>k.fresh(()=>Xn(r)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!E,n=>p({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(r=>p({level:"warn",event:"daemon.move.settle_failed",error:r}))}s(cr,"completeStartup");function me(){return Ze??=cr().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}s(me,"resumeStartup");try{process.on("SIGINT",Re),process.on("SIGTERM",Pe),process.on("exit",Ee),gn(),d!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),c!==null&&!c.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:c.moved,discarded:c.discarded,people:c.people}}),i!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),O(e.role)?W=await _r():br(Sr());const t=y.token;zt({epoch:t,requestHandover:nr,registerDetached:R,startupBlock:er,admitStartup:ar,repairMigrations:sr}),Q(),I=O(e.role)?Mr({tcp:e.tcp}):eo(e),await I.ready,Q(I.tcpAddress()??"");const a=yr()??fe("user").document_port;if(O(e.role)){const r=Fr(a,Br());try{await r.ready,se=r}catch(n){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:n instanceof Error?n.message:String(n)}})}}const v=fe("user").runtime;if(v?.issuer&&(D=Zr(v.issuer,R),v.unsandboxed===!0&&(B=ur({syncGrants:D}))),e.role==="api"){const r=s(()=>R(import("../core/providers/bundles.js").then(_=>_.syncProviderBundles()).catch(_=>{p({level:"error",event:"daemon.providers.bundle_sync_failed",error:_})})),"bundleTick"),n=s(()=>{R(Qr().catch(_=>{p({level:"error",event:"daemon.packages.sync_failed",error:_})})),r()},"packageTick");n(),F=setInterval(n,Fe*1e3),F.unref()}if(O(e.role)&&(ce=await Vr()),Z(e.role)&&(le=Xr()),de=await Yr({serves:O(e.role),runsLanes:Z(e.role)}),v?.unsandboxed===!0&&v.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),O(e.role)&&v!==void 0&&v.listener!==void 0&&v.unsandboxed!==!0&&($=await Hr(v,async()=>await tt(v.issuer.replace(/\/$/,"")),D),await $.ready,Q(I.tcpAddress()??"",`${v.listener.address}:${$.port()}`)),e.role===void 0)try{await yn()}catch(r){if(A=null,r instanceof Sn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},T;throw r}process.platform==="linux"&&P(C)&&(Ir(),await Er("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await me(),S={phase:"ready",message:"",blockerPaths:[]})}finally{A=null}return T}catch(t){try{await T()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}}s(no,"runDaemon");var aa=no;export{Zn as API_DRAIN_GRACE_MS,la as brokerCommandDeclaresCanvasHome,Se as brokerCommandEpoch,aa as default,Xn as exitedNodePass,Z as roleRunsLanes,O as roleServesRequests,no as runDaemon,Qn as superviseTick,Tn as teardownFleet};
21
+ `),process.exit(1)}}s(ke,"handleSignal");function Re(){ke("SIGINT")}s(Re,"onSigint");function Pe(){ke("SIGTERM")}s(Pe,"onSigterm");function Ee(){T().catch(()=>{})}s(Ee,"onExit");async function J(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(J,"enqueue");async function V(){!E||re||(Xe.check()&&D&&(p({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),re=!0,await J(async()=>{if(re=!1,!!E)try{f||await nn({log:l}),await Qn(Date.now(),rr)}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:t})})}}))}s(V,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const t=S.phase==="prepared";try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(t){if(A!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${A})`};A="repair";try{const a=await _n({dryRun:t.dryRun});if(t.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(v){const r=v instanceof Error?v.message:String(v);return setTimeout(()=>{T().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:r}}}finally{A=null}}s(sr,"repairMigrations");async function cr(){ee=e.intervalMs??ct;const t=y.token;L=new hn({epoch:t,enqueue:J}),jt(L),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},k.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const a=b;k.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const v=await jr(a);if(k.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:v.environmentId,created:v.created}})}),k.fresh(()=>{let r;try{r=st()}catch{return}r!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),Dt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&zr(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await k.fresh(async()=>{await at(),await nt();const r=e.role!==void 0;await ot(Date.now(),r),await it(Date.now(),r)}),e.role===void 0&&await k.fresh(async()=>{const{reconcile:r,migrated:n}=await Kt(bt);r.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),n.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await k.fresh(async()=>{const r=await he();for(const n of await Ne())r.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await Me(n.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await k.fresh(async()=>{await Ft();for(const r of vn){const n=await r.apply();n.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...n.summary}})}}),R(rt()),D){const r=s(()=>{R(D().catch(()=>{})),R(fr().then(n=>B?.observe(n)).then(()=>{},n=>{p({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");R(et().then(({completion:n})=>n).catch(n=>{p({level:"error",event:"daemon.grants.sweep_failed",error:n})})),r(),G=setInterval(r,Fe*1e3),G.unref(),pe=mr({joined:!0,register:R})}await J(async()=>{await un(),await fn()}),te=pr(),z=setInterval(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},ee),ne=await Gt(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))}),oe=await M.subscribe(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),ie=await M.subscribe(r=>{J(()=>k.fresh(()=>Xn(r)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!E,n=>p({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(r=>p({level:"warn",event:"daemon.move.settle_failed",error:r}))}s(cr,"completeStartup");function me(){return Ze??=cr().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}s(me,"resumeStartup");try{process.on("SIGINT",Re),process.on("SIGTERM",Pe),process.on("exit",Ee),gn(),d!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),c!==null&&!c.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:c.moved,discarded:c.discarded,people:c.people}}),i!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),O(e.role)?W=await _r():br(Sr());const t=y.token;zt({epoch:t,requestHandover:nr,registerDetached:R,startupBlock:er,admitStartup:ar,repairMigrations:sr}),Q(),I=O(e.role)?Mr({tcp:e.tcp}):eo(e),await I.ready,Q(I.tcpAddress()??"");const a=yr()??fe("user").document_port;if(O(e.role)){const r=Fr(a,Br());try{await r.ready,se=r}catch(n){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:n instanceof Error?n.message:String(n)}})}}const v=fe("user").runtime;if(v?.issuer&&(D=Zr(v.issuer,R),v.unsandboxed===!0&&(B=ur({syncGrants:D}))),e.role==="api"){const r=s(()=>R(import("../core/providers/bundles.js").then(_=>_.syncProviderBundles()).catch(_=>{p({level:"error",event:"daemon.providers.bundle_sync_failed",error:_})})),"bundleTick"),n=s(()=>{R(Qr().catch(_=>{p({level:"error",event:"daemon.packages.sync_failed",error:_})})),r()},"packageTick");n(),F=setInterval(n,Fe*1e3),F.unref()}if(O(e.role)&&(ce=await Vr()),Z(e.role)&&(le=Xr()),de=await Yr({serves:O(e.role),runsLanes:Z(e.role)}),v?.unsandboxed===!0&&v.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),O(e.role)&&v!==void 0&&v.listener!==void 0&&v.unsandboxed!==!0&&($=await Hr(v,async()=>await tt(v.issuer.replace(/\/$/,"")),D),await $.ready,Q(I.tcpAddress()??"",`${v.listener.address}:${$.port()}`)),e.role===void 0)try{await yn()}catch(r){if(A=null,r instanceof Sn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},T;throw r}process.platform==="linux"&&P(C)&&(Ir(),await Er("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await me(),S={phase:"ready",message:"",blockerPaths:[]})}finally{A=null}return T}catch(t){try{await T()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}}s(no,"runDaemon");var aa=no;export{Zn as API_DRAIN_GRACE_MS,la as brokerCommandDeclaresCanvasHome,Se as brokerCommandEpoch,aa as default,Xn as exitedNodePass,Z as roleRunsLanes,O as roleServesRequests,no as runDaemon,Qn as superviseTick,Tn as teardownFleet};
@@ -69,10 +69,6 @@ export declare function runDaemonInstallId(): Promise<{
69
69
  export interface SpawnDaemonOptions {
70
70
  /** The phase that proves a daemon launched by this call is available. */
71
71
  targetPhase?: 'ready' | 'prepared';
72
- /** Start even while another process's `crtr sys join` holds the daemon down. */
73
- ignoreJoinLock?: boolean;
74
- /** While another process's `crtr sys join` holds the daemon down, wait for it to finish, then start. For a handover successor. */
75
- waitForJoinLock?: boolean;
76
72
  }
77
73
  export interface SpawnDaemonResult {
78
74
  /** True when a new daemon process was spawned. */
@@ -172,7 +168,7 @@ export declare function waitForDaemonExit(pid: number, timeoutMs?: number, deps?
172
168
  * Returns how the daemon went down, for a truthful report. */
173
169
  export declare function stopDaemonProcess(pid: number, timeoutMs?: number, deps?: DaemonWaitDeps): Promise<'terminated' | 'killed'>;
174
170
  /** Stop the recorded daemon and sweep every stray crtrd of this canvas home.
175
- * Resolves once none remains. Shared by `crtr sys daemon stop` and `crtr sys join`. */
171
+ * Resolves once none remains. Shared by `crtr sys daemon stop` and `crtr sys signin`. */
176
172
  export declare function stopAllDaemons(): Promise<{
177
173
  stopped: boolean;
178
174
  pid?: number;
@@ -213,8 +209,7 @@ export interface EnsureDaemonDeps {
213
209
  * rather than at the end of the startup window. */
214
210
  export declare function daemonAutostartStartupFailure(): string | undefined;
215
211
  /** Start the daemon if it is not already running. No-op if already up, if
216
- * autostart is suppressed for this invocation, while `crtr sys join` holds
217
- * the join lock (see core/directory/join-lock.ts), while an attempt is in flight,
212
+ * autostart is suppressed for this invocation, while an attempt is in flight,
218
213
  * or while backing off from a recent failure.
219
214
  * Does not throw: a spawn error is recorded, and a launch or early-exit failure
220
215
  * is reported through `daemonAutostartStartupFailure()` so a waiting client
@@ -1,3 +1,3 @@
1
- var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as V}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as k,join as E}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as H,lstatSync as ee,mkdirSync as te,openSync as U,closeSync as j,fstatSync as K,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as M}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as D,isPidAlive as f}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as G}from"./startup-policy.js";import{readMachineConfig as se}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ce}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ue}from"../core/canvas/paths.js";import{envNoDaemonAutostart as le}from"../shared/env.js";import{awaitJoinLockRelease as de,joinInProgress as pe,joinInProgressError as fe,joinLockHolder as me}from"../core/directory/join-lock.js";import{waitForDaemonAvailability as he}from"../api/index.js";import{localClient as we}from"../api/node-transport.js";const _e=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function O(){const e={...process.env};for(const t of _e)delete e[t];return e}o(O,"sanitizedDaemonEnv");function Ee(){for(let e=k(Z(import.meta.url));;e=k(e)){if(H(E(e,"bin","runtime-generation-manifest.mjs")))return e;if(k(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Ee,"generationRoot");async function A(){const e=Ee(),t=I(E(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(E(r(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,E(e,"src","daemon","crtrd-cli.ts")]}const n=I(E(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),c=a("daemon");if(!c.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${c.error}`);return[c.runtime.entryPath]}o(A,"resolveDaemonLaunch");function De(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(De,"daemonCommandDeclaresCanvasHome");function xe(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&De(a,t)&&n!==process.pid&&r.push(n);return r}o(xe,"findDaemonPids");function ye(e){const t=xe().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>f(n));)V("sleep",["0.1"]);for(const n of t)if(f(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(ye,"sweepStrayDaemons");async function et(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=M(),r=await A();return e(t,[t,...r,"--canvas-home",g()],O())}o(et,"execDaemon");async function R(e){const t=await A(),r=B(M(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:O()});let n="",a="";r.stdout.setEncoding("utf8").on("data",u=>{n+=u}),r.stderr.setEncoding("utf8").on("data",u=>{a+=u});const c=await new Promise((u,m)=>{r.once("error",m),r.once("close",p=>u(p))});if(c!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${c}`);const s=n.trim().split(`
2
- `).at(-1)??"";return JSON.parse(s)}o(R,"runDaemonEntry");function tt(){return R(["export-sqlite"])}o(tt,"runDaemonExportSqlite");function rt(e,t){return R(["import-dump",e,t])}o(rt,"runDaemonImportDump");function nt(e){return R(["import-dump",e,"bodies"])}o(nt,"runDaemonBodiesDump");function ot(){return R(["import-dump","","install-id"])}o(ot,"runDaemonInstallId");const ge=3*6e4,z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return we({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function Se(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(Se,"probeErrorMessage");async function J(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=D()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(J,"probeDaemonServing");async function at(){try{return await J(),!0}catch{return!1}}o(at,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
- ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Re(e,t=G,r={},n="ready"){const a=r.readPidfile??D,c=r.isPidAlive??f,s=r.childExited,u=r.isDaemonServing,m=r.probeDaemonServing??(async w=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await J(w)}),p=r.probeDaemonHealth??L,x=r.sleepMs??$,y=r.now??Date.now;let i=null,l=null;return await he({windowMs:t,pollIntervalMs:N,now:y,sleep:x,retry:o(w=>w!==l,"retry"),probe:o(async w=>{const h=a();if(h===null||!c(h)){const d=s?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await m(w)}catch(d){throw d instanceof v&&(l=d),d}i=h;return}const _=await p(w);if(_.startup_phase==="prepared"){i=h;return}throw _.startup_phase==="blocked"?(l=new v(h,_.startup_blocked??"on-disk migration is blocked"),l):_.startup_phase==="ready"?(l=new F(h,_.startup_phase),l):new Error(`daemon ${h} is ${_.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),i===e?null:i}o(Re,"verifyDaemonStartup");async function ve(e,t=z,r={}){const n=r.readPidfile??D,a=r.isPidAlive??f,c=r.sleepMs??$,s=r.now??Date.now,u=s()+t;for(;s()<=u;){if(!a(e)&&n()!==e)return;await c(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(ve,"waitForDaemonExit");const Te=2e3,be=5e3;async function X(e,t=z,r={}){const n=r.isPidAlive??f,a=r.sleepMs??$,c=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await ve(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const s=c()+Te;for(;c()<=s;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(X,"stopDaemonProcess");async function it(){const e=D(),t=e!==null&&f(e),r=t&&await X(e)==="killed",n=ye(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(it,"stopAllDaemons");function ke(e,t,r=2048){let n;try{n=U(e,"r");const{size:a}=K(n),c=Math.max(t,a-r),s=a-c;if(s<=0)return"";const u=Buffer.alloc(s);return re(n,u,0,s,c),u.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{j(n)}catch{}}}o(ke,"readLogTailFrom");async function Ie(e={}){if(process.platform==="linux"&&H("/run/crtr/launcher.sock")&&!f(D()??-1)&&se()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=D();if(r!==null&&f(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(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 F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:Se(i)}}te(g(),{recursive:!0});const n=await A().catch(i=>{throw new Y(i)});e.waitForJoinLock===!0&&await de(ge);const a=me();if(a!==null&&a!==process.pid&&e.ignoreJoinLock!==!0)throw fe(a);const c=E(g(),"crtrd.err"),s=U(c,"a"),u=(()=>{try{return K(s).size}catch{return 0}})();ae()===void 0&&oe();const m=B(M(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:O()});j(s);const p=m.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let x=null;m.once("exit",(i,l)=>{x={code:i,signal:l}}),m.unref();let y;try{y=await Re(p,G,{childExited:o(()=>x,"childExited"),childStderrTail:o(()=>ke(c,u),"childStderrTail")},t)}catch(i){const l=ce(ue())===p;if(x===null&&!l&&!(i instanceof v))try{await X(p,be)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(Ie,"spawnDaemon");function Me(){return le()||process.argv.includes("--no-autostart")}o(Me,"autostartDisabled");const Oe=5e3,Ae=6e4;let W=!1,S,T=0,b=0;function Ne(e){return Math.min(Oe*2**(e-1),Ae)}o(Ne,"autostartBackoffMs");function Pe(){S=void 0,T=0,b=0}o(Pe,"resetDaemonAutostart");function st(){return S}o(st,"daemonAutostartStartupFailure");function ct(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??Ie,n=e.now??Date.now;if(!Me()&&!pe()&&!W&&!(n()<b)){if(t()){Pe();return}S=void 0,W=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof Y)&&(S=a.message),T+=1,b=n()+Ne(T)}).finally(()=>{W=!1})}}o(ct,"ensureDaemon");export{_e as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,Me as autostartDisabled,st as daemonAutostartStartupFailure,De as daemonCommandDeclaresCanvasHome,ct as ensureDaemon,et as execDaemon,xe as findDaemonPids,at as isDaemonServing,L as probeDaemonHealth,J as probeDaemonServing,Se as probeErrorMessage,Pe as resetDaemonAutostart,nt as runDaemonBodiesDump,tt as runDaemonExportSqlite,rt as runDaemonImportDump,ot as runDaemonInstallId,O as sanitizedDaemonEnv,Ie as spawnDaemon,it as stopAllDaemons,X as stopDaemonProcess,ye as sweepStrayDaemons,Re as verifyDaemonStartup,ve as waitForDaemonExit};
1
+ var V=Object.defineProperty;var o=(e,t)=>V(e,"name",{value:t,configurable:!0});import{spawn as U,execFileSync as J}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as M,join as D}from"node:path";import{fileURLToPath as Z,pathToFileURL as O}from"node:url";import{existsSync as W,lstatSync as ee,mkdirSync as te,openSync as H,closeSync as K,fstatSync as G,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as k}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as x,isPidAlive as m}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as j}from"./startup-policy.js";import{readMachineConfig as se}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ce}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ue}from"../core/canvas/paths.js";import{envNoDaemonAutostart as le}from"../shared/env.js";import{waitForDaemonAvailability as de}from"../api/index.js";import{localClient as pe}from"../api/node-transport.js";const fe=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function A(){const e={...process.env};for(const t of fe)delete e[t];return e}o(A,"sanitizedDaemonEnv");function me(){for(let e=M(Z(import.meta.url));;e=M(e)){if(W(D(e,"bin","runtime-generation-manifest.mjs")))return e;if(M(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(me,"generationRoot");async function I(){const e=me(),t=O(D(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(D(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",O(Q(import.meta.url).resolve("tsx/esm")).href,D(e,"src","daemon","crtrd-cli.ts")]}const n=O(D(e,"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(I,"resolveDaemonLaunch");function he(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(he,"daemonCommandDeclaresCanvasHome");function we(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&he(a,t)&&n!==process.pid&&r.push(n);return r}o(we,"findDaemonPids");function _e(e){const t=we().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>m(n));)J("sleep",["0.1"]);for(const n of t)if(m(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(_e,"sweepStrayDaemons");async function Xe(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=k(),r=await I();return e(t,[t,...r,"--canvas-home",g()],A())}o(Xe,"execDaemon");async function R(e){const t=await I(),r=U(k(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:A()});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,p)=>{r.once("error",p),r.once("close",h=>c(h))});if(s!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${s}`);const u=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(u)}o(R,"runDaemonEntry");function qe(){return R(["export-sqlite"])}o(qe,"runDaemonExportSqlite");function Ve(e,t){return R(["import-dump",e,t])}o(Ve,"runDaemonImportDump");function Je(e){return R(["import-dump",e,"bodies"])}o(Je,"runDaemonBodiesDump");function Qe(){return R(["import-dump","","install-id"])}o(Qe,"runDaemonInstallId");const z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return pe({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function Ee(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(Ee,"probeErrorMessage");async function Y(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=x()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(Y,"probeDaemonServing");async function Ze(){try{return await Y(),!0}catch{return!1}}o(Ze,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class X extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function De(e,t=j,r={},n="ready"){const a=r.readPidfile??x,s=r.isPidAlive??m,u=r.childExited,c=r.isDaemonServing,p=r.probeDaemonServing??(async _=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await Y(_)}),h=r.probeDaemonHealth??L,y=r.sleepMs??$,i=r.now??Date.now;let f=null,l=null;return await de({windowMs:t,pollIntervalMs:N,now:i,sleep:y,retry:o(_=>_!==l,"retry"),probe:o(async _=>{const w=a();if(w===null||!s(w)){const d=u?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await p(_)}catch(d){throw d instanceof v&&(l=d),d}f=w;return}const E=await h(_);if(E.startup_phase==="prepared"){f=w;return}throw E.startup_phase==="blocked"?(l=new v(w,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new F(w,E.startup_phase),l):new Error(`daemon ${w} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),f===e?null:f}o(De,"verifyDaemonStartup");async function xe(e,t=z,r={}){const n=r.readPidfile??x,a=r.isPidAlive??m,s=r.sleepMs??$,u=r.now??Date.now,c=u()+t;for(;u()<=c;){if(!a(e)&&n()!==e)return;await s(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(xe,"waitForDaemonExit");const ye=2e3,ge=5e3;async function q(e,t=z,r={}){const n=r.isPidAlive??m,a=r.sleepMs??$,s=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await xe(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const u=s()+ye;for(;s()<=u;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(q,"stopDaemonProcess");async function et(){const e=x(),t=e!==null&&m(e),r=t&&await q(e)==="killed",n=_e(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(et,"stopAllDaemons");function Se(e,t,r=2048){let n;try{n=H(e,"r");const{size:a}=G(n),s=Math.max(t,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return re(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{K(n)}catch{}}}o(Se,"readLogTailFrom");async function Re(e={}){if(process.platform==="linux"&&W("/run/crtr/launcher.sock")&&!m(x()??-1)&&se()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=x();if(r!==null&&m(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(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 F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:Ee(i)}}te(g(),{recursive:!0});const n=await I().catch(i=>{throw new X(i)}),a=D(g(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return G(s).size}catch{return 0}})();ae()===void 0&&oe();const c=U(k(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:A()});K(s);const p=c.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let h=null;c.once("exit",(i,f)=>{h={code:i,signal:f}}),c.unref();let y;try{y=await De(p,j,{childExited:o(()=>h,"childExited"),childStderrTail:o(()=>Se(a,u),"childStderrTail")},t)}catch(i){const f=ce(ue())===p;if(h===null&&!f&&!(i instanceof v))try{await q(p,ge)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(Re,"spawnDaemon");function ve(){return le()||process.argv.includes("--no-autostart")}o(ve,"autostartDisabled");const Te=5e3,be=6e4;let B=!1,S,T=0,b=0;function Me(e){return Math.min(Te*2**(e-1),be)}o(Me,"autostartBackoffMs");function Oe(){S=void 0,T=0,b=0}o(Oe,"resetDaemonAutostart");function tt(){return S}o(tt,"daemonAutostartStartupFailure");function rt(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??Re,n=e.now??Date.now;if(!ve()&&!B&&!(n()<b)){if(t()){Oe();return}S=void 0,B=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof X)&&(S=a.message),T+=1,b=n()+Me(T)}).finally(()=>{B=!1})}}o(rt,"ensureDaemon");export{fe as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,X as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,ve as autostartDisabled,tt as daemonAutostartStartupFailure,he as daemonCommandDeclaresCanvasHome,rt as ensureDaemon,Xe as execDaemon,we as findDaemonPids,Ze as isDaemonServing,L as probeDaemonHealth,Y as probeDaemonServing,Ee as probeErrorMessage,Oe as resetDaemonAutostart,Je as runDaemonBodiesDump,qe as runDaemonExportSqlite,Ve as runDaemonImportDump,Qe as runDaemonInstallId,A as sanitizedDaemonEnv,Re as spawnDaemon,et as stopAllDaemons,q as stopDaemonProcess,_e as sweepStrayDaemons,De as verifyDaemonStartup,xe as waitForDaemonExit};
@@ -36,12 +36,12 @@ Then pick what your app does from the sections in the sidebar: [use our AI](/doc
36
36
 
37
37
  ## Run `crtr cloud apps` yourself
38
38
 
39
- Everything on this site works with the SDK's own commands and the web console. If you also run crouter, the agent runtime Northlight is built on, you can join your machine to your Northlight account and manage your apps with `crtr cloud apps`, or let your own crouter agents build and manage them.
39
+ Everything on this site works with the SDK's own commands and the web console. If you also run crouter, the agent runtime Northlight is built on, you can sign your machine in to your Northlight account and manage your apps with `crtr cloud apps`, or let your own crouter agents build and manage them.
40
40
 
41
41
  ```bash
42
- npm install -g @north-light/cli
43
- crtr sys join --directory https://account.northlight.ai --token <token>
42
+ npm i -g @north-light/cli@latest
43
+ crtr sys signin
44
44
  crtr cloud apps mine
45
45
  ```
46
46
 
47
- The token comes from **Create join token** at `https://account.northlight.ai/account/machines`. The full steps, and what joining changes on your machine, are in [Join a machine to your Northlight account](https://crouter.docs.northlight.ai/docs/cli/join-northlight). The CLI is [`@north-light/cli`](https://www.npmjs.com/package/@north-light/cli) on npm, and crouter's own docs are at [crouter.docs.northlight.ai](https://crouter.docs.northlight.ai).
47
+ `crtr sys signin` asks you to approve once in your browser. The full steps, and what signing in changes on your machine, are in [Sign in a machine to your Northlight account](https://crouter.docs.northlight.ai/docs/cli/join-northlight). The CLI is [`@north-light/cli`](https://www.npmjs.com/package/@north-light/cli) on npm, and crouter's own docs are at [crouter.docs.northlight.ai](https://crouter.docs.northlight.ai).
@@ -1,37 +1,31 @@
1
1
  ---
2
- title: Join a machine to your Northlight account
3
- description: Join a laptop to your Northlight account with crtr sys join so crtr cloud apps commands run as you, and the crtr cloud apps command list.
2
+ title: Sign in a machine to your Northlight account
3
+ description: Sign a laptop in to your Northlight account with crtr sys signin so crtr cloud apps commands run as you, and the crtr cloud apps command list.
4
4
  ---
5
5
 
6
- # Join a machine to your Northlight account
6
+ # Sign in a machine to your Northlight account
7
7
 
8
- Joining makes this machine one of your Northlight account's machines, so `crtr cloud …` commands run as you. Join when you want to run `crtr cloud apps` yourself, or to let your own crtr agents build and manage your Northlight apps. Building an app works without it too: the [SDK docs site](https://sdk.docs.northlight.ai/docs/get-started) uses `npx @north-light/sdk` and the web console.
8
+ Signing in makes this machine one of your Northlight account's machines, so `crtr cloud …` commands run as you. Sign in when you want to run `crtr cloud apps` yourself, or to let your own crtr agents build and manage your Northlight apps. Building an app works without it too: the [SDK docs site](https://sdk.docs.northlight.ai/docs/get-started) uses `npx @north-light/sdk` and the web console.
9
9
 
10
- Create your account at `https://account.northlight.ai/signup` first. Then install the CLI (`npm i -g @north-light/cli`). Joining needs `crtr` 0.3.436 or later (older versions need `crtr sys daemon stop` first and fail if a viewer is open); `crtr --version` shows yours.
10
+ Create your account at `https://account.northlight.ai/signup` first. Then install the CLI and sign in:
11
11
 
12
- Then join your laptop to the account:
12
+ ```bash
13
+ npm i -g @north-light/cli@latest && crtr sys signin
14
+ ```
13
15
 
14
- 1. Open `https://account.northlight.ai/account/machines` and choose **Create join token**. A token needs a sign-in within the last 10 minutes, so the page asks you to sign in again if yours is older.
15
- 2. The page shows the join command with the token filled in. On your laptop, run it from a plain terminal: `crtr sys join --directory https://account.northlight.ai --token <token>`. Leave your crtr windows open: join stops the daemon itself, holds it down while it writes your identity (so an open viewer cannot restart it early), and starts it again on the joined settings. Run it outside any crtr node, because a node's engine stops with the daemon; from inside one, join refuses with `join_inside_node`. Add `--name <label>` to name the machine on the page. The token works once and expires at the time the page shows; the page shows it only once.
16
+ `crtr sys signin` prints a code and opens the confirm page in your browser. Check the code and click **Allow** once. That one approval signs this computer in to your account, moves this computer's crtr records into it, and registers the computer as one of your account's machines (a signing key is made on the computer; only its public half goes to the directory). Run it from a plain terminal. A computer that signed in earlier without being registered is registered by running `crtr sys signin` again.
16
17
 
17
- ```bash
18
- crtr sys join --directory https://account.northlight.ai --token <token> --name my-laptop
19
- ```
18
+ Check it: `crtr cloud apps mine` lists the apps you manage.
20
19
 
21
- It answers with `registered: true`, the machine id (`runtime:<id>`), your user id and `daemon: restarted` (`daemon: started` when crtr was not running: join starts the daemon, and its first grant sync installs `crtr cloud …` and your other provider plugins). Your open viewers and nodes reconnect on their own.
22
- 3. Check it: `crtr cloud apps mine` lists the apps you manage. Before you have joined, it answers `not_joined` and prints these same steps.
20
+ Things to know first:
23
21
 
24
- Things to know before you join:
25
-
26
- - **Joining rewrites your crtr home.** The person this install minted becomes your Northlight user, the next time the daemon starts: your nodes, crons, usage and history in this home are then yours on the account. If you would rather not do that to your everyday home, join from a home you can throw away.
27
- - **There is no unjoin.** The only undo is removing the machine on `/account/machines`.
28
- - **Removing the machine stops it.** Once you choose **Remove** next to a machine, it gets no new tokens at once and the ones it holds expire within 5 minutes. After that its `cloud` commands answer `machine_revoked`: "This machine was removed from your Northlight account." It stays that way until you create a new join token and run `crtr sys join` again. Files on the computer stay on it.
29
- - **Your Northlight runtime is unchanged.** `/account/machines` lists it as "Northlight (hosted)", the default: your runtime in Northlight's cloud. Your chat agent at `https://chat.northlight.ai` still runs `crtr cloud apps …` as before.
30
- - **Joining is not importing.** Join only lets this machine run `crtr cloud …` as you; its nodes and documents stay in its own crtr home. `crtr sys import start` is the separate step that moves them into your Northlight account and turns this computer into a machine your cloud runtime drives.
22
+ - **Signing in moves your crtr home into the account.** Your nodes, crons, usage and history become yours on Northlight, and the computer then runs as a machine your cloud runtime drives.
23
+ - **Removing the machine stops it.** Once you choose **Remove** next to a machine on `/account/machines`, it gets no new tokens at once and the ones it holds expire within 5 minutes. After that its `cloud` commands answer `machine_revoked`: "This machine was removed from your Northlight account." Run `crtr sys signin` again to register it. Files on the computer stay on it.
24
+ - **Your Northlight runtime is unchanged.** `/account/machines` lists it as "Northlight (hosted)", the default: your runtime in Northlight's cloud.
31
25
 
32
26
  ## `crtr cloud apps`
33
27
 
34
- Every app-management leaf of Northlight's `cloud` provider runs as you and needs a joined machine. `--app-id` takes `app:<client id>` or the bare client id.
28
+ Every app-management leaf of Northlight's `cloud` provider runs as you and needs a signed-in machine. `--app-id` takes `app:<client id>` or the bare client id.
35
29
 
36
30
  Your Northlight chat agent at `https://chat.northlight.ai` can run these commands as you, from your Northlight runtime. It can list and change an app (`mine` and `set-scopes` were checked on production). It cannot delete one. Generate keys on your laptop and give an agent only a public JWK, never the private key.
37
31
 
@@ -54,6 +48,6 @@ Your Northlight chat agent at `https://chat.northlight.ai` can run these command
54
48
  | `crtr cloud apps testers list --app-id <id>` | Lists the testers. |
55
49
  | `crtr cloud apps testers remove --app-id <id> --email …` (or `--phone …`) | Removes a tester and revokes their grants for the app. Not yet run on production. |
56
50
  | `crtr cloud apps set-run-notice-url --app-id <id> --url …` (or `--clear`) | Sets or clears the URL the runtime posts run notices to. https only, plain http on localhost for development, at most 512 characters. |
57
- | `crtr cloud apps delete --app-id <id> --confirm <client id>` | Deletes the app and removes every person's grant for it. Only you at a joined machine's terminal can run it: an agent, including your chat agent, is refused with `provider_refused`. |
51
+ | `crtr cloud apps delete --app-id <id> --confirm <client id>` | Deletes the app and removes every person's grant for it. Only you at a signed-in machine's terminal can run it: an agent, including your chat agent, is refused with `provider_refused`. |
58
52
 
59
53
  Deleting an app removes every person's grant for it and cannot be undone. Each runtime deletes the app's runs, space and schedules, and the app's next refresh fails with `invalid_grant`. Apps that hold the provider role cannot be deleted.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.731",
3
+ "version": "0.3.733",
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.731",
162
- "@north-light/plugin": "0.3.731",
161
+ "@north-light/identity": "0.3.733",
162
+ "@north-light/plugin": "0.3.733",
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",
@@ -985,9 +985,10 @@ export class CrtrClient {
985
985
  return new Uint8Array(await response.arrayBuffer());
986
986
  }
987
987
  /** The lean attach-graph projection: display rows, topology, and focus state
988
- * in one daemon-owned read rather than the full node-summary list. */
989
- canvasGraph() {
990
- return this.request('GET', routes.canvasGraph());
988
+ * in one daemon-owned read rather than the full node-summary list. With
989
+ * `root`, only the tree that contains that node. */
990
+ canvasGraph(root) {
991
+ return this.request('GET', root === undefined ? routes.canvasGraph() : `${routes.canvasGraph()}?root=${encodeURIComponent(root)}`);
991
992
  }
992
993
  prune(req) {
993
994
  return this.request('POST', routes.canvasPrune(), req);
@@ -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.71';
15
+ export const CONTRACT_LEVEL = '1.72';
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`. */
@@ -124,6 +124,8 @@ export class GraphOverlay {
124
124
  pendingConfirm;
125
125
  snapshot;
126
126
  snapshotSeq = 0;
127
+ loading = false;
128
+ reloadQueued = false;
127
129
  /** True when `source` is a `RemoteCanvasSource` — gates every local disk/
128
130
  * SQLite adornment (tokens, activity, fault, attach, focus) to a safe
129
131
  * default and makes Enter/r/m/x no-op instead of shelling local lifecycle
@@ -202,6 +204,15 @@ export class GraphOverlay {
202
204
  refresh() {
203
205
  if (this.handle === undefined)
204
206
  return;
207
+ // One read at a time. The 5 s chrome poll calls this; when a read takes
208
+ // longer than the poll, superseding the in-flight read discarded every
209
+ // result and the overlay never left "loading". Instead, let the read finish
210
+ // and run one more afterwards.
211
+ if (this.loading) {
212
+ this.reloadQueued = true;
213
+ return;
214
+ }
215
+ this.loading = true;
205
216
  const seq = ++this.snapshotSeq;
206
217
  void this.buildSnapshot().then((snapshot) => {
207
218
  if (seq !== this.snapshotSeq)
@@ -214,6 +225,12 @@ export class GraphOverlay {
214
225
  // writing raw stderr bytes into the frame.
215
226
  this.onRefreshFailure(err);
216
227
  this.tui.requestRender();
228
+ }).finally(() => {
229
+ this.loading = false;
230
+ if (this.reloadQueued) {
231
+ this.reloadQueued = false;
232
+ this.refresh();
233
+ }
217
234
  });
218
235
  }
219
236
  invalidate() {
@@ -234,7 +251,7 @@ export class GraphOverlay {
234
251
  focused: new Set(),
235
252
  };
236
253
  }
237
- const graph = await cliClient().canvasGraph();
254
+ const graph = await cliClient().canvasGraph(this.self);
238
255
  const subscriptions = new Map();
239
256
  const subscribers = new Map();
240
257
  // Edges arrive in `created` order — the same order the per-node reads
@@ -26,7 +26,6 @@ const daemonStart = defineLeaf({
26
26
  summary: 'start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)',
27
27
  params: [
28
28
  { kind: 'flag', name: 'prepare', type: 'bool', required: false, constraint: 'Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup.' },
29
- { kind: 'flag', name: 'force', type: 'bool', required: false, default: false, constraint: 'Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck.' },
30
29
  ],
31
30
  output: [
32
31
  { name: 'started', type: 'boolean', required: true, constraint: 'True when a new daemon process was spawned; false when one was already running.' },
@@ -39,14 +38,13 @@ const daemonStart = defineLeaf({
39
38
  ],
40
39
  outputKind: 'object',
41
40
  effects: [
42
- 'Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.',
43
41
  'Spawns dist/daemon/crtrd-cli.js detached + unref\'d; it outlives this process.',
44
42
  'Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid.'
45
43
  ],
46
44
  },
47
45
  run: async (input) => {
48
46
  try {
49
- const result = await spawnDaemon({ targetPhase: input.prepare === true ? 'prepared' : 'ready', ignoreJoinLock: input.force === true });
47
+ const result = await spawnDaemon({ targetPhase: input.prepare === true ? 'prepared' : 'ready' });
50
48
  return result;
51
49
  }
52
50
  catch (error) {
@@ -17,6 +17,7 @@ import { buildSourceJson } from '../../../core/import/export/source.js';
17
17
  import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId, spawnDaemon, stopAllDaemons } from '../../../daemon/manage.js';
18
18
  import { deleteMoveRecord, moveUnfinishedError, readMachineConfig, readMoveRecord, writeMachineConfig, writeMachineCredential, writeMoveRecord } from '../../../daemon/machine-link/config.js';
19
19
  import { notifyMoveFinished } from '../../../daemon/machine-link/move-notify.js';
20
+ import { registerSignedInMac } from '../../../core/directory/join.js';
20
21
  import { controlPlaneUrl, forgetSignIn, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../../core/directory/person-credential.js';
21
22
  import { NORTHLIGHT_DIRECTORY_URL } from '../../../core/directory/issuer.js';
22
23
  import { isPidAlive } from '../../../core/canvas/pid.js';
@@ -214,11 +215,22 @@ export async function finishMove(move) {
214
215
  }
215
216
  writeMachineCredential(credential.credential);
216
217
  writeMachineConfig({ apiUrl: move.apiUrl, environmentId: credential.environment_id, runId: move.runId, directoryUrl: move.directoryUrl, account: move.account });
218
+ await registerThisMac(move.directoryUrl);
217
219
  await stopAllDaemons();
218
220
  await spawnDaemon();
219
221
  // Only now has the computer switched over: until the machine-role daemon is up the record keeps every command at `move_unfinished`.
220
222
  deleteMoveRecord();
221
223
  }
224
+ /** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
225
+ export async function registerThisMac(directoryUrl) {
226
+ try {
227
+ await registerSignedInMac(directoryUrl, await personBearer(directoryUrl));
228
+ }
229
+ catch (error) {
230
+ // A directory that predates person-credential registration refuses it; the move is done either way, and `crtr sys signin` again registers once the directory accepts.
231
+ process.stderr.write(`this computer was not registered with the directory: ${error instanceof Error ? error.message : String(error)}\nRun \`crtr sys signin\` again to register it.\n`);
232
+ }
233
+ }
222
234
  const ACTIVATION_ATTEMPTS = 3;
223
235
  const ACTIVATION_GAP_MS = 30_000;
224
236
  /** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the