@north-light/cli 0.3.760 → 0.3.761
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/cli.js +5 -5
- package/dist/clients/attach/config.js +1 -1
- package/dist/clients/attach/viewer.js +467 -467
- package/dist/commands/api-client.d.ts +0 -5
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/daemon-generation.js +1 -1
- package/dist/commands/sys/import/move.d.ts +1 -34
- package/dist/commands/sys/import/move.js +5 -9
- package/dist/commands/sys/import/start.d.ts +0 -3
- package/dist/commands/sys/import/start.js +1 -1
- package/dist/commands/sys/signin.js +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -0
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +6 -4
- package/dist/core/command.d.ts +1 -1
- package/dist/core/runtime/front-door.js +9 -10
- package/dist/core/user-settings.d.ts +2 -2
- package/dist/core/worktree-mutation-async.js +5 -5
- package/dist/core/worktree-scripts.d.ts +13 -0
- package/dist/core/worktree-scripts.js +5 -0
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/handlers/daemon.js +1 -1
- package/dist/daemon/crtrd.js +11 -11
- package/dist/daemon/import-dump-run.js +4 -4
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/config.d.ts +0 -24
- package/dist/daemon/machine-link/config.js +4 -4
- package/dist/daemon/manage.d.ts +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/config.js +2 -1
- package/packages/crouter-api/dist/commands/api-client.js +1 -12
- package/packages/crouter-api/dist/commands/sys/import/move.js +5 -205
- package/packages/crouter-api/dist/commands/sys/import/start.js +15 -51
- package/packages/crouter-api/dist/commands/sys/signin.js +13 -54
- package/packages/crouter-api/dist/core/worktree-mutation-async.js +11 -3
- package/packages/crouter-api/dist/core/worktree-scripts.js +72 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +10 -1
- package/packages/crouter-api/dist/daemon/machine-link/config.js +1 -27
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/import/retry.d.ts +0 -1
- package/dist/commands/sys/import/retry.js +0 -1
- package/dist/daemon/machine-link/move-notify.d.ts +0 -4
- package/dist/daemon/machine-link/move-notify.js +0 -1
- package/packages/crouter-api/dist/commands/sys/import/retry.js +0 -38
- package/packages/crouter-api/dist/daemon/machine-link/move-notify.js +0 -15
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var F=Object.defineProperty;var l=(e,t)=>F(e,"name",{value:t,configurable:!0});import{createHash as L}from"node:crypto";import{existsSync as h,realpathSync as U}from"node:fs";import{
|
|
2
|
-
`))if(t.startsWith("worktree "))return t.slice(9).trim();return null}l(
|
|
3
|
-
`))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&s===`branch refs/heads/${r}`&&
|
|
4
|
-
${o.stdout}`).digest("hex");return{base:a,upstream:s?.sha??null,branch:n,checkout:u}}l(
|
|
1
|
+
var F=Object.defineProperty;var l=(e,t)=>F(e,"name",{value:t,configurable:!0});import{createHash as L}from"node:crypto";import{existsSync as h,realpathSync as U}from"node:fs";import{basename as K,isAbsolute as q,relative as z,resolve as w,sep as I}from"node:path";import{completeCleanup as V,getNode as E,recordSweepAttempt as G,resumableNodeCwds as O}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as Q}from"./exclusive-lock.js";import{gitAsync as c}from"./git.js";import{proveBranchContained as $,upstreamTip as j}from"./worktree-containment.js";import{refDeleteTransactionStdin as J}from"./worktree-landing.js";import{runWorktreeScript as X}from"./worktree-scripts.js";import{deleteTrashAsync as Y,removeWorktreeCheckoutAsync as P}from"./worktree-remove.js";import{WORKTREE_LOCK_WAIT_MS as Z,canonicalPath as T,checkoutPathForBranchInList as W,samePath as N,worktreeLockPathForCommonDir as ee}from"./worktree.js";const v=[2,5,15,30,60],te=v.length;function R(e){return e==null||e.state==="abandoned"?!1:e.state==="open"||e.cleanup!=="complete"}l(R,"isReconcilable");function De(e,t){const r=e.sweep?.next_attempt;if(r===void 0)return!0;const a=Date.parse(r);return Number.isNaN(a)||a<=t}l(De,"isDueForSweep");async function _(e,t){const r=await c(["rev-parse","--verify","--quiet",t],e);return r.status===0?r.stdout.trim():null}l(_,"revParseRef");function f(e){return(e.stderr.trim()||e.stdout.trim()).trim()}l(f,"detailOf");async function M(e){const t=await c(["rev-parse","--git-common-dir"],e);if(t.status!==0)return null;try{return U(w(e,t.stdout.trim()))}catch{return null}}l(M,"commonGitDirAsync");async function ae(e){for(const t of["rebase-merge","rebase-apply"]){const r=await c(["rev-parse","--git-path",t],e);if(r.status!==0)return null;if(h(w(e,r.stdout.trim())))return!0}return!1}l(ae,"isRebaseInProgressAsync");function re(e){for(const t of e.split(`
|
|
2
|
+
`))if(t.startsWith("worktree "))return t.slice(9).trim();return null}l(re,"mainWorktreePath");function se(e,t,r){let a=null;for(const s of e.split(`
|
|
3
|
+
`))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&s===`branch refs/heads/${r}`&&N(a,t))return a;return null}l(se,"registeredCheckoutPath");async function ne(e){const t=h(e.path),r=t?e.path:e.repo_root,a=await _(r,`refs/heads/${e.base_ref}`),s=await j(r,e.base_ref),n=await _(r,`refs/heads/${e.branch}`);if(!t)return{base:a,upstream:s?.sha??null,branch:n,checkout:"absent"};const i=await c(["rev-parse","HEAD"],e.path),o=await c(["status","--porcelain"],e.path),u=i.status!==0||o.status!==0?null:L("sha256").update(`${i.stdout.trim()}
|
|
4
|
+
${o.stdout}`).digest("hex");return{base:a,upstream:s?.sha??null,branch:n,checkout:u}}l(ne,"observe");function ie(e,t){return e.checkout===null||t.checkout===null?!1:e.base===t.base&&e.upstream===t.upstream&&e.branch===t.branch&&e.checkout===t.checkout}l(ie,"sameObservation");async function oe(e,t,r,a,s,n){if(r.status!=="refused"&&r.status!=="failed"||!await n.stillEligible())return;const i=(t.sweep?.attempts??0)+1,o=v[Math.min(i,v.length)-1]??v[0],u=(await E(e))?.managed_worktree;u==null||!R(u)||await G(e,{reason:r.reason,...r.detail===void 0?{}:{detail:r.detail},observed:a,attempts:i,lastAttemptAt:new Date(s).toISOString(),nextAttemptAt:new Date(s+o*6e4).toISOString(),quarantined:i>=te})}l(oe,"recordUnfinished");async function ue(e,t,r){const a=await _(e.path,`refs/heads/${e.base_ref}`);if(a===null)return{ok:!1,detail:`local base branch '${e.base_ref}' does not resolve`};if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const s=await c(["rebase",a],e.path);if(s.status!==0)return await c(["rebase","--abort"],e.path),{ok:!1,detail:f(s)};const n=await _(e.path,"HEAD");if(n===null)return{ok:!1,detail:"could not read the rebased worktree tip"};if((await c(["merge-base","--is-ancestor",a,n],e.path)).status!==0)return{ok:!1,detail:`the rebased branch is not a fast-forward of '${e.base_ref}'`};const i=W(t,e.base_ref);if(i===null){if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const d=await c(["update-ref",`refs/heads/${e.base_ref}`,n,a],e.path);return d.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:f(d)}}const o=await c(["rev-parse","HEAD"],i);if(o.status!==0||o.stdout.trim()!==a)return{ok:!1,detail:`base checkout ${i} is not at ${a}`};if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const u=await c(["merge","--ff-only",n],i);return u.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:f(u)}}l(ue,"finishBlockedLand");const p={status:"skipped",reason:"node_no_longer_terminal"},A={status:"skipped",reason:"checkout_in_use"};function le(e,t){const r=z(e,t);return r===""||r!==".."&&!r.startsWith(`..${I}`)&&!q(r)}l(le,"isWithinDirectory");async function D(e,t){const r=[w(t),T(t)];return(await e()).some(a=>{const s=[w(a),T(a)];return r.some(n=>s.some(i=>le(n,i)))})}l(D,"checkoutHasDependents");async function Se(e,t,r=Date.now(),a){const s=(await E(e))?.managed_worktree;if(!R(s)||s==null)return{status:"skipped",reason:"already_reconciled"};const{outcome:n,observed:i,trash:o}=a===void 0?await ce(s,t,async()=>(await O(e)).map(({cwd:u})=>u)):await a(s,(await O(e)).map(({cwd:u})=>u));return a===void 0&&await Y(s.path,o),n.status==="complete"?await de(e,s,t):(await oe(e,s,n,i,r,t),n)}l(Se,"reconcileManagedWorktree");async function ce(e,t,r){const a={base:null,upstream:null,branch:null,checkout:null};if(h(e.path)&&await D(r,e.path))return{outcome:A,observed:a};if(h(e.path)){const d=await X("worktree-teardown",K(e.path),e);if(d.status==="failed")return{outcome:{status:"refused",reason:"teardown_failed",detail:d.detail},observed:a};if(!await t.stillEligible())return{outcome:p,observed:a}}const s=h(e.path)?e.path:e.repo_root;if(!h(s))return{outcome:{status:"refused",reason:"repo_unavailable",detail:`neither the recorded checkout nor repository root exists, so ${e.branch} cannot be proved absent`},observed:a};const n=await M(s);if(n===null)return{outcome:{status:"failed",reason:"git_dir_unreadable",detail:`could not resolve the git common dir from ${s}`},observed:a};let i=a,o;const u=[];try{o=await Q(ee(n),async()=>await t.stillEligible()?(i=await ne(e),e.sweep!==void 0&&ie(e.sweep.observed,i)?{status:"refused",reason:e.sweep.reason,...e.sweep.detail===void 0?{}:{detail:e.sweep.detail},unchanged:!0}:h(e.path)?await he(e,t,r,u):await fe(e,i,t)):p,{timeoutMs:Z,timeoutError:l(()=>new Error(`timed out waiting for the managed-worktree lock on ${n}`),"timeoutError")})}catch(d){o={status:"failed",reason:"lock_unavailable",detail:d instanceof Error?d.message:String(d)}}return{outcome:o,observed:i,...u[0]===void 0?{}:{trash:u[0]}}}l(ce,"sweepManagedWorktreeOnHost");async function de(e,t,r){if(!await r.stillEligible())return p;const a=(await E(e))?.managed_worktree;return a==null||a.path!==t.path||a.branch!==t.branch?{status:"skipped",reason:"record_changed"}:(await V(e),{status:"complete"})}l(de,"persistComplete");async function fe(e,t,r){const a=e.repo_root;if(t.branch===null){const o=await c(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],a);return o.status!==1?{status:"failed",reason:"branch_inspection_failed",detail:f(o)}:{status:"complete"}}const s=await c(["worktree","list","--porcelain"],a);if(s.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:f(s)};const n=W(s.stdout,e.branch);if(n!==null)return{status:"refused",reason:"branch_checked_out_elsewhere",detail:`${e.branch} is checked out at ${n}`};const i=await $(a,e,t.branch);return i===null?{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries content no base or upstream ref contains; its checkout is already gone, so the branch is the only copy`}:B(e,a,t.branch,i,r)}l(fe,"concludeAbsentCheckout");async function he(e,t,r,a){const s=await c(["worktree","list","--porcelain"],e.path);if(s.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:f(s)};const n=e.disposal,i=n?.observed_branch??e.branch,o=se(s.stdout,e.path,i);if(o===null)return{status:"refused",reason:"not_registered",detail:`${e.path} is not registered to refs/heads/${i}; crtr will not act on a path it cannot prove it owns`};const u=re(s.stdout);if(u===null||N(u,o)||!h(u))return{status:"refused",reason:"repo_unavailable",detail:`the repository's main checkout is unavailable, so ${e.path} cannot be removed from outside itself`};const d=await ae(e.path);if(d===null)return{status:"failed",reason:"git_path_failed",detail:`could not inspect in-progress operations in ${e.path}`};if(d)return{status:"refused",reason:"rebase_in_progress",detail:`${e.path} is mid-rebase`};const b=await c(["rev-parse","--abbrev-ref","HEAD"],e.path);if(b.status!==0)return{status:"failed",reason:"branch_check_failed",detail:f(b)};if(b.stdout.trim()!==i)return{status:"refused",reason:"wrong_branch",detail:`expected ${i}, found ${b.stdout.trim()==="HEAD"?"detached HEAD":b.stdout.trim()}`};const y=await c(["status","--porcelain"],e.path);if(y.status!==0)return{status:"failed",reason:"status_failed",detail:f(y)};if(y.stdout.trim()!=="")return{status:"refused",reason:"dirty_worktree",detail:`${e.path} has uncommitted changes`};let m=await _(e.path,"HEAD");if(m===null)return{status:"failed",reason:"head_unreadable",detail:`could not read HEAD in ${e.path}`};if(n!==void 0){if(await M(e.path)!==n.common_dir||m!==n.observed_sha)return{status:"refused",reason:"disposal_authorization_stale",detail:`${e.path} changed since \`close\` authorized its disposal; rerun \`crtr node worktree close\` from that node to re-authorize, or ask the user with \`crtr human send\``};if(!await t.stillEligible())return p;if(await D(r,o))return A;const{result:C,trash:H}=await P(u,o);return H!==void 0&&a.push(H),C.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:f(C)}:{status:"complete"}}let g=await $(e.path,e,m);if(g===null&&e.land_intent!==void 0){const k=await ue(e,s.stdout,t);if(!k.ok)return k.ineligible===!0?p:{status:"refused",reason:"land_blocked",detail:k.detail};m=k.landedSha,g=await $(e.path,e,m)}if(g===null)return{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries commits its base does not contain, and this node never asked to land them`};if(!await t.stillEligible())return p;if(await D(r,o))return A;const{result:S,trash:x}=await P(u,o);return x!==void 0&&a.push(x),S.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:f(S)}:await B(e,u,m,g,t)}l(he,"reconcilePresentCheckout");async function B(e,t,r,a,s){if(!await s.stillEligible())return p;const n=J(e.branch,r,a.containingRef,a.containingSha),i=await c(["update-ref","--stdin"],t,n);return i.status!==0?{status:"refused",reason:"branch_delete_failed",detail:f(i)}:{status:"complete"}}l(B,"deleteBranchAndComplete");export{De as isDueForSweep,R as isReconcilable,Se as reconcileManagedWorktree,ce as sweepManagedWorktreeOnHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=Object.defineProperty;var a=(t,e)=>s(t,"name",{value:e,configurable:!0});import{drainState as r,endDrain as d,isDrained as i,settleDrain as m,startDrain as c}from"../../drain.js";import{boundDaemonControl as o}from"../../control.js";import{ownerOnly as u}from"../router.js";function l(){const t=o();if(t===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot hand over"};const{graceMs:e}=t.requestHandover();return{status:202,body:{accepted:!0,predecessor_pid:process.pid,predecessor_epoch:t.epoch,grace_ms:e}}}a(l,"handleRestart");async function b(t){if(t.body!==void 0)throw{status:400,code:"invalid_request",message:"admission request must not include a body"};const e=o();if(e===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot admit normal work"};return{status:200,body:await e.admitStartup()}}a(b,"handleAdmit");async function h(t){const e=t.body??{};if(typeof e!="object"||e===null||Array.isArray(e))throw{status:400,code:"invalid_request",message:"drain request body must be an object"};const n=e.settle_limit_ms;if(n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<0))throw{status:400,code:"invalid_request",message:"settle_limit_ms must be a non-negative number"};return await c(),{status:200,body:n===void 0?await r():await m({limitMs:n})}}a(h,"handleDrain");async function y(){const t=await i();return{status:200,body:{...await d(),was_drained:t}}}a(y,"handleEndDrain");const D=u([{method:"POST",pattern:"/v1/daemon/restart",handler:a(t=>l(),"handler")},{method:"POST",pattern:"/v1/daemon/admit",handler:b},{method:"POST",pattern:"/v1/daemon/drain",handler:h},{method:"DELETE",pattern:"/v1/daemon/drain",handler:y}]);export{D as daemonRoutes};
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var Qe=Object.defineProperty;var a=(e,d)=>Qe(e,"name",{value:d,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as R,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as dr}from"node:path";import{envCrtrdTcp as lr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as de}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as dt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as lt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as le}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{ensurePostgres as Ut,ensurePostgresHealthy as Ht,stopPostgres as zt,withPostgresStartLock as Wt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Kt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Vt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Yt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Jt,readBuiltinSnapshot as Qt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Xt,reapStaleSpares as Zt}from"../core/runtime/warm-pool.js";import{DaemonFleet as en}from"./fleet.js";import{copyNodeFilesToRows as rn}from"../core/runtime/first-boot-rows.js";import{emitEvent as l}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as tn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as nn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Ai}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const on=5e3,Ge=150;async function an(e){const d=Ce();if(d===null)throw l({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const m=wr(),c=[];for(const[i,s]of d.processes){const u=s.command;if(s.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||c.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of c){const s=xt(i.pid);if(s===null||!s.includes("broker-cli.js")||!me(s,m)||fe(s)===e||s.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+on;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const s=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(s)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):$e(s,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw l({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const v=[];for(const[i,s]of w.processes){const u=s.command;s.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);l({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:c.length,sigtermed:h,sigkilled:S}})}a(an,"reapPriorEpochBrokers");const sn=5e3;async function dn(e){const d=Array.from(e.entries());if(d.length===0)return;for(const[o]of d){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=d.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const c=new Promise(o=>{setTimeout(o,sn).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),c])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of d)await at(o,{reason:"daemon-teardown"});l({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(dr(de()),{recursive:!0}),nr(de(),[process.pid,...e].join(`
|
|
2
|
-
`),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function ln(e){const d=de();let m;try{m=or(d,"utf8")}catch(
|
|
3
|
-
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(d)}catch(
|
|
4
|
-
`)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,
|
|
1
|
+
var Qe=Object.defineProperty;var a=(e,d)=>Qe(e,"name",{value:d,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as b,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as dr}from"node:path";import{envCrtrdTcp as lr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as de}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as dt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as lt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as le}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{ensurePostgres as Ut,ensurePostgresHealthy as Ht,stopPostgres as zt,withPostgresStartLock as Wt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Kt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Vt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Yt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Jt,readBuiltinSnapshot as Qt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Xt,reapStaleSpares as Zt}from"../core/runtime/warm-pool.js";import{DaemonFleet as en}from"./fleet.js";import{copyNodeFilesToRows as rn}from"../core/runtime/first-boot-rows.js";import{emitEvent as c}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as tn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as nn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Ai}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const on=5e3,Ge=150;async function an(e){const d=Ce();if(d===null)throw c({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const m=wr(),l=[];for(const[i,s]of d.processes){const u=s.command;if(s.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||l.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of l){const s=xt(i.pid);if(s===null||!s.includes("broker-cli.js")||!me(s,m)||fe(s)===e||s.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&b(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+on;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const s=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(s)&&(process.platform==="linux"&&b(I)?await A({operation:"stop",pid:i.pid}):$e(s,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw c({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const v=[];for(const[i,s]of w.processes){const u=s.command;s.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);c({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:l.length,sigtermed:h,sigkilled:S}})}a(an,"reapPriorEpochBrokers");const sn=5e3;async function dn(e){const d=Array.from(e.entries());if(d.length===0)return;for(const[o]of d){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=d.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&b(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const l=new Promise(o=>{setTimeout(o,sn).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),l])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&b(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of d)await at(o,{reason:"daemon-teardown"});c({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(dr(de()),{recursive:!0}),nr(de(),[process.pid,...e].join(`
|
|
2
|
+
`),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function ln(e){const d=de();let m;try{m=or(d,"utf8")}catch(l){if(Fe(l))return;throw l}if(m.split(`
|
|
3
|
+
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(d)}catch(l){if(Fe(l))return;throw l}}a(ln,"removeOwnedPidfileMirror");const cn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Y=new Xr;Qr(e=>Y.handleFatalFault(e,!1));const pn=new et,mn=new Zr,Be=new rt,fn=new tt,un=new nt,wn=new ot,hn=new it,vn=new ct,gn=new pt,Sn=new mt,_n=new ut,yn=new ft,kn=new ht,bn=new vt,Rn=new gt,En=new St,Pn=new _t,xn=new yt,Dn=new kt;Rt();const In=new bt;async function Tn(e=Date.now(),d=cn){const m=Ne(),l=await Y.runFleetPreamble(m);let h,o,f;try{o=await le();const w=(await Ee()).filter(i=>!o.has(i.node_id));h=w.filter(i=>i.status==="active"||i.status==="idle"),f=w.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const v=new Set(f.map(i=>i.node_id));f.push(...(await Rr()).filter(i=>!v.has(i.node_id)&&!o.has(i.node_id)))}catch(w){c({level:"error",event:"canvas.node_list.failed",error:w});return}await Y.run(e,{rows:h,fleet:m,lifecycle:d,held:o}),await pn.run(e,{rows:h,held:o}),await mn.run(e);const S=await Be.run(e,{rows:[...h,...f],fleet:m});await fn.run(e,o),await Dn.run(e,o),await In.run(e,{lifecycle:d}),await un.run(e,{lifecycle:d,held:o}),await wn.run(e,{lifecycle:d}),await hn.run(e,{lifecycle:d}),await vn.run(e,{lifecycle:d}),await gn.run(e,{lifecycle:d,fleet:m,held:o}),Sn.run(e,{lifecycle:d}),_n.run(e,{lifecycle:d}),yn.run(e,{lifecycle:d}),kn.run(e,{lifecycle:d}),bn.run(e,{lifecycle:d}),Rn.run(e,{lifecycle:d}),En.run(e,{lifecycle:d}),await fr(),xn.run(e,{fleet:m,lifecycle:d}),await Pn.run(e,{rows:h}),Y.warnIfSaturated({fleet:m,lifecycle:d,thresholds:l,frozen:S})}a(Tn,"superviseTick");async function Cn(e,d=Date.now()){if((await le()).has(e))return;const m=await dt(e);if(m===null||!st(m))return;const l=await br(e);l===null||l.kind==="human"||await Be.runNode(d,l,Ne())}a(Cn,"exitedNodePass");function J(e){return e===void 0||e==="reconcile"||e==="all"}a(J,"roleRunsLanes");function F(e){return e===void 0||e==="api"||e==="all"}a(F,"roleServesRequests");const An=66e4;function Ln(e){const d=new Pr().registerAll(xr(()=>null).filter(s=>s.pattern==="/healthz")),m=a((s,u)=>{const _=(s.url??"/").split("?")[0];if((s.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){d.handle(s,u,null,{class:"person"});return}u.writeHead(404,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),l=ur();b(l)&&ke(l);const h=be(m),o=new Promise((s,u)=>{h.once("error",u),h.listen(l,()=>{h.off("error",u),sr(l,384),s()})});let f,S=null,w=o;const v=e.tcp??lr()??Te("user").api.tcp;if(v!==void 0&&v!==""){const s=/^(.*):(\d+)$/.exec(v.trim());if(s===null||Number(s[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${v}`);const u=be(m);u.on("error",_=>c({event:"api.server.failed",level:"error",error:_})),w=o.then(()=>new Promise(_=>{u.once("error",()=>_()),u.listen(Number(s[2]),s[1]===""?"0.0.0.0":s[1],()=>{const R=u.address();S=`${R.address}:${R.port}`,_()})})),f=u}let i=!1;return{ready:w,tcpAddress:a(()=>S,"tcpAddress"),async close(s={}){if(!i){i=!0,await Promise.all([xe(h,new Set,s.graceMs),f===void 0?Promise.resolve():xe(f,new Set,s.graceMs)]);try{b(l)&&ke(l)}catch{}}}}}a(Ln,"createProbeServer");const $n="daemon is draining for shutdown and admits no new work";async function Nn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();_r();const d=a(n=>{process.stderr.write(`[crtrd] ${n}
|
|
4
|
+
`)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,l=Gt(e.role);Kt(J(e.role));const h=a(async()=>l?await Ot(Re(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Re(16).toString("hex")}},"claimOwnership"),{database:o,ownership:f}=e.role!==void 0||m?{database:{url:await Bt()},ownership:await h()}:await Wt(async()=>({database:await Ut({log:d,startLockHeld:!0}),ownership:await h()}));if(!f.claimed){if(f.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${f.incumbentPid??"?"})
|
|
5
5
|
`);else{const n=[f.incumbentPid!==void 0?`pid ${f.incumbentPid}`:void 0,f.verdict!==void 0?`verdict ${f.verdict}`:void 0].filter(t=>t!==void 0),r=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${f.reason}${r}
|
|
6
|
-
`),f.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,s=null,u,_="";try{
|
|
7
|
-
`);await jt(),e.role===void 0&&nn({profiles:[],defaults:{},settings:{},state:{},apps:{}}),await L.listen(o.url);const n=a(r=>{V(r).catch(t=>
|
|
6
|
+
`),f.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,s=null,u,_="";try{l&&await an(S.token);for(const r of yr())process.stderr.write(`[crtrd] ${r}
|
|
7
|
+
`);await jt(),e.role===void 0&&nn({profiles:[],defaults:{},settings:{},state:{},apps:{}}),await L.listen(o.url);const n=a(r=>{V(r).catch(t=>c({level:"error",event:"daemon.settings.reload_failed",error:t}))},"reloadPerson");if(u=await L.subscribe(r=>{Oe().includes(r)&&n(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of Oe())n(r)},"onListenStart")}),e.role!==void 0&&Cr(),e.role==="all"&&Tr(),e.role!==void 0){let r;try{r=Qt()}catch(p){c({level:"error",event:"daemon.packages.snapshot_failed",error:p})}const t=await pe(async p=>(await De(p),r===void 0?void 0:await Jt(p,r,"release")));s=await pe(async p=>await Yt(p));for(const p of t?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${p.path}: ${p.error}
|
|
8
8
|
`)}else{w=await Ar(),w!==null&&($r(w.id),await V(w.id));const r=await pe(async t=>(await De(t),w===null?null:await Vt(t)));if(r!==null){for(const t of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${t.message}
|
|
9
9
|
`);for(const t of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${t.path}: ${t.error}
|
|
10
10
|
`);for(const t of r.quarantined)process.stderr.write(`[crtrd] plugin "${t.name}" has a damaged ${t.file} (${t.reason}); ${t.movedTo!==void 0?`moved to ${t.movedTo}`:"left in place and skipped"}
|
|
11
11
|
`);for(const t of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${t.plugin}" kind ${t.kind} not registered: ${t.message}
|
|
12
12
|
`);for(const t of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${t.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${t.error}
|
|
13
|
-
`)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&
|
|
14
|
-
`)}}catch(n){await L.close();try{if(
|
|
13
|
+
`)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&b(I)&&(Sr(),await A({operation:"users.sync",users:await hr()})),l){await lt(S.token);const r=await rn();Object.values(r).some(t=>t>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
|
|
14
|
+
`)}}catch(n){await L.close();try{if(l){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}await ce()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}let R=!0,Q,B=Promise.resolve(),X=!1,j,Z,ee,re,te,T;const U=new Set;let ne=!1,we=!1,x,E,H=!1,z,C,$,N,M,oe,ie,ae,se;const je=Jr();let D,g={phase:"initializing",message:"daemon startup is running and normal services are unavailable",blockerPaths:[]},Ue=null;function He(){return g.phase==="ready"?null:{phase:g.phase,message:g.message,blockerPaths:g.blockerPaths}}a(He,"startupBlock");function k(n){U.add(n),n.finally(()=>{U.delete(n)}).catch(()=>{})}a(k,"registerDetached");const ze={acceptsDetachedWork:a(()=>R,"acceptsDetachedWork"),registerDetached:k};async function We(){try{R=!1,qt.close(),ee?.(),ee=void 0,re?.(),u?.(),re=void 0,te?.(),te=void 0,ae?.(),ae=void 0,await L.close(),j!==void 0&&(clearInterval(j),j=void 0),Z?.(),Z=void 0,$!==void 0&&(clearInterval($),$=void 0),N!==void 0&&(clearInterval(N),N=void 0),se?.(),se=void 0;let n;do n=B,await n;while(n!==B);for(;U.size>0;)await Promise.allSettled([...U]);if(T!==void 0&&(l&&await dn(T),await T.exitsSettled(),T.dispose()),E!==void 0&&!H&&(H=!0,await E.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,M!==void 0){const r=M;M=void 0,await r.stop()}if(C!==void 0){const r=C;C=void 0,await r.close()}if(z!==void 0){const r=z;z=void 0,await r.close()}if(ne||(ln(process.pid),ne=!0),ne&&!we){if(l){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}we=!0,await ce()}}finally{Ct(),process.off("SIGINT",ge),process.off("SIGTERM",Se),process.off("exit",_e)}}a(We,"cleanupAttempt");const W=1e3;let he=!1;function qe(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return he?{graceMs:W}:(he=!0,y.fresh(()=>{c({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:W}})}),setTimeout(()=>{Ke()},W),{graceMs:W})}a(qe,"requestHandover");async function Ke(){try{await O()}catch(n){const r=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
15
15
|
${r}
|
|
16
|
-
`),process.exit(1)}try{process.platform==="linux"&&
|
|
17
|
-
`),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message:$n,blockerPaths:[]},E!==void 0&&!H&&(H=!0,await E.close({graceMs:An}))}a(Ve,"drainApi");async function ve(n){try{n==="SIGTERM"&&e.role==="api"&&await Ve(),await O(),await zt({claimed:a(async()=>{try{return
|
|
16
|
+
`),process.exit(1)}try{process.platform==="linux"&&b(I)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await At();const n=await Lt();y.fresh(()=>{c({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){y.fresh(()=>{c({level:"error",event:"daemon.handover.successor_failed",error:n})});const r=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${r}
|
|
17
|
+
`),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message:$n,blockerPaths:[]},E!==void 0&&!H&&(H=!0,await E.close({graceMs:An}))}a(Ve,"drainApi");async function ve(n){try{n==="SIGTERM"&&e.role==="api"&&await Ve(),await O(),await zt({claimed:a(async()=>{try{return l&&await Ft()}finally{await ce()}},"claimed")}),process.exit(0)}catch(r){process.exitCode=1;const t=r instanceof Error?r.stack??`${r.name}: ${r.message}`:String(r);process.stderr.write(`[crtrd] ${n} cleanup failed:
|
|
18
18
|
${t}
|
|
19
|
-
`),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){
|
|
19
|
+
`),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){R&&(B=B.then(n).then(()=>{},r=>{y.fresh(()=>{c({level:"error",event:"daemon.lane_job.failed",error:r})})}))}a(q,"enqueue");async function K(){!R||X||(je.check()&&D&&(c({level:"info",event:"daemon.resume.detected"}),k(D().catch(()=>{}))),X=!0,await q(async()=>{if(X=!1,!!R)try{m||await Ht({log:d}),await Tn(Date.now(),ze)}catch(n){y.fresh(()=>{c({level:"error",event:"daemon.tick.failed",error:n})})}}))}a(K,"enqueueTick");let G=null;async function Ye(){if(G!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${G instanceof Error?G.message:String(G)}`};if(g.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(g.phase!=="prepared"&&g.phase!=="recovering")throw{status:409,code:"not_prepared",message:g.message};const n=g.phase==="prepared";try{return await ye(),g={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(r){throw G=r,{status:500,code:"admission_failed",message:`daemon admission failed: ${r instanceof Error?r.message:String(r)}`}}}a(Ye,"admitStartup");async function Je(){Q=e.intervalMs??Yr;const n=S.token;T=new en({epoch:n,enqueue:q}),It(T),g={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},y.fresh(()=>{c({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Q}})});const r=_;if(y.fresh(()=>{c({level:"info",event:"daemon.install_id.resolved",fields:{install_id:r}})}),y.fresh(()=>{let t;try{t=Vr()}catch{return}t!==null&&c({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),wt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Ir(),!J(e.role)){g={phase:"ready",message:"",blockerPaths:[]};return}if(await y.fresh(async()=>{await Kr(),await zr();const t=e.role!==void 0;await Wr(Date.now(),t),await qr(Date.now(),t)}),e.role===void 0&&await y.fresh(async()=>{const t=await $t();t.changed&&c({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}})}),await y.fresh(async()=>{const t=await le();for(const p of await Ee())t.has(p.node_id)||p.status!=="active"||p.pi_pid!=null||p.frozen_at!=null||p.respawn_not_before!=null||(await Pe(p.node_id,new Date().toISOString()),c({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:p.node_id}))}),await y.fresh(async()=>{await Pt()}),k(Ur()),D){const t=a(()=>{k(D().catch(()=>{})),k(rr().then(p=>M?.observe(p)).then(()=>{},p=>{c({level:"warn",event:"daemon.peer.status_failed",error:p})}))},"refresh");k(jr().then(({completion:p})=>p).catch(p=>{c({level:"error",event:"daemon.grants.sweep_failed",error:p})})),t(),$=setInterval(t,Ie*1e3),$.unref(),se=er({joined:!0,register:k})}await q(async()=>{await Zt(),await Xt()}),Z=Ze(),j=setInterval(()=>{K().catch(t=>c({level:"error",event:"daemon.tick.failed",error:t}))},Q),ee=await Et(()=>{K().catch(t=>c({level:"error",event:"daemon.tick.failed",error:t}))}),re=await L.subscribe(()=>{K().catch(t=>c({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),te=await L.subscribe(t=>{q(()=>y.fresh(()=>Cn(t)))},{kinds:["execution_exit"]}),await K()}a(Je,"completeStartup");function ye(){return Ue??=Je().catch(n=>{throw g={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}a(ye,"resumeStartup");try{process.on("SIGINT",ge),process.on("SIGTERM",Se),process.on("exit",_e),tn(),w!==null&&c({level:"info",event:"daemon.person.resolved",fields:{person_id:w.id,source:w.source}}),s!==null&&!s.alreadyDone&&c({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:s.moved,discarded:s.discarded,people:s.people}}),i!==null&&c({level:"info",event:"daemon.permissions.boot",fields:{...i}}),v!==null&&c({level:"info",event:"daemon.person.retired",fields:{person_id:v.person,joined_from:v.joinedFrom,retired:v.retired,columns:v.columns}}),F(e.role)?z=await pr():mr(cr());const n=S.token;Tt({epoch:n,requestHandover:qe,registerDetached:k,startupBlock:He,admitStartup:Ye}),ue(),E=F(e.role)?Er({tcp:e.tcp}):Ln(e),await E.ready,ue(E.tcpAddress()??"");const r=Te("user").runtime;if(r?.issuer&&(D=Br(r.issuer,k),r.unsandboxed===!0&&(M=tr({syncGrants:D}))),e.role==="api"||e.role==="all"){const t=a(()=>k(import("../core/providers/bundles.js").then(P=>P.syncProviderBundles()).catch(P=>{c({level:"error",event:"daemon.providers.bundle_sync_failed",error:P})})),"bundleTick"),p=a(()=>{k(Gr().catch(P=>{c({level:"error",event:"daemon.packages.sync_failed",error:P})})),t()},"packageTick");p(),N=setInterval(p,Ie*1e3),N.unref()}return F(e.role)&&(oe=await Mr()),J(e.role)&&(ie=Fr()),ae=await Or({serves:F(e.role),runsLanes:J(e.role)}),r?.unsandboxed===!0&&r.listener!==void 0&&c({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),F(e.role)&&r!==void 0&&r.listener!==void 0&&r.unsandboxed!==!0&&(C=await Dr(r,async()=>await Hr(r.issuer.replace(/\/$/,"")),D),await C.ready,ue(E.tcpAddress()??"",`${r.listener.address}:${C.port()}`)),process.platform==="linux"&&b(I)&&(gr(),await vr("app:terminal")),e.prepare?g={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await ye(),g={phase:"ready",message:"",blockerPaths:[]}),O}catch(n){try{await O()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}}a(Nn,"runDaemon");var Ii=Nn;export{An as API_DRAIN_GRACE_MS,Ai as brokerCommandDeclaresCanvasHome,fe as brokerCommandEpoch,Ii as default,Cn as exitedNodePass,J as roleRunsLanes,F as roleServesRequests,Nn as runDaemon,Tn as superviseTick,dn as teardownFleet};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),0}if(t==="bodies"&&r!==void 0&&r!=="")return process.stdout.write(`${JSON.stringify(await
|
|
3
|
-
`),0;if(r===void 0||t!=="
|
|
1
|
+
var n=Object.defineProperty;var s=(r,t)=>n(r,"name",{value:t,configurable:!0});import{closeAllDbs as a,openDb as d}from"../core/canvas/db.js";import{chmodSync as m,writeFileSync as p}from"node:fs";import{join as f}from"node:path";import{dumpBodiesPre as l,dumpRows as c}from"../core/import/export/dump.js";import{STORE_FILE as w}from"../core/import/export/cloud.js";import{readStores as u}from"../core/import/export/stores.js";async function v(r,t){try{if(t==="install-id"){const o=await(await d()).prepare("SELECT value FROM canvas_meta WHERE key = 'install_id'").get();if(o===void 0)throw new Error("this canvas database has no install id");return process.stdout.write(`${JSON.stringify({installId:o.value})}
|
|
2
|
+
`),0}if(t==="bodies"&&r!==void 0&&r!=="")return process.stdout.write(`${JSON.stringify(await l(r))}
|
|
3
|
+
`),0;if(r===void 0||t!=="hosted")throw new Error("usage: import-dump <out dir> hosted|bodies|install-id");const e=await c(r,t),i=f(r,w);return p(i,JSON.stringify(await u()),{mode:384}),m(i,384),process.stdout.write(`${JSON.stringify(e)}
|
|
4
4
|
`),0}catch(e){return process.stderr.write(`${e.message}
|
|
5
|
-
`),1}finally{await
|
|
5
|
+
`),1}finally{await a()}}s(v,"runImportDump");export{v as runImportDump};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var U=Object.defineProperty;var t=(n,i)=>U(n,"name",{value:i,configurable:!0});import{chmodSync as A,closeSync as G,existsSync as L,mkdirSync as b,openSync as N,unlinkSync as J,writeFileSync as Y,rmSync as M}from"node:fs";import{createServer as K}from"node:http";import{dirname as X,join as z}from"node:path";import{spawn as F}from"node:child_process";import{SELF_UPDATE_SCRIPT as V}from"../core/self-update.js";import{apiSocketPath as W,crtrHome as C}from"../core/canvas/paths.js";import{bindDaemonEventSource as $}from"../core/events/source.js";import{emitEvent as l}from"../core/events/emit.js";import{brokerCommandDeclaresCanvasHome as Q}from"../core/runtime/broker-ownership.js";import{createMachineExecutor as Z,findBrokers as q,stopAllBrokers as ee}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as ne}from"../core/checkout-identities.js";import{machineWorktreeHandlers as oe}from"../core/worktree-machine.js";import{readPersonCredential as te}from"../core/directory/person-credential.js";import{socketDir as re}from"../core/layout.js";import{isDaemonRunning as ie,pidfilePath as y,readPidfile as ae}from"./pidfile.js";import{spawnDaemon as se}from"./manage.js";import{processGeneration as ce}from"../commands/sys/shared.js";import{cancelMachineCron as de,runMachineCron as le,stopOrphanedMachineCrons as me}from"./cron/machine-exec.js";import{startMachineLink as fe}from"./machine-link/client.js";import{readMachineConfig as pe,readMachineCredential as D}from"./machine-link/config.js";import{jobExitReporting as ue,stopMachineJob as he}from"./machine-link/job-sweep.js";import{machineSupervision as ve,SUPERVISION_TICK_MS as we}from"./machine-supervision.js";import{startBrokerMemoryCap as Se}from"./broker-memory-cap.js";const P=10*6e4,_e=3e4,ye=75;let g=0;function ge(n,i){if(Date.now()-g<P||!/^\d+\.\d+\.\d+$/.test(n))return;g=Date.now(),l({level:"warn",event:"daemon.machine.updating",fields:{release:n}});const a=N(z(C(),"crtrd.err"),"a"),r=F(process.execPath,[V,"--version",n],{stdio:["ignore",a,a]});G(a),r.on("error",s=>l({level:"error",event:"daemon.machine.update_failed",fields:{release:n},error:s})),r.on("exit",s=>{if(s===ye){g=Date.now()-P+_e;return}if(s!==0){l({level:"error",event:"daemon.machine.update_failed",fields:{release:n,exit_code:s}});return}i()})}t(ge,"updateToRelease");const R=1024;function Ie(n,i){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:n,signed_in:i,generation_id:ce()?.id??null,startup_phase:n?"ready":"recovering"}}t(Ie,"machineHealth");async function Ve(){const n=pe();if(n===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const i=te()!==void 0;if(i&&D(),ie())throw new Error("a crtrd is already running for this home");$(),i||(await ee(),await me(),l({level:"info",event:"daemon.machine.signed_out",fields:{environment:n.environmentId}})),b(re(),{recursive:!0,mode:493});const a=W();L(a)&&J(a);let r;const s=ue(()=>r),f=K((e,o)=>{const c=(e.url??"").split("?")[0];if(e.method==="POST"&&(c==="/job-exit"||c==="/job-activity")){const k=[];let _=0;e.on("data",d=>{_+=d.length,_<=R&&k.push(d)}),e.on("end",()=>{if(_>R){o.writeHead(413),o.end();return}let d={};try{d=JSON.parse(Buffer.concat(k).toString("utf8"))}catch{}const T=typeof d.node=="string"&&typeof d.job=="string";o.writeHead(T?202:400,{"content-type":"application/json; charset=utf-8"}),o.end("{}"),T&&(c==="/job-exit"?s.notice:s.activity)(d.node,d.job)});return}const x=(e.method??"GET")==="GET"&&(e.url??"/").split("?")[0]==="/healthz";o.writeHead(x?200:404,{"content-type":"application/json; charset=utf-8"}),o.end(JSON.stringify(x?Ie(r?.connected()===!0,i):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((e,o)=>{f.once("error",o),f.listen(a,()=>{f.off("error",o),A(a,384),e()})}),b(X(y()),{recursive:!0}),Y(y(),String(process.pid),"utf8");let I;const u=new Set,h=new Set;let v=!1;const m=Z({apiUrl:n.apiUrl,environmentId:n.environmentId,onExit:t(e=>r?.reportExit(e),"onExit")}),O=t(async(e,o)=>{u.add(e.executionId);for(const c of h)c.add(e.executionId);try{return await m.start(e,o)}finally{u.delete(e.executionId)}},"start");r=i?fe({apiUrl:n.apiUrl,environmentId:n.environmentId,credential:D,onOpen:t(()=>{s.onOpen(),v=!0},"onOpen"),onBehind:t(e=>ge(e,H),"onBehind"),handlers:{start:O,wake:m.wake,stop:m.stop,status:m.status,delete:m.delete,viewer:m.viewer,"cron.run":le,"cron.cancel":de,"job.stop":t(e=>he(e),"job.stop"),...oe,...ne}}):void 0;const E=r===void 0?void 0:ve({link:r,brokers:t(async()=>{const e=new Set(u);h.add(e);const o=await q().finally(()=>h.delete(e));return v&&(v=!1,r?.reportRunning([...new Set([...e,...o.filter(c=>Q(c.command,C())).map(c=>c.execution)])])),o},"brokers"),stop:t((e,o)=>m.stop({execution:{executionId:e,nodeId:o,attempt:0},options:{reason:"yield_stall"}}),"stop")});let w=!1;const j=E===void 0?void 0:setInterval(()=>{w||(w=!0,E(Date.now()).catch(e=>l({level:"error",event:"daemon.machine.supervision_failed",error:e})).finally(()=>{w=!1}))},we),B=Se();l({level:"info",event:"daemon.machine.started",fields:{environment:n.environmentId}});const S=t(()=>I??=(async()=>{r?.stop(),clearInterval(j),B(),await new Promise(e=>{f.close(()=>e()),f.closeAllConnections()}),ae()===process.pid&&(M(a,{force:!0}),M(y(),{force:!0})),process.off("SIGINT",p),process.off("SIGTERM",p)})(),"teardown"),H=t(async()=>{if(I===void 0){await S();try{const e=await se();l({level:"info",event:"daemon.machine.replaced",fields:{successor_pid:e.pid??e.existing_pid??null}}),process.exit(0)}catch(e){l({level:"error",event:"daemon.machine.successor_failed",error:e}),process.exit(1)}}},"replaceSelf"),p=t(()=>{S().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",p),process.on("SIGTERM",p),S}t(Ve,"runMachineDaemon");export{Ie as machineHealth,Ve as runMachineDaemon};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { CrtrError } from '../../core/errors.js';
|
|
2
1
|
/** The Northlight account, as the directory names it (`account` of the sign-in poll). */
|
|
3
2
|
export interface NorthlightAccount {
|
|
4
3
|
id: string;
|
|
@@ -20,29 +19,6 @@ export declare function readMachineConfig(): MachineConfig | undefined;
|
|
|
20
19
|
export declare function writeMachineConfig(config: MachineConfig): void;
|
|
21
20
|
export declare function readMachineCredential(): string;
|
|
22
21
|
export declare function writeMachineCredential(secret: string): void;
|
|
23
|
-
/** A move to Northlight in progress. `running`: the cloud run has not reached `done`, so a failure undoes the move. `committed`: the account holds the
|
|
24
|
-
* records and only the switch-over (machine credential, `machine.json`, restart) is left. `activated`: the machine-role daemon is up, so the switch-over is
|
|
25
|
-
* complete and commands run; the record stays only until `notified` — the asking node's message is stored in the account — is true, then it is deleted. */
|
|
26
|
-
export interface MoveRecord {
|
|
27
|
-
runId: string;
|
|
28
|
-
apiUrl: string;
|
|
29
|
-
directoryUrl: string;
|
|
30
|
-
account: NorthlightAccount;
|
|
31
|
-
notify: string | null;
|
|
32
|
-
state: 'running' | 'committed' | 'activated';
|
|
33
|
-
notified: boolean;
|
|
34
|
-
/** The exporter's process, so a later `crtr sys signin` can tell a running move from one whose exporter was killed. */
|
|
35
|
-
pid: number;
|
|
36
|
-
}
|
|
37
|
-
export declare const moveRecordPath: () => string;
|
|
38
|
-
/** The move record, or undefined when no move is running or unfinished. A present but malformed file throws. */
|
|
39
|
-
export declare function readMoveRecord(): MoveRecord | undefined;
|
|
40
|
-
export declare function writeMoveRecord(record: MoveRecord): void;
|
|
41
|
-
export declare function deleteMoveRecord(): void;
|
|
42
|
-
/** Whether a move's records are in the Northlight account but this computer has not switched over (the record says `committed`). */
|
|
43
|
-
export declare const isMoveCommitted: () => boolean;
|
|
44
|
-
/** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
|
|
45
|
-
export declare const moveUnfinishedError: (reason?: string) => CrtrError;
|
|
46
22
|
/** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
|
|
47
23
|
export declare const installIdPath: () => string;
|
|
48
24
|
export declare function readOrCreateInstallId(): string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}
|
|
3
|
-
`,{mode:384}),
|
|
4
|
-
`),t
|
|
1
|
+
var m=Object.defineProperty;var t=(r,n)=>m(r,"name",{value:n,configurable:!0});import{chmodSync as l,existsSync as i,mkdirSync as c,readFileSync as a,writeFileSync as d}from"node:fs";import{randomBytes as h}from"node:crypto";import{dirname as s,join as o}from"node:path";import{runtimeRoot as u,secretsDir as y}from"../../core/layout.js";import{joinedIssuer as I}from"../../core/directory/join.js";const p=t(()=>o(u(),"machine.json"),"machineConfigPath"),f=t(()=>o(y(),"machine-credential"),"machineCredentialPath");function g(){const r=p();if(!i(r))return;const n=JSON.parse(a(r,"utf8"));if(typeof n.apiUrl!="string"||typeof n.environmentId!="string"||n.runId!==void 0&&typeof n.runId!="string"||typeof n.directoryUrl!="string")throw new Error(`${r} must hold {apiUrl, environmentId, directoryUrl}`);const e=n.account!==void 0&&typeof n.account?.id=="string"&&typeof n.account.display=="string"?{id:n.account.id,display:n.account.display}:void 0;return{apiUrl:n.apiUrl,environmentId:n.environmentId,...n.runId===void 0?{}:{runId:n.runId},directoryUrl:n.directoryUrl,...e===void 0?{}:{account:e}}}t(g,"readMachineConfig");function M(r){c(s(p()),{recursive:!0}),d(p(),`${JSON.stringify(r,null,2)}
|
|
2
|
+
`)}t(M,"writeMachineConfig");function b(){const r=f();if(!i(r))throw new Error(`no machine credential at ${r}`);return a(r,"utf8").trim()}t(b,"readMachineCredential");function O(r){const n=f();c(s(n),{recursive:!0}),d(n,`${r}
|
|
3
|
+
`,{mode:384}),l(n,384)}t(O,"writeMachineCredential");const x=t(()=>o(u(),"install-id"),"installIdPath");function P(){const r=x();if(i(r))return a(r,"utf8").trim();const n=Array.from(h(8),e=>"abcdefghijklmnopqrstuvwxyz0123456789"[e%36]).join("");return c(s(r),{recursive:!0}),d(r,`${n}
|
|
4
|
+
`),n}t(P,"readOrCreateInstallId");const v=t(()=>["pg","canvas.db","canvas.db.imported"].some(r=>i(o(u(),r))),"hasLocalCanvas"),k=t(()=>g()===void 0&&!v()&&I()===null,"computerIsUnset");export{k as computerIsUnset,v as hasLocalCanvas,x as installIdPath,p as machineConfigPath,f as machineCredentialPath,g as readMachineConfig,b as readMachineCredential,P as readOrCreateInstallId,M as writeMachineConfig,O as writeMachineCredential};
|
package/dist/daemon/manage.d.ts
CHANGED
|
@@ -48,7 +48,7 @@ export interface DaemonExportSqliteResult {
|
|
|
48
48
|
userVersion: number;
|
|
49
49
|
}
|
|
50
50
|
/** Run the selected generation's `crtrd-cli import-dump`: the row files of the running canvas into `out`/rows. */
|
|
51
|
-
export declare function runDaemonImportDump(out: string, kind: '
|
|
51
|
+
export declare function runDaemonImportDump(out: string, kind: 'hosted'): Promise<DumpResult>;
|
|
52
52
|
/** Run `crtrd-cli import-dump <out> bodies`: every `bodies` row into `out`/rows/bodies (the pre-pause dump; the later `runDaemonImportDump` adds the rows written since). */
|
|
53
53
|
export declare function runDaemonBodiesDump(out: string): Promise<{
|
|
54
54
|
parts: string[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.761",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.761",
|
|
161
|
+
"@north-light/plugin": "0.3.761",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -95,7 +95,8 @@ export function loadUserKeybindings(agentDir = defaultAgentDir()) {
|
|
|
95
95
|
const ATTACH_KEYBINDING_OVERRIDES = {
|
|
96
96
|
'tui.input.newLine': { defaultKeys: ['shift+enter', 'alt+enter'], description: 'Insert new line' },
|
|
97
97
|
// Ctrl+K/U/D/J/G scroll the transcript (crtr.attach.scroll.*), so the editor gives them up.
|
|
98
|
-
|
|
98
|
+
// Cmd+Delete arrives as super+backspace (CSI 127;9u) when the terminal or tmux sends it distinctly.
|
|
99
|
+
'tui.editor.deleteToLineStart': { defaultKeys: ['super+backspace'], description: 'Delete to line start' },
|
|
99
100
|
'tui.editor.deleteToLineEnd': { defaultKeys: [], description: 'Delete to line end' },
|
|
100
101
|
'tui.editor.deleteCharForward': { defaultKeys: ['delete'], description: 'Delete character forward' },
|
|
101
102
|
};
|
|
@@ -20,7 +20,7 @@ import { gunzipSync } from 'node:zlib';
|
|
|
20
20
|
import { CrtrClient, ApiError } from '../api/index.js';
|
|
21
21
|
import { localClient } from '../api/node-transport.js';
|
|
22
22
|
import { northlightFetch, notSignedIn, readPersonCredential } from '../core/directory/person-credential.js';
|
|
23
|
-
import {
|
|
23
|
+
import { readMachineConfig } from '../daemon/machine-link/config.js';
|
|
24
24
|
import { northlightUnreachable } from '../core/directory/reach.js';
|
|
25
25
|
import { apiErrorToCliError } from '../core/io.js';
|
|
26
26
|
import { autostartDisabled, daemonAutostartStartupFailure, ensureDaemon } from '../daemon/manage.js';
|
|
@@ -169,12 +169,6 @@ function asApiError(error) {
|
|
|
169
169
|
const next = typeof error.details?.['next'] === 'string' ? error.details['next'] : undefined;
|
|
170
170
|
return new ApiError(error.exitCode === ExitCode.NETWORK ? 503 : 401, error.code, error.message, { error: error.code, message: error.message, ...(next === undefined ? {} : { next }) });
|
|
171
171
|
}
|
|
172
|
-
/** A move whose cloud run reached `done` but whose computer has not switched over: the account holds the records, the local daemon stays drained,
|
|
173
|
-
* and no command may run against either side until `crtr sys signin` finishes it (design D14). The record is deleted only once the machine-role daemon
|
|
174
|
-
* is up (`finishMove`, or that daemon's own start), so a `machine.json` written before a failed restart does not lift this. */
|
|
175
|
-
export function moveUnfinished() {
|
|
176
|
-
return isMoveCommitted() ? moveUnfinishedError() : undefined;
|
|
177
|
-
}
|
|
178
172
|
/** The local-socket `CrtrClient` every CLI verb uses. Autostart is on by
|
|
179
173
|
* default: on a cold socket the injected `onColdSocket` hook fires
|
|
180
174
|
* `ensureDaemon()` (spawns crtrd detached via the branded host), then the
|
|
@@ -190,11 +184,6 @@ export function moveUnfinished() {
|
|
|
190
184
|
* Both callers use the shared startup policy so a valid on-disk migration
|
|
191
185
|
* cannot outlast the initiating CLI command. */
|
|
192
186
|
export function cliClient(opts) {
|
|
193
|
-
if (opts?.local !== true) {
|
|
194
|
-
const unfinished = moveUnfinished();
|
|
195
|
-
if (unfinished !== undefined)
|
|
196
|
-
throw unfinished;
|
|
197
|
-
}
|
|
198
187
|
if (opts?.local === true && relayReachesControlPlane()) {
|
|
199
188
|
throw new CrtrError('no_local_daemon', 'this node reaches Northlight\'s shared control plane, not a daemon on this computer', ExitCode.USAGE, {
|
|
200
189
|
next: 'Ask the person to run this in their own terminal on this computer.',
|