@north-light/cli 0.3.642 → 0.3.643
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/core/import/load/copy.d.ts +0 -1
- package/dist/core/import/load/copy.js +8 -8
- package/dist/daemon/cron/lease-recovery.d.ts +1 -1
- package/dist/daemon/cron/passes.d.ts +2 -0
- package/dist/daemon/cron-run.d.ts +1 -1
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/crtrd.js +18 -18
- package/dist/daemon/reconcilers/broker-supervision.d.ts +2 -0
- package/dist/daemon/reconcilers/broker-supervision.js +1 -1
- package/dist/daemon/reconcilers/controller-death.d.ts +2 -0
- package/dist/daemon/reconcilers/controller-death.js +1 -1
- package/dist/daemon/reconcilers/cron-lane.d.ts +1 -0
- package/dist/daemon/reconcilers/cron-lane.js +1 -1
- package/dist/daemon/reconcilers/live-obligation.d.ts +3 -0
- package/dist/daemon/reconcilers/live-obligation.js +1 -1
- package/dist/daemon/reconcilers/node-deadline.d.ts +2 -1
- package/dist/daemon/reconcilers/node-deadline.js +1 -1
- package/dist/daemon/reconcilers/storage-maintenance.d.ts +2 -0
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/dist/daemon/reconcilers/structured-request-lane.d.ts +2 -1
- package/dist/daemon/reconcilers/structured-request-lane.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -10,7 +10,6 @@ export interface CopyResult {
|
|
|
10
10
|
/** `import_manifest.inserted_keys`: a zstd-compressed JSON array of primary-key tuples (each value as text). */
|
|
11
11
|
export declare const encodeKeys: (keys: string[][]) => Buffer;
|
|
12
12
|
export declare const decodeKeys: (data: Buffer) => string[][];
|
|
13
|
-
/** The nodes a `committed` import run inserted: its rows are not verified yet, and retention must not delete them (their `run_events` cascade with the run root) before verify compares them. */
|
|
14
13
|
export declare function nodesAwaitingVerify(db: CanvasDb): Promise<Set<string>>;
|
|
15
14
|
export interface CopyInput {
|
|
16
15
|
db: CanvasDb;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
SELECT s.${s(a)}::text AS source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${o.map(
|
|
3
|
-
FROM (SELECT * FROM ${
|
|
1
|
+
var D=Object.defineProperty;var i=(r,n)=>D(r,"name",{value:n,configurable:!0});import{zstdCompressSync as F,zstdDecompressSync as U}from"node:zlib";import{BODIES_TABLE as C,COPIED_TABLES as H,KEY_MAPPED_TABLES as L}from"../bundle/layout.js";import{q as s,rowKey as x,topologicalOrder as j}from"./catalog.js";import{fillEnvironments as v}from"./prepare.js";import{ImportLaneError as w}from"./stage.js";const A=i((r,n)=>`${s(r)}.${s(n)}`,"sq"),W=i(r=>F(Buffer.from(JSON.stringify(r))),"encodeKeys"),q=i(r=>JSON.parse(U(r).toString("utf8")),"decodeKeys"),M=new Map;async function z(r){const n=await r.prepare("SELECT run_id FROM import_runs WHERE state = 'committed' OR (state = 'failed' AND committed_at IS NOT NULL)").all(),p=new Set;for(const{run_id:u}of n){let m=M.get(u);if(m===void 0){const E=await r.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = 'nodes'").get(u);if(E===void 0)continue;m=new Set(q(E.inserted_keys).map(O=>O[0])),M.set(u,m)}for(const E of m)p.add(E)}return p}i(z,"nodesAwaitingVerify");const B=i(r=>j(r,H),"copyOrder");async function X(r){const{db:n,runId:p,schema:u,target:m,catalog:E,source:O}=r,d=i(e=>A(u,e),"S"),c=i(e=>A(m,e),"T"),_={inserted:{},mapped:{}},R=i(async(e,a)=>{_.inserted[e]=a.length,await n.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(p,e,W(a))},"manifest");for(const[e,a]of Object.entries(L)){const o=E.tables.get(e).columns.filter(l=>l!==a),T=await n.prepareUncached(`WITH src AS MATERIALIZED (
|
|
2
|
+
SELECT s.${s(a)}::text AS source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${o.map(l=>`s.${s(l)}`).join(", ")}
|
|
3
|
+
FROM (SELECT * FROM ${d(e)} ORDER BY ${s(a)}::bigint) s),
|
|
4
4
|
ins AS (INSERT INTO ${c(e)} (${s(a)}, ${o.map(s).join(", ")}) SELECT target_key, ${o.map(s).join(", ")} FROM src RETURNING 1),
|
|
5
5
|
km AS (INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) SELECT ?, ?, source_key, target_key::text FROM src RETURNING target_key)
|
|
6
|
-
SELECT target_key FROM km ORDER BY target_key::bigint`).all(c(e),a,
|
|
7
|
-
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(
|
|
8
|
-
ORDER BY ${
|
|
6
|
+
SELECT target_key FROM km ORDER BY target_key::bigint`).all(c(e),a,O.installId,e);await R(e,T.map(l=>[l.target_key]))}await n.prepareUncached(`UPDATE ${d("review_comments")} c SET created_seq = m.target_key::bigint FROM import_key_map m
|
|
7
|
+
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(O.installId);const N=B(E);for(const e of N){if(e in L)continue;if(e==="profiles"){if(N.indexOf("identities")>N.indexOf("profiles"))throw new w("copy","bundle_invalid","identities must be copied before profiles");await v(n,u,m,O,r.person)}const a=E.tables.get(e),S=Number((await n.prepareUncached(`SELECT count(*) AS n FROM ${d(e)}`).get()).n);if(S===0){_.inserted[e]=0;continue}const o=x(a),T=a.columns.filter(t=>!a.identity.includes(t)),l=a.identity.length>0?a.identity.map(t=>`s.${s(t)}`).join(", "):o.map(t=>`s.${s(t)}`).join(", ");let h=T.map(t=>`s.${s(t)}`),g="";if(e==="messages"){const t=`NOT EXISTS (SELECT 1 FROM ${c("messages")} t WHERE t.message_id = s.message_id)`,f=Number((await n.prepareUncached(`SELECT count(*) AS n FROM ${d("messages")} s WHERE ${t}`).get()).n);if(g=` WHERE ${t}`,f===0){_.inserted[e]=0,await R(e,[]);continue}const b=Number((await n.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(f)).seq);h=T.map($=>$==="seq"?`${b-f} + row_number() OVER (ORDER BY s.seq)`:`s.${s($)}`)}const k=o.map(t=>`${s(t)}::text`).join(", "),y=a.primaryKey.length===0;y&&(g=` WHERE NOT EXISTS (SELECT 1 FROM ${c(e)} t WHERE ${o.map(t=>`t.${s(t)} IS NOT DISTINCT FROM s.${s(t)}`).join(" AND ")})`);const I=await n.prepareUncached(`INSERT INTO ${c(e)} (${T.map(s).join(", ")}) SELECT ${h.join(", ")} FROM ${d(e)} s${g}
|
|
8
|
+
ORDER BY ${l}${y?"":` ON CONFLICT (${o.map(s).join(", ")}) DO NOTHING`} RETURNING ${k}`).all();if(e===C){const t=await n.prepareUncached(`SELECT s.hash FROM ${d(e)} s JOIN ${c(e)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();if(t.length>0)throw new w("copy","unique_conflict",`the target holds other text under body ${t[0].hash}; its boot repair has not rekeyed that row`,{table:e,hashes:t.map(f=>f.hash)})}e===C?_.inserted[e]=I.length:await R(e,I.map(t=>Object.values(t))),_.mapped[e]=S-I.length}await n.prepareUncached(`DELETE FROM ${c("charge_totals")} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${d("charges")})`).run(),await n.prepareUncached(`INSERT INTO ${c("charge_totals")} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
9
9
|
SELECT month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, ''), COALESCE(SUM(usd), 0), COALESCE(SUM(billed_usd), 0)
|
|
10
|
-
FROM ${c("charges")} WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${
|
|
11
|
-
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,a]of[["object",
|
|
10
|
+
FROM ${c("charges")} WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${d("charges")})
|
|
11
|
+
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,a]of[["object",r.idMap.object],["grant",r.idMap.grant],["kind",r.idMap.kind]])for(const[S,o]of a)await n.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(p,e,S,o);for(const e of r.pathMap)await n.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, 'path', ?, ?) ON CONFLICT DO NOTHING").run(p,e.from,e.to);return await n.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(),p),_}i(X,"copyRows");export{B as copyOrder,X as copyRows,q as decodeKeys,W as encodeKeys,z as nodesAwaitingVerify};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { RunDueCronOptions } from './passes.js';
|
|
2
2
|
/** Recover leases from prior daemon instances. Verify launch identity, not pid liveness: a reboot can recycle the pid, and killing its new owner would signal a stranger. */
|
|
3
|
-
export declare function recoverStaleCronLeases(now: number, options?: RunDueCronOptions): Promise<void>;
|
|
3
|
+
export declare function recoverStaleCronLeases(now: number, options?: Pick<RunDueCronOptions, 'register'>): Promise<void>;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export interface RunDueCronOptions {
|
|
2
2
|
/** Registers settlement work for graceful-teardown draining. */
|
|
3
3
|
register?: (work: Promise<void>) => void;
|
|
4
|
+
/** Nodes of a committed, not yet `done` import run: a cron anchored on one does not fire. */
|
|
5
|
+
held: ReadonlySet<string>;
|
|
4
6
|
}
|
|
5
7
|
export declare function expireDueCrons(nowIso: string): Promise<void>;
|
|
6
8
|
export declare function applyOverlapPolicies(now: number, nowIso: string): Promise<void>;
|
|
@@ -37,4 +37,4 @@ export declare function startCron(c: Cron, opts: {
|
|
|
37
37
|
* broker slot ledger is the one admission gate, so such a run's node is born
|
|
38
38
|
* or revived frozen at the cap and the node-lifecycle tick starts it when a
|
|
39
39
|
* slot frees. The cron itself always fires and settles. */
|
|
40
|
-
export declare function runDueCrons(now: number, options
|
|
40
|
+
export declare function runDueCrons(now: number, options: RunDueCronOptions): Promise<Promise<void>[]>;
|
package/dist/daemon/cron-run.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var q=Object.defineProperty;var i=(e,f)=>q(e,"name",{value:f,configurable:!0});import{randomUUID as N}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as H,formatCronOutputHead as O}from"./cron/capture.js";import{clearLiveRun as
|
|
2
|
-
${F}`.trim().slice(0,H)},lease:"release"}).then(o,r);return}ae(e,{runId:t,outOfBand:s,startedAtIso:u,startedAtMs:d,finishedAtMs:Date.now(),code:a.exitCode,timedOut:a.timedOut,processError:a.processError,stdoutHead:O(a.stdout,a.stdoutTruncated),stderrHead:O(a.stderr,a.stderrTruncated),stdoutSha256:a.stdoutSha256,wasReplaced:y,wasSelfCanceled:$}).then(o,r)},r)},"settleCommand");if(!await fe(e.cron_id,M,u,n.pid)&&!R.selfCanceled){
|
|
1
|
+
var q=Object.defineProperty;var i=(e,f)=>q(e,"name",{value:f,configurable:!0});import{randomUUID as N}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as H,formatCronOutputHead as O}from"./cron/capture.js";import{clearLiveRun as h,cronDaemonInstanceId as M,ensureCronOwnerLease as Y,registerLiveRun as z}from"./cron/live-runs.js";import{closeCronExecution as G,openCronExecution as J}from"./cron/run-socket.js";import{appProcessSandboxed as K}from"../core/spaces/process.js";import{nodeAgentDir as Q}from"../core/canvas/paths.js";import{uidForApp as V}from"../core/spaces/users.js";import{buildArmedRunContext as W}from"./cron/armed-context.js";import{ensureCronFolder as X}from"./cron/folders.js";import{fireOnMachine as Z,machineEnvironmentOfCron as j,machineLinkLive as ee}from"./cron/machine-fire.js";import{advanceRecurrence as P}from"./cron/recurrence.js";import{checkCronFire as ne,cronPrincipalOf as te}from"./cron/authority.js";import{refusalError as re}from"../core/ledger/index.js";import{startRefusal as oe}from"../core/runtime/start-check.js";import{settleClosedRun as ae,settleUnspawnedRun as D}from"./cron/closed.js";import{settleRun as U}from"./cron/settle.js";import{applyOverlapPolicies as ie,expireDueCrons as se}from"./cron/passes.js";import{dueClockCrons as de,acquireCronRunLease as le,releaseCronRunLease as ue,attachCronRunPid as fe}from"../core/canvas/crons.js";import{emitEvent as me}from"../core/events/emit.js";import{runAppCommand as ce}from"../core/runtime/run-command.js";import{CRON_OUTPUT_HEAD_BYTES as Fe}from"./cron/capture.js";import{cronDaemonInstanceId as Ne,markSelfCanceledCronRun as Ye}from"./cron/live-runs.js";import{recoverStaleCronLeases as Ge}from"./cron/lease-recovery.js";function Pe(e,f){return B(e,f).settled}i(Pe,"executeCron");function B(e,f){const{outOfBand:s}=f;let l=i(()=>{},"admit");const m=new Promise(o=>{l=o}),g=new Promise((o,r)=>{let b=!1;const t=N();let x=i(()=>{},"undo");const S=i(d=>{if(x(),!b){r(d);return}b=!1,ue(e.cron_id,t).then(()=>r(d),u=>{me({level:"error",event:"cron.lease.release_failed",error:u,fields:{cron_id:e.cron_id}}),r(d)})},"fail");(async()=>{const d=Date.now(),u=new Date(d).toISOString(),E={runId:t,outOfBand:s,startedAtIso:u,startedAtMs:d},I=await j(e);if(I!==null&&!s&&!await ee(I)){o(null);return}if(await Y(),!await le(e.cron_id,M,u,s,t)){o(null);return}b=!0;let c=await ne(te(e));if(c.allowed){const n=await oe({grantee:e.grantee,sub:e.sub,grant_id:e.grant_id});n!==null&&(c={allowed:!1,reason:"limit_reached",message:re(n).message})}if(!c.allowed){try{if(!s&&e.recur!=null){const p=await P(e,d);if(p!==null)throw p}}catch(p){D(e,E,"run could not be armed",p).then(o,r);return}const n=Date.now();U(e,{outOfBand:s,outcome:{kind:"refused",reason:c.reason,message:c.message},record:{runId:t,startedAtIso:u,finishedAtMs:n,durationMs:n-d,exitCode:null,stdoutHead:null,stderrHead:`${c.reason}: ${c.message}`.slice(0,H)},lease:"release"}).then(o,r);return}if(I!==null){Z(e,{environmentId:I,runId:t,outOfBand:s,startedAtIso:u,startedAtMs:d},l).then(o,S);return}let v;try{if(e.isolated&&X(e.grantee,e.cron_id),{env:v}=await W(e,t),!s&&e.recur!=null){const n=await P(e,d);if(n!==null)throw n}}catch(n){D(e,E,"run could not be armed",n).then(o,r);return}let A=null,T=!1;const R={runId:t,replaced:!1,selfCanceled:!1,kill:i(()=>{A!==null?A():T=!0},"kill")};z(e.cron_id,R),x=i(()=>h(e.cron_id,t),"undo"),l();const w=K()?{executionId:t,kind:"cron",cronId:e.cron_id,fromExec:e.armed_from_exec,grantee:e.grantee,sub:e.sub,grantId:e.grant_id,scopes:e.scopes,originRunId:e.origin_run_id,isolated:e.isolated,anchor:e.anchor_node,uid:await V(e.grantee),rebuilt:!1,refusal:null}:null,_=i(()=>{w!==null&&G(t)},"closeExecution");x=i(()=>{h(e.cron_id,t),_()},"undo"),i(async()=>(w!==null&&await J(w,e.cwd,e.profile),ce({command:e.command,cwd:e.cwd,env:v,app:e.grantee,isolated:e.isolated,principal:{sub:e.sub,grantId:e.grant_id,scopes:e.scopes},...e.isolated?{folder:e.cwd}:{},...w!==null?{cron:{executionId:t,...e.anchor_node===null||e.isolated?{}:{anchorDir:Q(e.anchor_node,e.grantee)}}}:e.anchor_node===null||e.isolated?{}:{nodeId:e.anchor_node},timeoutMs:e.run_timeout_s*1e3,headBytes:H})),"launch")().then(async n=>{if(n.pid===null){h(e.cron_id,t),_(),n.completion.then(a=>{D(e,E,"run failed to spawn",a.processError??new Error("bash did not provide a process id")).then(o,r)},r);return}x=i(()=>{h(e.cron_id,t),_(),n.terminate()},"undo");let p=!1;const k=i(()=>{n.completion.then(a=>{const y=R.replaced,$=R.selfCanceled,C=w?.refusal??null;if(h(e.cron_id,t),_(),p){o(null);return}if(C!==null&&!y){const L=Date.now(),F=O(a.stderr,a.stderrTruncated);U(e,{outOfBand:s,outcome:{kind:"refused",reason:C.reason,message:C.message},record:{runId:t,startedAtIso:u,finishedAtMs:L,durationMs:L-d,exitCode:a.exitCode,stdoutHead:O(a.stdout,a.stdoutTruncated)||null,stderrHead:`${C.reason}: ${C.message}
|
|
2
|
+
${F}`.trim().slice(0,H)},lease:"release"}).then(o,r);return}ae(e,{runId:t,outOfBand:s,startedAtIso:u,startedAtMs:d,finishedAtMs:Date.now(),code:a.exitCode,timedOut:a.timedOut,processError:a.processError,stdoutHead:O(a.stdout,a.stdoutTruncated),stderrHead:O(a.stderr,a.stderrTruncated),stdoutSha256:a.stdoutSha256,wasReplaced:y,wasSelfCanceled:$}).then(o,r)},r)},"settleCommand");if(!await fe(e.cron_id,M,u,n.pid)&&!R.selfCanceled){p=!0,n.terminate(),k();return}A=n.terminate,T&&n.terminate(),k()},n=>{h(e.cron_id,t),_(),D(e,E,"run failed to spawn",n).then(o,r)}).catch(S)})().catch(S)});return g.then(l,l),{admitted:m,settled:g}}i(B,"startCron");async function Ue(e,f){const s=new Date(e).toISOString();await se(s),await ie(e,s);const l=[];for(const m of await de(s)){if(m.anchor_node!=null&&f.held.has(m.anchor_node))continue;const{admitted:g,settled:o}=B(m,{outOfBand:!1}),r=o.then(()=>{});r.catch(()=>{}),await g,l.push(r),f.register?.(r)}for(const m of l)m.catch(()=>{});return l}i(Ue,"runDueCrons");export{Fe as CRON_OUTPUT_HEAD_BYTES,Ne as cronDaemonInstanceId,Pe as executeCron,Ye as markSelfCanceledCronRun,Ge as recoverStaleCronLeases,Ue as runDueCrons,B as startCron};
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var ir=Object.defineProperty;var a=(e,l)=>ir(e,"name",{value:l,configurable:!0});import{applyBootSettings as ar}from"./boot-settings.js";import{startPeerOutbox as sr}from"./peer/outbox.js";import{reportMachineStatus as cr}from"../core/peer/directory.js";import{createPeerRelay as lr}from"./peer/relay-service.js";import{writeFileSync as dr,readFileSync as mr,rmSync as pr,mkdirSync as Re,existsSync as R,unlinkSync as Pe,chmodSync as Ee}from"node:fs";import{createServer as Y}from"node:http";import{dirname as fr}from"node:path";import{envCrtrdTcp as Ie,envDocumentPort as ur}from"../shared/env.js";import{openCanvasConversationStore as hr,serveCanvasConversationStore as wr}from"../core/canvas/sessions.js";import{installConversationStore as vr}from"../core/conversation-store/index.js";import{pollRunObservers as gr}from"./runs/observer.js";import{randomBytes as xe}from"node:crypto";import{apiSocketPath as De,crtrHome as Sr}from"../core/canvas/paths.js";import{activeAppUsers as yr}from"../core/spaces/users.js";import{ensureAppSpace as _r,ensureUserFiles as br}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as kr}from"./launcher-events.js";import{initializeEmptyLayout as Rr,layoutNeedsMigration as Pr,socketDir as Te}from"../core/layout.js";import{migrateLooseKeys as Er}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Ir}from"../core/profiles/relocate.js";import{getNode as xr,listNodesForSupervision as Ce,listParkedResidentsWithWakeMail as Dr,setFrozen as Le}from"../core/canvas/index.js";import{createApiServer as Tr,closeServer as $e}from"./api/server.js";import{Router as Cr}from"./api/router.js";import{healthRoutes as Lr}from"./api/handlers/health.js";import{createDocumentListener as $r}from"./api/document-listener.js";import{documentSecret as Ar}from"./api/document-secret.js";import{createAppListener as Nr}from"./api/app-listener.js";import{registerMachineEnvironment as Mr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Gr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Or,resolvePerson as Fr,retireLocalPerson as Br,setPersonId as Hr}from"../core/canvas/person.js";import{backfillNodeApps as Ae,runPermissionsBoot as jr}from"../core/permissions/boot.js";import{startRunNotices as zr}from"./run-notices.js";import{startGrantEffects as Ur}from"./reconcilers/grant-effects.js";import{syncPackages as qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Wr}from"../core/model-auth/activations.js";import{createGrantSync as Jr,GRANT_SYNC_INTERVAL_S as Ne}from"../core/grants/sync.js";import{sweepSandboxes as Kr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Vr}from"./cron/run-socket.js";import{hasSyncedGrants as Yr}from"../core/grants/mirror.js";import{readConfig as de}from"../core/config.js";import{reconcileUndeliveredTickets as Qr}from"./human/sweep.js";import{resetHandedOffDeliveries as Xr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as Zr}from"../core/canvas/daemon-actions.js";import{sweepReviews as et}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as rt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as tt}from"./supervise-cadence.js";import{createResumeDetector as nt}from"./resume-detector.js";import{setFatalFaultAnnouncer as ot}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as it}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as at}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as st}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ct}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as lt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as dt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as mt}from"./reconcilers/action-lane.js";import{endLiveExecution as pt,migrateLegacyExecutionIdentities as ft}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as ut}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ht}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as wt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as vt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as gt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as St}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as yt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as _t}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as bt}from"./reconcilers/ledger-r2.js";import{ImportLaneReconciler as kt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Rt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Pt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Et}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as It,subscribeImageBuilt as xt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Dt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Me,capturePidCommand as Tt,captureTeardownSnapshot as Ge,isPidAlive as Ct,isAnyPidAlive as Oe,killProcessTreePids as Fe}from"../core/canvas/pid.js";import{bindFleet as Lt,boundFleet as $t}from"../core/runtime/fleet.js";import{bindDaemonControl as At,clearDaemonControl as Nt}from"./control.js";import{execDaemon as Mt,spawnDaemon as Gt}from"./manage.js";import{reconcileAndMigrateBoot as Ot}from"../core/canvas/boot.js";import{resolveInstallId as Ft}from"../core/canvas/install-id.js";import{setInstallId as Bt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ht,daemonOwnershipApplies as jt,daemonOwnershipClaimed as zt,releaseDaemonOwnership as Be}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Ut,closeAllDbs as pe,openDb as He,withCanvasWrite as fe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Wt,ensurePostgresHealthy as Jt,stopPostgres as Kt,withPostgresStartLock as Vt}from"./postgres/index.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Yt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Qt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Xt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Zt}from"../core/scoped-state/migrate-app-installs.js";import{publish as en,readBuiltinSnapshot as rn}from"../core/graph/package-publish.js";import{startRepoSync as tn}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as nn,reapStaleSpares as on}from"../core/runtime/warm-pool.js";import{DaemonFleet as an}from"./fleet.js";import{copyNodeFilesToRows as sn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as cn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as ln}from"../core/events/source.js";import{activateCanvasImport as dn,MigrationBlockedError as mn,runForcedCanvasImport as pn}from"../migrations/activation.js";import{adoptInstallPerson as fn,convertLegacyScopedStore as un,personStoresCopied as hn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as wn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as je,installPreludeSnapshot as vn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ze}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Ue}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ue}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Vi}from"../core/runtime/broker-ownership.js";function he(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(he,"brokerCommandEpoch");const gn=5e3,qe=150;async function Sn(e){const l=Me();if(l===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const u=Sr(),f=[];for(const[n,d]of l.processes){const y=d.command;if(d.zombie||!y.includes("broker-cli.js")||!ue(y,u)||he(y)===e)continue;const P=y.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||f.push({pid:n,nodeId:P})}let v=0;const s=[];for(const n of f){const d=Tt(n.pid);if(d===null||!d.includes("broker-cli.js")||!ue(d,u)||he(d)===e||d.trim().split(/\s+/).at(-1)!==n.nodeId)continue;const y=Ge(n.pid,null);if(!y.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:n.pid}):process.kill(n.pid,"SIGTERM")}catch{continue}v++,s.push({pid:n.pid,snap:y})}}const h=Date.now()+gn;for(;Date.now()<h&&s.some(n=>Oe(n.snap.tree.length>0?n.snap.tree:[n.pid]));)await new Promise(n=>setTimeout(n,qe));let g=0;for(const n of s){const d=n.snap.tree.length>0?n.snap.tree:[n.pid];Oe(d)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:n.pid}):Fe(d,"SIGKILL",n.snap.identities),g++)}g>0&&await new Promise(n=>setTimeout(n,qe));const p=Me();if(p===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const c=[];for(const[n,d]of p.processes){const y=d.command;d.zombie||!y.includes("broker-cli.js")||ue(y,u)&&he(y)!==e&&c.push(n)}if(c.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${c.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:f.length,sigtermed:v,sigkilled:g}})}a(Sn,"reapPriorEpochBrokers");const yn=5e3;async function _n(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[s]of l){const h=(await xr(s))?.status;(h==="active"||h==="idle")&&await Le(s,new Date().toISOString())}const u=l.map(([,s])=>({pid:s.pid,snap:Ge(s.pid,null),exited:s.handle.exited}));for(const s of u)if(!s.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:s.pid}):process.kill(s.pid,"SIGTERM")}catch{}const f=new Promise(s=>{setTimeout(s,yn).unref()});await Promise.allSettled(u.map(s=>Promise.race([s.exited.then(()=>{}),f])));const v=[];for(const s of u)Ct(s.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:s.pid}):Fe(s.snap.tree.length>0?s.snap.tree:[s.pid],"SIGKILL",s.snap.identities),v.push(s));await Promise.all(v.map(s=>s.exited));for(const[s]of l)await pt(s,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:u.length,sigkilled:v.length}})}a(_n,"teardownFleet");function We(){Re(fr(me()),{recursive:!0}),dr(me(),String(process.pid),"utf8")}a(We,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Je,"isMissingPathError");function Ke(e){const l=me();let u;try{u=mr(l,"utf8")}catch(f){if(Je(f))return;throw f}if(u.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{pr(l)}catch(f){if(Je(f))return;throw f}}a(Ke,"removeOwnedPidfileMirror");const bn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Q=new it;ot(e=>Q.handleFatalFault(e,!1));const kn=new at,Rn=new st,Pn=new ct,En=new lt,In=new dt,xn=new mt,Dn=new ht,Tn=new wt,Cn=new vt,Ln=new gt,$n=new yt,An=new _t,Nn=new bt,Mn=new kt,Gn=new Rt,On=new Pt,Fn=new Et,Bn=new It;async function Hn(e=Date.now(),l=bn){const u=$t(),f=await Q.runFleetPreamble(u);let v,s;try{const g=await Ce();v=g.filter(c=>c.status==="active"||c.status==="idle"),s=g.filter(c=>c.status==="done"||c.status==="canceled"||c.status==="dead");const p=new Set(s.map(c=>c.node_id));s.push(...(await Dr()).filter(c=>!p.has(c.node_id)))}catch(g){m({level:"error",event:"canvas.node_list.failed",error:g});return}await Q.run(e,{rows:v,fleet:u,lifecycle:l}),await kn.run(e,{rows:v});const h=await Rn.run(e,{rows:[...v,...s],fleet:u});await Pn.run(e),await Fn.run(e),await Bn.run(e,{lifecycle:l}),await En.run(e,{lifecycle:l}),await In.run(e,{lifecycle:l}),await xn.run(e,{lifecycle:l}),await Dn.run(e,{lifecycle:l}),await Tn.run(e,{lifecycle:l,fleet:u}),Cn.run(e,{lifecycle:l}),Ln.run(e,{lifecycle:l}),$n.run(e,{lifecycle:l}),An.run(e,{lifecycle:l}),Nn.run(e,{lifecycle:l}),Mn.run(e,{lifecycle:l}),await gr(),On.run(e,{fleet:u,lifecycle:l}),await Gn.run(e,{rows:v}),Q.warnIfSaturated({fleet:u,lifecycle:l,thresholds:f,frozen:h})}a(Hn,"superviseTick");function j(e){return e===void 0||e==="reconcile"}a(j,"roleRunsLanes");function N(e){return e===void 0||e==="api"}a(N,"roleServesRequests");const jn=66e4;function zn(e){const l=new Cr().registerAll(Lr(()=>null).filter(n=>n.pattern==="/healthz")),u=a((n,d)=>{const y=(n.url??"/").split("?")[0];if((n.method??"GET").toUpperCase()==="GET"&&y==="/healthz"){l.handle(n,d,null,{class:"person"});return}d.writeHead(404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),f=De();R(f)&&Pe(f);const v=Y(u),s=new Promise((n,d)=>{v.once("error",d),v.listen(f,()=>{v.off("error",d),Ee(f,384),n()})});let h,g=null;const p=e.tcp??Ie()??de("user").api.tcp;if(p!==void 0&&p!==""){const n=/^(.*):(\d+)$/.exec(p.trim());if(n===null||Number(n[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${p}`);const d=Y(u);d.on("error",y=>m({event:"api.server.failed",level:"error",error:y})),d.listen(Number(n[2]),n[1]===""?"0.0.0.0":n[1],()=>{g=`${n[1]===""?"0.0.0.0":n[1]}:${n[2]}`}),h=d}let c=!1;return{ready:s,tcpAddress:a(()=>g,"tcpAddress"),async close(n={}){if(!c){c=!0,await Promise.all([$e(v,new Set,n.graceMs),h===void 0?Promise.resolve():$e(h,new Set,n.graceMs)]);try{R(f)&&Pe(f)}catch{}}}}}a(zn,"createProbeServer");const Un="daemon is draining for shutdown and admits no new work";async function qn(e){Re(Te(),{recursive:!0,mode:493}),process.platform==="linux"&&Ee(Te(),493);const l=De();if(R(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const u=Y((p,c)=>{if(p.method==="GET"&&p.url==="/healthz"){c.writeHead(200,{"content-type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}c.writeHead(503,{"content-type":"application/json; charset=utf-8"}),c.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((p,c)=>{u.once("error",c),u.listen(l,()=>{u.off("error",c),p()})});let f;const v=e.tcp??Ie();if(v){const p=/^(.*):(\d+)$/.exec(v);if(!p||Number(p[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const c=Y(u.listeners("request")[0]);await new Promise((n,d)=>{c.once("error",d),c.listen(Number(p[2]),p[1],()=>{c.off("error",d),n()})}),f=c}We();let s;const h=a(()=>(s??=(async()=>{u.closeAllConnections(),f?.closeAllConnections(),await Promise.all([u,f].filter(p=>p!==void 0).map(p=>new Promise((c,n)=>p.close(d=>d?n(d):c())))),Ke(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),s),"cleanup"),g=a(()=>{h().then(()=>process.exit(0),p=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(p)}
|
|
2
|
-
`),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}
|
|
3
|
-
`)},"logPostgres"),u=!!process.env.CRTR_TEST_PG_URL,
|
|
4
|
-
`);else{const
|
|
5
|
-
`),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 g=h.claim;let
|
|
6
|
-
`);for(const
|
|
7
|
-
`);await
|
|
8
|
-
`)}else{const
|
|
9
|
-
`);for(const o of
|
|
10
|
-
`);for(const o of
|
|
11
|
-
`);for(const o of
|
|
12
|
-
`);for(const o of
|
|
13
|
-
`)}if(P=await
|
|
14
|
-
`)}}catch(
|
|
15
|
-
${
|
|
16
|
-
`),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await
|
|
17
|
-
`),process.exit(1)}process.exit(0)}
|
|
1
|
+
var ar=Object.defineProperty;var s=(e,c)=>ar(e,"name",{value:c,configurable:!0});import{applyBootSettings as sr}from"./boot-settings.js";import{startPeerOutbox as cr}from"./peer/outbox.js";import{reportMachineStatus as lr}from"../core/peer/directory.js";import{createPeerRelay as dr}from"./peer/relay-service.js";import{writeFileSync as mr,readFileSync as pr,rmSync as fr,mkdirSync as Re,existsSync as R,unlinkSync as Pe,chmodSync as Ee}from"node:fs";import{createServer as Y}from"node:http";import{dirname as ur}from"node:path";import{envCrtrdTcp as Ie,envDocumentPort as hr}from"../shared/env.js";import{openCanvasConversationStore as wr,serveCanvasConversationStore as vr}from"../core/canvas/sessions.js";import{installConversationStore as gr}from"../core/conversation-store/index.js";import{pollRunObservers as Sr}from"./runs/observer.js";import{randomBytes as xe}from"node:crypto";import{apiSocketPath as De,crtrHome as yr}from"../core/canvas/paths.js";import{activeAppUsers as _r}from"../core/spaces/users.js";import{ensureAppSpace as br,ensureUserFiles as kr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Rr}from"./launcher-events.js";import{initializeEmptyLayout as Pr,layoutNeedsMigration as Er,socketDir as Te}from"../core/layout.js";import{migrateLooseKeys as Ir}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as xr}from"../core/profiles/relocate.js";import{getNode as Dr,listNodesForSupervision as Ce,listParkedResidentsWithWakeMail as Tr,setFrozen as Le}from"../core/canvas/index.js";import{createApiServer as Cr,closeServer as $e}from"./api/server.js";import{Router as Lr}from"./api/router.js";import{healthRoutes as $r}from"./api/handlers/health.js";import{createDocumentListener as Ar}from"./api/document-listener.js";import{documentSecret as Nr}from"./api/document-secret.js";import{createAppListener as Mr}from"./api/app-listener.js";import{registerMachineEnvironment as Gr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markCloudRole as Fr,resolvePerson as Br,retireLocalPerson as Hr,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Ae,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as Ur}from"./run-notices.js";import{startGrantEffects as qr}from"./reconcilers/grant-effects.js";import{syncPackages as Wr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Kr,GRANT_SYNC_INTERVAL_S as Ne}from"../core/grants/sync.js";import{sweepSandboxes as Vr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Yr}from"./cron/run-socket.js";import{hasSyncedGrants as Qr}from"../core/grants/mirror.js";import{readConfig as de}from"../core/config.js";import{reconcileUndeliveredTickets as Xr}from"./human/sweep.js";import{resetHandedOffDeliveries as Zr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as et}from"../core/canvas/daemon-actions.js";import{sweepReviews as rt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as tt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as nt}from"./supervise-cadence.js";import{createResumeDetector as ot}from"./resume-detector.js";import{setFatalFaultAnnouncer as it}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as at}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as st}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ct}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as lt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as dt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as mt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as pt}from"./reconcilers/action-lane.js";import{endLiveExecution as ft,migrateLegacyExecutionIdentities as ut}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as ht}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as wt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as vt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as gt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as St}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as yt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as _t}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as bt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as kt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as Me}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Rt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Pt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Et}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as It}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as xt,subscribeImageBuilt as Dt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Tt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ge,capturePidCommand as Ct,captureTeardownSnapshot as Oe,isPidAlive as Lt,isAnyPidAlive as Fe,killProcessTreePids as Be}from"../core/canvas/pid.js";import{bindFleet as $t,boundFleet as At}from"../core/runtime/fleet.js";import{bindDaemonControl as Nt,clearDaemonControl as Mt}from"./control.js";import{execDaemon as Gt,spawnDaemon as Ot}from"./manage.js";import{reconcileAndMigrateBoot as Ft}from"../core/canvas/boot.js";import{resolveInstallId as Bt}from"../core/canvas/install-id.js";import{setInstallId as Ht}from"../core/runtime/nodes.js";import{claimDaemonOwnership as jt,daemonOwnershipApplies as zt,daemonOwnershipClaimed as Ut,releaseDaemonOwnership as He}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as qt,closeAllDbs as pe,openDb as je,withCanvasWrite as fe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Wt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Jt,ensurePostgresHealthy as Kt,stopPostgres as Vt,withPostgresStartLock as Yt}from"./postgres/index.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Xt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Zt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as en}from"../core/scoped-state/migrate-app-installs.js";import{publish as rn,readBuiltinSnapshot as tn}from"../core/graph/package-publish.js";import{startRepoSync as nn}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as on,reapStaleSpares as an}from"../core/runtime/warm-pool.js";import{DaemonFleet as sn}from"./fleet.js";import{copyNodeFilesToRows as cn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as ln}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as dn}from"../core/events/source.js";import{activateCanvasImport as mn,MigrationBlockedError as pn,runForcedCanvasImport as fn}from"../migrations/activation.js";import{adoptInstallPerson as un,convertLegacyScopedStore as hn,personStoresCopied as wn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as vn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as ze,installPreludeSnapshot as gn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as Ue}from"../core/scoped-state/person-rows.js";import{userScopeRoot as qe}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ue}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Qi}from"../core/runtime/broker-ownership.js";function he(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(he,"brokerCommandEpoch");const Sn=5e3,We=150;async function yn(e){const c=Ge();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const u=yr(),p=[];for(const[r,l]of c.processes){const y=l.command;if(l.zombie||!y.includes("broker-cli.js")||!ue(y,u)||he(y)===e)continue;const P=y.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||p.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of p){const l=Ct(r.pid);if(l===null||!l.includes("broker-cli.js")||!ue(l,u)||he(l)===e||l.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const y=Oe(r.pid,null);if(!y.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:y})}}const h=Date.now()+Sn;for(;Date.now()<h&&i.some(r=>Fe(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,We));let g=0;for(const r of i){const l=r.snap.tree.length>0?r.snap.tree:[r.pid];Fe(l)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):Be(l,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,We));const d=Ge();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const f=[];for(const[r,l]of d.processes){const y=l.command;l.zombie||!y.includes("broker-cli.js")||ue(y,u)&&he(y)!==e&&f.push(r)}if(f.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${f.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:v,sigkilled:g}})}s(yn,"reapPriorEpochBrokers");const _n=5e3;async function bn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Dr(i))?.status;(h==="active"||h==="idle")&&await Le(i,new Date().toISOString())}const u=c.map(([,i])=>({pid:i.pid,snap:Oe(i.pid,null),exited:i.handle.exited}));for(const i of u)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const p=new Promise(i=>{setTimeout(i,_n).unref()});await Promise.allSettled(u.map(i=>Promise.race([i.exited.then(()=>{}),p])));const v=[];for(const i of u)Lt(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):Be(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await ft(i,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:u.length,sigkilled:v.length}})}s(bn,"teardownFleet");function Je(){Re(ur(me()),{recursive:!0}),mr(me(),String(process.pid),"utf8")}s(Je,"writePidfile");function Ke(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ke,"isMissingPathError");function Ve(e){const c=me();let u;try{u=pr(c,"utf8")}catch(p){if(Ke(p))return;throw p}if(u.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{fr(c)}catch(p){if(Ke(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const kn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},Q=new at;it(e=>Q.handleFatalFault(e,!1));const Rn=new st,Pn=new ct,En=new lt,In=new dt,xn=new mt,Dn=new pt,Tn=new wt,Cn=new vt,Ln=new gt,$n=new St,An=new _t,Nn=new bt,Mn=new kt,Gn=new Rt,On=new Pt,Fn=new Et,Bn=new It,Hn=new xt;async function jn(e=Date.now(),c=kn){const u=At(),p=await Q.runFleetPreamble(u);let v,i,h;try{i=await Me();const d=(await Ce()).filter(r=>!i.has(r.node_id));v=d.filter(r=>r.status==="active"||r.status==="idle"),h=d.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const f=new Set(h.map(r=>r.node_id));h.push(...(await Tr()).filter(r=>!f.has(r.node_id)&&!i.has(r.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await Q.run(e,{rows:v,fleet:u,lifecycle:c,held:i}),await Rn.run(e,{rows:v,held:i});const g=await Pn.run(e,{rows:[...v,...h],fleet:u});await En.run(e,i),await Bn.run(e,i),await Hn.run(e,{lifecycle:c}),await In.run(e,{lifecycle:c,held:i}),await xn.run(e,{lifecycle:c}),await Dn.run(e,{lifecycle:c}),await Tn.run(e,{lifecycle:c}),await Cn.run(e,{lifecycle:c,fleet:u,held:i}),Ln.run(e,{lifecycle:c}),$n.run(e,{lifecycle:c}),An.run(e,{lifecycle:c}),Nn.run(e,{lifecycle:c}),Mn.run(e,{lifecycle:c}),Gn.run(e,{lifecycle:c}),await Sr(),Fn.run(e,{fleet:u,lifecycle:c}),await On.run(e,{rows:v}),Q.warnIfSaturated({fleet:u,lifecycle:c,thresholds:p,frozen:g})}s(jn,"superviseTick");function j(e){return e===void 0||e==="reconcile"}s(j,"roleRunsLanes");function N(e){return e===void 0||e==="api"}s(N,"roleServesRequests");const zn=66e4;function Un(e){const c=new Lr().registerAll($r(()=>null).filter(r=>r.pattern==="/healthz")),u=s((r,l)=>{const y=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&y==="/healthz"){c.handle(r,l,null,{class:"person"});return}l.writeHead(404,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=De();R(p)&&Pe(p);const v=Y(u),i=new Promise((r,l)=>{v.once("error",l),v.listen(p,()=>{v.off("error",l),Ee(p,384),r()})});let h,g=null;const d=e.tcp??Ie()??de("user").api.tcp;if(d!==void 0&&d!==""){const r=/^(.*):(\d+)$/.exec(d.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${d}`);const l=Y(u);l.on("error",y=>m({event:"api.server.failed",level:"error",error:y})),l.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=l}let f=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!f){f=!0,await Promise.all([$e(v,new Set,r.graceMs),h===void 0?Promise.resolve():$e(h,new Set,r.graceMs)]);try{R(p)&&Pe(p)}catch{}}}}}s(Un,"createProbeServer");const qn="daemon is draining for shutdown and admits no new work";async function Wn(e){Re(Te(),{recursive:!0,mode:493}),process.platform==="linux"&&Ee(Te(),493);const c=De();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const u=Y((d,f)=>{if(d.method==="GET"&&d.url==="/healthz"){f.writeHead(200,{"content-type":"application/json; charset=utf-8"}),f.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}f.writeHead(503,{"content-type":"application/json; charset=utf-8"}),f.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,f)=>{u.once("error",f),u.listen(c,()=>{u.off("error",f),d()})});let p;const v=e.tcp??Ie();if(v){const d=/^(.*):(\d+)$/.exec(v);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const f=Y(u.listeners("request")[0]);await new Promise((r,l)=>{f.once("error",l),f.listen(Number(d[2]),d[1],()=>{f.off("error",l),r()})}),p=f}Je();let i;const h=s(()=>(i??=(async()=>{u.closeAllConnections(),p?.closeAllConnections(),await Promise.all([u,p].filter(d=>d!==void 0).map(d=>new Promise((f,r)=>d.close(l=>l?r(l):f())))),Ve(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
|
|
2
|
+
`),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}s(Wn,"serveLayoutRefusal");async function Jn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Er())return Wn(e);Pr();const c=s(n=>{process.stderr.write(`[crtrd] ${n}
|
|
3
|
+
`)},"logPostgres"),u=!!process.env.CRTR_TEST_PG_URL,p=zt(e.role);Xt(j(e.role));const v=s(async()=>p?await jt(xe(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:xe(16).toString("hex")}},"claimOwnership"),{database:i,ownership:h}=u?{database:{url:await qt()},ownership:await v()}:await Yt(async()=>({database:await Jt({log:c,startLockHeld:!0}),ownership:await v()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
|
|
4
|
+
`);else{const n=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(w=>w!==void 0),a=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
|
|
5
|
+
`),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 g=h.claim;let d=null,f=null,r=null,l=null,y,P="";try{p&&await yn(g.token);for(const t of xr())process.stderr.write(`[crtrd] ${t}
|
|
6
|
+
`);for(const t of await Ir())process.stderr.write(`[crtrd] ${t}
|
|
7
|
+
`);await je(),await Wt(i.url,c);const n=e.role===void 0&&!await wn();let a=null;n&&(hn({kind:"user",root:qe()}),a=vn(qe())),e.role===void 0&&gn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await H.listen(i.url);const w=s(t=>{Ue(t).catch(o=>m({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(y=await H.subscribe(t=>{ze().includes(t)&&w(t)},{kinds:["settings"],onListenStart:s(()=>{for(const t of ze())w(t)},"onListenStart")}),e.role!==void 0&&Fr(),e.role!==void 0){let t;try{t=tn()}catch(b){m({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await fe(async b=>(await Ae(b),t===void 0?void 0:await rn(b,t,"release")));l=await fe(async b=>await en(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
|
|
8
|
+
`)}else{const t=await fe(async o=>(await Ae(o),await Zt(o)));for(const o of t.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
|
|
9
|
+
`);for(const o of t.invalid)process.stderr.write(`[crtrd] package file is not a document: ${o.path}: ${o.error}
|
|
10
|
+
`);for(const o of t.quarantined)process.stderr.write(`[crtrd] plugin "${o.name}" has a damaged ${o.file} (${o.reason}); ${o.movedTo!==void 0?`moved to ${o.movedTo}`:"left in place and skipped"}
|
|
11
|
+
`);for(const o of t.kinds.refused)process.stderr.write(`[crtrd] plugin "${o.plugin}" kind ${o.kind} not registered: ${o.message}
|
|
12
|
+
`);for(const o of t.kinds.invalid)process.stderr.write(`[crtrd] plugin "${o.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${o.error}
|
|
13
|
+
`)}if(P=await Bt(),Ht(P),e.role===void 0&&(d=await Br(),d!==null)){if(jr(d.id),await un(d.id),process.platform==="darwin"){const{readConfig:t,updateConfig:o}=await import("../core/config.js");if(t("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",ke=>{ke.paths??={},ke.paths.user_files??=b()})}}f=await Hr(),f.joinedFrom!==null&&await Ue(f.person),await sr(),r=await zr()}if(process.platform==="linux"&&R(D)&&(Rr(),await A({operation:"users.sync",users:await _r()})),p){await ht(g.token);const t=await cn();Object.values(t).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(t)}
|
|
14
|
+
`)}}catch(n){await H.close();try{if(p){const{released:a}=await He(g);if(!a)throw new Error("daemon ownership claim was not released")}await pe()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}let T=!0,X,z=Promise.resolve(),Z=!1,U,ee,re,C;const q=new Set;let te=!1,we=!1,E,L,ne,W=!1,J,M,G,O,F,oe,ie,ae,se;const Ye=ot();let I,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Qe=null;function Xe(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Xe,"startupBlock");function k(n){q.add(n),n.finally(()=>{q.delete(n)}).catch(()=>{})}s(k,"registerDetached");const ve={acceptsDetachedWork:s(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await nn(ve,je);async function Ze(){try{T=!1,Qt.close(),ee?.(),ee=void 0,re?.(),y?.(),re=void 0,ae?.(),ae=void 0,await H.close(),U!==void 0&&(clearInterval(U),U=void 0),G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),se?.(),se=void 0;let n;do n=z,await n;while(n!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(p&&await bn(C),await C.exitsSettled(),C.dispose()),ne!==void 0&&await ne.close(),L!==void 0&&!W&&(W=!0,await L.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,F!==void 0){const a=F;F=void 0,await a.stop()}if(M!==void 0){const a=M;M=void 0,await a.close()}if(J!==void 0){const a=J;J=void 0,await a.close()}if(te||(Ve(process.pid),te=!0),te&&!we){if(p){const{released:a}=await He(g);if(!a)throw new Error("daemon ownership claim was not released")}we=!0,await pe()}}finally{Mt(),process.off("SIGINT",ye),process.off("SIGTERM",_e),process.off("exit",be)}}s(Ze,"cleanupAttempt");const K=1e3;let ge=!1;function er(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return ge?{graceMs:K}:(ge=!0,_.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{rr()},K),{graceMs:K})}s(er,"requestHandover");async function rr(){try{await x()}catch(n){const a=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
15
|
+
${a}
|
|
16
|
+
`),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Gt();const n=await Ot({waitForJoinLock:!0});_.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
|
|
17
|
+
`),process.exit(1)}process.exit(0)}s(rr,"performHandover");function x(){if(E!==void 0)return E;const n=Ze();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function tr(){S={phase:"initializing",message:qn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:zn}))}s(tr,"drainApi");async function Se(n){try{n==="SIGTERM"&&e.role==="api"&&await tr(),await x(),await Vt({claimed:s(async()=>{try{return p&&await Ut()}finally{await pe()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
|
|
18
18
|
${w}
|
|
19
|
-
`),process.exit(1)}}
|
|
19
|
+
`),process.exit(1)}}s(Se,"handleSignal");function ye(){Se("SIGINT")}s(ye,"onSigint");function _e(){Se("SIGTERM")}s(_e,"onSigterm");function be(){x().catch(()=>{})}s(be,"onExit");async function ce(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(ce,"enqueue");async function V(){!T||Z||(Ye.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Kt({log:c}),await jn(Date.now(),ve)}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(V,"enqueueTick");let B=null;async function nr(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const n=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw B=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(nr,"admitStartup");async function or(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await fn({dryRun:n.dryRun});if(n.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 le(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(or,"repairMigrations");async function ir(){X=e.intervalMs??nt;const n=g.token;C=new sn({epoch:n,enqueue:ce}),$t(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const a=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Gr(a);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=tt()}catch{return}t!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),yt(),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&&Or(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await rt(),await Xr(),await Zr(Date.now()),await et(Date.now())}),await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ft(ut);t.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await Me();for(const o of await Ce())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Le(o.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Tt();for(const t of ln){const o=await t.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(Yr()),I){const t=s(()=>{k(I().catch(()=>{})),k(lr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Vr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),G=setInterval(t,Ne*1e3),G.unref(),se=cr({joined:!0,register:k})}await ce(async()=>{await an(),await on()}),U=setInterval(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},X),ee=await Dt(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))}),re=await H.subscribe(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>m({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(ir,"completeStartup");function le(){return Qe??=ir().catch(n=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),dn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...r}}),f!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:f.person,joined_from:f.joinedFrom,retired:f.retired,columns:f.columns}}),N(e.role)?J=await vr():gr(wr());const n=g.token;Nt({epoch:n,requestHandover:er,registerDetached:k,startupBlock:Xe,admitStartup:nr,repairMigrations:or}),Je(),L=N(e.role)?Cr({tcp:e.tcp}):Un(e),await L.ready;const a=hr()??de("user").document_port;if(N(e.role)){const t=Ar(a,Nr());try{await t.ready,ne=t}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=de("user").runtime;if(w?.issuer&&(I=Kr(w.issuer,k),w.unsandboxed===!0&&(F=dr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Wr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),O=setInterval(t,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await Ur()),j(e.role)&&(ie=Jr()),ae=await qr({serves:N(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(M=await Mr(w,async()=>await Qr(w.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await mn()}catch(t){if($=null,t instanceof pn)return S={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(kr(),await br("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Jn,"runDaemon");var Ki=Jn;export{zn as API_DRAIN_GRACE_MS,Qi as brokerCommandDeclaresCanvasHome,he as brokerCommandEpoch,Ki as default,j as roleRunsLanes,N as roleServesRequests,Jn as runDaemon,jn as superviseTick,bn as teardownFleet};
|
|
@@ -10,6 +10,8 @@ export interface BrokerSupervisionContext {
|
|
|
10
10
|
rows: readonly NodeRow[];
|
|
11
11
|
fleet: FleetRegistry;
|
|
12
12
|
lifecycle: DetachedWorkLifecycle;
|
|
13
|
+
/** Nodes of a committed, not yet `done` import run: no fatal-fault notice or park for them. */
|
|
14
|
+
held: ReadonlySet<string>;
|
|
13
15
|
}
|
|
14
16
|
type TreeSample = {
|
|
15
17
|
cpuPercent: number;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
var j=Object.defineProperty;var m=(a,e)=>j(a,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as P,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as x}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as re}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as ie,listUnnotifiedFatalFaultNodes as ae,markFaultNotified as se,readFault as G,readLiveTurn as F,recordFault as oe}from"../../core/canvas/recovery.js";import{errorClassFromFault as le}from"../../core/fault-classifier.js";import{nextFaultRetry as de}from"../../core/runtime/fault-recovery.js";import{publishNotice as L}from"../../core/runtime/close.js";import{openDb as O,withCanvasWrite as ce}from"../../core/canvas/db.js";import{getById as ue}from"../../core/graph/objects.js";import{watcherIdsOf as fe}from"../../core/graph/watches.js";import{headlessBrokerHost as pe}from"../../core/runtime/host.js";import{endExecution as me,liveExecutionForNode as C,requestExecutionStop as _e}from"../../core/canvas/executions.js";import{runnerForExecution as he}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as we,resetStaleExecutionMail as ke}from"../../core/canvas/deliveries.js";import{runningJobs as ge}from"../../core/graph/jobs.js";import{focusOf as ve}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ye}from"../api/viewer-presence.js";import{deliverLive as be}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Se}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Pe}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as $e}from"../../core/runtime/fleet.js";import{readConfig as Me}from"../../core/config.js";import{beginPendingPark as Ae,clearSupervisionMark as h,consumePendingPark as $,pendingParkIds as Ee,pendingParkStartedAt as Ne,readSupervisionMark as M,writeSupervisionMark as A}from"../park-pending.js";import{shouldParkAfterSummary as Re}from"../park-activity.js";import{applyParkEvent as E,noticeUnfinishedIdle as Ie,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Fe}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as Oe}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Ce,envTestUnattendedParkMs as De,parkSummaryGraceMs as We,envUnattendedParkMs as Be}from"../../shared/env.js";const R=ee(Z);async function Ge(a){return!await ie(a)&&((await Fe(a))?.trim()??"")!==""}m(Ge,"awaitsBirthTurn");async function q(a){const e=await C(a);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}m(q,"remoteExecutionOf");async function Le(a){return(await F(a))?.busy===!0}m(Le,"liveBusy");async function xt(a){const e=(await F(a))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}m(xt,"liveTurnProgressMs");function U(a,e){return e===null?null:`${a}:${e}`}m(U,"incarnationOf");async function S(a){const e=await F(a.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,r=a.launched_at===null||a.launched_at===void 0?Number.NaN:Date.parse(a.launched_at);return!Number.isFinite(t)||!Number.isFinite(r)||t<r?null:t}m(S,"busySinceForIncarnation");const W=3*6e4,Y=2e4,I=20*6e4,qe=2,Ue=5*6e4;function Ye(a,e){return a===null||a.parent!=null?!1:a.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&a.run_id===a.node_id}m(Ye,"settlesOnFatalProviderFault");function He(){const a=Be();if(a!==void 0)return a;const e=Me("user").lifecycle.unattendedParkMs;return Ce()?De()??e:e}m(He,"unattendedParkMsForDaemon");function H(){return We()}m(H,"parkSummaryGraceMsForDaemon");function V(a,e,t,r){return a!==!0||e!=="refresh"||t?"leave":r===null||r<W?"pending":"kill"}m(V,"yieldStallVerdict");function Ve(a){return!a.busy||a.quietForMs===null||a.quietForMs<I?"leave":a.cpuPercent===null||a.hasDescendants!==!1&&a.cpuPercent>qe?"pending":"wedged"}m(Ve,"wedgeVerdict");function K(a){const e=new Map,t=new Map;for(const r of a.split(`
|
|
2
|
-
`)){const i=r.trim();if(i==="")continue;const n=i.split(/\s+/);if(n.length<3)continue;const o=Number(n[0]),l=Number(n[1]),d=Number(n[2]);if(!Number.isFinite(o)||!Number.isFinite(l)||!Number.isFinite(d))continue;e.set(o,d);const s=t.get(l);s===void 0?t.set(l,[o]):s.push(o)}return{byPid:e,childrenOf:t}}m(K,"parsePsTree");function Ke(a,e){const{byPid:t,childrenOf:r}=K(a);if(!t.has(e))return null;let i=0;const n=[e],o=new Set;for(;n.length>0;){const l=n.pop();if(o.has(l))continue;o.add(l),i+=t.get(l)??0;const d=r.get(l);d!==void 0&&n.push(...d)}return i}m(Ke,"sumTreeCpu");function ze(a,e){const{byPid:t,childrenOf:r}=K(a);return t.has(e)?(r.get(e)??[]).length>0:null}m(ze,"treeHasDescendants");class Ft{static{m(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??(t=>this.readTreeSample(t)),this.signal=e.signal??((t,r)=>{if(process.platform==="linux"&&J(Q)){if(r!=="SIGTERM"&&r!=="SIGKILL")throw new Error(`unsupported launcher signal ${r}`);return X({operation:"stop",pid:t,signal:r}).then(()=>{})}process.kill(t,r)})}async runFleetPreamble(e){return $e()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const r=He();for(const i of await ae())await D.fresh(async()=>{try{await this.handleFatalFault(i)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:n})}});for(const i of t.rows){const n=i.node_id,o=t.fleet.get(n),l=o===void 0?await q(n):null;if(o===void 0&&l===null||i.status!=="active"&&i.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{o!==void 0?(await this.handleYieldStall(i,o,t.fleet,e),await this.handleWedgeDetection(i,o,t.fleet,e)):(await this.handleRemoteYieldStall(i,l,e),await this.handleRemoteWedge(i,l,e)),await this.handleUnattendedParking(n,await P(n),o?.pid??l.pid,l,e,t,r)}catch(d){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:d})}})}for(const i of await Ee())await t.fleet.has(i)||await $(i);await ke(e)}async parkResetCondition(e,t,r,i){if(t.pi_session_id==null||t.pi_pid!==r||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await O(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await G(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||de(n,i)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,r,i,n,o,l){if(await te(e)){await h(e,"unattended_since"),await $(e);return}if(t===null){await h(e,"unattended_since"),await $(e);return}const d=await this.parkResetCondition(e,t,r,n),s=await Ne(e);if(s!==void 0){if(n-s<H())return;const k=await $(e);if(k===void 0||(await h(e,"unattended_since"),!await Re(e,t,k)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await E(e,"park"),this.teardownBroker(e,i);return}if(d||await Le(e)||await Ge(e)){await h(e,"unattended_since");return}const p=await M(e,"unattended_since");if(p===void 0){await A(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),v=u!=="cancel"&&Oe(t.grantee??"app:terminal",n)?0:l;if(!(n-p<v)){if(await h(e,"unattended_since"),u==="release"){await E(e,u),w&&await Ie(e),this.teardownBroker(e,i);return}if(u==="cancel"){await E(e,u),this.teardownBroker(e,i);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await E(e,"park"),this.teardownBroker(e,i);return}o.lifecycle.acceptsDetachedWork()&&(await Ae(e,n),o.lifecycle.registerDetached(this.requestParkSummary(e,i)))}}async requestParkSummary(e,t){try{const r=await be(e,Te("park",{},Pe),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:r}})}catch(r){if(await $(e)===void 0)return;if(r instanceof Se){await E(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:r})}}async warnOverCapInTmux(e,t,r){const i=Date.now();if(i-this.lastOverCapWarnAt<Ue)return;this.lastOverCapWarnAt=i;const{warning:n,automaticReviveCap:o}=t,l=r.stalled+r.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:o,frozen_stalled:r.stalled,frozen_waiting_on_mail:r.waitingOnMail}});const d=l===0?"":` \u2014 ${l} frozen (${r.stalled} stalled, ${r.waitingOnMail} waiting on mail)`,s=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${o})${d} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await R("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
|
|
2
|
+
`)){const i=r.trim();if(i==="")continue;const n=i.split(/\s+/);if(n.length<3)continue;const o=Number(n[0]),l=Number(n[1]),d=Number(n[2]);if(!Number.isFinite(o)||!Number.isFinite(l)||!Number.isFinite(d))continue;e.set(o,d);const s=t.get(l);s===void 0?t.set(l,[o]):s.push(o)}return{byPid:e,childrenOf:t}}m(K,"parsePsTree");function Ke(a,e){const{byPid:t,childrenOf:r}=K(a);if(!t.has(e))return null;let i=0;const n=[e],o=new Set;for(;n.length>0;){const l=n.pop();if(o.has(l))continue;o.add(l),i+=t.get(l)??0;const d=r.get(l);d!==void 0&&n.push(...d)}return i}m(Ke,"sumTreeCpu");function ze(a,e){const{byPid:t,childrenOf:r}=K(a);return t.has(e)?(r.get(e)??[]).length>0:null}m(ze,"treeHasDescendants");class Ft{static{m(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??(t=>this.readTreeSample(t)),this.signal=e.signal??((t,r)=>{if(process.platform==="linux"&&J(Q)){if(r!=="SIGTERM"&&r!=="SIGKILL")throw new Error(`unsupported launcher signal ${r}`);return X({operation:"stop",pid:t,signal:r}).then(()=>{})}process.kill(t,r)})}async runFleetPreamble(e){return $e()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const r=He();for(const i of await ae())t.held.has(i)||await D.fresh(async()=>{try{await this.handleFatalFault(i)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:n})}});for(const i of t.rows){const n=i.node_id,o=t.fleet.get(n),l=o===void 0?await q(n):null;if(o===void 0&&l===null||i.status!=="active"&&i.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{o!==void 0?(await this.handleYieldStall(i,o,t.fleet,e),await this.handleWedgeDetection(i,o,t.fleet,e)):(await this.handleRemoteYieldStall(i,l,e),await this.handleRemoteWedge(i,l,e)),await this.handleUnattendedParking(n,await P(n),o?.pid??l.pid,l,e,t,r)}catch(d){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:d})}})}for(const i of await Ee())await t.fleet.has(i)||await $(i);await ke(e)}async parkResetCondition(e,t,r,i){if(t.pi_session_id==null||t.pi_pid!==r||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await O(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await G(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||de(n,i)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,r,i,n,o,l){if(await te(e)){await h(e,"unattended_since"),await $(e);return}if(t===null){await h(e,"unattended_since"),await $(e);return}const d=await this.parkResetCondition(e,t,r,n),s=await Ne(e);if(s!==void 0){if(n-s<H())return;const k=await $(e);if(k===void 0||(await h(e,"unattended_since"),!await Re(e,t,k)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await E(e,"park"),this.teardownBroker(e,i);return}if(d||await Le(e)||await Ge(e)){await h(e,"unattended_since");return}const p=await M(e,"unattended_since");if(p===void 0){await A(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),v=u!=="cancel"&&Oe(t.grantee??"app:terminal",n)?0:l;if(!(n-p<v)){if(await h(e,"unattended_since"),u==="release"){await E(e,u),w&&await Ie(e),this.teardownBroker(e,i);return}if(u==="cancel"){await E(e,u),this.teardownBroker(e,i);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await E(e,"park"),this.teardownBroker(e,i);return}o.lifecycle.acceptsDetachedWork()&&(await Ae(e,n),o.lifecycle.registerDetached(this.requestParkSummary(e,i)))}}async requestParkSummary(e,t){try{const r=await be(e,Te("park",{},Pe),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:r}})}catch(r){if(await $(e)===void 0)return;if(r instanceof Se){await E(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:r})}}async warnOverCapInTmux(e,t,r){const i=Date.now();if(i-this.lastOverCapWarnAt<Ue)return;this.lastOverCapWarnAt=i;const{warning:n,automaticReviveCap:o}=t,l=r.stalled+r.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:o,frozen_stalled:r.stalled,frozen_waiting_on_mail:r.waitingOnMail}});const d=l===0?"":` \u2014 ${l} frozen (${r.stalled} stalled, ${r.waitingOnMail} waiting on mail)`,s=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${o})${d} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await R("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
|
|
3
3
|
`).map(async u=>{if(u!=="")try{await R("tmux",["display-message","-C","-d","10000","-c",u,s],{encoding:"utf8",timeout:2e3})}catch{try{await R("tmux",["display-message","-c",u,s],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await pe.teardown(e):await this.stopRemote(t,"teardown")}async stopRemote(e,t){await _e(e.nodeId,{afterTurn:!1,reason:t});const r=await he(e.runner).stop(e,{reason:t});return r.confirmed?await me(e.executionId,{reason:t}):f({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:r.error}),r}async handleRemoteYieldStall(e,t,r){const i=e.node_id;if(e.intent!=="refresh"||await S(e)!==null){await h(i,"stall_noticed_at");return}const n=await M(i,"stall_noticed_at");if(n===void 0){await A(i,"stall_noticed_at",r);return}V(!0,e.intent,!1,r-n)==="kill"&&(await C(i))?.executionId===t.executionId&&(f({level:"warn",event:"broker.yield_stall.remote_stop",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},execution_id:t.executionId,elapsed_ms:r-n,grace_ms:W}}),await this.stopRemote(t,"yield_stall"))}async handleRemoteWedge(e,t,r){const i=e.node_id,n=await S(e);if(n===null){await h(i,"wedge_noticed_at");return}const o=r-n;if(o<I)return;const l=await P(i);if(l===null||(await C(i))?.executionId!==t.executionId||await S(l)!==n||await M(i,"wedge_noticed_at")===n)return;await A(i,"wedge_noticed_at",n);const d=Math.round(o/6e4);await this.reportWedge(i,{quietForMs:o,cpuPercent:null,hasDescendants:null,kickAttempted:!1,kicked:!1,kickSuppressionReason:"remote_no_process_evidence",pid:t.pid,label:`Child wedged \u2014 ${x(l)} (${i}) runs in a sandbox and is mid-turn but has shown NO engine progress for ${d}+ minutes. The daemon cannot see its processes there, so it did not stop the broker; if it is not running a long command, interrupt or close it.`})}async handleYieldStall(e,t,r,i){const n=e.node_id,o=U(t.pid,e.pi_pid_identity);if(e.intent!=="refresh"||await S(e)!==null||o===null){await h(n,"stall_noticed_at"),o!==null&&this.yieldTermedAt.delete(o);return}const l=await M(n,"stall_noticed_at");if(l===void 0){await A(n,"stall_noticed_at",i);return}const d={since:l,termedAt:this.yieldTermedAt.get(o)};if(V(!0,e.intent,!1,i-d.since)!=="kill")return;const s=await P(n);if(!(r.get(n)!==t||s?.pi_pid!==t.pid||s.pi_pid_identity!==e.pi_pid_identity||B(t.pid,e.pi_pid_identity)!=="alive"))if(d.termedAt===void 0){if(!await this.signalYieldStall(n,t.pid,"SIGTERM"))return;this.yieldTermedAt.set(o,i),d.termedAt=i,f({level:"warn",event:"broker.yield_stall.sigterm",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:i-d.since,grace_ms:W}})}else i-d.termedAt>=Y&&await this.signalYieldStall(n,t.pid,"SIGKILL")&&f({level:"warn",event:"broker.yield_stall.sigkill",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:i-d.termedAt,grace_ms:Y,stall_elapsed_ms:i-d.since}})}async signalYieldStall(e,t,r){try{return await this.signal(t,r),!0}catch(i){return f({level:"error",event:"broker.yield_stall.signal_failed",...c(e)?{node_id:e}:{},error:i,fields:{...c(e)?{}:{affected_node_id:e},pid:t,signal:r}}),!1}}async readTreeSample(e){try{const{stdout:t}=await R("ps",["-ax","-o","pid=,ppid=,pcpu="],{encoding:"utf8",timeout:2e3});if(typeof t!="string")return null;const r=Ke(t,e),i=ze(t,e);return r===null||i===null?null:{cpuPercent:r,hasDescendants:i}}catch{return null}}async handleWedgeDetection(e,t,r,i){const n=e.node_id,o=U(t.pid,e.pi_pid_identity),l=await S(e);if(l===null||o===null){await h(n,"wedge_noticed_at");return}const d=i-l,s=d>=I?await this.sampleTree(t.pid):null,p=await P(n),u=p===null?null:await S(p);if(r.get(n)!==t||p===null||p.pi_pid!==t.pid||p.pi_pid_identity!==e.pi_pid_identity||u!==l)return;const w=s?.cpuPercent??null,v=s?.hasDescendants??null;if(Ve({busy:!0,quietForMs:d,cpuPercent:w,hasDescendants:v})!=="wedged"||await M(n,"wedge_noticed_at")===l)return;await A(n,"wedge_noticed_at",l);const k=x(p),y=Math.round((d??I)/6e4),b=v??!0,T=!b&&B(t.pid,e.pi_pid_identity)!=="alive"?"pid_identity_unproven":null;let N=!1,_=!1,g;if(b)g=`Child wedged \u2014 ${k} (${n}) is alive and mid-turn but has shown NO engine progress for ${y}+ minutes and its process is near-idle. It will NOT recover on its own \u2014 read \`crtr canvas read wedged-child-on-runaway-bash\` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.`;else if(T!==null)g=`Child wedged \u2014 ${k} (${n}) is alive and mid-turn but has shown NO engine progress for ${y}+ minutes and it has no subprocess to kill (the engine itself stalled). The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.`;else{N=!0;try{await this.signal(t.pid,"SIGTERM"),_=!0,g=`Child wedged \u2014 ${k} (${n}) is alive and mid-turn but has shown NO engine progress for ${y}+ minutes and it has no subprocess to kill (the engine itself stalled). The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.`}catch(z){f({level:"error",event:"broker.wedge.signal_failed",...c(n)?{node_id:n}:{},error:z,fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,signal:"SIGTERM"}}),g=`Child wedged \u2014 ${k} (${n}) is alive and mid-turn but has shown NO engine progress for ${y}+ minutes and it has no subprocess to kill (the engine itself stalled). The daemon attempted SIGTERM to the broker, but the signal call failed.`}}await this.reportWedge(n,{quietForMs:d,cpuPercent:w,hasDescendants:b,kickAttempted:N,kicked:_,kickSuppressionReason:T,pid:t.pid,label:g})}async reportWedge(e,t){f({level:"error",event:"broker.wedge.detected",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},pid:t.pid,quiet_ms:t.quietForMs,cpu_percent:t.cpuPercent,has_descendants:t.hasDescendants,kick_attempted:t.kickAttempted,kicked:t.kicked,...t.kickSuppressionReason===null?{}:{kick_suppression_reason:t.kickSuppressionReason}}});try{await oe(e,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:t.label})}catch(r){f({level:"error",event:"broker.wedge.fault_record_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:r})}await L(e,"notice.crash",t.label,{reason:"child-wedged",child:e,quiet_ms:t.quietForMs,cpu_percent:t.cpuPercent,kick_attempted:t.kickAttempted,kicked:t.kicked,...t.kickSuppressionReason===null?{}:{kick_suppression_reason:t.kickSuppressionReason}})}async handleFatalFault(e,t=!0){const r=await G(e);if(r===null||r.retry.disposition!=="fatal"||r.link!=="pi\u2192provider"||r.notifiedSince===r.since)return;const i=await P(e),n=await q(e),o=i!==null?x(i):e,l=r.kind==="auth",d=(r.message.split(`
|
|
4
4
|
`)[0]??"").slice(0,200),s=r.providerError,p=s===void 0?"":` Provider: ${s.provider}/${s.model}.`+(s.status===void 0?"":` HTTP status: ${s.status}.`)+(s.errno===void 0?"":` Errno: ${s.errno}.`)+(s.code===void 0?"":` Code: ${s.code}.`)+(s.body===void 0?"":` Body: ${s.body.slice(0,200)}.`)+(s.ratelimit===void 0?"":` Rate limit: ${s.ratelimit.scope??"account"}${s.ratelimit.claim===void 0?"":` (${s.ratelimit.claim})`}${s.ratelimit.model===void 0?"":` on ${s.ratelimit.model}`}.`),u=r.kind==="context-overflow",w=Ye(i,typeof s?.code=="string"?s.code:void 0),v=u||w,k=u?`exceeded its model context window and is now dead. Shrink the task or loaded context, or choose a larger-context model before spawning it again. Error: ${d}`:`got a non-retryable ${r.kind} error and will NOT recover on its own; `+(w?"its terminal run has failed. ":"it stays alive, and waking it clears the fault as soon as one turn completes \u2014 a wake that hits the same cause fails again. "+(l?"Its provider credential is dead \u2014 re-authenticate (`/login`, or re-auth crtr); it recovers on its next wake once the auth reloads. ":""))+`Error: ${d}.${p}`,y=u?"failed":"hit a fatal provider fault",b=new Set((await ne(e)).map(_=>_.node_id)),T=await fe(await O(),await ue(await O(),e)),N=[{relation:"Child",recipients:T.filter(_=>b.has(_))},{relation:"Watched node",recipients:T.filter(_=>!b.has(_))}];f({level:"error",event:"fault.fatal.fanout",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},kind:r.kind,link:r.link,terminal_overflow:u,terminal_provider_fault:w}}),await ce(async()=>{for(const{relation:_,recipients:g}of N)g.length!==0&&await L(e,"notice.crash",`${_} ${y} \u2014 ${o} (${e}) ${k}`,{reason:u?"child-context-overflow":"child-fault-fatal",child:e,kind:r.kind,message:d,...s===void 0?{}:{provider_error:s}},"normal",null,g);await se(r.faultId),t&&v&&await re(e,"crash",{reason:u?"context_overflow":s?.code==="cap_exhausted"?"cap_exhausted":"provider_fatal",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:r.message,fault_kind:r.kind,error_class:le(r).class,...typeof s?.code=="string"?{provider_code:s.code}:{},...s?.payment===void 0?{}:{payment:s.payment}}}})}),t&&v&&this.teardownBroker(e,n).then(_=>{_.confirmed||f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:_.error??new Error("Broker teardown not confirmed")})},_=>f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:_}))}}export{Ft as BrokerSupervisionReconciler,qe as WEDGE_CPU_MAX_PERCENT,I as WEDGE_QUIET_MS,W as YIELD_STALL_GRACE_MS,H as parkSummaryGraceMsForDaemon,Ye as settlesOnFatalProviderFault,Ke as sumTreeCpu,ze as treeHasDescendants,He as unattendedParkMsForDaemon,Ve as wedgeVerdict,V as yieldStallVerdict};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type NodeRow } from '../../core/canvas/index.js';
|
|
2
2
|
export interface ControllerDeathContext {
|
|
3
3
|
rows: readonly NodeRow[];
|
|
4
|
+
/** Nodes of a committed, not yet `done` import run: their waits are verified rows and stay as imported. */
|
|
5
|
+
held: ReadonlySet<string>;
|
|
4
6
|
}
|
|
5
7
|
export declare class ControllerDeathReconciler {
|
|
6
8
|
run(now: number, ctx: ControllerDeathContext): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var r=(t,o)=>a(t,"name",{value:o,configurable:!0});import{liveControllerWaits as i}from"../../core/canvas/waits.js";import{operationIdContext as l}from"../../core/events/operation-id.js";import{enqueueControllerDeathNotice as c}from"../../core/feed/messages.js";class h{static{r(this,"ControllerDeathReconciler")}async run(o,n){for(const e of await i())n.held.has(e.nodeId)||await l.fresh(async()=>{await c(e.nodeId,e.controllerId)})}}export{h as ControllerDeathReconciler};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { DetachedWorkLifecycle } from './broker-supervision.js';
|
|
2
2
|
export interface CronLaneContext {
|
|
3
3
|
lifecycle: DetachedWorkLifecycle;
|
|
4
|
+
held: ReadonlySet<string>;
|
|
4
5
|
}
|
|
5
6
|
export declare class CronLaneReconciler {
|
|
6
7
|
run(now: number, ctx: CronLaneContext): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var
|
|
1
|
+
var c=Object.defineProperty;var o=(i,r)=>c(i,"name",{value:r,configurable:!0});import{emitEvent as a}from"../../core/events/emit.js";import{operationIdContext as n}from"../../core/events/operation-id.js";import{sweepOrphanCronFolders as l}from"../cron/folders.js";import{reapRebuiltCronExecutions as s}from"../cron/run-socket.js";import{recoverStaleCronLeases as f,runDueCrons as p}from"../cron-run.js";import{isDrained as d}from"../drain.js";import{runThrottledLane as m}from"./throttled-lane.js";class g{static{o(this,"CronLaneReconciler")}async run(r,t){await n.fresh(async()=>{try{await f(r,{register:o(e=>t.lifecycle.registerDetached(e),"register")})}catch(e){a({level:"error",event:"cron.lease_recovery.failed",error:e})}});try{await s()}catch(e){a({level:"error",event:"cron.execution.reap_failed",error:e})}try{await m("cron-folder-sweep","",r,6e4,6e4,async()=>{await l()})}catch(e){a({level:"error",event:"cron.folder.sweep_failed",error:e})}if(t.lifecycle.acceptsDetachedWork()&&!await d())try{await p(r,{register:o(e=>t.lifecycle.registerDetached(e),"register"),held:t.held})}catch(e){a({level:"error",event:"cron.run.failed",error:e})}}}export{g as CronLaneReconciler};
|
|
@@ -13,6 +13,9 @@ export declare function hasLiveObligation(nodeId: string): Promise<boolean>;
|
|
|
13
13
|
* Deferred mail deliberately does not count: it rides the node's next natural
|
|
14
14
|
* cycle rather than causing one. */
|
|
15
15
|
export declare function hasPendingWake(nodeId: string): Promise<boolean>;
|
|
16
|
+
/** The nodes of an import run that has committed but is not `done` (see `nodesAwaitingVerify`). The fleet does nothing to them: the supervision tick drops them from every
|
|
17
|
+
* lane that reads node rows, and the lanes that read other tables (deadlines, controller waits, structured requests, fatal faults, placement residue, retention) test this set. */
|
|
18
|
+
export declare function importedNodesHeld(): Promise<ReadonlySet<string>>;
|
|
16
19
|
/** The retention sweep's hold: a node with a launch claim, durable work that
|
|
17
20
|
* must wake it, or a person looking at it is never pruned, whatever its age.
|
|
18
21
|
* Unseen mail is deliberately not a hold: it never wakes a terminal node, and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=Object.defineProperty;var
|
|
1
|
+
var w=Object.defineProperty;var i=(t,e)=>w(t,"name",{value:e,configurable:!0});import{getNode as h,hasActiveLiveSubscription as m,hasLiveSubscriber as y,hasPendingCronWake as g}from"../../core/canvas/index.js";import{fullName as l}from"../../core/canvas/labels.js";import{hasLiveControllerWait as b,hasLiveObjectWait as k}from"../../core/canvas/waits.js";import{newestReportName as v}from"../../core/feed/reports.js";import{countTickets as x}from"../../core/canvas/attention.js";import{hasUnseenWakeMail as s}from"../../core/canvas/deliveries.js";import{readOutputRequest as $}from"../../core/runtime/output-result.js";import{focusOf as d}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as O}from"../api/viewer-presence.js";import{publishNotice as u}from"../../core/runtime/close.js";import{readFault as L}from"../../core/canvas/recovery.js";import{transition as f}from"../../core/runtime/lifecycle.js";import{openDb as N}from"../../core/canvas/db.js";import{nodesAwaitingVerify as W}from"../../core/import/load/copy.js";async function o(t){return await m(t)||await b(t)||await k(t)||await g(t)||await x(t)>0||await $(t)!==null}i(o,"hasLiveObligation");async function G(t){return await o(t)||await s(t)?!0:await c(t)}i(G,"hasPendingWake");async function A(){return await W(await N())}i(A,"importedNodesHeld");async function J(t){const e=await A();return async a=>e.has(a)||await t.isClaimed(a)||await o(a)||await c(a)}i(J,"retentionHold");async function c(t,e){return(e!==void 0?e.live!==null:await d(t)!==null)||await O(t)}i(c,"hasHumanViewer");async function K(t,e,a){return(await C(t,e,a)).event}i(K,"parkEvent");async function C(t,e,a){const r=i(p=>({event:p,heldOnlyBySubscriber:!1}),"held");if(await c(t,a)||await o(t))return r("release");const n=await L(t);return n?.link==="pi\u2192provider"&&n.retry.disposition==="fatal"?r("release"):e==="resident"?r(await s(t)?"release":"park"):await s(t)?r("release"):await y(t)?{event:"release",heldOnlyBySubscriber:!0}:r("cancel")}i(C,"parkVerdict");async function Q(t,e){const a=e==="cancel"?await f(t,e,{reason:"stranded"}):await f(t,e);if(e!=="park")return;const r=await v(t),n=r===null?`It left no report behind; \`crtr node inspect show ${t}\` shows where it stands.`:`Its latest report is where it left things: \`crtr canvas read ${r}\`.`;await u(t,"notice.close",`Resident concluded \u2014 ${l(a)} (${t}) had nothing left to wake it through its unattended grace, so its conversation was concluded. It submitted no final report. ${n} A message to it reopens it on a fresh cycle.`,{reason:"child-auto-done",child:t},"deferred")}i(Q,"applyParkEvent");async function X(t){const e=await h(t);e!==null&&await u(t,"notice.crash",`Child went idle unfinished \u2014 ${l(e)} (${t}) stopped without pushing a final report and has no wait that will wake it. Its engine was released; the cause is not recorded. \`crtr node inspect show ${t}\` shows where it stands; a message to it revives it.`,{reason:"child-idle-unfinished",child:t},"urgent")}i(X,"noticeUnfinishedIdle");export{Q as applyParkEvent,c as hasHumanViewer,o as hasLiveObligation,G as hasPendingWake,A as importedNodesHeld,X as noticeUnfinishedIdle,K as parkEvent,C as parkVerdict,J as retentionHold};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { type RowClaim } from './row-claim.js';
|
|
2
2
|
/** Enforce absolute spawn deadlines independently of the tick's live-row scan. */
|
|
3
3
|
export declare class NodeDeadlineReconciler {
|
|
4
|
-
run
|
|
4
|
+
/** `held`: nodes of a committed, not yet `done` import run, which the fleet leaves alone. */
|
|
5
|
+
run(now: number, held: ReadonlySet<string>): Promise<void>;
|
|
5
6
|
}
|
|
6
7
|
/** The one deadline terminalization path. Structured-request expiry reuses it
|
|
7
8
|
* even when a profile is paused, because its dedicated broker must not resume. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var
|
|
1
|
+
var m=Object.defineProperty;var c=(r,a)=>m(r,"name",{value:a,configurable:!0});import{dueNodeDeadlines as w,getNode as u}from"../../core/canvas/index.js";import{emitEvent as d}from"../../core/events/emit.js";import{isProfilePaused as p}from"../../core/profiles/manifest.js";import{operationIdContext as h}from"../../core/events/operation-id.js";import{errorClassFromFault as v}from"../../core/fault-classifier.js";import{publishNotice as x}from"../../core/runtime/close.js";import{readFault as y}from"../../core/canvas/recovery.js";import{requestBrokerTeardown as _}from"../../core/runtime/host.js";import{transition as D}from"../../core/runtime/lifecycle.js";import{withRowClaim as N}from"./row-claim.js";const O=6e4;class z{static{c(this,"NodeDeadlineReconciler")}async run(a,n){let t;try{t=await w(new Date(a).toISOString())}catch(e){d({level:"error",event:"node_deadline.scan_failed",error:e});return}for(const e of t)n.has(e.node_id)||p(e.profile_id)||e.deadline_at===null||e.deadline_at===void 0||h.fresh(()=>{N("nodes",e.node_id,O,i=>k(e.node_id,e.deadline_at,a,i)).catch(i=>{d({level:"error",event:"node_deadline.expire_failed",node_id:e.node_id,error:i,fields:{deadline_at:e.deadline_at}})})})}}async function k(r,a,n,t){await t?.assertOwned();const e=await u(r);if(e===null||e.status==="done")return;if(e.status==="canceled"||e.status==="dead"){await t?.assertOwned();const o=await _(r);if(!o.confirmed)throw o.error??new Error("broker teardown was not confirmed");return}const i=await y(r),l=i?.retry.disposition==="fatal"?i:null;let s;await t?.assertOwned();try{s=await D(r,"cancel",{reason:"deadline_exceeded",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",deadline:{deadline_at:a,elapsed_ms:n-Date.parse(a)},...l===null?{}:{message:l.message,fault_kind:l.kind,error_class:v(l).class}}}})}catch(o){throw d({level:"error",event:"node_deadline.terminalize_failed",node_id:r,error:o,fields:{deadline_at:a}}),o}if(s.status!=="canceled"||s.outcome_reason!=="deadline_exceeded")return;await t?.assertOwned();const f=await _(r);if(!f.confirmed)throw f.error??new Error("broker teardown was not confirmed");await t?.assertOwned();try{await x(r,"notice.deadline","child-deadline-exceeded",{reason:"child-deadline-exceeded",child:r})}catch(o){d({level:"error",event:"node_deadline.notify_failed",node_id:r,error:o,fields:{deadline_at:a}})}try{d({level:"error",event:"node_deadline.expired",node_id:r,fields:{deadline_at:a,elapsed_ms:n-Date.parse(a)}})}catch{}}c(k,"expireNodeDeadline");export{z as NodeDeadlineReconciler,k as expireNodeDeadline};
|
|
@@ -9,6 +9,8 @@ export interface StorageMaintenanceContext {
|
|
|
9
9
|
lifecycle: DetachedWorkLifecycle;
|
|
10
10
|
/** A live engine handle is the sweep's proof that a node is NOT disposable. */
|
|
11
11
|
fleet: FleetRegistry;
|
|
12
|
+
/** Nodes of a committed, not yet `done` import run: no residue reap, retention prune or context strip. */
|
|
13
|
+
held: ReadonlySet<string>;
|
|
12
14
|
}
|
|
13
15
|
/** Recurring storage cleanup. Each sweep's throttle and overlap guard is a `reconciler_leases` row (`runThrottledLane`),
|
|
14
16
|
* so two reconciler processes never run one sweep at once and a restart does not repeat a sweep early. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var S=Object.defineProperty;var f=(
|
|
1
|
+
var S=Object.defineProperty;var f=(_,e)=>S(_,"name",{value:e,configurable:!0});import{rm as R}from"node:fs/promises";import{closeFocusRow as I,getFocusById as A,listFocuses as N,listNodes as T}from"../../core/canvas/index.js";import{pruneExpiredIdempotencyKeys as P}from"../../core/runs/operations.js";import{getNode as C,lastActivityMs as p,listTerminalPlacementResidue as D,pruneExpiredCreateRequests as F,pruneNodes as x}from"../../core/canvas/canvas.js";import{lastContextStripMs as M,stripContextDir as L}from"../../core/canvas/context-strip.js";import{isAppRun as W}from"../../core/canvas/app-run.js";import{isSafeNodeId as d}from"../../core/canvas/paths.js";import{emitEvent as a}from"../../core/events/emit.js";import{operationIdContext as s}from"../../core/events/operation-id.js";import{listLivePanesAsync as b,tearDownNode as G}from"../../core/runtime/placement.js";import{reapStaleSpares as V}from"../../core/runtime/warm-pool.js";import{GroveInstanceSweepReconciler as k}from"./grove-instance-sweep.js";import{ManagedWorktreeSweepReconciler as O}from"./managed-worktree-sweep.js";import{compactRunEvents as q}from"../../core/runs/events.js";import{archiveExpiredRunEvents as U}from"../../core/events/run-event-chunks.js";import{blobStore as H}from"../../core/blobs/index.js";import{runThrottledLane as c}from"./throttled-lane.js";import{openDb as w}from"../../core/canvas/db.js";import{touchMachineEnvironment as Y}from"../../core/environments.js";import{retentionHold as y}from"./live-obligation.js";import{pruneMemoryReads as z}from"../../core/canvas/memory-reads.js";import{existsSync as K}from"node:fs";import{launcherRequest as $}from"../../launcher/client.js";import{LAUNCHER_SOCKET as B}from"../../launcher/spec.js";import{cachePassDue as Q}from"../../launcher/limits/policy.js";const X=10*6e4,l=60*1e3,g=60*1e3,h=5*6e4,Z=2,j=1440*6e4,J=2e3,ee=6e4;class Te{static{f(this,"StorageMaintenanceReconciler")}focusGcInFlight=!1;lastCachePassAt=null;cachePassInFlight=!1;worktreeSweep=new O;groveInstanceSweep=new k;async run(e,r){await this.reapDeadResidue(e,r.held),this.scheduleFocusGc(r),await this.gcWarmPool(e),await this.touchEnvironment(e),await this.gcCreateRequests(e),await this.gcViewerAttachments(e);try{await c("run-event-maintenance","",e,J,ee,async t=>{await U(await H(),e);const n=await q(e,t.state===null?0:Number(t.state));await t.save(String(n.cursor))})}catch(t){console.warn(`run event maintenance failed: ${String(t)}`)}await c("memory-read-prune","",e,60*6e4,10*6e4,async()=>{try{await z(e)}catch(t){console.warn(`memory-read log prune failed: ${String(t)}`)}}),await c("storage-analyze","",e,1440*6e4,10*6e4,async()=>{await(await w()).exec("ANALYZE")}),await this.sweepRetention(e,r),this.scheduleCachePass(e,r),this.scheduleContextStrip(e,r),this.worktreeSweep.run(e,r),this.groveInstanceSweep.run(e,r)}scheduleCachePass(e,r){this.cachePassInFlight||!Q(this.lastCachePassAt,e)||process.platform!=="linux"||!K(B)||r.lifecycle.acceptsDetachedWork()&&(this.lastCachePassAt=e,this.cachePassInFlight=!0,r.lifecycle.registerDetached($({operation:"cache.purge"}).then(()=>{}).catch(t=>{s.fresh(()=>{a({level:"warn",event:"app.cache.pass_failed",error:t})})}).then(()=>{this.cachePassInFlight=!1})))}msSinceTerminalActivity(e,r){const t=p(e);return t===0?Number.POSITIVE_INFINITY:r-t}async sweepRetention(e,r){r.lifecycle.acceptsDetachedWork()&&await c("retention-sweep","",e,h,h,()=>s.fresh(async()=>{try{const t=await x({ttlDays:Z,held:await y(r.fleet),removeDirs:f(n=>{r.lifecycle.registerDetached(Promise.all(n.map(o=>R(o,{recursive:!0,force:!0}))).then(()=>{}).catch(o=>{s.fresh(()=>{a({level:"error",event:"canvas.retention.failed",error:o})})}))},"removeDirs")});t.pruned.length>0&&a({level:"info",event:"canvas.retention.pruned",outcome:"succeeded",fields:{pruned_count:t.pruned.length}})}catch(t){a({level:"error",event:"canvas.retention.failed",error:t})}}))}scheduleContextStrip(e,r){r.lifecycle.acceptsDetachedWork()&&r.lifecycle.registerDetached(c("context-strip","",e,h,10*6e4,()=>this.stripFinishedContexts(e,r)).then(()=>{},t=>{a({level:"error",event:"canvas.context_strip.failed",error:t})}))}async stripFinishedContexts(e,r){const t=await y(r.fleet),n=f(async i=>i!==null&&["done","canceled","dead"].includes(i.status)&&(i.pi_pid??null)===null&&(i.frozen_at??null)===null&&!W(i)&&p(i)<e-j&&!await t(i.node_id),"eligible");let o=0,m=0;try{for(const i of await T({status:["done","canceled","dead"]})){if(!d(i.node_id)||!await n(i))continue;const v=await M(i.node_id);if(v!==null&&v>=p(i)||!await n(await C(i.node_id)))continue;let u;try{u=await L(i.node_id)}catch(E){s.fresh(()=>{a({level:"warn",event:"canvas.context_strip.node_failed",error:E,fields:{node_id:i.node_id}})});continue}u.removed.length>0&&(o+=1,m+=u.bytes)}}catch(i){s.fresh(()=>{a({level:"error",event:"canvas.context_strip.failed",error:i})})}o>0&&s.fresh(()=>{a({level:"info",event:"canvas.context_strip.completed",outcome:"succeeded",fields:{node_count:o,bytes:m}})})}async reapDeadResidue(e,r){let t;try{t=await D()}catch(n){s.fresh(()=>{a({level:"error",event:"residue.reap_scan.failed",error:n})});return}for(const n of t)if(!r.has(n.node_id)){try{if(this.msSinceTerminalActivity(n,e)<X)continue}catch(o){s.fresh(()=>{a({level:"error",event:"residue.reap.failed",...d(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})});continue}await s.fresh(async()=>{try{a({level:"info",event:"residue.reaped",...d(n.node_id)?{node_id:n.node_id}:{},fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}}),await G(n.node_id)}catch(o){a({level:"error",event:"residue.reap.failed",...d(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})}})}}scheduleFocusGc(e){if(this.focusGcInFlight||!e.lifecycle.acceptsDetachedWork())return;this.focusGcInFlight=!0;const r=this.gcStaleFocuses().finally(()=>{this.focusGcInFlight=!1});e.lifecycle.registerDetached(r)}async gcStaleFocuses(){let e;try{e=await N()}catch(t){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:t})});return}if(e.length===0)return;let r;try{r=await b()}catch(t){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:t})});return}if(r!==null)for(const t of e){if(t.pane===null||r.has(t.pane))continue;if(!await s.fresh(async()=>{try{return(await A(t.focus_id))?.pane!==t.pane||(a({level:"info",event:"focus.gc.removed",...d(t.node_id)?{node_id:t.node_id}:{},fields:{focus_id:t.focus_id,focus_node_id:t.node_id,pane:t.pane}}),await I(t.focus_id)),!0}catch(o){return a({level:"error",event:"focus.gc.failed",error:o}),!1}}))return}}async gcCreateRequests(e){await c("create-request-gc","",e,g,g,()=>s.fresh(async()=>{const r=await F(e),t=await P(e);t>0&&a({level:"info",event:"canvas.idempotency_keys.reaped",outcome:"succeeded",fields:{reaped_count:t}}),r>0&&a({level:"info",event:"canvas.create_requests.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async gcViewerAttachments(e){await c("viewer-attachment-gc","",e,l,l,()=>s.fresh(async()=>{const r=Number((await(await w()).prepare("DELETE FROM viewer_attachments WHERE expires_at <= ?").run(new Date(e).toISOString())).changes);r>0&&a({level:"info",event:"viewer_attachments.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async touchEnvironment(e){await c("environment-touch","",e,l,l,()=>s.fresh(async()=>{try{await Y(new Date(e).toISOString())}catch(r){a({level:"warn",event:"environment.touch.failed",error:r})}}))}async gcWarmPool(e){await c("warm-pool-gc","",e,l,l,()=>s.fresh(async()=>{const r=await V();r.length>0&&a({level:"info",event:"warm_pool.spares_reaped",outcome:"succeeded",fields:{reaped_count:r.length}})}))}}export{j as CONTEXT_STRIP_GRACE_MS,X as DEAD_REAP_GRACE_MS,h as RETENTION_SWEEP_INTERVAL_MS,Z as RETENTION_TTL_DAYS,Te as StorageMaintenanceReconciler};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Settles rows whose waiter disappeared and retries every incomplete durable effect. */
|
|
2
2
|
export declare class StructuredRequestReconciler {
|
|
3
|
-
run
|
|
3
|
+
/** `held`: nodes of a committed, not yet `done` import run; a request of theirs stays as imported. */
|
|
4
|
+
run(now: number, held: ReadonlySet<string>): Promise<void>;
|
|
4
5
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var s=(t,r)=>_(t,"name",{value:r,configurable:!0});import{withCanvasWrite as w}from"../../core/canvas/db.js";import{incompleteStructuredRequestEffects as m,pendingStructuredRequestsPast as p,settleStructuredRequestIn as q}from"../../core/canvas/structured-requests.js";import{emitEvent as c}from"../../core/events/emit.js";import{applySettlementEffects as u}from"../structured-requests/effects.js";import{withRowClaim as a}from"./row-claim.js";const d=6e4,l=s(t=>{c({level:"error",event:"structured_request.reconcile_failed",error:t})},"reportFailure");class E{static{s(this,"StructuredRequestReconciler")}async run(r,n){try{for(const e of await p(r))e.node_id!==null&&n.has(e.node_id)||a("structured_requests",e.request_id,d,async i=>{const o=await w(async f=>(await i.assertOwned(),await q(f,e.request_id,{intended:"expired",now:r})));o.changed&&o.row!==null&&await u(o.row,i)}).catch(l);for(const e of await m())e.node_id!==null&&n.has(e.node_id)||a("structured_requests",e.request_id,d,async i=>{await u(e,i)}).catch(l)}catch(e){c({level:"error",event:"structured_request.reconcile_failed",error:e})}}}export{E as StructuredRequestReconciler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.643",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
},
|
|
146
146
|
"license": "UNLICENSED",
|
|
147
147
|
"dependencies": {
|
|
148
|
-
"@north-light/identity": "0.3.
|
|
148
|
+
"@north-light/identity": "0.3.643",
|
|
149
149
|
"@earendil-works/chord": "1.1.0",
|
|
150
150
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
151
151
|
"@earendil-works/pi-ai": "1.1.0",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.643",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.643",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.643",
|
|
32
32
|
"cron-parser": "^5.6.0",
|
|
33
33
|
"esbuild": "^0.27.7",
|
|
34
34
|
"jose": "^6.2.12",
|
|
@@ -11956,17 +11956,17 @@
|
|
|
11956
11956
|
},
|
|
11957
11957
|
"packages/crouter-api": {
|
|
11958
11958
|
"name": "@north-light/api",
|
|
11959
|
-
"version": "0.3.
|
|
11959
|
+
"version": "0.3.643",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.643",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.643",
|
|
11970
11970
|
"license": "UNLICENSED",
|
|
11971
11971
|
"dependencies": {
|
|
11972
11972
|
"jose": "^6.2.1"
|
|
@@ -11974,21 +11974,21 @@
|
|
|
11974
11974
|
},
|
|
11975
11975
|
"packages/crouter-plugin": {
|
|
11976
11976
|
"name": "@north-light/plugin",
|
|
11977
|
-
"version": "0.3.
|
|
11977
|
+
"version": "0.3.643",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.643",
|
|
11981
|
+
"@north-light/identity": "0.3.643"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.643",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.643",
|
|
11990
|
+
"@north-light/identity": "0.3.643",
|
|
11991
|
+
"@north-light/plugin": "0.3.643",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|