@north-light/cli 0.3.650 → 0.3.652
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/clients/attach/chrome/ticket-panel.js +1 -1
- package/dist/clients/attach/viewer.js +487 -489
- package/dist/clients/inbox/controller.d.ts +6 -6
- package/dist/clients/inbox/controller.js +1 -1
- package/dist/clients/inbox/tui.js +1 -1
- package/dist/commands/human/queue.js +1 -1
- package/dist/commands/node/bash.js +3 -3
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/core/grants/sync.d.ts +3 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/convention.d.ts +1 -3
- package/dist/core/human/convention.js +2 -2
- package/dist/core/human/types.d.ts +0 -7
- package/dist/core/peer/client.d.ts +2 -0
- package/dist/core/peer/client.js +1 -1
- package/dist/core/peer/directory.d.ts +5 -1
- package/dist/core/peer/directory.js +1 -1
- package/dist/core/peer/token.d.ts +3 -3
- package/dist/core/peer/token.js +3 -2
- package/dist/daemon/api/handlers/bash-jobs.js +2 -2
- package/dist/daemon/crtrd.js +1 -1
- package/dist/daemon/manage.js +3 -3
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/dist/core/human/claim.d.ts +0 -23
- package/dist/core/human/claim.js +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var C=Object.defineProperty;var o=(t,e)=>C(t,"name",{value:e,configurable:!0});import{normalizeMachineId as m,rememberMachineName as g}from"./names.js";import{openDb as E}from"../canvas/db.js";import{directoryIssuer as $}from"../directory/issuer.js";import{runtimeClient as M}from"../grants/sync.js";import{crtrVersion as I}from"../../shared/crtr-version.js";import{installedPluginIds as R}from"../directory/join.js";import{peerTokens as S}from"./token.js";import{isCloudRole as A,requestPersonId as O}from"../canvas/person-state.js";const U=5*6e4,b=1e4;class u extends Error{static{o(this,"DirectoryError")}status;constructor(e,s){super(s),this.status=e,this.name="DirectoryError"}}function D(){return A()?O():void 0}o(D,"actingPerson");function T(t){if(!t||typeof t!="object")return null;const{kind:e,relay:s}=t;return e==="stable"?{kind:"stable"}:e==="relay"&&typeof s=="string"?{kind:"relay",relay:s}:null}o(T,"asReach");function k(t){const e=t,s=T(e?.reach);if(!e||typeof e.machine_id!="string"||typeof e.url!="string"||s===null)throw new u(502,"the directory answered a machine record with a missing machine_id, url or reach");return{machine_id:e.machine_id,name:typeof e.name=="string"?e.name:e.machine_id,url:e.url.replace(/\/$/,""),reach:s,crtr_version:typeof e.crtr_version=="string"?e.crtr_version:null,last_seen:typeof e.last_seen=="string"?e.last_seen:null,kind:e.kind==="device"?"device":"runtime",plugins:Array.isArray(e.plugins)?e.plugins.filter(f=>typeof f=="string"):[],...typeof e.is_default=="boolean"?{is_default:e.is_default}:{}}}o(k,"asMachine");function L(t,e){const s=new Map,f=new Map,y=o(n=>{let r=s.get(n??"");return r||(r=new Map,s.set(n??"",r)),r},"reachOf"),_=o((n,r)=>r===void 0?n:`${n}?user_id=${encodeURIComponent(r)}`,"forPerson");async function w(n,r,i){const l=t.issuer();if(l===null)throw new u(0,"this daemon has no directory");const c=l.replace(/\/$/,"");for(let a=0;;a++){let h;try{const d=await t.tokens.get(c);h=await t.fetch(`${c}${r}`,{method:n,headers:{authorization:`Bearer ${d}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:JSON.stringify(i)},signal:AbortSignal.timeout(b)})}catch(d){throw new u(0,`the directory could not be reached: ${d instanceof Error?d.message:String(d)}`)}if(h.status===401&&a===0){t.tokens.drop(c);continue}if(!h.ok)throw new u(h.status,`directory ${n} ${r} answered ${h.status}`);try{return await h.json()}catch{throw new u(502,`directory ${n} ${r} answered a body that is not JSON`)}}}return o(w,"call"),{async list(){const n=t.person?.(),r=await w("GET",_("/v1/machines",n));if(!Array.isArray(r))throw new u(502,"the directory answered a machine list that is not an array");const i=r.map(k),l=t.now(),c=y(n);for(const a of i)c.set(a.machine_id,{machine:a,at:l}),g(a.machine_id,a.name);return f.set(n??"",i),i},lastList(){return f.get(t.person?.()??"")??null},async reach(n){const r=m(n),i=t.person?.(),l=y(i),c=l.get(r);if(c&&t.now()-c.at<U)return c.machine;try{const a=k(await w("GET",_(`/v1/machines/${encodeURIComponent(r)}/reach`,i)));return l.set(r,{machine:a,at:t.now()}),g(a.machine_id,a.name),a}catch(a){if(a instanceof u&&a.status===404)return l.delete(r),null;if(c&&a instanceof u&&a.status===0)return c.machine;throw a}},async status(n){const r=e(),i=await w("PUT",`/v1/machines/${encodeURIComponent(r)}/status`,n);if(!i||typeof i.machine_id!="string"||typeof i.url!="string")throw new u(502,"the directory answered a status record with a missing machine_id or url");return{machine_id:i.machine_id,url:i.url.replace(/\/$/,""),reach:T(i.reach)}},invalidate(n){if(n===void 0){s.clear(),f.clear();return}const r=m(n);for(const i of s.values())i.delete(r)}}}o(L,"createDirectoryClient");function v(){return m(M().runtime)}o(v,"ownMachineId");const p=L({issuer:$,tokens:S,fetch:o((t,e)=>fetch(t,e),"fetch"),now:Date.now,person:D},v),q=o(()=>p.list(),"listMachines"),B=o(t=>p.reach(t),"machineReach"),x="machine_url";async function K(){return(await(await E()).prepare("SELECT value FROM runtime_state WHERE key = ?").get(x))?.value??null}o(K,"machineUrl");async function N(t){await(await E()).prepare("INSERT INTO runtime_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(x,t)}o(N,"storeMachineUrl");async function W(t=p){if($()===null)return null;try{M()}catch{return null}const e=await t.status({plugins:R(),crtr_version:I()});if(e.machine_id!==v())throw new u(502,"the directory answered a status for another machine");return await N(e.url),e}o(W,"reportMachineStatus");export{b as DIRECTORY_CALL_TIMEOUT_MS,u as DirectoryError,U as REACH_TTL_MS,D as actingPerson,L as createDirectoryClient,p as directory,q as listMachines,B as machineReach,K as machineUrl,m as normalizeMachineId,v as ownMachineId,W as reportMachineStatus};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { type DirectoryToken } from '../grants/sync.js';
|
|
2
2
|
export declare const REFRESH_BEFORE_EXPIRY_MS = 30000;
|
|
3
|
-
export type Mint = (issuer: string, audience?: string) => Promise<DirectoryToken>;
|
|
3
|
+
export type Mint = (issuer: string, audience?: string, sub?: string) => Promise<DirectoryToken>;
|
|
4
4
|
export interface TokenCache {
|
|
5
5
|
/** A token for `audience` (a peer machine URL or the relay origin), or for the directory's own `/v1` when omitted. */
|
|
6
|
-
get(issuer: string, audience?: string): Promise<string>;
|
|
6
|
+
get(issuer: string, audience?: string, sub?: string): Promise<string>;
|
|
7
7
|
/** Forget a token the far side refused (revoked key, clock skew); the next `get` mints a new one. */
|
|
8
|
-
drop(issuer: string, audience?: string): void;
|
|
8
|
+
drop(issuer: string, audience?: string, sub?: string): void;
|
|
9
9
|
clear(): void;
|
|
10
10
|
}
|
|
11
11
|
export declare function createTokenCache(mint?: Mint, now?: () => number): TokenCache;
|
package/dist/core/peer/token.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
${t??""}
|
|
1
|
+
var k=Object.defineProperty;var f=(o,p)=>k(o,"name",{value:p,configurable:!0});import{mintDirectoryToken as d}from"../grants/sync.js";const g=3e4;function y(o=d,p=Date.now){const c=new Map,a=new Map,i=f((e,t,n)=>`${e.replace(/\/$/,"")}
|
|
2
|
+
${t??""}
|
|
3
|
+
${n??""}`,"keyOf");return{async get(e,t,n){const r=i(e,t,n),s=c.get(r);if(s&&s.expires_at-g>p())return s.access_token;let l=a.get(r);return l||(l=(n===void 0?o(e,t):o(e,t,n)).then(_=>(c.set(r,_),_)).finally(()=>{a.delete(r)}),a.set(r,l)),(await l).access_token},drop(e,t,n){c.delete(i(e,t,n))},clear(){c.clear(),a.clear()}}}f(y,"createTokenCache");const w=y();export{g as REFRESH_BEFORE_EXPIRY_MS,y as createTokenCache,w as peerTokens};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var M=Object.defineProperty;var m=(o,t)=>M(o,"name",{value:t,configurable:!0});import{killBashJobObject as C,recordBashJobObject as D}from"../../../core/spaces/stop.js";import{readerFor as L}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as x,appProcessSandboxed as z}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as G}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as q}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as
|
|
1
|
+
var M=Object.defineProperty;var m=(o,t)=>M(o,"name",{value:t,configurable:!0});import{killBashJobObject as C,recordBashJobObject as D}from"../../../core/spaces/stop.js";import{readerFor as L}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as x,appProcessSandboxed as z}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as G}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as q}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as J}from"../../../core/canvas/node-agent-paths.js";import{getNode as S}from"../../../core/canvas/canvas.js";import{isBrokerLive as Q}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as W}from"../../../core/runtime/reopen.js";import{reviveNode as Y}from"../../../core/runtime/revive.js";import{checkStart as Z}from"../../../core/runtime/start-check.js";import{bashJobPaths as N,isBashJobProcessGroupAlive as V,isSafeBashJobId as O,readBashNiceness as tt,signalBashJob as et,stopBackgroundBashJob as ot}from"../../../core/bash-jobs.js";import{applyJobReport as nt,jobRow as it,ownerRunsRemotely as A,runningJobs as I,setJobDeadline as T,markJobQuietOk as rt}from"../../../core/graph/jobs.js";import{withCanvasWrite as E,openDb as h}from"../../../core/canvas/db.js";import{getById as B}from"../../../core/graph/objects.js";import{blobStore as P}from"../../../core/blobs/index.js";import{ApiError as a}from"../../../api/index.js";import{BASH_JOB_OUTPUT_DEFAULT_BYTES as at,BASH_JOB_OUTPUT_MAX_BYTES as st}from"../../../api/index.js";import{notFound as dt}from"../../../core/errors.js";import{freshChildNodeExecPath as ut}from"../../../core/runtime/branded-host.js";async function g(o){const t=o.params.id;if(t===void 0||!K(t))throw new a(400,"invalid_node_id",`invalid node id: ${JSON.stringify(t)}`);if(await S(t)===null)throw dt(`unknown node: ${t}`,{received:t});const e=o.params.jobId;if(e!==void 0){if(!O(e))throw new a(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return{nodeId:t,jobId:e,dir:await J(t)}}return{nodeId:t,dir:await J(t)}}m(g,"requireTarget");async function pt(o){const{nodeId:t,dir:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may start a job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.start requires a JSON body");const s=e;await q(t,s.expected_execution_id);const n=s.job_id,r=s.cwd,d=s.env;if(typeof n!="string"||!O(n)||typeof r!="string"||!d||typeof d!="object"||Array.isArray(d)||Object.entries(d).some(([l,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l)||typeof p!="string"))throw new a(400,"invalid_request","invalid job id, cwd or environment");const b=await S(t);if(await Z({grantee:b.grantee??"app:terminal",sub:b.sub,grant_id:b.grant_id}),!z())throw new a(400,"invalid_request","job.start is only used with the root launcher");const u=N(i,n);if(!(k(u.root,u.jobRun)||k(u.root,u.jobBg))||![u.cmdSh,u.jobLog].every(l=>k(u.root,l)))throw new a(404,"job_not_found","job was not prepared by this node");const f=H(u.dir,"job.starting");try{$(u.root,f,"")}catch(l){throw l.code==="EEXIST"?new a(409,"job_already_started","job was already started"):l}let _;try{const l=d,p=X("bash",l,r),j=await S(t),v=await ut();return _=await x({nodeId:t,app:j.grantee??"app:terminal",isolated:j.isolated,cwd:r,env:l,capture:!1,command:[p,"-c",G,"--",u.cmdSh,u.jobLog,u.jobExit,u.jobRun,u.jobDone,p,String(tt(i)),v,u.jobActivity]}),$(u.root,u.jobPgid,String(_.pid),384),$(u.root,u.jobPgidIdentity,`launcher:${_.pid}`,384),{status:201,body:{pid:_.pid}}}catch(l){if(_!==void 0)try{await _.stop()}catch(p){throw new AggregateError([l,p],`job ${n} launched but could not be recorded or stopped`)}try{U(u.root,f)}catch(p){if(p.code!=="ENOENT")throw p}throw l}}m(pt,"handleStart");async function lt(o){const{nodeId:t}=await g(o),i=Date.now(),e=await A(await h(),t);return{status:200,body:(await I(await h(),t)).map(n=>({job_id:n.jobId,command:n.command,purpose:n.purpose,started_at:new Date(n.startedAtMs).toISOString(),elapsed_ms:Math.max(0,i-n.startedAtMs),output_key:n.outputKey,deadline_at:n.deadlineAtMs===null?null:new Date(n.deadlineAtMs).toISOString(),pgid:n.pgid,pgid_alive:!e&&n.pgid!==null&&n.pgidIdentity!==null&&V(n.pgid,n.pgidIdentity)}))}}m(lt,"handleList");function R(o,t,i){const e=o.query.get(t);if(e===null)return;const s=Number(e);if(!/^[0-9]+$/.test(e)||!Number.isSafeInteger(s)||s<1||s>i)throw new a(400,"invalid_request",`${t} must be an integer from 1 to ${i}`);return s}m(R,"boundedQueryInt");async function ct(o){const{nodeId:t,jobId:i}=await g(o),e=R(o,"tail_lines",Number.MAX_SAFE_INTEGER),s=R(o,"max_bytes",st)??at,n=await h(),r=await B(n,i??"");if(r===null||r.type!=="job"||r.owner!==t||r.deleted_at!==null)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);const d=await it(n,r);if(d===null)throw new Error(`job object ${r.id} has no jobs row`);const b=await P(),u=await b.list(`${d.output_key}/`),w=[];let f=0,_=0,l=u.length;for(;l>0&&f<=s&&(e===void 0||_<=e+1);){const c=u[--l],y=await b.get(c);if(y===null)throw new Error(`job ${r.id} output chunk ${c} is listed but cannot be read`);w.unshift(y),f+=y.length;for(const F of y)F===10&&_++}let p=Buffer.concat(w),j=l>0;if(p.length>s){p=p.subarray(p.length-s);let c=0;for(;c<p.length&&(p[c]&192)===128;)c++;p=p.subarray(c),j=!0}let v=p.toString("utf8");if(e!==void 0){const c=v.split(`
|
|
2
2
|
`),y=c[c.length-1]===""?e+1:e;c.length>y&&(v=c.slice(c.length-y).join(`
|
|
3
|
-
`),j=!0)}return{status:200,body:{job_id:r.id,output:v,truncated:j}}}m(ct,"handleOutput");async function bt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.query.get("foreground")==="1"){if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await q(t,o.body?.expected_execution_id);const w=await ot(e,i,!0,t);if(w.kind==="missing")throw new a(404,"job_not_found",`no job ${i} for ${t}`);if(w.kind==="retired")throw new a(404,"job_not_found",`job ${i} for ${t} is no longer running`);if(w.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${i} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:i,signaled:w.signaled}}}const n=(await I(await
|
|
3
|
+
`),j=!0)}return{status:200,body:{job_id:r.id,output:v,truncated:j}}}m(ct,"handleOutput");async function bt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.query.get("foreground")==="1"){if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await q(t,o.body?.expected_execution_id);const w=await ot(e,i,!0,t);if(w.kind==="missing")throw new a(404,"job_not_found",`no job ${i} for ${t}`);if(w.kind==="retired")throw new a(404,"job_not_found",`job ${i} for ${t} is no longer running`);if(w.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${i} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:i,signaled:w.signaled}}}const n=(await I(await h(),t)).find(w=>w.jobId===i);if(n===void 0)throw new a(404,"job_not_found",`no running background job ${i} for ${t}`);const r=await A(await h(),t);if(!r&&(n.pgid===null||n.pgidIdentity===null))throw new a(409,"job_not_stoppable",`job ${i} reported no trusted process identity`);await W(t);const d=r?!0:await et(n.pgid,n.pgidIdentity,t);await C(i,async w=>{const f=await L(w,o);return f.class==="person"?f.person:f.class==="app"?f.app:f.node});const b=await S(t);if(b!==null&&!Q(b))try{await Y(t,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:t,job_id:i,signaled:d}}}m(bt,"handleStop");async function wt(o){const{nodeId:t,jobId:i,dir:e}=await g(o);if(i===void 0)throw new a(400,"invalid_request","a job id is required");if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may record its job");const s=o.body,n=N(e,i),r=s?.purpose,d=s?.deadline_at_ms;if(typeof s?.command!="string"||r!=null&&typeof r!="string"||d!=null&&!Number.isFinite(d))throw new a(400,"invalid_request","job.background requires command, and optionally purpose and deadline_at_ms");if(!await A(await h(),t)&&!k(n.root,n.jobBg))throw new a(404,"job_not_found",`job ${i} of ${t} is not backgrounded`);return{status:201,body:{id:(await D(t,i,{command:s.command,purpose:r??null,deadlineAtMs:d??null})).id}}}m(wt,"handleBackground");async function ft(o,t){if(t===void 0)throw new a(400,"invalid_request","a job id is required");const i=await B(await h(),t);if(i===null||i.type!=="job"||i.owner!==o)throw new a(404,"job_not_found",`no job ${t} for ${o}`);if(!(await I(await h(),o)).some(e=>e.jobId===t))throw new a(409,"job_not_running",`job ${t} for ${o} is no longer running`);return t}m(ft,"requireRunningJob");async function mt(o){const{nodeId:t,jobId:i}=await g(o);if(o.principal.class!=="broker"||o.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may report its job");const e=o.body;if(!e||typeof e!="object"||Array.isArray(e))throw new a(400,"invalid_request","job.report requires a JSON body");await q(t,e.expected_execution_id);const s=await B(await h(),i??"");if(s===null||s.type!=="job"||s.owner!==t)throw new a(404,"job_not_found",`no job ${String(i)} for ${t}`);if(!(await I(await h(),t)).some(d=>d.jobId===i))throw new a(409,"job_not_running",`job ${String(i)} for ${t} is no longer running`);const n=e.output;if(n!==void 0){if(!Number.isSafeInteger(n.seq)||n.seq<0||typeof n.data_base64!="string")throw new a(400,"invalid_request","output requires seq and data_base64");const d=await E(async b=>await b.prepare("SELECT output_key FROM jobs WHERE object = ?").get(i));await(await P()).put(`${d.output_key}/${String(n.seq).padStart(8,"0")}`,Buffer.from(n.data_base64,"base64"))}const r=e.activity;if(r!==void 0&&(!Number.isFinite(r.last_ms)||!Number.isFinite(r.sampled_ms)||!Array.isArray(r.files)))throw new a(400,"invalid_request","activity requires last_ms, sampled_ms and files");return await E(async d=>nt(d,i,{...typeof e.pgid=="number"?{pgid:e.pgid}:{},...typeof e.pgid_identity=="string"?{pgidIdentity:e.pgid_identity}:{},...typeof e.exit_code=="number"?{exitCode:e.exit_code}:{},...e.vanished===!0?{vanished:!0}:{},...r===void 0?{}:{activity:{lastActivityMs:r.last_ms,sampledAtMs:r.sampled_ms,files:r.files}}})),{status:204}}m(mt,"handleReport");async function ht(o){const{nodeId:t,jobId:i}=await g(o),e=await ft(t,i),s=o.body,n=s?.deadline_at_ms,r=s?.keep===!0;if(s?.quiet_ok!==!0&&!r&&!Number.isFinite(n))throw new a(400,"invalid_request","patch requires quiet_ok, keep or deadline_at_ms");if(r&&n!==void 0)throw new a(400,"invalid_request","keep and deadline_at_ms are exclusive");return await E(async d=>{s?.quiet_ok===!0&&await rt(d,e),r?await T(d,e,null):Number.isFinite(n)&&await T(d,e,n)}),{status:204}}m(ht,"handlePatch");const xt=[{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/background",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/report",handler:mt},{method:"PATCH",pattern:"/v1/nodes/:id/jobs/:jobId",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:pt},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:lt},{method:"GET",pattern:"/v1/nodes/:id/jobs/:jobId/output",handler:ct},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:bt}];export{xt as bashJobRoutes};
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -16,4 +16,4 @@ ${a}
|
|
|
16
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
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)}}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};
|
|
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())}),e.role===void 0&&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};
|
package/dist/daemon/manage.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as V}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as k,join as E}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as H,lstatSync as ee,mkdirSync as te,openSync as U,closeSync as j,fstatSync as K,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as
|
|
2
|
-
`).at(-1)??"";return JSON.parse(s)}o(R,"runDaemonEntry");function
|
|
3
|
-
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function
|
|
1
|
+
var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as V}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as k,join as E}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as H,lstatSync as ee,mkdirSync as te,openSync as U,closeSync as j,fstatSync as K,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as M}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as D,isPidAlive as f}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as G}from"./startup-policy.js";import{readMachineConfig as se}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ce}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ue}from"../core/canvas/paths.js";import{envNoDaemonAutostart as le}from"../shared/env.js";import{awaitJoinLockRelease as de,joinInProgress as pe,joinInProgressError as fe,joinLockHolder as me}from"../core/directory/join-lock.js";import{waitForDaemonAvailability as he}from"../api/index.js";import{localClient as we}from"../api/node-transport.js";const _e=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function O(){const e={...process.env};for(const t of _e)delete e[t];return e}o(O,"sanitizedDaemonEnv");function Ee(){for(let e=k(Z(import.meta.url));;e=k(e)){if(H(E(e,"bin","runtime-generation-manifest.mjs")))return e;if(k(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Ee,"generationRoot");async function A(){const e=Ee(),t=I(E(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(E(r(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,E(e,"src","daemon","crtrd-cli.ts")]}const n=I(E(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),c=a("daemon");if(!c.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${c.error}`);return[c.runtime.entryPath]}o(A,"resolveDaemonLaunch");function De(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(De,"daemonCommandDeclaresCanvasHome");function xe(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&De(a,t)&&n!==process.pid&&r.push(n);return r}o(xe,"findDaemonPids");function ye(e){const t=xe().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>f(n));)V("sleep",["0.1"]);for(const n of t)if(f(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(ye,"sweepStrayDaemons");async function et(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=M(),r=await A();return e(t,[t,...r,"--canvas-home",g()],O())}o(et,"execDaemon");async function R(e){const t=await A(),r=B(M(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:O()});let n="",a="";r.stdout.setEncoding("utf8").on("data",u=>{n+=u}),r.stderr.setEncoding("utf8").on("data",u=>{a+=u});const c=await new Promise((u,m)=>{r.once("error",m),r.once("close",p=>u(p))});if(c!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${c}`);const s=n.trim().split(`
|
|
2
|
+
`).at(-1)??"";return JSON.parse(s)}o(R,"runDaemonEntry");function tt(){return R(["export-sqlite"])}o(tt,"runDaemonExportSqlite");function rt(e,t){return R(["import-dump",e,t])}o(rt,"runDaemonImportDump");function nt(e){return R(["import-dump",e,"bodies"])}o(nt,"runDaemonBodiesDump");function ot(){return R(["import-dump","","install-id"])}o(ot,"runDaemonInstallId");const ge=3*6e4,z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return we({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function Se(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(Se,"probeErrorMessage");async function J(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=D()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(J,"probeDaemonServing");async function at(){try{return await J(),!0}catch{return!1}}o(at,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
|
|
3
|
+
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Re(e,t=G,r={},n="ready"){const a=r.readPidfile??D,c=r.isPidAlive??f,s=r.childExited,u=r.isDaemonServing,m=r.probeDaemonServing??(async w=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await J(w)}),p=r.probeDaemonHealth??L,x=r.sleepMs??$,y=r.now??Date.now;let i=null,l=null;return await he({windowMs:t,pollIntervalMs:N,now:y,sleep:x,retry:o(w=>w!==l,"retry"),probe:o(async w=>{const h=a();if(h===null||!c(h)){const d=s?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await m(w)}catch(d){throw d instanceof v&&(l=d),d}i=h;return}const _=await p(w);if(_.startup_phase==="prepared"){i=h;return}throw _.startup_phase==="blocked"?(l=new v(h,_.startup_blocked??"on-disk migration is blocked"),l):_.startup_phase==="ready"?(l=new F(h,_.startup_phase),l):new Error(`daemon ${h} is ${_.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),i===e?null:i}o(Re,"verifyDaemonStartup");async function ve(e,t=z,r={}){const n=r.readPidfile??D,a=r.isPidAlive??f,c=r.sleepMs??$,s=r.now??Date.now,u=s()+t;for(;s()<=u;){if(!a(e)&&n()!==e)return;await c(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(ve,"waitForDaemonExit");const Te=2e3,be=5e3;async function X(e,t=z,r={}){const n=r.isPidAlive??f,a=r.sleepMs??$,c=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await ve(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const s=c()+Te;for(;c()<=s;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(X,"stopDaemonProcess");async function it(){const e=D(),t=e!==null&&f(e),r=t&&await X(e)==="killed",n=ye(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(it,"stopAllDaemons");function ke(e,t,r=2048){let n;try{n=U(e,"r");const{size:a}=K(n),c=Math.max(t,a-r),s=a-c;if(s<=0)return"";const u=Buffer.alloc(s);return re(n,u,0,s,c),u.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{j(n)}catch{}}}o(ke,"readLogTailFrom");async function Ie(e={}){if(process.platform==="linux"&&H("/run/crtr/launcher.sock")&&!f(D()??-1)&&se()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=D();if(r!==null&&f(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:Se(i)}}te(g(),{recursive:!0});const n=await A().catch(i=>{throw new Y(i)});e.waitForJoinLock===!0&&await de(ge);const a=me();if(a!==null&&a!==process.pid&&e.ignoreJoinLock!==!0)throw fe(a);const c=E(g(),"crtrd.err"),s=U(c,"a"),u=(()=>{try{return K(s).size}catch{return 0}})();ae()===void 0&&oe();const m=B(M(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:O()});j(s);const p=m.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let x=null;m.once("exit",(i,l)=>{x={code:i,signal:l}}),m.unref();let y;try{y=await Re(p,G,{childExited:o(()=>x,"childExited"),childStderrTail:o(()=>ke(c,u),"childStderrTail")},t)}catch(i){const l=ce(ue())===p;if(x===null&&!l&&!(i instanceof v))try{await X(p,be)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(Ie,"spawnDaemon");function Me(){return le()||process.argv.includes("--no-autostart")}o(Me,"autostartDisabled");const Oe=5e3,Ae=6e4;let W=!1,S,T=0,b=0;function Ne(e){return Math.min(Oe*2**(e-1),Ae)}o(Ne,"autostartBackoffMs");function Pe(){S=void 0,T=0,b=0}o(Pe,"resetDaemonAutostart");function st(){return S}o(st,"daemonAutostartStartupFailure");function ct(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??Ie,n=e.now??Date.now;if(!Me()&&!pe()&&!W&&!(n()<b)){if(t()){Pe();return}S=void 0,W=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof Y)&&(S=a.message),T+=1,b=n()+Ne(T)}).finally(()=>{W=!1})}}o(ct,"ensureDaemon");export{_e as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,Me as autostartDisabled,st as daemonAutostartStartupFailure,De as daemonCommandDeclaresCanvasHome,ct as ensureDaemon,et as execDaemon,xe as findDaemonPids,at as isDaemonServing,L as probeDaemonHealth,J as probeDaemonServing,Se as probeErrorMessage,Pe as resetDaemonAutostart,nt as runDaemonBodiesDump,tt as runDaemonExportSqlite,rt as runDaemonImportDump,ot as runDaemonInstallId,O as sanitizedDaemonEnv,Ie as spawnDaemon,it as stopAllDaemons,X as stopDaemonProcess,ye as sweepStrayDaemons,Re as verifyDaemonStartup,ve as waitForDaemonExit};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.652",
|
|
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.652",
|
|
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.652",
|
|
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.652",
|
|
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.652",
|
|
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.652",
|
|
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.652",
|
|
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.652",
|
|
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.652",
|
|
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.652",
|
|
11981
|
+
"@north-light/identity": "0.3.652"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.652",
|
|
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.652",
|
|
11990
|
+
"@north-light/identity": "0.3.652",
|
|
11991
|
+
"@north-light/plugin": "0.3.652",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
export interface TicketClaim {
|
|
2
|
-
token: string;
|
|
3
|
-
host: string;
|
|
4
|
-
pid: number;
|
|
5
|
-
claimedAt: string;
|
|
6
|
-
heartbeatAt: string;
|
|
7
|
-
tmuxClient?: string;
|
|
8
|
-
}
|
|
9
|
-
export interface ClaimOptions {
|
|
10
|
-
host?: string;
|
|
11
|
-
pid?: number;
|
|
12
|
-
tmuxClient?: string;
|
|
13
|
-
now?: Date;
|
|
14
|
-
}
|
|
15
|
-
export declare function readTicketClaim(dir: string): TicketClaim | null;
|
|
16
|
-
export declare function isStaleClaim(claim: TicketClaim, now?: number, localHost?: string): boolean;
|
|
17
|
-
/** Exclude another live presenter; the daemon owns whether the request can settle. */
|
|
18
|
-
export declare function claimTicket(dir: string, opts?: ClaimOptions): TicketClaim | null;
|
|
19
|
-
export declare function heartbeatClaim(dir: string, token: string, now?: Date): boolean;
|
|
20
|
-
export declare function releaseClaimLocked(dir: string, token: string): boolean;
|
|
21
|
-
export declare function releaseClaim(dir: string, token: string): boolean;
|
|
22
|
-
export declare function claimExists(dir: string): boolean;
|
|
23
|
-
export declare function withTicketLock<T>(dir: string, operation: () => T): T;
|
package/dist/core/human/claim.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var x=Object.defineProperty;var n=(t,e)=>x(t,"name",{value:e,configurable:!0});import{existsSync as f,renameSync as y,unlinkSync as p,writeFileSync as h}from"node:fs";import{hostname as l}from"node:os";import{randomUUID as g}from"node:crypto";import{claimPath as o}from"./convention.js";import{readJsonOrNull as S}from"../fs-utils.js";import{withExclusiveDirectoryLock as a}from"../exclusive-lock.js";const b=3e4;function C(t){if(typeof t!="object"||t===null)return null;const e=t;return typeof e.token!="string"||typeof e.host!="string"||!Number.isInteger(e.pid)||typeof e.claimedAt!="string"||typeof e.heartbeatAt!="string"?null:{token:e.token,host:e.host,pid:e.pid,claimedAt:e.claimedAt,heartbeatAt:e.heartbeatAt,...typeof e.tmuxClient=="string"?{tmuxClient:e.tmuxClient}:{}}}n(C,"parseClaim");function u(t){return C(S(o(t)))}n(u,"readTicketClaim");function d(t){try{return process.kill(t,0),!0}catch{return!1}}n(d,"isLiveLocalPid");function A(t,e=Date.now(),r=l()){if(t.host===r)return!d(t.pid);const i=Date.parse(t.heartbeatAt);return!Number.isFinite(i)||e-i>b}n(A,"isStaleClaim");function I(t,e={}){return a(`${t}/.ticket-lock`,()=>{const r=o(t),i=u(t);if(i!==null&&!A(i,Date.now(),e.host??l()))return null;f(r)&&p(r);const c=e.host??l(),k=e.pid??process.pid,s=(e.now??new Date).toISOString(),m={token:g(),host:c,pid:k,claimedAt:s,heartbeatAt:s,...e.tmuxClient?{tmuxClient:e.tmuxClient}:{}};return h(r,`${JSON.stringify(m)}
|
|
2
|
-
`,{flag:"wx",mode:384}),m})}n(I,"claimTicket");function J(t,e,r=new Date){return a(`${t}/.ticket-lock`,()=>{const i=u(t);if(i===null||i.token!==e)return!1;const c=`${o(t)}.${e}.heartbeat`;return h(c,`${JSON.stringify({...i,heartbeatAt:r.toISOString()})}
|
|
3
|
-
`,{flag:"wx",mode:384}),y(c,o(t)),!0})}n(J,"heartbeatClaim");function w(t,e){const r=u(t);return r===null||r.token!==e?!1:(p(o(t)),!0)}n(w,"releaseClaimLocked");function _(t,e){return a(`${t}/.ticket-lock`,()=>w(t,e))}n(_,"releaseClaim");function v(t){return f(o(t))}n(v,"claimExists");function F(t,e){return a(`${t}/.ticket-lock`,e)}n(F,"withTicketLock");export{v as claimExists,I as claimTicket,J as heartbeatClaim,A as isStaleClaim,u as readTicketClaim,_ as releaseClaim,w as releaseClaimLocked,F as withTicketLock};
|