@north-light/cli 0.3.773 → 0.3.774
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/grants/mirror.js +5 -5
- package/dist/core/grants/shadow.d.ts +11 -0
- package/dist/core/grants/shadow.js +1 -1
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var n=(e,r)=>L(e,"name",{value:r,configurable:!0});import{createHash as C}from"node:crypto";import{parsePrincipal as T,parseScope as M}from"@north-light/identity";import{openDb as l,withCanvasWrite as F}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as O,userSubject as $}from"../permissions/facts.js";import{GROUP_TYPE as _,OBJECT_TYPE as k}from"../permissions/builtin.js";import{liveReads as P,liveRecord as U,shadowCheck as G}from"./shadow.js";const H=["not_started","pending","ready","failed","unavailable"],W=["ultra","strong","medium","light"];function J(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(J,"principalPayer");function V(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(V,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function c(e,r,t=[]){const s=x();return await(await l()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(c,"grantRows");async function u(e,r,t=[]){return(await c(e,r,t))[0]}n(u,"grantRow");function q(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(q,"jsonbSafe");function p(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"||!q(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(p,"entries");function B(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!H.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(B,"dependencyOf");function j(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=B(s);o&&(r[t]=o)}return r}n(j,"dependenciesOf");function X(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 o of W){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(X,"inferenceEndpointOf");function w(e,r,t,s){return r===e&&t&&s}n(w,"computedFor");function f(e){if(!w(e.rev,e.computed_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,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:p(JSON.parse(e.scopes_json)),resolved_scopes:p(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:j(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?X(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(f,"record");async function d(e){if(!e||e.status!=="active")return null;try{if(P()){const t=await U(e,()=>f(e));return t===null?null:(p(t.scopes),h({...t,resolved_scopes:p(t.resolved_scopes)}))}const r=h(f(e));return r!==null&&G(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(d,"active");function y(e){return e.grantee!=="app:terminal"&&A()}n(y,"mirrorOnly");async function fe(){return(await K()).filter(e=>!y(e))}n(fe,"localGrants");async function _e(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(_e,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",Y=new RegExp(`^(${g}):(${g}|\\*)$`);function z(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=Y.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(z,"providerIdsFromGrants");async function ye(){const e=x();return(await(await l()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
2
2
|
SELECT DISTINCT e->>'scope' AS scope FROM (
|
|
3
3
|
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${S()}${e.sql}) d OFFSET 0) p
|
|
4
4
|
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
|
|
5
5
|
CROSS JOIN LATERAL regexp_match(s.scope, '^(${g}):(?:${g}|\\*)$') m
|
|
6
|
-
WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(
|
|
6
|
+
WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(ye,"activeProviderIds");async function ge(){const e=x();return await(await l()).prepare(`SELECT 1 FROM grants WHERE ${m}${S()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(ge,"anyActiveGrant");async function Ee(e,r){return await u("1",`sub = ? AND ${m}${S()} AND EXISTS (
|
|
7
7
|
SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
8
|
-
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(
|
|
8
|
+
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(Ee,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",Z="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function S(){return A()?" AND grantee = 'app:terminal'":""}n(S,"localOnly");async function ve(){return(await c("DISTINCT sub",Z)).map(e=>e.sub)}n(ve,"grantSubs");async function xe(e){return b(e===void 0?await c("*","status = 'active'"):await c("*","sub = ? AND status = 'active'",[e]))}n(xe,"activeGrants");async function me(e){const r=await c("*","sub = ? AND status = 'active'",[e]);return new Set(z(r.flatMap(t=>{try{return[f(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(me,"grantedProviderIds");function Se(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(Se,"isProviderBundleRow");async function Ne(e){const r=await c("*","sub = ? AND status = 'active'",[e]);return(await Promise.all(r.map(d))).flatMap(t=>t===null?[]:[t])}n(Ne,"activeGrantsOfPerson");async function K(){return b(await c("*","true"))}n(K,"allGrants");async function Te(e){return(await c("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!w(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:p(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(Te,"grantsOfPerson");function b(e){return e.flatMap(r=>{try{return[f(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(b,"records");function Q(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(Q,"grantExpired");function h(e){if(e.status!=="active"||Q(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>M(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(h,"activeRecord");function N(e){return Array.isArray(e)?`[${e.map(N).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${N(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(N,"canonicalJson");function Ae(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 C("sha256").update(N(r)).digest("base64url").slice(0,22)}n(Ae,"grantVersion");async function Oe(e){return!!await u("1","id = ?",[e])}n(Oe,"hasGrant");async function je(e){return await u("rev, status","id = ?",[e])??null}n(je,"grantSyncState");async function we(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(we,"grantSyncStateFor");async function ee(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(ee,"grantRecord");async function be(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=await d(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(be,"grantStanding");async function he(e){return(await c("id",e)).map(r=>r.id)}n(he,"grantIdsWhere");async function Re(e){const r=e?await ee(e):null;return r!==null&&V(r)?"app":"user"}n(Re,"payerOfGrant");async function re(e){return d(await u("*","id = ?",[e]))}n(re,"activeGrant");async function De(e,r){const t=await u("*","grantee = ? AND grantee_prefix IS NULL AND sub = ?",[e,r]);if(t)return d(t);const s=await c("*","sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)",[r,e]);return s.sort((o,a)=>a.grantee_prefix.length-o.grantee_prefix.length),d(s[0])}n(De,"grantFor");async function Ie(e){if(y({grantee:e}))return null;const r=await c("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}n(Ie,"activeGrantForApp");async function Le(e){const r=await re(e);return r&&r.run_notice_url&&!y(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(Le,"runNoticeTarget");async function Ce(e){const r=await c("*","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(Ce,"terminalGrant");async function Me(){return(await(await l()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Me,"grantsSource");async function Fe(e){return(await(await l()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Fe,"hasSyncedGrants");async function $e(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($e,"dropLocalGrantMirror");function ke(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n(ke,"teamsOf");async function Pe(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");if(a.grantee==="*"!=(a.grantee_prefix!=null))throw new TypeError("invalid grant sync response");o.add(a.id),p(a.scopes),p(a.resolved_scopes)}await F(async a=>{let E=0;const v=[...o];E+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const R=a.prepare(`INSERT INTO grants
|
|
9
9
|
(id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
10
10
|
status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
|
|
11
11
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -19,6 +19,6 @@ var I=Object.defineProperty;var n=(e,r)=>I(e,"name",{value:r,configurable:!0});i
|
|
|
19
19
|
grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
|
|
20
20
|
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
21
21
|
excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
|
|
22
|
-
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const i of e)E+=Number((await
|
|
22
|
+
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const i of e)E+=Number((await R.run(i.id,i.runtime,i.sub,i.grantee,i.grantee_prefix??null,i.rev,JSON.stringify(i.scopes),JSON.stringify(i.resolved_scopes),i.spend_cap,i.expires_at,i.status,i.revoked_at,i.approved_at,J(i.payer,i.sub,i.grantee),JSON.stringify(j(i.dependencies)),i.run_notice_url??null,i.inference_endpoint?JSON.stringify(i.inference_endpoint):null,i.synced_at,i.rev)).changes);await O(a,"directory",_,"member",s.flatMap(({team:i,members:D})=>D.map(I=>({resourceId:i,subject:$(I)})))),await se(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.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(Pe,"replaceGrants");const te=["editor","messenger","user_of"],ne="app-admin";async function se(e){const t=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
|
|
23
23
|
JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
|
|
24
|
-
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(
|
|
24
|
+
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(_)).map(s=>({resourceId:s.object,subject:s.subject_type===_?{type:_,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of te)await O(e,ne,k,s,t)}n(se,"reconcileAppAdminFacts");async function Ue(){const e=await(await l()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Ue,"grantsGeneration");export{ne as APP_ADMIN_WRITER,re as activeGrant,Ie as activeGrantForApp,Ee as activeGrantNamesApp,xe as activeGrants,Ne as activeGrantsOfPerson,ye as activeProviderIds,h as activeRecord,K as allGrants,ge as anyActiveGrant,N as canonicalJson,j as dependenciesOf,$e as dropLocalGrantMirror,V as endpointPays,Q as grantExpired,De as grantFor,he as grantIdsWhere,ee as grantRecord,be as grantStanding,ve as grantSubs,je as grantSyncState,we as grantSyncStateFor,Ae as grantVersion,me as grantedProviderIds,Ue as grantsGeneration,Te as grantsOfPerson,Me as grantsSource,Oe as hasGrant,Fe as hasSyncedGrants,X as inferenceEndpointOf,Se as isProviderBundleRow,fe as localGrants,y as mirrorOnly,_e as otherLiveGrantOfApp,Re as payerOfGrant,J as principalPayer,z as providerIdsFromGrants,se as reconcileAppAdminFacts,Pe as replaceGrants,Le as runNoticeTarget,x as runtimeScope,ke as teamsOf,Ce as terminalGrant};
|
|
@@ -3,6 +3,9 @@ import { type GrantRecord } from './mirror.js';
|
|
|
3
3
|
export declare function setShadowTtl(ms: number): void;
|
|
4
4
|
/** Test hook: forget every cached answer. */
|
|
5
5
|
export declare function resetShadowCache(): void;
|
|
6
|
+
/** Drop `sub`'s cached answer, or every answer when `sub` is null. Called on a `grant:<id>` signal (and on a listen restart, when signals
|
|
7
|
+
* may have been lost), so the next read after a grant write re-asks the directory instead of serving the pre-write answer for up to the TTL. */
|
|
8
|
+
export declare function forgetShadowAnswer(sub: string | null): void;
|
|
6
9
|
/** How many checks agreed, disagreed (live answer differs at the same rev), lagged (live rev differs: a sync has not landed) or failed since this process started. */
|
|
7
10
|
export declare const shadowCounts: {
|
|
8
11
|
agree: number;
|
|
@@ -13,3 +16,11 @@ export declare const shadowCounts: {
|
|
|
13
16
|
export declare function shadowIdle(): Promise<void>;
|
|
14
17
|
/** Compare one stored grant with the directory's live answer, in the background, on the fleet only. Never throws and never delays the caller. */
|
|
15
18
|
export declare function shadowCheck(stored: GrantRecord): void;
|
|
19
|
+
/** Phase 5 read flag: on the fleet, with `CRTR_GRANT_LIVE_READS=1`, a grant's answer comes from the directory, not the stored columns.
|
|
20
|
+
* Rollback is unsetting it; the stored columns are still written until phase 6. */
|
|
21
|
+
export declare function liveReads(): boolean;
|
|
22
|
+
/** The grant a stored row stands for, as the directory answers it now: the row gives identity (id, runtime, sub, grantee), the live answer
|
|
23
|
+
* gives everything that decides access. Null when the live answer no longer holds the grant. A wildcard-grantee row (`grantee_prefix`)
|
|
24
|
+
* is not in the per-sub answer, so it keeps its stored columns until the directory serves it. Throws on a directory failure: the caller
|
|
25
|
+
* refuses rather than reading the columns. */
|
|
26
|
+
export declare function liveRecord(row: Pick<GrantRecord, 'id' | 'runtime' | 'sub' | 'grantee' | 'grantee_prefix'> & Record<string, unknown>, stored: () => GrantRecord): Promise<GrantRecord | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var
|
|
1
|
+
var $=Object.defineProperty;var o=(e,r)=>$(e,"name",{value:r,configurable:!0});import{directoryIssuer as h}from"../directory/issuer.js";import{outboundFetch as k}from"../events/outbound.js";import{warn as f}from"../output.js";import{canonicalJson as w,dependenciesOf as E,inferenceEndpointOf as M,endpointPays as T,principalPayer as S}from"./mirror.js";let x=5e3;function F(e){x=e}o(F,"setShadowTtl");const b=512,N=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function L(){g.clear()}o(L,"resetShadowCache");const g=new Map,d=new Map,_=new Map;function j(e){const r=e===null?[...new Set([...g.keys(),...d.keys()])]:[e];for(const n of r)g.delete(n),d.delete(n),_.set(n,(_.get(n)??0)+1)}o(j,"forgetShadowAnswer");const c={agree:0,disagree:0,lagging:0,error:0};async function O(e,r,n){const{mintDirectoryToken:s}=await import("./sync.js"),a=await s(e),p=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",t=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${p}`,i=await k("grant_shadow",t,{headers:{Authorization:`Bearer ${a.access_token}`},signal:AbortSignal.timeout(1e4)});if(!i.ok)throw new Error(`grant-answers ${i.status}`);const l=await i.json();if(l.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:l.epochs,checkedAt:Date.now()}}return{epochs:l.epochs,grants:new Map((l.grants??[]).map(y=>[String(y.id),y])),checkedAt:Date.now()}}o(O,"fetchAnswer");async function A(e,r){const n=g.get(r);if(n&&Date.now()-n.checkedAt<x)return n;const s=d.get(r);if(s)return s;const a=_.get(r)??0,p=O(e,r,n).then(t=>((_.get(r)??0)!==a||(g.delete(r),g.set(r,t),g.size>b&&g.delete(g.keys().next().value)),t)).finally(()=>{d.get(r)===p&&d.delete(r)});return d.set(r,p),p}o(A,"answerFor");const m=new Set;async function G(){await Promise.all([...m])}o(G,"shadowIdle");async function C(e){const r=h();if(r===null)return;const n=(await A(r,e.sub)).grants.get(e.id);if(!n){c.disagree++,f(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){c.lagging++;return}const s={...n,payer:S(n.payer,e.sub,e.grantee)},a={...e,resolved_scopes:I(e.resolved_scopes,n.resolved_scopes)},p=N.filter(t=>t==="resolved_scopes"?R(s[t])!==R(a[t]):w(s[t]??null)!==w(a[t]??null));if(p.length===0){c.agree++;return}c.disagree++,f(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:p})}`)}o(C,"compare");function R(e){return Array.isArray(e)?JSON.stringify([...new Set(e.map(r=>`${r.scope}|${r.mode}`))].sort()):w(e??null)}o(R,"scopeSet");function I(e,r){if(!Array.isArray(r))return e;const n=new Set(r.flatMap(t=>{const i=t?.scope;return typeof i=="string"?[i]:[]})),s=new Set([...n].filter(t=>t.endsWith(":*")).map(t=>t.slice(0,-2)));if(s.size===0)return e;const a=new Set;return e.flatMap(t=>{const i=t.scope.slice(0,t.scope.indexOf(":"));if(i==="crtr"||!s.has(i))return[t];const l=a.has(i)?[]:[{...t,scope:`${i}:*`}];return a.add(i),n.has(t.scope)?[t,...l]:l})}o(I,"compactLike");let v,u={agree:0,disagree:0,lagging:0,error:0};function D(){v||(v=setInterval(()=>{const e={agree:c.agree-u.agree,disagree:c.disagree-u.disagree,lagging:c.lagging-u.lagging,error:c.error-u.error};u={...c},e.agree+e.disagree+e.lagging+e.error>0&&f(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),v.unref())}o(D,"startSummary");function V(e){if(!process.env.CRTR_RUNTIME)return;D();const r=C(e).catch(n=>{c.error++,f(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>m.delete(r));m.add(r)}o(V,"shadowCheck");function W(){return!!process.env.CRTR_RUNTIME&&process.env.CRTR_GRANT_LIVE_READS==="1"&&h()!==null}o(W,"liveReads");async function X(e,r){if(e.grantee_prefix)return r();const n=(await A(h(),e.sub)).grants.get(e.id);if(!n)return null;const s=n.status;if(s!=="active"&&s!=="revoked"&&s!=="removed")throw new TypeError("invalid live grant status");if(!Number.isInteger(n.rev))throw new TypeError("invalid live grant rev");const a=S(n.payer,e.sub,e.grantee);return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:null,rev:n.rev,scopes:n.scopes,resolved_scopes:n.resolved_scopes,spend_cap:typeof n.spend_cap=="number"?n.spend_cap:null,expires_at:typeof n.expires_at=="string"?n.expires_at:null,status:s,revoked_at:typeof n.revoked_at=="string"?n.revoked_at:null,approved_at:e.approved_at??null,payer:a,dependencies:E(n.dependencies),run_notice_url:typeof n.run_notice_url=="string"&&n.run_notice_url!==""?n.run_notice_url:null,inference_endpoint:T({payer:a})?M(n.inference_endpoint):null,synced_at:typeof n.synced_at=="string"?n.synced_at:""}}o(X,"liveRecord");export{j as forgetShadowAnswer,W as liveReads,X as liveRecord,L as resetShadowCache,F as setShadowTtl,V as shadowCheck,c as shadowCounts,G as shadowIdle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var x=Object.defineProperty;var a=(t,e)=>x(t,"name",{value:e,configurable:!0});import{canvasPoolSize as
|
|
1
|
+
var x=Object.defineProperty;var a=(t,e)=>x(t,"name",{value:e,configurable:!0});import{canvasPoolSize as R,openDb as p}from"../../core/canvas/db.js";import{isCloudRole as A}from"../../core/canvas/person.js";import{endExecution as M,liveExecutionForNode as D}from"../../core/canvas/executions.js";import{emitEvent as m}from"../../core/events/emit.js";import{afterRevocationStop as P}from"../../core/grants/on-sync.js";import{activeGrants as S,grantIdsWhere as E,grantStanding as g,mirrorOnly as G}from"../../core/grants/mirror.js";import{forgetShadowAnswer as _}from"../../core/grants/shadow.js";import{removeApp as C,removePersonData as F}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as W,wakeGrantWaiters as U}from"../../core/grants/watch.js";import{discardOrphanedTokens as b,discardTokensForGrant as B}from"../../core/providers/token-cache.js";import{isUnsandboxedMachine as $}from"../../core/runtime/unsandboxed.js";import{runnerForExecution as H}from"../../core/runtime/runner/index.js";import{closeGrantStreams as J,heldGrantIds as z}from"../../core/runs/events.js";import{stopNodeSandboxes as K}from"../../core/spaces/stop.js";import{holdRecovery as V}from"../../core/runtime/recovery-hold.js";import{brokerSignalBus as k}from"../broker-signals/bus.js";import{withRowClaim as X}from"./row-claim.js";const Y=6e4,j=a(()=>Math.max(1,Math.floor(R()/3)),"grantSlotLimit");let h=0;const L=[];async function q(t){for(;h>=j();)await new Promise(e=>{L.push(e)});h+=1;try{return await t()}finally{h-=1,L.shift()?.()}}a(q,"withGrantSlot");const Q=3e4,Z=5;function d(t,e,r){m({level:"error",event:`daemon.grants.${t}`,error:e,fields:r})}a(d,"failed");function I(t,e,r){try{const n=e.sub===null||e.grantee===null?b(r):B({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},r);n.tokens>0&&m({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:n.tokens}})}catch(n){d("outbound_tokens_discard_failed",n,{grant:t})}}a(I,"discardTokens");async function N(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){m({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}a(N,"reconcileProviderBundles");async function ee(t,e){if(U(t),e.standing==="inactive"){const r=J(t);r>0&&m({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:r}})}await N()}a(ee,"serveEffects");async function te(t,e){const r=await X("nodes",t,Y,async n=>{const o=await D(t);if(o===null)return;await n.assertOwned(),m({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:o.executionId}});const c=a(async()=>{await n.assertOwned(),await M(o.executionId,{reason:"permission_revoked"}),await P(t)},"finish");if(o.runner==="process"){const u=await K(t,"permission_revoked",{holdRecovery:!0,after:c});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);return}const w=await V(t);if(w!==null)try{const u=await H(o.runner).stop(o,{reason:"permission_revoked"});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);await c()}finally{await w.release()}},{waitForLock:!0})}a(te,"stopRevokedNode");async function re(t,e){if(!(e.grantee!==null&&G({grantee:e.grantee}))){if(e.standing==="inactive"){const r=await(await p()).prepare("SELECT DISTINCT n.node_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id = ?").all(t);for(const{node_id:n}of r)try{await te(n,t)}catch(o){d("node_stop_failed",o,{grant:t,node_id:n})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await C(e.grantee,e.sub):A()?await F(e.grantee,e.sub):m({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await p()).prepare("UPDATE grants SET removal_done_at = ? WHERE id = ? AND rev = ? AND removal_done_at IS NULL").run(new Date().toISOString(),t,e.rev)}catch(r){d("removal_failed",r,{grant:t,grantee:e.grantee})}}}a(re,"laneEffects");async function ne(t,e,r){let n;await q(async()=>{const o=await g(e);I(e,o,r??await S(o.sub??void 0)),t.serves&&(n=ee(e,o)),t.runsLanes&&o.standing!=="lagging"&&await re(e,o)}),await n}a(ne,"applyGrantEffects");async function ae(t){const e=new Set;if(t.serves)for(const n of z())e.add(n);if(t.runsLanes){const n=await(await p()).prepare("SELECT DISTINCT n.grant_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id IS NOT NULL").all();for(const{grant_id:o}of n)e.add(o)}const r=[];for(const n of e)(await g(n)).status===null&&r.push(n);return r}a(ae,"goneGrantIds");async function ke(t,e={}){const r=new Map,n=a((s,l)=>{const i=(r.get(s)??Promise.resolve()).then(()=>ne(t,s,l)).catch(f=>d("effects_failed",f,{grant:s})).finally(()=>{r.get(s)===i&&r.delete(s)});return r.set(s,i),i},"run"),o=a(async()=>{const s=t.serves?N():void 0;try{t.serves&&W();const l=await S();b(l);const i=new Set(await E(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const f of await ae(t))i.add(f);await Promise.all([...i].map(f=>n(f,l)))}catch(l){d("catch_up_failed",l,{})}await s},"catchUp"),c=new Map;let w=!1;const u=a(async()=>{if(!w){w=!0;try{const s=new Set(await E(`status = 'removed' AND removal_done_at IS NULL${$()?" AND grantee = 'app:terminal'":""}`));for(const i of c.keys())s.has(i)||c.delete(i);const l=[...s].filter(i=>!r.has(i)&&(c.get(i)?.notBefore??0)<=Date.now());await Promise.all(l.map(async i=>{await n(i);const f=(c.get(i)?.failures??0)+1;c.set(i,{failures:f,notBefore:Date.now()+y*2**Math.min(f,Z)})}))}catch(s){d("removal_sweep_failed",s,{})}finally{w=!1}}},"sweepRemovals"),y=e.sweepMs??Q,v=t.runsLanes?setInterval(()=>{u()},y):void 0;v?.unref();const O=await k.subscribe(s=>{n(s)},{kinds:["grant"],onListenStart:a(()=>{o()},"onListenStart")}),T=await k.subscribe(s=>{oe(s)},{kinds:["grant"],onListenStart:a(()=>{_(null)},"onListenStart")});return()=>{v!==void 0&&clearInterval(v),O(),T()}}a(ke,"startGrantEffects");async function oe(t){try{const e=await(await p()).prepare("SELECT sub FROM grants WHERE id = ?").get(t);_(e?.sub??null)}catch(e){_(null),d("answer_forget_failed",e,{grant:t})}}a(oe,"forgetAnswerOf");export{ne as applyGrantEffects,ke as startGrantEffects};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.774",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.774",
|
|
161
|
+
"@north-light/plugin": "0.3.774",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.774",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.774",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.774",
|
|
31
|
+
"@north-light/identity": "0.3.774"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
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.774",
|
|
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.774",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
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.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.774",
|
|
32
|
+
"@north-light/plugin": "0.3.774",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.774",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.774",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.774",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.774",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.774",
|
|
11927
|
+
"@north-light/identity": "0.3.774"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.774",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.774",
|
|
11936
|
+
"@north-light/identity": "0.3.774",
|
|
11937
|
+
"@north-light/plugin": "0.3.774",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|