@north-light/cli 0.3.662 → 0.3.664
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/viewer.js +1 -1
- package/dist/core/canvas/schema-pg/020-machine-calls-status-all.sql +8 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/grants/mirror.d.ts +16 -1
- package/dist/core/grants/mirror.js +7 -2
- package/dist/core/packages/directory-sync.js +4 -4
- package/dist/core/providers/bundles.js +2 -2
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/executor.d.ts +7 -0
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +14 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/daemon/broker-signals/bus.d.ts +3 -2
- package/dist/daemon/broker-signals/bus.js +1 -1
- package/dist/daemon/crtrd.d.ts +4 -0
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +9 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +8 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +11 -0
- package/dist/daemon/machine-link/holder.js +4 -4
- package/dist/daemon/peer/ingress.js +1 -1
- package/dist/daemon/reconcilers/grant-effects.d.ts +5 -4
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +5 -0
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +4 -0
- package/dist/daemon/reconcilers/node-lifecycle/tick.d.ts +3 -0
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
var
|
|
1
|
+
var R=Object.defineProperty;var n=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as h}from"node:crypto";import{parseScope as D}from"@north-light/identity";import{openDb as p,withCanvasWrite as S}from"../canvas/db.js";import{isUnsandboxedMachine as T}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as L}from"../permissions/facts.js";import{GROUP_TYPE as C}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function E(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(E,"runtimeScope");async function i(e,r,t=[]){const s=E();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(i,"grantRows");async function u(e,r,t=[]){return(await i(e,r,t))[0]}n(u,"grantRow");function M(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(M,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!M(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:a}=e;return typeof r!="string"||!$.includes(r)||t!==void 0&&typeof t!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...a===void 0?{}:{step:a}}}n(U,"dependencyOf");function N(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const a=U(s);a&&(r[t]=a)}return r}n(N,"dependenciesOf");function F(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const a of k){const o=t[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(F,"inferenceEndpointOf");function f(e){if(e.computed_rev!==e.rev||e.scopes_json===null||e.resolved_scopes_json===null)throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:N(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?F(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return V(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(d,"active");function _(e){return e.grantee!=="app:terminal"&&T()}n(_,"mirrorOnly");async function re(){return(await W()).filter(e=>!_(e))}n(re,"localGrants");async function ne(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(ne,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",G=new RegExp(`^(${y}):(${y})$`);function H(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const a=G.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}n(H,"providerIdsFromGrants");async function te(){const e=E();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
2
|
+
SELECT DISTINCT e->>'scope' AS scope FROM grants
|
|
3
|
+
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
4
|
+
WHERE ${O}${w()}${e.sql}) s
|
|
5
|
+
CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
|
|
6
|
+
WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(te,"activeProviderIds");async function se(){const e=E();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${O}${w()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(se,"anyActiveGrant");const O="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function w(){return T()?" AND grantee = 'app:terminal'":""}n(w,"localOnly");async function ae(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}n(ae,"grantSubs");async function oe(e){return m(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(oe,"activeGrants");async function ce(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(H(r.flatMap(t=>{try{return[f(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ce,"grantedProviderIds");function ie(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(ie,"isProviderBundleRow");async function ue(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=d(t);return s===null?[]:[s]})}n(ue,"activeGrantsOfPerson");async function W(){return m(await i("*","true"))}n(W,"allGrants");async function pe(e){return m(await i("*","sub = ?",[e]))}n(pe,"grantsOfPerson");function m(e){return e.flatMap(r=>{try{return[f(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(m,"records");function J(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(J,"grantExpired");function V(e){if(e.status!=="active"||J(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>D(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(V,"activeRecord");function x(e){return Array.isArray(e)?`[${e.map(x).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${x(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(x,"canonicalJson");function de(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return h("sha256").update(x(r)).digest("base64url").slice(0,22)}n(de,"grantVersion");async function le(e){return!!await u("1","id = ?",[e])}n(le,"hasGrant");async function fe(e){return await u("rev, status","id = ?",[e])??null}n(fe,"grantSyncState");async function _e(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(_e,"grantSyncStateFor");async function q(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(q,"grantRecord");async function ye(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=d(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(ye,"grantStanding");async function ge(e){return(await i("id",e)).map(r=>r.id)}n(ge,"grantIdsWhere");async function ve(e){return(e?(await q(e))?.payer:null)??"user"}n(ve,"payerOfGrant");async function B(e){return d(await u("*","id = ?",[e]))}n(B,"activeGrant");async function Ee(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}n(Ee,"grantFor");async function me(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}n(me,"activeGrantForApp");async function xe(e){const r=await B(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(xe,"runNoticeTarget");async function Se(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}n(Se,"terminalGrant");async function Te(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Te,"grantsSource");async function Ne(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Ne,"hasSyncedGrants");async function Oe(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Oe,"dropLocalGrantMirror");async function we(){return await S(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(we,"backfillComputedRev");function Ae(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:t,members:s}=r??{};if(typeof t!="string"||!/^team:\S+$/.test(t)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:t,members:s}})}n(Ae,"teamsOf");async function je(e,r,t,s=[]){const a=new Set;for(const o of e){if(a.has(o.id)||!o.id||!o.runtime||!o.sub||!o.grantee||!Number.isInteger(o.rev)||!["active","revoked","removed"].includes(o.status))throw new TypeError("invalid grant sync response");a.add(o.id),l(o.scopes),l(o.resolved_scopes)}await S(async o=>{let g=0;const v=[...a];g+=Number((await(v.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):o.prepareUncached("DELETE FROM grants").run())).changes);const A=o.prepare(`INSERT INTO grants
|
|
2
7
|
(id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
3
8
|
status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
|
|
4
9
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -12,4 +17,4 @@ var O=Object.defineProperty;var t=(e,r)=>O(e,"name",{value:r,configurable:!0});i
|
|
|
12
17
|
grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
|
|
13
18
|
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
14
19
|
excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
|
|
15
|
-
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const
|
|
20
|
+
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)g+=Number((await A.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(N(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(o,"directory",C,"member",s.flatMap(({team:c,members:j})=>j.map(b=>({resourceId:c,subject:L(b)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),g>0&&await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(je,"replaceGrants");async function be(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(be,"grantsGeneration");export{B as activeGrant,me as activeGrantForApp,oe as activeGrants,ue as activeGrantsOfPerson,te as activeProviderIds,V as activeRecord,W as allGrants,se as anyActiveGrant,we as backfillComputedRev,N as dependenciesOf,Oe as dropLocalGrantMirror,J as grantExpired,Ee as grantFor,ge as grantIdsWhere,q as grantRecord,ye as grantStanding,ae as grantSubs,fe as grantSyncState,_e as grantSyncStateFor,de as grantVersion,ce as grantedProviderIds,be as grantsGeneration,pe as grantsOfPerson,Te as grantsSource,le as hasGrant,Ne as hasSyncedGrants,F as inferenceEndpointOf,ie as isProviderBundleRow,re as localGrants,_ as mirrorOnly,ne as otherLiveGrantOfApp,ve as payerOfGrant,H as providerIdsFromGrants,je as replaceGrants,xe as runNoticeTarget,E as runtimeScope,Ae as teamsOf,Se as terminalGrant};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
1
|
+
var E=Object.defineProperty;var i=(e,n)=>E(e,"name",{value:n,configurable:!0});import{mkdtempSync as S,mkdirSync as A,rmSync as I,writeFileSync as N}from"node:fs";import{tmpdir as $}from"node:os";import{dirname as x,join as f}from"node:path";import{withCanvasWrite as m,openDb as O}from"../canvas/db.js";import{emitEvent as p}from"../events/emit.js";import{outboundFetch as P}from"../events/outbound.js";import{directoryIssuer as w}from"../directory/issuer.js";import{activeProviderIds as T,anyActiveGrant as j}from"../grants/mirror.js";import{mintDirectoryToken as D}from"../grants/sync.js";import{publish as M,readPackageSnapshot as R,withdraw as W}from"../graph/package-publish.js";import{normalizeSourceUrl as k}from"./source-url.js";const F=25e3,L=15e3;async function g(e,n){const o=w();if(o===null)return{ok:!1,reason:"unavailable"};try{const t=await D(o),r=await P("package_sync",`${o}${e}`,{method:n.method,headers:{Authorization:`Bearer ${t.access_token}`,...n.body===void 0?{}:{"content-type":"application/json"},...n.etag===void 0?{}:{"If-None-Match":`"${n.etag}"`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},signal:AbortSignal.timeout(n.wait)});if(r.status===304)return{ok:!0,notModified:!0};if(r.status===404)return{ok:!1,reason:"not_found"};if(r.status===409){const l=await r.json().catch(()=>({}));return(l.error?.code??l.code)==="name_taken"?{ok:!1,reason:"name_taken",holder:l.error?.details?.holder_source??l.error?.holder_source??l.holder_source}:{ok:!1,reason:"not_public"}}return r.ok?{ok:!0,pkg:await r.json()}:{ok:!1,reason:"unavailable"}}catch(t){return p({level:"warn",event:"daemon.packages.fetch_failed",fields:{path:e},error:t}),{ok:!1,reason:"unavailable"}}}i(g,"call");const h=i((e,n)=>g(`/v1/packages/${encodeURIComponent(e)}`,{method:"GET",etag:n,wait:L}),"getPackage"),y=i((e,n)=>g("/v1/packages/resolve",{method:"POST",body:{source_url:e,name:n},wait:F}),"resolvePackage");async function v(e){const n=S(f($(),"crtr-pkg-"));try{for(const t of e.files){const r=f(n,t.path);if(!r.startsWith(`${n}/`))throw new Error(`package file escapes its folder: ${t.path}`);A(x(r),{recursive:!0}),N(r,t.text)}const o={...R(n,{app:e.name,origin:e.origin,version:e.version,revision:e.revision,source:e.source===null?null:k(e.source),launchKinds:e.kinds,objectKinds:e.object_kinds}),digest:e.digest};return await m(async t=>await M(t,o,"package-sync"))}finally{I(n,{recursive:!0,force:!0})}}i(v,"publishDirectoryPackage");async function C(e){return await e.prepare(`SELECT p.name, m.url FROM scope_plugins p LEFT JOIN scope_marketplaces m
|
|
2
2
|
ON m.person = p.person AND m.owner_key = p.owner_key AND m.name = p.source_marketplace
|
|
3
|
-
WHERE p.owner_key LIKE 'app:%' AND p.enabled = 1`).all()}i(
|
|
4
|
-
JOIN identities i ON i.object = p.app AND i.scheme = 'app' WHERE p.origin <> 'builtin'`).all()).map(o=>({name:o.external_id.replace(/^app:/,""),origin:o.origin,source:o.source,digest:o.digest,withdrawn:o.withdrawn_at!==null}))}i(
|
|
3
|
+
WHERE p.owner_key LIKE 'app:%' AND p.enabled = 1`).all()}i(C,"wantedPlugins");async function G(e){return(await e.prepare(`SELECT i.external_id, p.origin, p.source, p.digest, p.withdrawn_at FROM package_publications p
|
|
4
|
+
JOIN identities i ON i.object = p.app AND i.scheme = 'app' WHERE p.origin <> 'builtin'`).all()).map(o=>({name:o.external_id.replace(/^app:/,""),origin:o.origin,source:o.source,digest:o.digest,withdrawn:o.withdrawn_at!==null}))}i(G,"publications");async function ne(e,n){const o=await y(n,e);return"pkg"in o?{out:o,published:await v(o.pkg)}:{out:o}}i(ne,"syncInstall");function J(e,n){for(const o of n.invalid)p({level:"error",event:"daemon.packages.invalid_file",fields:{app:e,path:o.path,error:o.error}});for(const o of n.kinds.refused)p({level:"warn",event:"daemon.packages.kind_refused",fields:{app:e,kind:o.kind,message:o.message}})}i(J,"reportPublished");async function d(e){J(e.name,await v(e))}i(d,"publishAndReport");const _=new Set;function b(e,n,o){if(o.ok)return;const t=`${e}
|
|
5
5
|
${n}
|
|
6
|
-
${o.reason}`;
|
|
6
|
+
${o.reason}`;_.has(t)||(_.add(t),o.reason!=="unavailable"&&p({level:"warn",event:"daemon.packages.resolve_refused",fields:{name:e,source:n??"",reason:o.reason}}))}i(b,"refused");async function oe(){if(w()===null)return;const e=await O(),n=await T(),o=await C(e),t=new Map((await G(e)).map(a=>[a.name,a])),r=new Set([...n,...o.map(a=>a.name)]);for(const a of o){const s=t.get(a.name),c=a.url===null?null:k(a.url);if(c!==null&&(s===void 0||s.withdrawn||s.source!==c)){const u=await y(c,a.name);"pkg"in u?await d(u.pkg):b(a.name,c,u)}}for(const a of r){const s=t.get(a);if(s===void 0||s.withdrawn){if(n.includes(a)){const u=await h(a);"pkg"in u?await d(u.pkg):b(a,null,u)}continue}const c=await h(a,s.digest);"pkg"in c&&await d(c.pkg)}const l=await j();for(const[a,s]of t)s.withdrawn||r.has(a)||s.origin==="provider"&&!l||await m(async c=>{await W(c,a)})}i(oe,"syncPackages");export{h as getPackage,v as publishDirectoryPackage,J as reportPublished,y as resolvePackage,ne as syncInstall,oe as syncPackages};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),g(d(e,"bundle.tar"),{force:!0}),g(d(e,"etag"),{force:!0})}o(
|
|
1
|
+
var ce=Object.defineProperty;var o=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{existsSync as b,readdirSync as W,readFileSync as _,rmSync as g,statSync as D}from"node:fs";import{join as d}from"node:path";import{validateCommandManifest as fe}from"../../api/command-manifest/manifest.js";import{crtrHome as z}from"../canvas/paths.js";import{isCloudRole as w}from"../canvas/person-state.js";import{withCanvasWrite as le}from"../canvas/db.js";import{bundleVersion as pe,isInstalledGeneration as me,recordCheckedGeneration as ve}from"../command-plugins/bundle.js";import{readState as ge,updateConfig as he,updateState as we}from"../config.js";import{directoryIssuer as L}from"../directory/issuer.js";import{emitEvent as p}from"../events/emit.js";import{describeOutboundFailure as $e,outboundFetch as ye,outboundRefusal as q,OutboundError as be}from"../events/outbound.js";import{withExclusiveDirectoryLockAsync as K}from"../exclusive-lock.js";import{atomicWriteText as T,ensureDir as N,pathExists as Z}from"../fs-utils.js";import{reconcilePackages as _e}from"../graph/package-reconcile.js";import{readPluginManifest as A}from"../manifest.js";import{bundleSwapLockPath as V}from"../plugin-swap-lock.js";import{pluginsDir as J,userScopeRoot as X}from"../scope.js";import{installedProviderPlugins as Se}from"./roots.js";import{activeProviderIds as Q,anyActiveGrant as Me}from"../grants/mirror.js";import{ProviderError as c}from"./errors.js";const Pe="[A-Za-z0-9_-]{1,64}",Y=new RegExp(`^${Pe}$`),Ee=3e4,ee=3e4;function $(e){return d(J("user"),e)}o($,"pluginRoot");function S(e){return d(J("user"),`.${e}.etag`)}o(S,"etagFile");function Te(e){if(!w())return ge("user").plugins[e]?.etag;try{return _(S(e),"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}}o(Te,"storedEtag");async function ne(e,n){if(!w())return ve("user",e,n,{swapped:!1});n===void 0?g(S(e),{force:!0}):T(S(e),n)}o(ne,"recordEtag");async function re(e){if(!w())try{await le(async n=>await _e(n))}catch(n){p({level:"error",event:"daemon.providers.docs_reconcile_failed",fields:{provider:e},error:n})}}o(re,"reconcileProviderDocs");function Ae(e,n,r){return w()?A(n)?.version===r&&Z(d(n,"commands.json")):me(e,"user",n,r)}o(Ae,"installedGeneration");function R(){return d(z(),"providers")}o(R,"providersRoot");function te(e,n){return d(R(),e,`v${n}`)}o(te,"majorDir");function B(e){if(!Y.test(e))throw new c("not_found",`"${e}" is not a provider id`,{param:"provider"})}o(B,"assertId");function I(){const e=L();if(!e)throw new c("not_found","provider bundles need a directory-connected runtime");return e}o(I,"directoryBase");async function oe(e,n){const r=`${I()}/providers/${encodeURIComponent(e)}/plugin${n.version!==void 0?`?version=${n.version}`:""}`;let t;try{t=await ye("bundle_fetch",r,{headers:{Accept:"application/x-tar",...n.ifNoneMatch!==void 0?{"If-None-Match":n.ifNoneMatch}:{}},signal:AbortSignal.timeout(Ee)})}catch(i){return{status:"failed",message:`could not reach ${r}: ${i instanceof Error?i.message:String(i)}`,cause:i}}if(t.status===304){if(n.ifNoneMatch===void 0){const i=`HTTP 304 from ${r} without a conditional request`;return{status:"failed",message:i,cause:q("bundle_fetch",r,i)}}return{status:304}}if(t.status===404||t.status===410)return await t.body?.cancel().catch(()=>{}),{status:t.status===404?404:410,message:`HTTP ${t.status} from ${r}`};if(t.status<200||t.status>=300){await t.body?.cancel().catch(()=>{});{const i=`HTTP ${t.status} from ${r}`;return{status:"failed",message:i,cause:q("bundle_fetch",r,i)}}}let a;try{a=new Uint8Array(await t.arrayBuffer())}catch(i){return{status:"failed",message:`reading ${r} failed: ${i instanceof Error?i.message:String(i)}`,cause:new be("bundle_fetch",r,i)}}const u=t.headers.get("etag");return{status:200,raw:a,...u!==null?{etag:u}:{}}}o(oe,"fetchProviderBundle");const k=new WeakSet;class x extends Error{static{o(this,"BundleInvalid")}issues;constructor(n,r){super(n),this.issues=r}}function ae(e,n,r){if(r.provider===void 0)return"the archive carries no provider block";if(r.provider.id!==e)return`the archive is provider "${r.provider.id}", not "${e}"`;if(n!==void 0&&r.provider.major!==n)return`the archive is major ${r.provider.major}, not ${n}`;const t=["hooks","kinds","page_components","memory_extensions"].filter(a=>r[a]!==void 0);if(t.length>0)return`a provider bundle may not carry ${t.join(", ")}`}o(ae,"wrongBundle");function O(e,n,r){p({level:"error",event:"daemon.providers.bundle_invalid",fields:{provider:e,...n!==void 0?{major:n}:{},...r instanceof x?{issues:r.issues}:{}},error:r})}o(O,"logInvalid");function C(e,n,r,t,a){p({level:"info",event:"daemon.providers.bundle_checked",fields:{provider:e,...n!==void 0?{major:n}:{},status:r,...t!==void 0?{etag:t}:{},outcome:a}})}o(C,"logChecked");function ie(e,n,r){p({level:"warn",event:"daemon.providers.bundle_fetch_failed",fields:{provider:e,...n!==void 0?{major:n}:{},message:r instanceof Error?r.message:String(r),...$e(r instanceof Error?r.cause:void 0)}})}o(ie,"logFailure");async function se(){return import("../../commands/pkg/plugin-manage.js")}o(se,"pluginManage");const M=new Map,P=o(e=>`${z()}\0${e}`,"installKey");function Ie(e){const n=e,r=n?.code??n?.cause?.code;return typeof r=="string"&&/^[A-Z][A-Z0-9_]{1,30}$/.test(r)?`${r} on provider install directory`:e instanceof c&&e.message.includes("HTTP 404")?"directory returned HTTP 404":e instanceof c&&e.message.includes("HTTP 410")?"directory returned HTTP 410":"provider bundle could not be installed"}o(Ie,"publicInstallCause");function ke(e){if(m(e)===void 0)return M.get(P(e))??{status:"installing"}}o(ke,"providerInstallState");function xe(e){return new c("provider_unavailable",`provider "${e}" unavailable: ${ke(e)?.error??"bundle installation pending"}`)}o(xe,"unavailableProviderError");function m(e){const n=A($(e));if(!(n?.provider===void 0||n.transport?.kind!=="http"&&n.transport?.kind!=="machine")&&Z(d($(e),"commands.json"))){try{if(D(d($(e),"commands.json")).size===0)return}catch{return}return{provider:n.provider,transport:n.transport.kind==="machine"?{kind:"machine"}:{kind:"http",endpoint:n.transport.endpoint}}}}o(m,"installedManifest");async function H(e,n,r=!1){const t=X();m(e)===void 0&&M.set(P(e),{status:"installing"});try{return N(d(t,"tmp")),await K(V(t,e),async()=>{const a=$(e),u=A(a);if(u!==null&&u.provider===void 0)throw new c("provider_unavailable",`plugin "${e}" is installed and is not the directory's provider bundle`);const i=m(e)!==void 0;if(i&&r)return"unchanged";const f=i&&n?Te(e):void 0,s=await oe(e,f!==void 0?{ifNoneMatch:f}:{});if(s.status===304)return C(e,m(e)?.provider.major,304,f,"unchanged"),"unchanged";if(s.status===404||s.status===410)throw new c("not_found",`the directory serves no provider "${e}" (${s.message})`,{param:"provider"});if(s.status==="failed")throw new c("provider_unavailable",`provider "${e}" bundle fetch failed: ${s.message}`,{cause:s.cause});const l=pe(s.raw);if(i&&Ae(e,a,l))return await ne(e,s.etag),C(e,m(e)?.provider.major,200,s.etag,"unchanged"),"unchanged";const{installPluginArchive:h}=await se();w()&&g(S(e),{force:!0});try{await h(e,s.raw,{scope:"user",scopeRootPath:t,root:a,version:l,etag:s.etag,enable:!i,bundle:{endpoint:`${I()}/providers/${encodeURIComponent(e)}/plugin`},transport:{kind:"http",endpoint:I()},accept:o(v=>ae(e,void 0,v),"accept"),record:!w()})}catch(v){O(e,void 0,v);const U=new c("not_found",`provider "${e}" served an invalid bundle: ${v instanceof Error?v.message:String(v)}`,{param:"provider"});throw k.add(U),U}return w()&&await ne(e,s.etag),await re(e),p({level:"info",event:"daemon.providers.bundle_installed",fields:{provider:e,major:m(e)?.provider.major,version:l,replaced:i,...s.etag!==void 0?{etag:s.etag}:{}}}),M.delete(P(e)),i?"updated":"installed"},{timeoutMs:ee,timeoutError:o(()=>new c("provider_unavailable",`timed out waiting for another process replacing plugin "${e}"`),"timeoutError")})}catch(a){throw m(e)===void 0&&M.set(P(e),{status:"install_failed",error:Ie(a)}),a instanceof c?a:(p({level:"error",event:"daemon.providers.bundle_install_failed",fields:{provider:e},error:a}),xe(e))}}o(H,"refreshInstalled");async function ln(e){B(e),m(e)===void 0&&await H(e,!1,!0)}o(ln,"ensureProviderBundle");async function pn(e,n){return B(e),n.version!==void 0&&m(e)?.provider.major!==n.version?F(e,n.version,n.conditional):H(e,n.conditional)}o(pn,"refreshProviderBundle");async function ue(e,n,r){const{validatePluginArchive:t}=await se(),a=await t(r);if(a.bundle===void 0)throw new x(`provider "${e}" major ${n} bundle is invalid: ${a.issues.map(i=>i.message).join("; ")}`,a.issues);const u=ae(e,n,a.bundle);if(u!==void 0)throw new x(`provider "${e}" major ${n} bundle is invalid: ${u}`,[]);if(a.bundle.transport===void 0)throw new x(`provider "${e}" major ${n} bundle declares no transport`,[]);return a.bundle}o(ue,"validateArchive");function Ce(e){N(e),T(d(e,"retired"),`${new Date().toISOString()}
|
|
2
|
+
`),g(d(e,"bundle.tar"),{force:!0}),g(d(e,"etag"),{force:!0})}o(Ce,"retire");function de(e,n){return new c("provider_version_retired",`provider "${e}" major ${n} is retired`,{param:"version"})}o(de,"retiredError");async function F(e,n,r){const t=te(e,n),a=d(t,"bundle.tar"),u=b(a),i=u&&r&&b(d(t,"etag"))?_(d(t,"etag"),"utf8"):void 0,f=await oe(e,{version:n,...i!==void 0?{ifNoneMatch:i}:{}});if(f.status===304)return C(e,n,304,i,"unchanged"),"unchanged";if(f.status===410)throw Ce(t),p({level:"info",event:"daemon.providers.major_retired",fields:{provider:e,major:n}}),de(e,n);if(f.status===404)throw new c("not_found",`provider "${e}" never served major ${n}`,{param:"version"});if(f.status==="failed")throw new c("provider_unavailable",`provider "${e}" major ${n} bundle fetch failed: ${f.message}`,{cause:f.cause});try{await ue(e,n,f.raw)}catch(h){O(e,n,h);const v=new c(u?"provider_unavailable":"not_found",h instanceof Error?h.message:String(h),{param:"version"});throw k.add(v),v}N(t),g(d(t,"retired"),{force:!0});const s=u&&Buffer.from(f.raw).equals(_(a));s||T(a,f.raw),f.etag!==void 0?T(d(t,"etag"),f.etag):g(d(t,"etag"),{force:!0});const l=s?"unchanged":u?"updated":"installed";return C(e,n,200,f.etag,l),l}o(F,"refreshPinned");function je(){const e=[],n=R();if(!b(n))return e;for(const r of W(n)){if(!Y.test(r))continue;let t;try{t=W(d(n,r))}catch{continue}for(const a of t){const u=/^v([1-9][0-9]*)$/.exec(a);u&&b(d(n,r,a,"bundle.tar"))&&e.push([r,Number(u[1])])}}return e}o(je,"cachedMajors");function De(e){const n=fe(e,{transport:"http",reservedCoreNames:new Set});if(n.manifest===void 0)throw new c("not_found","the provider bundle's commands.json no longer validates");return n.manifest}o(De,"readCommands");const E=new Map,G=new Map;function Ne(e,n){const r=D(n),t=`${r.ino}:${r.mtimeMs}:${r.size}`,a=G.get(e);if(a?.stamp===t)return a.commands;const u=De(JSON.parse(_(n,"utf8")));return G.set(e,{stamp:t,commands:u}),u}o(Ne,"installedCommands");async function mn(e,n){B(e);const r=m(e);if(n===void 0||r?.provider.major===n){if(r===void 0)throw new c("not_found",`provider "${e}" has no installed bundle`,{param:"provider"});const l=$(e),h=Ne(e,d(l,"commands.json"));return{id:e,major:r.provider.major,provider:r.provider,commands:h,transport:r.transport,source:"installed",root:l}}if(!Number.isInteger(n)||n<1)throw new c("invalid_request","version must be an integer of at least 1",{param:"version"});const t=te(e,n);if(b(d(t,"retired")))throw de(e,n);const a=d(t,"bundle.tar");b(a)||await F(e,n,!1);const u=`${e}/${n}`,i=D(a),f=`${i.mtimeMs}:${i.size}`;let s=E.get(u)?.stamp===f?E.get(u).bundle:void 0;if(s===void 0){try{s=await ue(e,n,new Uint8Array(_(a)))}catch(l){throw O(e,n,l),new c("not_found",`provider "${e}" has no valid bundle for major ${n}`,{param:"version"})}E.set(u,{stamp:f,bundle:s})}return{id:e,major:n,provider:s.provider,commands:s.commands,transport:s.transport.kind==="machine"?{kind:"machine"}:{kind:"http",endpoint:s.transport.endpoint},source:"pinned"}}o(mn,"resolveProviderBundle");let y=null;const Re=4*6e4,Be=1e3,Oe=2e3;function j(e,n){e.stage=n,e.stageAgeMs=0}o(j,"enter");function He(e,n){return e?.provider?.id===n&&e.bundle?.endpoint===`${I()}/providers/${encodeURIComponent(n)}/plugin`}o(He,"isDirectoryBundle");async function Fe(e){return(await Q()).includes(e)}o(Fe,"grantNames");async function Ge(e){await K(V(X(),e),async()=>{if(!(await Fe(e)||!He(A($(e)),e))){g($(e),{recursive:!0,force:!0}),w()?g(S(e),{force:!0}):(await he("user",n=>{delete n.plugins[e]}),await we("user",n=>{delete n.plugins[e]})),g(d(R(),e),{recursive:!0,force:!0}),G.delete(e),M.delete(P(e));for(const n of[...E.keys()])n.startsWith(`${e}/`)&&E.delete(n);await re(e),p({level:"info",event:"daemon.providers.bundle_uninstalled",fields:{provider:e}})}},{timeoutMs:ee,timeoutError:o(()=>new c("provider_unavailable",`timed out waiting for another process replacing plugin "${e}"`),"timeoutError")})}o(Ge,"uninstallProvider");async function Ue(e){if(await Me()){for(const n of Se())if(!(n.manifest.provider===void 0||e.has(n.name)))try{await Ge(n.name)}catch(r){p({level:"error",event:"daemon.providers.bundle_uninstall_failed",fields:{provider:n.name},error:r})}}}o(Ue,"uninstallDisconnected");async function We(e){if(!L())return;j(e,"reading grants");const n=await Q();for(const r of n){j(e,`refreshing installed bundle ${r}`);try{await H(r,!0)}catch(t){t instanceof Object&&k.has(t)||ie(r,void 0,t)}}j(e,"uninstalling disconnected bundles"),await Ue(new Set(n));for(const[r,t]of je()){j(e,`refreshing pinned bundle ${r} v${t}`);try{await F(r,t,!0)}catch(a){if(a instanceof c&&a.code==="provider_version_retired"||a instanceof Object&&k.has(a))continue;ie(r,t,a)}}}o(We,"syncOnce");function vn(){if(y!==null){y.rerun=!0;const t=y.stageAgeMs;return t>=Re&&p({level:"error",event:"daemon.providers.sync_stalled",fields:{stage:y.stage,stalled_ms:t}}),y.promise}const e={promise:Promise.resolve(),stage:"starting",stageAgeMs:0,rerun:!1};y=e;let n=Date.now();const r=setInterval(()=>{const t=Date.now();e.stageAgeMs+=Math.min(Math.max(t-n,0),Oe),n=t},Be);return r.unref(),e.promise=(async()=>{try{do e.rerun=!1,await We(e);while(e.rerun)}finally{clearInterval(r),y=null}})(),e.promise}o(vn,"syncProviderBundles");export{ln as ensureProviderBundle,ke as providerInstallState,pn as refreshProviderBundle,mn as resolveProviderBundle,vn as syncProviderBundles,xe as unavailableProviderError};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var S=Object.defineProperty;var o=(e,n)=>S(e,"name",{value:n,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as E,withCanvasWrite as N}from"../../../canvas/db.js";import{brokerSignalBus as k}from"../../../../daemon/broker-signals/bus.js";import{MachineCallFailedError as O,MachineLostError as _,MachineOfflineError as d}from"./ops.js";const D={start:60,wake:15,stop:15,status:15,"status.all":15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60},M=1e3;async function x(e,n,a,l={}){const s=g(),c=new Date().toISOString();if(!await N(async r=>await r.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,c)===void 0?!1:(await r.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(s,e,n,JSON.stringify(a),c),await r.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new d(e,"no live link");const i=Date.now()+(l.timeoutMs??D[n]*1e3);let u,f=!1;const h=await k.subscribe(r=>{r===s&&(f=!0,u?.())},{kinds:["machine_call"]});try{return await T(e,n,s,i,l.rereadMs??M,r=>new Promise(w=>{if(f){f=!1,w();return}const p=setTimeout(()=>{u=void 0,w()},r);u=o(()=>{clearTimeout(p),u=void 0,f=!1,w()},"wake")}))}finally{h()}}o(x,"callMachine");async function T(e,n,a,l,s,c){for(;;){const t=await(await E()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(a);if(t===void 0)throw new _(e,a);if(t.state==="done")return t.result_json===null?null:JSON.parse(t.result_json);if(t.state==="failed"){const i=t.result_json===null?{}:JSON.parse(t.result_json);throw i.code==="machine_offline"?new d(e,i.message,i.sent===!0):i.code==="machine_lost"?new _(e,a):new O(e,n,i.message??"unknown")}if(t.claimed_generation!==null&&t.lease_expires_at!==null&&t.lease_expires_at<=new Date().toISOString()){if(await m(a,"lease expired")===void 0)continue;throw new _(e,a)}if(Date.now()>=l){const i=await m(a,"timed out");if(i===void 0)continue;throw i===null?new d(e,"no holder claimed the call"):new _(e,a)}await c(Math.min(s,Math.max(0,l-Date.now())))}}o(T,"waitForCall");async function m(e,n){const a=await(await E()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
|
|
2
2
|
result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
|
|
3
|
-
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return
|
|
3
|
+
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return a===void 0?void 0:a.claimed_generation===null?null:Number(a.claimed_generation)}o(m,"failOpenCall");export{D as MACHINE_CALL_TIMEOUT_S,x as callMachine};
|
|
@@ -7,6 +7,13 @@ export interface MachineExecutorDeps {
|
|
|
7
7
|
environmentId: string;
|
|
8
8
|
/** Seconds `stop` waits after SIGTERM before SIGKILL. */
|
|
9
9
|
stopGraceS?: number;
|
|
10
|
+
/** Called when a broker this executor spawned exits. */
|
|
11
|
+
onExit?: (exit: {
|
|
12
|
+
execution: string;
|
|
13
|
+
node: string;
|
|
14
|
+
code: number | null;
|
|
15
|
+
signal: string | null;
|
|
16
|
+
}) => void;
|
|
10
17
|
}
|
|
11
18
|
/** Broker processes: `{pid, execution, node}` for each `broker-cli.js ... --epoch <execution> <node>` command line. Throws when the process table cannot
|
|
12
19
|
* be read: an unreadable table is not an empty one, and a caller that read it as "no brokers" would start a second broker or report a stop that did not happen. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var B=Object.defineProperty;var s=(o,r)=>B(o,"name",{value:r,configurable:!0});import{spawn as G}from"node:child_process";import{closeSync as H,existsSync as E,mkdirSync as y,openSync as F,statSync as j}from"node:fs";import{rm as K}from"node:fs/promises";import{basename as b,dirname as v,join as T}from"node:path";import{fileURLToPath as X}from"node:url";import{contextDir as J,jobDir as V,nodeRunDir as C,crtrHome as N,viewSocketPath as Y}from"../../../canvas/paths.js";import{captureTeardownSnapshot as W,isAnyPidAlive as z,killProcessTreePids as A,listProcessTableAsync as Q}from"../../../canvas/pid.js";import{scopesFilePath as O}from"../../../canvas/paths.js";import{writeFileBeneath as M}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as q}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as Z}from"../../broker-ownership.js";import{isShippedCanvasExtension as g}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as ee,mergeCanvasExtensions as oe}from"../../canvas-extensions.js";import{layoutRoot as te,runtimeRoot as ne}from"../../../layout.js";import{composeAppProcessEnv as re,overlayBrokerEnv as ie}from"../../spawn-env.js";const S=s(()=>T(v(X(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),D=s(o=>{if(o!==void 0)try{process.kill(-o,"SIGKILL")}catch{}},"killGroup"),ce=s(o=>new Promise(r=>setTimeout(r,o)),"sleep");async function I(){const o=[],r=await Q();if(r===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:n,command:e}of r){const t=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);t!==null&&o.push({pid:n,execution:t[1],node:t[2],command:e})}return o}s(I,"findBrokers");const se=new Set([502,503,504]),ae=1e3,de=3e4,ue=3e4,L=9e4;async function fe(o,r,n,e){const t=Date.now()+L;for(let c=ae;;c=Math.min(c*2,de)){e?.throwIfAborted();const i=AbortSignal.timeout(Math.min(ue,Math.max(1,t-Date.now())));let a,d;try{a=await fetch(`${o.replace(/\/$/,"")}/v1/executions/${r}/start`,{headers:{authorization:`Bearer ${n}`},signal:e===void 0?i:AbortSignal.any([i,e])}),d=`the control plane answered ${a.status} for the start bundle of ${r}`}catch(f){e?.throwIfAborted(),d=`the control plane could not be reached for the start bundle of ${r}: ${f instanceof Error?f.message:String(f)}`}if(a?.ok)return await a.json();if(a!==void 0&&!se.has(a.status))throw new Error(d);if(Date.now()+c>=t)throw new Error(`${d} (gave up after ${L/1e3} seconds of retries)`);e?.throwIfAborted(),await new Promise(f=>{const m=setTimeout(l,c);function l(){clearTimeout(m),e?.removeEventListener("abort",l),f()}s(l,"done"),e?.addEventListener("abort",l,{once:!0})})}}s(fe,"fetchBundle");const le=["CRTR_HOME","CRTR_RUNTIME_HOME"];function P(o,r){const n={...o};for(const e of le)delete n[e];return n.CRTR_CONTEXT_DIR!==void 0&&(n.CRTR_CONTEXT_DIR=J(r.id,n.CRTR_GRANTEE??r.app)),n.CRTR_SCOPES_FILE!==void 0&&(n.CRTR_SCOPES_FILE=O(r.id)),n}s(P,"localLaunchEnv");function pe(o){const r=s(i=>b(i).replace(/\.[jt]s$/,""),"stem"),n=new Set(ee.map(r)),e=s(i=>g(i)||b(v(i))==="pi-extensions"&&(n.has(r(i))||r(i).startsWith("canvas-")&&!E(i)),"shipped"),t=[],c=[];for(let i=0;i<o.length;i++)if(o[i]==="-e"&&o[i+1]!==void 0){const a=o[++i];if(e(a))continue;if(!E(a))throw new Error(`extension ${a} does not exist on this machine`);c.push(a)}else t.push(o[i]);return[...oe(c).flatMap(i=>["-e",i]),...t]}s(pe,"localExtensionArgv");function me(o,r){const n=JSON.parse(o);return JSON.stringify({...n,argv:pe(n.argv),env:P(n.env??{},r)})}s(me,"machineLaunchRecipe");function he(o,r,n){const e=o.launch,t=ie({argv:[],env:P(e.env??{},o.node)},re(o.node.cwd,null,o.node.app,o.machine_env??{},{}));return Object.assign(t,{CRTR_HOME:te(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ne(),CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:n,CRTR_ENVIRONMENT_ID:r.environmentId,CRTR_VIEW_WSS:"0",[q]:"1"})}s(he,"machineBrokerEnv");async function U(o,r,n){const{tree:e,identities:t}=W(o,null,n);if(t===null)return{confirmed:!1,error:`the process tree of broker ${o} could not be read, so shutdown cannot be confirmed`};const c=s(async(i,a)=>{for(let d=0;z(i);d+=100){if(d>=a)return!1;await ce(100)}return!0},"waitUntilDead");try{process.kill(o,"SIGTERM")}catch{}return await c([o],r),A(e,"SIGTERM",t),await c(e,2e3)?{confirmed:!0}:(A(e,"SIGKILL",t),await c(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${o} survived SIGKILL`})}s(U,"stopBroker");async function Me(o=1e4){const n=(await Promise.all((await I()).filter(e=>Z(e.command,N())).map(e=>U(e.pid,o)))).filter(e=>!e.confirmed);if(n.length>0)throw new Error(n.map(e=>e.error??"a broker did not stop").join("; "))}s(Me,"stopAllBrokers");function De(o){const r=(o.stopGraceS??10)*1e3,n=s(async e=>(await I()).find(t=>t.execution===e),"brokerOf");return{async start(e,t){const c=await n(e.executionId);if(c!==void 0)return{pid:c.pid};if(t?.throwIfAborted(),!E(e.cwd)||!j(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!E(S()))throw new Error(`the broker entry ${S()} does not exist`);const i=await fe(o.apiUrl,e.executionId,e.nodeToken,t);t?.throwIfAborted();const a=i.launch,d=C(e.nodeId);y(d,{recursive:!0}),M(d,T(d,"broker-launch.json"),me(e.launchJson,i.node),{atomic:!0}),a.env?.CRTR_SCOPES_FILE!==void 0&&M(d,O(e.nodeId),JSON.stringify(a.scopes??[]),{atomic:!0});const f=V(e.nodeId);y(f,{recursive:!0});const m=F(T(f,"broker.log"),"a"),l=he(i,o,e.executionId);delete l.CRTR_NODE_TOKEN;try{t?.throwIfAborted();const u=G(process.execPath,[S(),"--canvas-home",N(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",m,m,"pipe"],env:l});let R,k=!1;const x=s(()=>{R!==void 0&&o.onExit?.({execution:e.executionId,node:e.nodeId,...R})},"report");u.once("exit",(_,p)=>{R={code:_,signal:p},k&&x()});const h=u.stdio[3];if(h==null||!("end"in h))throw D(u.pid),new Error("broker token pipe did not open");const $=await new Promise((_,p)=>{u.once("error",p),u.once("spawn",()=>{u.off("error",p),h.once("error",w=>{D(u.pid),p(w)}),h.end(e.nodeToken,w=>{w?p(w):_(u.pid)})})});return k=!0,x(),u.unref(),{pid:$}}finally{H(m)}},async wake({execution:e}){const t=await n(e.executionId);if(t===void 0)return"no_broker";try{return process.kill(t.pid,"SIGUSR1"),"signalled"}catch(c){if(c.code==="ESRCH")return"no_broker";throw c}},async stop({execution:e,options:t}){const c=await n(e.executionId);return c===void 0?{confirmed:!0}:await U(c.pid,r,t.excludePid)},async status({execution:e}){const t=await n(e.executionId);return t===void 0?{state:"gone"}:{state:"running",pid:t.pid}},async"status.all"(e){return{running:(await I()).map(t=>({execution:t.execution,pid:t.pid}))}},async delete({nodeId:e}){return await K(C(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:Y(e.nodeId)}}}}s(De,"createMachineExecutor");export{De as createMachineExecutor,fe as fetchBundle,I as findBrokers,pe as localExtensionArgv,he as machineBrokerEnv,me as machineLaunchRecipe,Me as stopAllBrokers};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var N=Object.defineProperty;var
|
|
1
|
+
var N=Object.defineProperty;var u=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as d}from"node:test";import e from"node:assert/strict";import{spawn as P}from"node:child_process";import{mkdirSync as R,mkdtempSync as E,readFileSync as k,rmSync as v,writeFileSync as _}from"node:fs";import{tmpdir as w}from"node:os";import{join as l}from"node:path";import{EventEmitter as A}from"node:events";import{Readable as D}from"node:stream";import{createServer as H}from"node:http";import{createNode as M}from"../../../canvas/canvas.js";import{closeDb as L,openDb as T}from"../../../canvas/db.js";import{isPidAlive as h}from"../../../canvas/pid.js";import{bindPerson as F,installTerminalGrant as j,useEmptyPersonSettings as U}from"../../../__tests__/helpers/person.js";import{setAppEnvVar as g}from"../../../profiles/app-env-store.js";import{setProfileEnvVar as O}from"../../../profiles/env-store.js";import{createProfile as V}from"../../../profiles/manifest.js";import{putEnvRow as G}from"../../../secrets/env-rows.js";import{appSpace as J}from"../../../layout.js";import{executionStartRoutes as $}from"../../../../daemon/api/handlers/execution-start.js";import{Router as X}from"../../../../daemon/api/router.js";import{contextDir as S,scopesFilePath as C}from"../../../canvas/paths.js";import{layoutRoot as B,runtimeRoot as K}from"../../../layout.js";import{CANVAS_EXTENSIONS as m}from"../../canvas-extensions.js";import{createMachineExecutor as Y,fetchBundle as I,localExtensionArgv as z,machineBrokerEnv as f,machineLaunchRecipe as b}from"./executor.js";let p;const Q={HOME:process.env.HOME,CRTR_HOME:process.env.CRTR_HOME};x(()=>{process.env.HOME=p=E(l(w(),"crtr-machine-exec-")),process.env.CRTR_HOME=l(p,".crouter"),R(process.env.CRTR_HOME,{recursive:!0})}),q(async()=>{await L(),v(p,{recursive:!0,force:!0});for(const[n,o]of Object.entries(Q))o===void 0?delete process.env[n]:process.env[n]=o});async function W(n,o){const i=new X().registerAll($),a=Object.assign(D.from([]),{method:"GET",url:`/v1/executions/${o}/start`,headers:{}});let r="";const t=Object.assign(new A,{headersSent:!1,writableEnded:!1,writableFinished:!1});return t.setHeader=()=>t,t.writeHead=()=>(t.headersSent=!0,t),t.end=s=>(s&&(r+=s),t.writableEnded=!0,t.writableFinished=!0,t),await i.handle(a,t,null,n),JSON.parse(r)}u(W,"bundleFor"),d("a machine broker gets the profile, app and deployment rows, the app pi dir and the launch env, with the process runner's precedence",async()=>{await U(),await T();const n=await j(),o=(await V("machine-env")).profileId;await g("app:terminal","SHARED","from-app",n),await g("app:terminal","APP_SECRET","app-secret",n),await O(o,"SHARED","from-profile",n),await O(o,"PROFILE_VAR","profile-value",n),await G({person:null,kind:"deployment",id:"_deployment"},"DEPLOY_VAR","deploy-value");const i=l(p,"work");R(i,{recursive:!0}),await M({node_id:"m1",name:"m1",created:new Date().toISOString(),cwd:i,kind:"general",mode:"base",lifecycle:"resident",status:"active",parent:null,profile_id:o,grantee:"app:terminal"}),await(await T()).prepare("INSERT INTO executions (execution_id, node_id, state, started_at, launch_json, runner) VALUES ('em1', 'm1', 'launching', 't', ?, 'machine')").run(JSON.stringify({argv:["x"],env:{LAUNCH_VAR:"launch",CRTR_NODE_ID:"m1"}}));const a={class:"broker",app:"app:terminal",node:"m1",run:null,uid:process.getuid?.()??0,sub:await F(),grant:null,client_id:null,scopes:null},r=await W(a,"em1");e.equal(r.machine_env?.APP_SECRET,"app-secret");const t=f(r,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1");e.equal(t.APP_SECRET,"app-secret"),e.equal(t.PROFILE_VAR,"profile-value"),e.equal(t.DEPLOY_VAR,"deploy-value"),e.equal(t.SHARED,"from-profile","the profile's row wins over the app's"),e.equal(t.LAUNCH_VAR,"launch"),e.equal(t.PI_CODING_AGENT_DIR,l(J("app:terminal").home,".pi","agent")),e.equal(t.CRTR_API_URL,"http://cloud.invalid"),e.equal(t.CRTR_EXECUTION_ID,"em1"),e.doesNotThrow(()=>f({...r,node:{...r.node,profile:"profile-the-mac-does-not-hold"}},{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1")),e.equal(t.GITHUB_TOKEN,void 0)}),d("stop ends the broker and the detached command it left behind, and confirms both gone",async()=>{const n=E(l(w(),"crtr-machine-stop-")),o=l(n,"child.pid"),i=l(n,"broker-cli.js");_(i,`const { spawn } = require('node:child_process');
|
|
2
2
|
const c = spawn('sleep', ['300'], { detached: true, stdio: 'ignore' }); c.unref();
|
|
3
3
|
require('node:fs').writeFileSync(${JSON.stringify(o)}, String(c.pid));
|
|
4
|
-
setInterval(() => {}, 1000);`);const
|
|
4
|
+
setInterval(() => {}, 1000);`);const a=P(process.execPath,[i,"--canvas-home",n,"--epoch","exec-stop-1","node-stop-1"],{detached:!0,stdio:"ignore"});a.unref();try{let r=0;for(let c=0;c<100&&r===0;c++)try{r=Number(k(o,"utf8"))}catch{await new Promise(y=>setTimeout(y,50))}e.ok(r>0&&h(r),"the detached child is running");const t=Y({apiUrl:"http://cloud.invalid",environmentId:"env1",stopGraceS:3});e.ok((await t["status.all"]({})).running.some(c=>c.execution==="exec-stop-1"&&c.pid===a.pid),"status.all lists the running broker");const s=await t.stop({execution:{executionId:"exec-stop-1",nodeId:"node-stop-1"},options:{reason:"test"}});e.deepEqual(s,{confirmed:!0}),e.equal(h(a.pid),!1,"the broker is gone"),e.equal(h(r),!1,"the detached child is gone")}finally{try{process.kill(-a.pid,"SIGKILL")}catch{}v(n,{recursive:!0,force:!0})}}),d("a bundle the control plane built on its Linux layout starts a broker on this machine's own home, runtime, context, scopes and extension paths",()=>{const n={CRTR_HOME:"/work/crtr",CRTR_RUNTIME_HOME:"/opt/crouter/runtime",CRTR_CONTEXT_DIR:"/work/crtr/apps/terminal/nodes/m2/context",CRTR_SCOPES_FILE:"/work/crtr/runtime/nodes/m2/run/scopes.json",CRTR_NODE_ID:"m2",CRTR_KIND:"general",CRTR_GRANTEE:"app:terminal",CRTR_PROFILE_ID:"p-1"},i={launch:{argv:[...m.flatMap(t=>["-e",`/opt/crouter/runtime/generations/96276ec4/dist/pi-extensions/${t.split("/").pop()}`]),"-n","m2"],env:n,scopes:["a:b"]},node:{id:"m2",app:"app:terminal",cwd:p,profile:null},machine_env:{APP_SECRET:"s"}},a=f(i,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em2");e.equal(a.CRTR_HOME,B()),e.equal(a.CRTR_RUNTIME_HOME,process.env.CRTR_RUNTIME_HOME??K()),e.equal(a.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(a.CRTR_SCOPES_FILE,C("m2")),e.equal(a.CRTR_NODE_ID,"m2"),e.equal(a.CRTR_PROFILE_ID,"p-1"),e.equal(a.APP_SECRET,"s");for(const[t,s]of Object.entries(a))e.ok(!/\/work\/crtr|\/opt\/crouter/.test(s??""),`${t} names a control plane path: ${s}`);const r=JSON.parse(b(JSON.stringify(i.launch),i.node));e.deepEqual(r.argv.filter((t,s)=>r.argv[s-1]==="-e"),m),e.equal(r.argv.at(-1),"m2"),e.equal(r.env.CRTR_HOME,void 0),e.equal(r.env.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(r.env.CRTR_SCOPES_FILE,C("m2")),e.deepEqual(r.scopes,["a:b"]),e.ok(!/\/work\/crtr|\/opt\/crouter/.test(JSON.stringify(r))),e.throws(()=>b(JSON.stringify({argv:["-e","/opt/crouter/runtime/generations/x/custom.js"],env:{}}),{id:"m2",app:"app:terminal"}),/does not exist on this machine/)}),d("the broker's mandatory extensions are this install's complete list, whatever set the control plane's release shipped",()=>{const n=u(t=>["-e",`/opt/crouter/runtime/generations/old/dist/pi-extensions/${t}.js`],"server"),o=l(p,"custom-ext.js");_(o,"");const i=[...m,o].flatMap(t=>["-e",t]),r=[...m.map(t=>t.split("/").pop().replace(/\.[jt]s$/,"")).slice(1).flatMap(n),...n("canvas-retired-hook"),"-e",o,"-n","label","prompt text"];e.deepEqual(z(r),[...i,"-n","label","prompt text"])}),d("a control plane that answers 502 and then 200 still gives the start bundle, while a 404 fails at once with its status",async()=>{const n=[502,200],o=H((i,a)=>{const r=i.url?.includes("/gone/")?404:n.shift()??200;a.writeHead(r,{"content-type":"application/json"}),a.end(JSON.stringify(r===200?{launch:{argv:[]},node:{id:"n"}}:{error:"x"}))});await new Promise(i=>o.listen(0,"127.0.0.1",i));try{const i=`http://127.0.0.1:${o.address().port}`;e.deepEqual((await I(i,"exec-502","token")).node,{id:"n"}),e.deepEqual(n,[],"the 502 was asked again"),await e.rejects(I(i,"gone","token"),/answered 404/)}finally{o.close()}});
|
|
@@ -3,7 +3,7 @@ import type { AutoDroppedWorktree, AbandonManagedWorktreeResult } from '../../..
|
|
|
3
3
|
import type { CloseOnHostOutcome } from '../../../worktree-close.js';
|
|
4
4
|
import type { AbandonOutcome, FinalizeWorktreeOutcome } from '../../../worktree-mutation-async.js';
|
|
5
5
|
import type { RunnerExecution, RunnerStartInput, RunnerStatus, RunnerStopOptions, RunnerStopResult, RunnerViewerAddress, RunnerWakeResult } from '../types.js';
|
|
6
|
-
export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "delete", "viewer", "cron.run", "cron.cancel", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize"];
|
|
6
|
+
export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "status.all", "delete", "viewer", "cron.run", "cron.cancel", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize"];
|
|
7
7
|
export type MachineOp = (typeof MACHINE_OPS)[number];
|
|
8
8
|
/** A `start` call carries the whole start input and the node token the control plane minted: the Mac has no database, so it cannot mint one.
|
|
9
9
|
* The token sits in `machine_calls.args_json` until the row is deleted a day after it finishes; the execution's token row holds its hash. */
|
|
@@ -23,6 +23,15 @@ export interface MachineStopArgs {
|
|
|
23
23
|
export interface MachineStatusArgs {
|
|
24
24
|
execution: RunnerExecution;
|
|
25
25
|
}
|
|
26
|
+
/** Every broker running on the machine, from one scan of its process table: the control plane's timed check of all its executions
|
|
27
|
+
* there in one call. A machine on a release before this op answers `this machine does not execute status.all`. */
|
|
28
|
+
export type MachineStatusAllArgs = Record<string, never>;
|
|
29
|
+
export interface MachineStatusAllResult {
|
|
30
|
+
running: Array<{
|
|
31
|
+
execution: string;
|
|
32
|
+
pid: number;
|
|
33
|
+
}>;
|
|
34
|
+
}
|
|
26
35
|
export interface MachineDeleteArgs {
|
|
27
36
|
nodeId: string;
|
|
28
37
|
}
|
|
@@ -118,6 +127,10 @@ export interface MachineOpTable {
|
|
|
118
127
|
args: MachineStatusArgs;
|
|
119
128
|
result: RunnerStatus;
|
|
120
129
|
};
|
|
130
|
+
'status.all': {
|
|
131
|
+
args: MachineStatusAllArgs;
|
|
132
|
+
result: MachineStatusAllResult;
|
|
133
|
+
};
|
|
121
134
|
delete: {
|
|
122
135
|
args: MachineDeleteArgs;
|
|
123
136
|
result: null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var s=Object.defineProperty;var n=(t,e)=>s(t,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","delete","viewer","cron.run","cron.cancel","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize"];class c extends Error{static{n(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,o=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=o}}class l extends c{static{n(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{n(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{n(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,o){super(`${r} on machine ${e} failed: ${o}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};
|
|
1
|
+
var s=Object.defineProperty;var n=(t,e)=>s(t,"name",{value:e,configurable:!0});const i=["start","wake","stop","status","status.all","delete","viewer","cron.run","cron.cancel","worktree.create","worktree.rollback","worktree.close","worktree.abandon","worktree.finalize"];class c extends Error{static{n(this,"MachineOfflineError")}environmentId;sent;code="machine_offline";constructor(e,r,o=!1){super(`machine ${e} is offline${r?`: ${r}`:""}`),this.environmentId=e,this.sent=o}}class l extends c{static{n(this,"MachineLaunchUncertainError")}uncertain=!0;constructor(e,r){super(e,r,!0)}}class h extends Error{static{n(this,"MachineLostError")}environmentId;callId;code="machine_lost";constructor(e,r){super(`call ${r} to machine ${e} was lost`),this.environmentId=e,this.callId=r}}class d extends Error{static{n(this,"MachineCallFailedError")}environmentId;op;code="machine_call_failed";constructor(e,r,o){super(`${r} on machine ${e} failed: ${o}`),this.environmentId=e,this.op=r}}export{i as MACHINE_OPS,d as MachineCallFailedError,l as MachineLaunchUncertainError,h as MachineLostError,c as MachineOfflineError};
|
|
@@ -11,10 +11,11 @@ export declare function cachedBrokerNodeFields(node: BrokerExtensionNodeDTO): Br
|
|
|
11
11
|
* (D39): a grant id, run or node id, structured request, queue, limit, or environment object. `fault_retry` carries a node id: the
|
|
12
12
|
* fault-retry backstop publishes it in the commit that claims the nudge, and the API process holding that node's stream turns it
|
|
13
13
|
* into a `fault-retry` line. `machine` carries a machine environment object id (a call is pending for the API process holding its link);
|
|
14
|
-
* `machine_call` carries a call id (the caller waiting on it re-reads the row)
|
|
14
|
+
* `machine_call` carries a call id (the caller waiting on it re-reads the row); `execution_exit` carries a node id whose machine broker
|
|
15
|
+
* exited (the lane processes run that node's lifecycle pass). `document` carries a document object id: it was edited or
|
|
15
16
|
* deleted, and a browser document stream re-reads it. The writers fire them (the
|
|
16
17
|
* schema's triggers, or the unit that owns the writer); the bus only delivers. */
|
|
17
|
-
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document"];
|
|
18
|
+
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document", "execution_exit"];
|
|
18
19
|
export type BrokerSignalKind = (typeof BROKER_SIGNAL_KINDS)[number];
|
|
19
20
|
export type BrokerSignalSubscriber = (id: string, kind: BrokerSignalKind) => void;
|
|
20
21
|
export interface BrokerSignalSubscription {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|
|
1
|
+
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","execution_exit"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|
package/dist/daemon/crtrd.d.ts
CHANGED
|
@@ -9,6 +9,10 @@ interface DaemonTickLifecycle extends DetachedWorkLifecycle {
|
|
|
9
9
|
}
|
|
10
10
|
/** Supervision tick over the daemon's current live set. */
|
|
11
11
|
export declare function superviseTick(now?: number, lifecycle?: DaemonTickLifecycle): Promise<void>;
|
|
12
|
+
/** The node-lifecycle pass for one node whose machine broker exit was just reported (`execution_exit`), as the tick would run it.
|
|
13
|
+
* Every lane process hears the signal; only a pass that still finds the exit unconsumed runs, because the one that consumed it already
|
|
14
|
+
* decided (a later one would read the cleared pid as a stranded launch). A node whose stop is held is left to its stopper by the pass. */
|
|
15
|
+
export declare function exitedNodePass(nodeId: string, now?: number): Promise<void>;
|
|
12
16
|
export interface DaemonOpts {
|
|
13
17
|
/** Milliseconds between supervision polls. Default 2000. */
|
|
14
18
|
intervalMs?: number;
|