@north-light/cli 0.3.614 → 0.3.616

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.
@@ -59,6 +59,9 @@ export declare function inferenceEndpointOf(value: unknown): InferenceEndpoint |
59
59
  export declare function mirrorOnly(grant: Pick<GrantRecord, 'grantee'>): boolean;
60
60
  /** Every mirrored grant this machine acts on: `allGrants()` without the mirror-only ones. */
61
61
  export declare function localGrants(): Promise<GrantRecord[]>;
62
+ /** Whether a grant of `app` other than `sub`'s is mirrored here and not removed, read from the rows as they are now: the removal
63
+ * cascade asks it once per removed grant, so it queries one row instead of parsing the whole mirror (`localGrants()`). */
64
+ export declare function otherLiveGrantOfApp(app: string, sub: string): Promise<boolean>;
62
65
  /** Every provider id a scope of an active grant's resolved set names: a
63
66
  * `<id>:<group>` string whose id is not `crtr` (the runtime's own namespace). */
64
67
  export declare function providerIdsFromGrants(grants: readonly GrantRecord[]): string[];
@@ -1,4 +1,4 @@
1
- var N=Object.defineProperty;var t=(e,r)=>N(e,"name",{value:r,configurable:!0});import{createHash as O}from"node:crypto";import{parseScope as h}from"@north-light/identity";import{openDb as d,withCanvasWrite as m}from"../canvas/db.js";import{isUnsandboxedMachine as j}from"../runtime/unsandboxed.js";import{replaceWrittenBy as A,userSubject as b}from"../permissions/facts.js";import{GROUP_TYPE as R}from"../permissions/builtin.js";const D=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function I(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(I,"runtimeScope");async function c(e,r,n=[]){const s=I();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(c,"grantRows");async function u(e,r,n=[]){return(await c(e,r,n))[0]}t(u,"grantRow");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"||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function L(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!D.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(L,"dependencyOf");function x(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=L(s);a&&(r[n]=a)}return r}t(x,"dependenciesOf");function C(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of k){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(C,"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:x(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?C(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function p(e){if(!e||e.status!=="active")return null;try{return $(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(p,"active");function g(e){return e.grantee!=="app:terminal"&&j()}t(g,"mirrorOnly");async function Y(){return(await G()).filter(e=>!g(e))}t(Y,"localGrants");const E="[A-Za-z0-9_-]{1,64}",M=new RegExp(`^(${E}):(${E})$`);function F(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=M.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(F,"providerIdsFromGrants");async function Z(e){const r=await c("*","sub = ? AND status = 'active'",[e]);return new Set(F(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(Z,"grantedProviderIds");function K(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(K,"isProviderBundleRow");async function Q(e){return(await c("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=p(n);return s===null?[]:[s]})}t(Q,"activeGrantsOfPerson");async function G(){return(await c("*","true")).flatMap(e=>{try{return[f(e)]}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return[];throw r}})}t(G,"allGrants");function U(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(U,"grantExpired");function $(e){if(e.status!=="active"||U(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>h(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t($,"activeRecord");function v(e){return Array.isArray(e)?`[${e.map(v).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${v(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(v,"canonicalJson");function ee(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 O("sha256").update(v(r)).digest("base64url").slice(0,22)}t(ee,"grantVersion");async function re(e){return!!await u("1","id = ?",[e])}t(re,"hasGrant");async function ne(e){return await u("rev, status","id = ?",[e])??null}t(ne,"grantSyncState");async function te(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(te,"grantSyncStateFor");async function P(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(P,"grantRecord");async function se(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 n={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{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=p(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(se,"grantStanding");async function ae(e){return(await c("id",e)).map(r=>r.id)}t(ae,"grantIdsWhere");async function oe(e){return(e?(await P(e))?.payer:null)??"user"}t(oe,"payerOfGrant");async function W(e){return p(await u("*","id = ?",[e]))}t(W,"activeGrant");async function ie(e,r){return p(await u("*","grantee = ? AND sub = ?",[e,r]))}t(ie,"grantFor");async function ce(e){if(g({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 p(r[0])}t(ce,"activeGrantForApp");async function ue(e){const r=await W(e);return r&&r.run_notice_url&&!g(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(ue,"runNoticeTarget");async function pe(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 p(r[0])}t(pe,"terminalGrant");async function de(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(de,"grantsSource");async function le(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(le,"hasSyncedGrants");async function fe(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))}t(fe,"dropLocalGrantMirror");async function _e(){return await m(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))}t(_e,"backfillComputedRev");function ye(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(ye,"teamsOf");async function ge(e,r,n,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 m(async o=>{let _=0;const y=[...a];_+=Number((await(y.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${y.map(()=>"?").join(",")})`).run(...y):o.prepareUncached("DELETE FROM grants").run())).changes);const S=o.prepare(`INSERT INTO grants
1
+ var w=Object.defineProperty;var t=(e,r)=>w(e,"name",{value:r,configurable:!0});import{createHash as O}from"node:crypto";import{parseScope as h}from"@north-light/identity";import{openDb as d,withCanvasWrite as m}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as j,userSubject as b}from"../permissions/facts.js";import{GROUP_TYPE as R}from"../permissions/builtin.js";const D=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function I(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(I,"runtimeScope");async function u(e,r,n=[]){const s=I();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(u,"grantRows");async function c(e,r,n=[]){return(await u(e,r,n))[0]}t(c,"grantRow");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"||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function L(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!D.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(L,"dependencyOf");function x(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=L(s);a&&(r[n]=a)}return r}t(x,"dependenciesOf");function C(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of k){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(C,"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:x(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?C(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function p(e){if(!e||e.status!=="active")return null;try{return $(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(p,"active");function _(e){return e.grantee!=="app:terminal"&&A()}t(_,"mirrorOnly");async function Y(){return(await G()).filter(e=>!_(e))}t(Y,"localGrants");async function Z(e,r){return!_({grantee:e})&&await c("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(Z,"otherLiveGrantOfApp");const E="[A-Za-z0-9_-]{1,64}",M=new RegExp(`^(${E}):(${E})$`);function F(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=M.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(F,"providerIdsFromGrants");async function K(e){const r=await u("*","sub = ? AND status = 'active'",[e]);return new Set(F(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(K,"grantedProviderIds");function Q(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(Q,"isProviderBundleRow");async function ee(e){return(await u("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=p(n);return s===null?[]:[s]})}t(ee,"activeGrantsOfPerson");async function G(){return(await u("*","true")).flatMap(e=>{try{return[f(e)]}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return[];throw r}})}t(G,"allGrants");function U(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(U,"grantExpired");function $(e){if(e.status!=="active"||U(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>h(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t($,"activeRecord");function v(e){return Array.isArray(e)?`[${e.map(v).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${v(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(v,"canonicalJson");function re(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 O("sha256").update(v(r)).digest("base64url").slice(0,22)}t(re,"grantVersion");async function ne(e){return!!await c("1","id = ?",[e])}t(ne,"hasGrant");async function te(e){return await c("rev, status","id = ?",[e])??null}t(te,"grantSyncState");async function se(e,r){return await c("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(se,"grantSyncStateFor");async function P(e){const r=await c("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(P,"grantRecord");async function ae(e){const r=await c("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={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{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=p(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ae,"grantStanding");async function oe(e){return(await u("id",e)).map(r=>r.id)}t(oe,"grantIdsWhere");async function ie(e){return(e?(await P(e))?.payer:null)??"user"}t(ie,"payerOfGrant");async function W(e){return p(await c("*","id = ?",[e]))}t(W,"activeGrant");async function ce(e,r){return p(await c("*","grantee = ? AND sub = ?",[e,r]))}t(ce,"grantFor");async function ue(e){if(_({grantee:e}))return null;const r=await u("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}t(ue,"activeGrantForApp");async function pe(e){const r=await W(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(pe,"runNoticeTarget");async function de(e){const r=await u("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}t(de,"terminalGrant");async function le(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(le,"grantsSource");async function fe(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(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))}t(_e,"dropLocalGrantMirror");async function ye(){return await m(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))}t(ye,"backfillComputedRev");function ge(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(ge,"teamsOf");async function ve(e,r,n,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 m(async o=>{let y=0;const g=[...a];y+=Number((await(g.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):o.prepareUncached("DELETE FROM grants").run())).changes);const S=o.prepare(`INSERT INTO grants
2
2
  (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
3
3
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -12,4 +12,4 @@ var N=Object.defineProperty;var t=(e,r)=>N(e,"name",{value:r,configurable:!0});i
12
12
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
13
13
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
14
14
  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 i of e)_+=Number((await S.run(i.id,i.runtime,i.sub,i.grantee,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,i.payer,JSON.stringify(x(i.dependencies)),i.run_notice_url??null,i.inference_endpoint?JSON.stringify(i.inference_endpoint):null,i.synced_at,i.rev)).changes);await A(o,"directory",R,"member",s.flatMap(({team:i,members:T})=>T.map(w=>({resourceId:i,subject:b(w)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),_>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()})}t(ge,"replaceGrants");async function ve(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(ve,"grantsGeneration");export{W as activeGrant,ce as activeGrantForApp,Q as activeGrantsOfPerson,$ as activeRecord,G as allGrants,_e as backfillComputedRev,x as dependenciesOf,fe as dropLocalGrantMirror,U as grantExpired,ie as grantFor,ae as grantIdsWhere,P as grantRecord,se as grantStanding,ne as grantSyncState,te as grantSyncStateFor,ee as grantVersion,Z as grantedProviderIds,ve as grantsGeneration,de as grantsSource,re as hasGrant,le as hasSyncedGrants,C as inferenceEndpointOf,K as isProviderBundleRow,Y as localGrants,g as mirrorOnly,oe as payerOfGrant,F as providerIdsFromGrants,ge as replaceGrants,ue as runNoticeTarget,I as runtimeScope,ye as teamsOf,pe as terminalGrant};
15
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const i of e)y+=Number((await S.run(i.id,i.runtime,i.sub,i.grantee,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,i.payer,JSON.stringify(x(i.dependencies)),i.run_notice_url??null,i.inference_endpoint?JSON.stringify(i.inference_endpoint):null,i.synced_at,i.rev)).changes);await j(o,"directory",R,"member",s.flatMap(({team:i,members:T})=>T.map(N=>({resourceId:i,subject:b(N)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),y>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()})}t(ve,"replaceGrants");async function me(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(me,"grantsGeneration");export{W as activeGrant,ue as activeGrantForApp,ee as activeGrantsOfPerson,$ as activeRecord,G as allGrants,ye as backfillComputedRev,x as dependenciesOf,_e as dropLocalGrantMirror,U as grantExpired,ce as grantFor,oe as grantIdsWhere,P as grantRecord,ae as grantStanding,te as grantSyncState,se as grantSyncStateFor,re as grantVersion,K as grantedProviderIds,me as grantsGeneration,le as grantsSource,ne as hasGrant,fe as hasSyncedGrants,C as inferenceEndpointOf,Q as isProviderBundleRow,Y as localGrants,_ as mirrorOnly,Z as otherLiveGrantOfApp,ie as payerOfGrant,F as providerIdsFromGrants,ve as replaceGrants,pe as runNoticeTarget,I as runtimeScope,ge as teamsOf,de as terminalGrant};
@@ -1 +1 @@
1
- var h=Object.defineProperty;var l=(r,o)=>h(r,"name",{value:o,configurable:!0});import{rmSync as O}from"node:fs";import{join as D}from"node:path";import{deleteNodes as T,nodeFiles as C,removeNodeFiles as F}from"../canvas/canvas.js";import{hasUnreconciledWorktree as W}from"../canvas/worktrees.js";import{withCanvasWrite as p,openDb as m}from"../canvas/db.js";import{cancelCron as L}from"../canvas/crons.js";import{emitEvent as w}from"../events/emit.js";import{appSpace as N,appsRoot as u,secretsDir as H}from"../layout.js";import{notifyRunDeleted as y}from"../runs/events.js";import{cancelOpenQuestions as M}from"../runs/questions.js";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{markGranteeUploadsDeletePending as U,releaseRunUploads as A,turnSharesOffFor as q}from"../storage/tables.js";import{stopNodeSandboxes as I}from"../spaces/stop.js";import{activeAppUser as P,markAppUserRemoved as k}from"../spaces/users.js";import{launcherRequest as b}from"../../launcher/client.js";import{LaunchRefused as j}from"../../launcher/spec.js";import{localGrants as B}from"./mirror.js";import{launcherPresent as g,listSandboxes as x,stopSandboxPid as G}from"./sandboxes.js";import{filterAsync as R}from"../async-array.js";async function Ee(r,o){if(r==="app:terminal")throw new Error("app:terminal cannot be removed");const s=o===void 0||!(await B()).some(d=>d.grantee===r&&d.sub!==o&&d.status!=="removed");await _(r,o,s)}l(Ee,"removeApp");async function pe(r,o){await _(r,o,!1,!0)}l(pe,"removePersonData");async function _(r,o,s,d=!1){const f=N(r),t=s?await P(r):null;w({level:"info",event:"daemon.grants.removal_started",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:t?.uid??null}});const i=o===void 0?{sql:"grantee = ?",args:[r]}:{sql:"grantee = ? AND sub = ?",args:[r,o]};for(const{node_id:e}of await(await m()).prepare(`SELECT node_id FROM node_rows WHERE ${i.sql} ORDER BY created DESC`).all(...i.args))await M({node_id:e},"the app was removed");const a=await p(async e=>(await e.prepare(`UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id IN (SELECT node_id FROM node_rows WHERE ${i.sql})`).run(new Date().toISOString(),...i.args),(await e.prepare(`SELECT node_id FROM node_rows WHERE ${i.sql} ORDER BY created DESC`).all(...i.args)).map(n=>n.node_id)));for(const{cron_id:e}of await(await m()).prepare(`SELECT cron_id FROM crons WHERE ${i.sql}`).all(...i.args))await L(e);const c=(await Promise.all(a.map(e=>I(e,"app_removed",{deleting:!0})))).filter(e=>!e.confirmed);if(c.length)throw new Error(`sandbox teardown could not be confirmed for ${c.length} node(s) of ${r}`);if(t&&g())for(const e of await x())e.uid===t.uid&&await G(e.pid);const v=await R(a,async e=>(await(await m()).prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(e))?.run_id===e);if(await p(async e=>{if(s&&await q(r,e),await A(a,e),s&&await U(r,e),!a.length)return;const n=a.map(()=>"?").join(","),S=await e.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${n}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${n})`).all(...a,...a);await e.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${n})`).run(...a);for(const{message_id:E}of S)await e.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(E,E)}),d){const e=await R(a,W);if(e.length)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${e.join(", ")}`);for(const n of a)await F(await C(n))}await T(a);for(const e of v)y(e);if(s&&(O(D(H(),"env",f.root.slice(u().length+1)),{recursive:!0,force:!0}),$(u(),f.root)),t&&g())try{await b({operation:"user.delete",uid:t.uid})}catch(e){if(!(e instanceof j&&e.refusal==="invalid_uid"))throw e}t&&await k(t.uid),w({level:"info",event:"daemon.grants.removal_completed",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:t?.uid??null,nodes:a.length}})}l(_,"cascade");export{Ee as removeApp,pe as removePersonData};
1
+ var h=Object.defineProperty;var d=(r,o)=>h(r,"name",{value:o,configurable:!0});import{rmSync as O}from"node:fs";import{join as D}from"node:path";import{deleteNodes as T,nodeFiles as C,removeNodeFiles as F}from"../canvas/canvas.js";import{hasUnreconciledWorktree as L}from"../canvas/worktrees.js";import{withCanvasWrite as E,openDb as f}from"../canvas/db.js";import{cancelCron as W}from"../canvas/crons.js";import{emitEvent as p}from"../events/emit.js";import{appSpace as N,appsRoot as w,secretsDir as H}from"../layout.js";import{notifyRunDeleted as y}from"../runs/events.js";import{cancelOpenQuestions as M}from"../runs/questions.js";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{markGranteeUploadsDeletePending as A,releaseRunUploads as U,turnSharesOffFor as q}from"../storage/tables.js";import{stopNodeSandboxes as I}from"../spaces/stop.js";import{activeAppUser as P,markAppUserRemoved as k}from"../spaces/users.js";import{launcherRequest as j}from"../../launcher/client.js";import{LaunchRefused as B}from"../../launcher/spec.js";import{otherLiveGrantOfApp as b}from"./mirror.js";import{launcherPresent as u,listSandboxes as x,stopSandboxPid as G}from"./sandboxes.js";import{filterAsync as g}from"../async-array.js";async function Ee(r,o){if(r==="app:terminal")throw new Error("app:terminal cannot be removed");const s=o===void 0||!await b(r,o);await R(r,o,s)}d(Ee,"removeApp");async function pe(r,o){await R(r,o,!1,!0)}d(pe,"removePersonData");async function R(r,o,s,_=!1){const l=N(r),i=s?await P(r):null;p({level:"info",event:"daemon.grants.removal_started",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null}});const t=o===void 0?{sql:"grantee = ?",args:[r]}:{sql:"grantee = ? AND sub = ?",args:[r,o]};for(const{node_id:e}of await(await f()).prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args))await M({node_id:e},"the app was removed");const a=await E(async e=>(await e.prepare(`UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id IN (SELECT node_id FROM node_rows WHERE ${t.sql})`).run(new Date().toISOString(),...t.args),(await e.prepare(`SELECT node_id FROM node_rows WHERE ${t.sql} ORDER BY created DESC`).all(...t.args)).map(n=>n.node_id)));for(const{cron_id:e}of await(await f()).prepare(`SELECT cron_id FROM crons WHERE ${t.sql}`).all(...t.args))await W(e);const m=(await Promise.all(a.map(e=>I(e,"app_removed",{deleting:!0})))).filter(e=>!e.confirmed);if(m.length)throw new Error(`sandbox teardown could not be confirmed for ${m.length} node(s) of ${r}`);if(i&&u())for(const e of await x())e.uid===i.uid&&await G(e.pid);const v=await g(a,async e=>(await(await f()).prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(e))?.run_id===e);if(await E(async e=>{if(s&&await q(r,e),await U(a,e),s&&await A(r,e),!a.length)return;const n=a.map(()=>"?").join(","),S=await e.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${n}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${n})`).all(...a,...a);await e.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${n})`).run(...a);for(const{message_id:c}of S)await e.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(c,c)}),_){const e=await g(a,L);if(e.length)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${e.join(", ")}`);for(const n of a)await F(await C(n))}await T(a);for(const e of v)y(e);if(s&&(O(D(H(),"env",l.root.slice(w().length+1)),{recursive:!0,force:!0}),$(w(),l.root)),i&&u())try{await j({operation:"user.delete",uid:i.uid})}catch(e){if(!(e instanceof B&&e.refusal==="invalid_uid"))throw e}i&&await k(i.uid),p({level:"info",event:"daemon.grants.removal_completed",fields:{grantee:r,...o===void 0?{}:{sub:o},uid:i?.uid??null,nodes:a.length}})}d(R,"cascade");export{Ee as removeApp,pe as removePersonData};
@@ -1,6 +1,11 @@
1
- var M=Object.defineProperty;var c=(a,r)=>M(a,"name",{value:r,configurable:!0});import{zstdCompressSync as U,zstdDecompressSync as k}from"node:zlib";import{BODIES_TABLE as C,COPIED_TABLES as F,KEY_MAPPED_TABLES as w}from"../bundle/layout.js";import{q as s,rowKey as H,topologicalOrder as x}from"./catalog.js";import{fillEnvironments as v}from"./prepare.js";import{ImportLaneError as L}from"./stage.js";const b=c((a,r)=>`${s(a)}.${s(r)}`,"sq"),j=c(a=>U(Buffer.from(JSON.stringify(a))),"encodeKeys"),Y=c(a=>JSON.parse(k(a).toString("utf8")),"decodeKeys"),q=c(a=>x(a,F),"copyOrder");async function J(a){const{db:r,runId:S,schema:I,target:g,catalog:T,source:f}=a,o=c(e=>b(I,e),"S"),E=c(e=>b(g,e),"T"),d={inserted:{},mapped:{}},N=c(async(e,n)=>{d.inserted[e]=n.length,await r.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(S,e,j(n))},"manifest");for(const[e,n]of Object.entries(w)){const i=T.tables.get(e).columns.filter(p=>p!==n).map(s).join(", "),m=[],_=await r.prepareUncached(`SELECT ${s(n)}::text AS key FROM ${o(e)} ORDER BY ${s(n)}::bigint`).all();for(const{key:p}of _){const l=await r.prepareUncached(`INSERT INTO ${E(e)} (${i}) SELECT ${i} FROM ${o(e)} WHERE ${s(n)}::text = ? RETURNING ${s(n)}::text AS key`).get(p);await r.prepare("INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) VALUES (?, ?, ?, ?)").run(f.installId,e,p,l.key),m.push([l.key])}await N(e,m)}await r.prepareUncached(`UPDATE ${o("review_comments")} c SET created_seq = m.target_key::bigint FROM import_key_map m
2
- WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(f.installId);const h=q(T);for(const e of h){if(e in w)continue;if(e==="profiles"){if(h.indexOf("identities")>h.indexOf("profiles"))throw new L("copy","bundle_invalid","identities must be copied before profiles");await v(r,I,g,f,a.person)}const n=T.tables.get(e),O=Number((await r.prepareUncached(`SELECT count(*) AS n FROM ${o(e)}`).get()).n);if(O===0){d.inserted[e]=0;continue}const i=H(n),m=n.columns.filter(t=>!n.identity.includes(t)),_=n.identity.length>0?n.identity.map(t=>`s.${s(t)}`).join(", "):i.map(t=>`s.${s(t)}`).join(", ");let p=m.map(t=>`s.${s(t)}`),l="";if(e==="messages"){const t=`NOT EXISTS (SELECT 1 FROM ${E("messages")} t WHERE t.message_id = s.message_id)`,u=Number((await r.prepareUncached(`SELECT count(*) AS n FROM ${o("messages")} s WHERE ${t}`).get()).n);if(l=` WHERE ${t}`,u===0){d.inserted[e]=0,await N(e,[]);continue}const D=Number((await r.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(u)).seq);p=m.map(y=>y==="seq"?`${D-u} + row_number() OVER (ORDER BY s.seq)`:`s.${s(y)}`)}const A=i.map(t=>`${s(t)}::text`).join(", "),$=n.primaryKey.length===0;$&&(l=` WHERE NOT EXISTS (SELECT 1 FROM ${E(e)} t WHERE ${i.map(t=>`t.${s(t)} IS NOT DISTINCT FROM s.${s(t)}`).join(" AND ")})`);const R=await r.prepareUncached(`INSERT INTO ${E(e)} (${m.map(s).join(", ")}) SELECT ${p.join(", ")} FROM ${o(e)} s${l}
3
- ORDER BY ${_}${$?"":` ON CONFLICT (${i.map(s).join(", ")}) DO NOTHING`} RETURNING ${A}`).all();if(e===C){const t=await r.prepareUncached(`SELECT s.hash FROM ${o(e)} s JOIN ${E(e)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();if(t.length>0)throw new L("copy","unique_conflict",`the target holds other text under body ${t[0].hash}; its boot repair has not rekeyed that row`,{table:e,hashes:t.map(u=>u.hash)})}e===C?d.inserted[e]=R.length:await N(e,R.map(t=>Object.values(t))),d.mapped[e]=O-R.length}await r.prepareUncached(`DELETE FROM ${E("charge_totals")} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${o("charges")})`).run(),await r.prepareUncached(`INSERT INTO ${E("charge_totals")} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
1
+ var M=Object.defineProperty;var c=(s,r)=>M(s,"name",{value:r,configurable:!0});import{zstdCompressSync as D,zstdDecompressSync as U}from"node:zlib";import{BODIES_TABLE as C,COPIED_TABLES as F,KEY_MAPPED_TABLES as L}from"../bundle/layout.js";import{q as n,rowKey as H,topologicalOrder as j}from"./catalog.js";import{fillEnvironments as v}from"./prepare.js";import{ImportLaneError as w}from"./stage.js";const A=c((s,r)=>`${n(s)}.${n(r)}`,"sq"),x=c(s=>D(Buffer.from(JSON.stringify(s))),"encodeKeys"),V=c(s=>JSON.parse(U(s).toString("utf8")),"decodeKeys"),q=c(s=>j(s,F),"copyOrder");async function J(s){const{db:r,runId:T,schema:f,target:I,catalog:S,source:_}=s,E=c(e=>A(f,e),"S"),i=c(e=>A(I,e),"T"),m={inserted:{},mapped:{}},u=c(async(e,a)=>{m.inserted[e]=a.length,await r.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(T,e,x(a))},"manifest");for(const[e,a]of Object.entries(L)){const o=S.tables.get(e).columns.filter(p=>p!==a),l=await r.prepareUncached(`WITH src AS MATERIALIZED (
2
+ SELECT s.${n(a)}::text AS source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${o.map(p=>`s.${n(p)}`).join(", ")}
3
+ FROM (SELECT * FROM ${E(e)} ORDER BY ${n(a)}::bigint) s),
4
+ ins AS (INSERT INTO ${i(e)} (${n(a)}, ${o.map(n).join(", ")}) SELECT target_key, ${o.map(n).join(", ")} FROM src RETURNING 1),
5
+ km AS (INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) SELECT ?, ?, source_key, target_key::text FROM src RETURNING target_key)
6
+ SELECT target_key FROM km ORDER BY target_key::bigint`).all(i(e),a,_.installId,e);await u(e,l.map(p=>[p.target_key]))}await r.prepareUncached(`UPDATE ${E("review_comments")} c SET created_seq = m.target_key::bigint FROM import_key_map m
7
+ WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(_.installId);const g=q(S);for(const e of g){if(e in L)continue;if(e==="profiles"){if(g.indexOf("identities")>g.indexOf("profiles"))throw new w("copy","bundle_invalid","identities must be copied before profiles");await v(r,f,I,_,s.person)}const a=S.tables.get(e),d=Number((await r.prepareUncached(`SELECT count(*) AS n FROM ${E(e)}`).get()).n);if(d===0){m.inserted[e]=0;continue}const o=H(a),l=a.columns.filter(t=>!a.identity.includes(t)),p=a.identity.length>0?a.identity.map(t=>`s.${n(t)}`).join(", "):o.map(t=>`s.${n(t)}`).join(", ");let h=l.map(t=>`s.${n(t)}`),N="";if(e==="messages"){const t=`NOT EXISTS (SELECT 1 FROM ${i("messages")} t WHERE t.message_id = s.message_id)`,O=Number((await r.prepareUncached(`SELECT count(*) AS n FROM ${E("messages")} s WHERE ${t}`).get()).n);if(N=` WHERE ${t}`,O===0){m.inserted[e]=0,await u(e,[]);continue}const k=Number((await r.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(O)).seq);h=l.map($=>$==="seq"?`${k-O} + row_number() OVER (ORDER BY s.seq)`:`s.${n($)}`)}const b=o.map(t=>`${n(t)}::text`).join(", "),y=a.primaryKey.length===0;y&&(N=` WHERE NOT EXISTS (SELECT 1 FROM ${i(e)} t WHERE ${o.map(t=>`t.${n(t)} IS NOT DISTINCT FROM s.${n(t)}`).join(" AND ")})`);const R=await r.prepareUncached(`INSERT INTO ${i(e)} (${l.map(n).join(", ")}) SELECT ${h.join(", ")} FROM ${E(e)} s${N}
8
+ ORDER BY ${p}${y?"":` ON CONFLICT (${o.map(n).join(", ")}) DO NOTHING`} RETURNING ${b}`).all();if(e===C){const t=await r.prepareUncached(`SELECT s.hash FROM ${E(e)} s JOIN ${i(e)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();if(t.length>0)throw new w("copy","unique_conflict",`the target holds other text under body ${t[0].hash}; its boot repair has not rekeyed that row`,{table:e,hashes:t.map(O=>O.hash)})}e===C?m.inserted[e]=R.length:await u(e,R.map(t=>Object.values(t))),m.mapped[e]=d-R.length}await r.prepareUncached(`DELETE FROM ${i("charge_totals")} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${E("charges")})`).run(),await r.prepareUncached(`INSERT INTO ${i("charge_totals")} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
4
9
  SELECT month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, ''), COALESCE(SUM(usd), 0), COALESCE(SUM(billed_usd), 0)
5
- FROM ${E("charges")} WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${o("charges")})
6
- GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,n]of[["object",a.idMap.object],["grant",a.idMap.grant],["kind",a.idMap.kind]])for(const[O,i]of n)await r.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(S,e,O,i);for(const e of a.pathMap)await r.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, 'path', ?, ?) ON CONFLICT DO NOTHING").run(S,e.from,e.to);return await r.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(),S),d}c(J,"copyRows");export{q as copyOrder,J as copyRows,Y as decodeKeys,j as encodeKeys};
10
+ FROM ${i("charges")} WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${E("charges")})
11
+ GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,a]of[["object",s.idMap.object],["grant",s.idMap.grant],["kind",s.idMap.kind]])for(const[d,o]of a)await r.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(T,e,d,o);for(const e of s.pathMap)await r.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, 'path', ?, ?) ON CONFLICT DO NOTHING").run(T,e.from,e.to);return await r.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(),T),m}c(J,"copyRows");export{q as copyOrder,J as copyRows,V as decodeKeys,x as encodeKeys};
@@ -18,5 +18,7 @@ export interface RunOptions {
18
18
  }
19
19
  /** How long a loading run waits for the directory to copy the person's grants onto the fleet runtime before it fails `grant_missing` (design-import-fleet-grants G10). */
20
20
  export declare const GRANT_WAIT_MS: number;
21
+ /** How far the copy transaction moves the run's lease ahead: renewals cannot land while it holds the row. Copy is bounded by the pause budget of 10 minutes. */
22
+ export declare const COPY_LEASE_MS: number;
21
23
  /** Process one claimed run. Never throws: the outcome is the row's state. */
22
24
  export declare function processRun(row: RunRow, claim: RowClaim, options?: RunOptions): Promise<void>;
@@ -1,3 +1,3 @@
1
- var Q=Object.defineProperty;var c=(e,i)=>Q(e,"name",{value:i,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as Y}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as M}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as N,encodeKeys as B}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ue}from"./prepare.js";import{boundSub as ce,checkSourcePerson as fe,checkStagedBlobKeys as le,checkStagedPersons as me,checkStagedReferences as _e,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,moveRunBlobs as he}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Ee,grantMissing as Se,mapProfileIds as ve,rewriteIds as Re,rewritePerson as Oe}from"./rewrite.js";import{dropStaging as W,ImportLaneError as w,stage as Te,stagingSchema as Pe,targetSchema as ke}from"./stage.js";import{verifyRun as je}from"./verify.js";import{sandboxPathMap as Ie,writeNodeFiles as De}from"./path-map.js";import{allStoreKeys as Ae,readPluginsStore as Ce,recordImportedActivations as Me,writeStores as Ne}from"./stores.js";import{publishImportedPlugins as Be}from"./publish-plugins.js";import{COPIED_TABLES as We}from"../bundle/layout.js";import{ClaimLostError as He}from"../../../daemon/reconcilers/row-claim.js";const H=10*6e4,R=c(()=>new Date().toISOString(),"now"),O=c(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Le(e,i){const n=await e.get(v.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}c(Le,"readSource");async function Ke(e,i,n,r,s,d){const t=await e.get(v.rows(n.run_id,"grants")),l=t===null?[]:x(t),m=[];for(const a of l){const u=ce(a.sub,r,n.person,"grants.sub");await Ee(i,s,d,u,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=H)throw Se(m);return!1}c(Ke,"grantsReady");async function ct(e,i,n={}){const r=n.blobs??await Y(),s=await S(),d=Pe(e.run_id),t=c(async a=>{await i.assertOwned(),await O(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const m=[];try{const a=await Le(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const u=await ke(s),T=[...We],g=await ae(s,u,[...T,"grants"]);if(!l){const f={},k=[],j=[],I=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await fe(s,u,a.person,e.person),!await Ke(r,s,e,a.person,u,I)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await Be(await Ce(r,e.run_id));if(h.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=H)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${h.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:h.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...h.refused),await t("stage");const K=await Te(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:u,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:I,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await me(_)))y(f,o,p);for(const[o,p]of Object.entries(await le(_)))y(f,o,p);await t("rewrite-person"),await Oe(_),await t("prune");const U=await ie(s,d,g,a),E=a.kind==="hosted"?Ie(a.pathPrefixes??[]):[];await t("rewrite-paths"),await de(s,d,E),await oe(s,d,E,r,e.run_id),await pe(s,d),await we(_);const F=await ve(_);await re(s,d,u,a.installId,e.person),await t("rewrite-ids");const D=await Re(_,F);await t("drop");const J=await ue(s,d,u),q=await ye(_);for(const[o,p]of Object.entries({...U}))y(f,o,p);for(const[o,p]of Object.entries(q))y(f,o,p);await _e(_),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,u,g,T,new Set,$),await t("blobs"),await he(s,d,u,e.person,r,e.run_id,m),await t("copy"),await M(async o=>{await i.assertOwned();const p=await ne({db:o,runId:e.run_id,schema:d,target:u,catalog:g,source:a,person:e.person,idMap:D,pathMap:E}),A=await Je(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await De(o,d,e.run_id,a);const C=await Ne({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,z]of Object.entries(C.inserted))p.inserted[G]=z.length;return k.push(...C.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Fe(f,p),unresolved_plugins:k,refused_plugins:j}),R(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const b=await je(s,e.run_id,d,u,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const P=v.manifest(e.run_id);await r.put(P,await qe(e.run_id)),await W(s,e.run_id);for(const f of Ae(e.run_id))await r.delete(f);await be(r,e.run_id),await M(async f=>{await Me(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(P,R(),e.run_id)})}catch(a){if(a instanceof He)throw a;const u=Ue(a);await W(s,e.run_id).catch(()=>{}),l||await ge(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id)}}c(ct,"processRun");function Ue(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}c(Ue,"failureOf");function y(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}c(y,"addDropped");function Fe(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}c(Fe,"withInserted");async function Je(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,l]of d){const m=await Z(e,t);m!==null&&await X(e,m,l.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await L(e,i,"revisions",s.map(t=>[t.rev_id])),await L(e,i,"revision_parents",s.flatMap(t=>t.parents.map(l=>[t.rev_id,l]))),s.length}c(Je,"arrive");async function L(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,B(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...N(s.inserted_keys),...r]),i,n)}c(L,"appendManifest");async function qe(e){const n=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return V(Buffer.from(n.map(r=>JSON.stringify({table:r.table_name,keys:N(r.inserted_keys)})).join(`
1
+ var z=Object.defineProperty;var u=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as C}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as N,encodeKeys as L}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ce}from"./prepare.js";import{boundSub as ue,checkSourcePerson as fe,checkStagedBlobKeys as le,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,moveRunBlobs as he}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Ee,grantMissing as Se,mapProfileIds as ve,rewriteIds as Re,rewritePerson as Oe}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as Pe,stagingSchema as Te,targetSchema as ke}from"./stage.js";import{verifyRun as je}from"./verify.js";import{sandboxPathMap as Ie,writeNodeFiles as De}from"./path-map.js";import{allStoreKeys as Ae,readPluginsStore as Me,recordImportedActivations as Ce,writeStores as Ne}from"./stores.js";import{publishImportedPlugins as Le}from"./publish-plugins.js";import{COPIED_TABLES as Be}from"../bundle/layout.js";import{ClaimLostError as We}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,He=30*6e4,R=u(()=>new Date().toISOString(),"now"),O=u(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Ke(e,i){const n=await e.get(v.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}u(Ke,"readSource");async function Ue(e,i,n,r,s,d){const t=await e.get(v.rows(n.run_id,"grants")),l=t===null?[]:x(t),_=[];for(const a of l){const c=ue(a.sub,r,n.person,"grants.sub");await Ee(i,s,d,c,a.grantee)===void 0&&_.push(a.grantee)}if(_.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=W)throw Se(_);return!1}u(Ue,"grantsReady");async function ft(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=Te(e.run_id),t=u(async a=>{await i.assertOwned(),await O(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const _=[];try{const a=await Ke(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const c=await ke(s),P=[...Be],g=await ae(s,c,[...P,"grants"]);if(!l){const f={},k=[],j=[],I=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await fe(s,c,a.person,e.person),!await Ue(r,s,e,a.person,c,I)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await Le(await Me(r,e.run_id));if(h.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=W)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${h.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:h.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...h.refused),await t("stage");const K=await Pe(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const m={db:s,schema:d,target:c,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:I,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await _e(m)))y(f,o,p);for(const[o,p]of Object.entries(await le(m)))y(f,o,p);await t("rewrite-person"),await Oe(m),await t("prune");const U=await ie(s,d,g,a),E=a.kind==="hosted"?Ie(a.pathPrefixes??[]):[];await t("rewrite-paths"),await de(s,d,E),await oe(s,d,E,r,e.run_id),await pe(s,d),await we(m);const F=await ve(m);await re(s,d,c,a.installId,e.person),await t("rewrite-ids");const D=await Re(m,F);await t("drop");const J=await ce(s,d,c),q=await ye(m);for(const[o,p]of Object.entries({...U}))y(f,o,p);for(const[o,p]of Object.entries(q))y(f,o,p);await me(m),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,c,g,P,new Set,$),await t("blobs"),await he(s,d,c,e.person,r,e.run_id,_),await t("copy"),await C(async o=>{await i.assertOwned({extendLeaseMs:He});const p=await ne({db:o,runId:e.run_id,schema:d,target:c,catalog:g,source:a,person:e.person,idMap:D,pathMap:E}),A=await qe(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await De(o,d,e.run_id,a);const M=await Ne({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,Y]of Object.entries(M.inserted))p.inserted[G]=Y.length;return k.push(...M.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Je(f,p),unresolved_plugins:k,refused_plugins:j}),R(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const b=await je(s,e.run_id,d,c,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const T=v.manifest(e.run_id);await r.put(T,await $e(e.run_id)),await B(s,e.run_id);for(const f of Ae(e.run_id))await r.delete(f);await be(r,e.run_id),await C(async f=>{await Ce(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(T,R(),e.run_id)})}catch(a){if(a instanceof We)throw a;const c=Fe(a);await B(s,e.run_id).catch(()=>{}),l||await ge(r,_,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id)}}u(ft,"processRun");function Fe(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}u(Fe,"failureOf");function y(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(y,"addDropped");function Je(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}u(Je,"withInserted");async function qe(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,l]of d){const _=await Z(e,t);_!==null&&await X(e,_,l.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await H(e,i,"revisions",s.map(t=>[t.rev_id])),await H(e,i,"revision_parents",s.flatMap(t=>t.parents.map(l=>[t.rev_id,l]))),s.length}u(qe,"arrive");async function H(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,L(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(L([...N(s.inserted_keys),...r]),i,n)}u(H,"appendManifest");async function $e(e){const n=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Q(Buffer.from(n.map(r=>JSON.stringify({table:r.table_name,keys:N(r.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}c(qe,"manifestFile");export{H as GRANT_WAIT_MS,ct as processRun};
3
+ `))}u($e,"manifestFile");export{He as COPY_LEASE_MS,W as GRANT_WAIT_MS,ft as processRun};
@@ -1,9 +1,11 @@
1
+ import { allGrants } from '../../core/grants/mirror.js';
1
2
  export interface GrantEffectsRoles {
2
3
  serves: boolean;
3
4
  runsLanes: boolean;
4
5
  }
5
- /** Do this process's part of whatever changed grant `grantId`, from its row as it reads now. Idempotent. */
6
- export declare function applyGrantEffects(roles: GrantEffectsRoles, grantId: string): Promise<void>;
6
+ /** Do this process's part of whatever changed grant `grantId`, from its row as it reads now. Idempotent. `mirror`, when given, is the
7
+ * whole grant mirror a catch-up pass read once for every grant it applies; without it the mirror is read here. */
8
+ export declare function applyGrantEffects(roles: GrantEffectsRoles, grantId: string, mirror?: Awaited<ReturnType<typeof allGrants>>): Promise<void>;
7
9
  /** Subscribe this process to `grant:<id>` signals. Returns the unsubscribe. A process that runs lanes also looks every `sweepMs` for a
8
10
  * removal that is still owed (a cascade that failed, or one no signal or catch-up reached) and runs it again. */
9
11
  export declare function startGrantEffects(roles: GrantEffectsRoles, tuning?: {
@@ -1 +1 @@
1
- var k=Object.defineProperty;var a=(t,e)=>k(t,"name",{value:e,configurable:!0});import{canvasPoolSize as x,openDb as p}from"../../core/canvas/db.js";import{isCloudRole as L}from"../../core/canvas/person.js";import{endLiveExecution as O,liveExecutionForNode as D}from"../../core/canvas/executions.js";import{emitEvent as u}from"../../core/events/emit.js";import{afterRevocationStop as M}from"../../core/grants/on-sync.js";import{allGrants as h,grantIdsWhere as y,grantStanding as E,mirrorOnly as R}from"../../core/grants/mirror.js";import{removeApp as A,removePersonData as P}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as G,wakeGrantWaiters as C}from"../../core/grants/watch.js";import{discardOrphanedTokens as g,discardTokensForGrant as W}from"../../core/providers/token-cache.js";import{isUnsandboxedMachine as F}from"../../core/runtime/unsandboxed.js";import{runnerForExecution as U}from"../../core/runtime/runner/index.js";import{closeGrantStreams as B,heldGrantIds as $}from"../../core/runs/events.js";import{stopNodeSandboxes as H}from"../../core/spaces/stop.js";import{brokerSignalBus as J}from"../broker-signals/bus.js";import{withRowClaim as z}from"./row-claim.js";const K=6e4,V=a(()=>Math.max(1,Math.floor(x()/3)),"grantSlotLimit");let v=0;const b=[];async function X(t){for(;v>=V();)await new Promise(e=>{b.push(e)});v+=1;try{return await t()}finally{v-=1,b.shift()?.()}}a(X,"withGrantSlot");const Y=3e4,j=5;function d(t,e,n){u({level:"error",event:`daemon.grants.${t}`,error:e,fields:n})}a(d,"failed");function q(t,e,n){try{const r=e.sub===null||e.grantee===null?g(n):W({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},n);r.tokens>0&&u({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:r.tokens}})}catch(r){d("outbound_tokens_discard_failed",r,{grant:t})}}a(q,"discardTokens");async function N(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){u({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}a(N,"reconcileProviderBundles");async function Q(t,e){if(C(t),e.standing==="inactive"){const n=B(t);n>0&&u({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:n}})}await N()}a(Q,"serveEffects");async function Z(t,e){const n=await z("nodes",t,K,async r=>{const i=await D(t);if(i===null)return;await r.assertOwned(),u({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:i.executionId}});const l=a(async()=>{await r.assertOwned(),await O(t,{reason:"permission_revoked"}),await M(t)},"finish");if(i.runner==="process"){const m=await H(t,"permission_revoked",{holdRecovery:!0,after:l});if(!m.confirmed)throw m.error??new Error(`stop of ${t} was not confirmed`);return}const f=await U(i.runner).stop(i,{reason:"permission_revoked"});if(!f.confirmed)throw f.error??new Error(`stop of ${t} was not confirmed`);await l()})}a(Z,"stopRevokedNode");async function I(t,e){if(!(e.grantee!==null&&R({grantee:e.grantee}))){if(e.standing==="inactive"){const n=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:r}of n)try{await Z(r,t)}catch(i){d("node_stop_failed",i,{grant:t,node_id:r})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await A(e.grantee,e.sub):L()?await P(e.grantee,e.sub):u({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(n){d("removal_failed",n,{grant:t,grantee:e.grantee})}}}a(I,"laneEffects");async function ee(t,e){let n;await X(async()=>{const r=await E(e);q(e,r,await h()),t.serves&&(n=Q(e,r)),t.runsLanes&&r.standing!=="lagging"&&await I(e,r)}),await n}a(ee,"applyGrantEffects");async function te(t){const e=new Set;if(t.serves)for(const r of $())e.add(r);if(t.runsLanes){const r=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:i}of r)e.add(i)}const n=[];for(const r of e)(await E(r)).status===null&&n.push(r);return n}a(te,"goneGrantIds");async function Se(t,e={}){const n=new Map,r=a(o=>{const c=(n.get(o)??Promise.resolve()).then(()=>ee(t,o)).catch(s=>d("effects_failed",s,{grant:o})).finally(()=>{n.get(o)===c&&n.delete(o)});return n.set(o,c),c},"run"),i=a(async()=>{const o=t.serves?N():void 0;try{t.serves&&G(),g(await h());const c=new Set(await y(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const s of await te(t))c.add(s);await Promise.all([...c].map(r))}catch(c){d("catch_up_failed",c,{})}await o},"catchUp"),l=new Map;let f=!1;const m=a(async()=>{if(!f){f=!0;try{const o=new Set(await y(`status = 'removed' AND removal_done_at IS NULL${F()?" AND grantee = 'app:terminal'":""}`));for(const s of l.keys())o.has(s)||l.delete(s);const c=[...o].filter(s=>!n.has(s)&&(l.get(s)?.notBefore??0)<=Date.now());await Promise.all(c.map(async s=>{await r(s);const S=(l.get(s)?.failures??0)+1;l.set(s,{failures:S,notBefore:Date.now()+_*2**Math.min(S,j)})}))}catch(o){d("removal_sweep_failed",o,{})}finally{f=!1}}},"sweepRemovals"),_=e.sweepMs??Y,w=t.runsLanes?setInterval(()=>{m()},_):void 0;w?.unref();const T=await J.subscribe(o=>{r(o)},{kinds:["grant"],onListenStart:a(()=>{i()},"onListenStart")});return()=>{w!==void 0&&clearInterval(w),T()}}a(Se,"startGrantEffects");export{ee as applyGrantEffects,Se as startGrantEffects};
1
+ var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{canvasPoolSize as T,openDb as v}from"../../core/canvas/db.js";import{isCloudRole as x}from"../../core/canvas/person.js";import{endLiveExecution as O,liveExecutionForNode as D}from"../../core/canvas/executions.js";import{emitEvent as d}from"../../core/events/emit.js";import{afterRevocationStop as M}from"../../core/grants/on-sync.js";import{allGrants as h,grantIdsWhere as y,grantStanding as E,mirrorOnly as R}from"../../core/grants/mirror.js";import{removeApp as A,removePersonData as P}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as G,wakeGrantWaiters as C}from"../../core/grants/watch.js";import{discardOrphanedTokens as g,discardTokensForGrant as F}from"../../core/providers/token-cache.js";import{isUnsandboxedMachine as W}from"../../core/runtime/unsandboxed.js";import{runnerForExecution as U}from"../../core/runtime/runner/index.js";import{closeGrantStreams as B,heldGrantIds as $}from"../../core/runs/events.js";import{stopNodeSandboxes as H}from"../../core/spaces/stop.js";import{brokerSignalBus as J}from"../broker-signals/bus.js";import{withRowClaim as z}from"./row-claim.js";const K=6e4,V=o(()=>Math.max(1,Math.floor(T()/3)),"grantSlotLimit");let _=0;const b=[];async function X(t){for(;_>=V();)await new Promise(e=>{b.push(e)});_+=1;try{return await t()}finally{_-=1,b.shift()?.()}}o(X,"withGrantSlot");const Y=3e4,j=5;function m(t,e,r){d({level:"error",event:`daemon.grants.${t}`,error:e,fields:r})}o(m,"failed");function q(t,e,r){try{const n=e.sub===null||e.grantee===null?g(r):F({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},r);n.tokens>0&&d({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:n.tokens}})}catch(n){m("outbound_tokens_discard_failed",n,{grant:t})}}o(q,"discardTokens");async function N(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){d({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}o(N,"reconcileProviderBundles");async function Q(t,e){if(C(t),e.standing==="inactive"){const r=B(t);r>0&&d({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:r}})}await N()}o(Q,"serveEffects");async function Z(t,e){const r=await z("nodes",t,K,async n=>{const a=await D(t);if(a===null)return;await n.assertOwned(),d({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:a.executionId}});const c=o(async()=>{await n.assertOwned(),await O(t,{reason:"permission_revoked"}),await M(t)},"finish");if(a.runner==="process"){const w=await H(t,"permission_revoked",{holdRecovery:!0,after:c});if(!w.confirmed)throw w.error??new Error(`stop of ${t} was not confirmed`);return}const u=await U(a.runner).stop(a,{reason:"permission_revoked"});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);await c()},{waitForLock:!0})}o(Z,"stopRevokedNode");async function I(t,e){if(!(e.grantee!==null&&R({grantee:e.grantee}))){if(e.standing==="inactive"){const r=await(await v()).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 Z(n,t)}catch(a){m("node_stop_failed",a,{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 A(e.grantee,e.sub):x()?await P(e.grantee,e.sub):d({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await v()).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){m("removal_failed",r,{grant:t,grantee:e.grantee})}}}o(I,"laneEffects");async function ee(t,e,r){let n;await X(async()=>{const a=await E(e);q(e,a,r??await h()),t.serves&&(n=Q(e,a)),t.runsLanes&&a.standing!=="lagging"&&await I(e,a)}),await n}o(ee,"applyGrantEffects");async function te(t){const e=new Set;if(t.serves)for(const n of $())e.add(n);if(t.runsLanes){const n=await(await v()).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:a}of n)e.add(a)}const r=[];for(const n of e)(await E(n)).status===null&&r.push(n);return r}o(te,"goneGrantIds");async function Se(t,e={}){const r=new Map,n=o((s,l)=>{const i=(r.get(s)??Promise.resolve()).then(()=>ee(t,s,l)).catch(f=>m("effects_failed",f,{grant:s})).finally(()=>{r.get(s)===i&&r.delete(s)});return r.set(s,i),i},"run"),a=o(async()=>{const s=t.serves?N():void 0;try{t.serves&&G();const l=await h();g(l);const i=new Set(await y(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const f of await te(t))i.add(f);await Promise.all([...i].map(f=>n(f,l)))}catch(l){m("catch_up_failed",l,{})}await s},"catchUp"),c=new Map;let u=!1;const w=o(async()=>{if(!u){u=!0;try{const s=new Set(await y(`status = 'removed' AND removal_done_at IS NULL${W()?" 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()+S*2**Math.min(f,j)})}))}catch(s){m("removal_sweep_failed",s,{})}finally{u=!1}}},"sweepRemovals"),S=e.sweepMs??Y,p=t.runsLanes?setInterval(()=>{w()},S):void 0;p?.unref();const k=await J.subscribe(s=>{n(s)},{kinds:["grant"],onListenStart:o(()=>{a()},"onListenStart")});return()=>{p!==void 0&&clearInterval(p),k()}}o(Se,"startGrantEffects");export{ee as applyGrantEffects,Se as startGrantEffects};
@@ -1,6 +1,14 @@
1
+ import { processRun } from '../../core/import/load/run.js';
1
2
  import type { DetachedWorkLifecycle } from './broker-supervision.js';
2
3
  export declare const IMPORT_LEASE_MS: number;
3
4
  export declare class ImportLaneReconciler {
5
+ private readonly options;
6
+ constructor(options?: {
7
+ process?: typeof processRun;
8
+ leaseMs?: number;
9
+ });
10
+ /** Runs this process is processing now: a pass never claims one again, whatever its lease says. */
11
+ private readonly processing;
4
12
  run(now: number, ctx: {
5
13
  lifecycle: DetachedWorkLifecycle;
6
14
  }): void;
@@ -1 +1 @@
1
- var p=Object.defineProperty;var n=(i,e)=>p(i,"name",{value:e,configurable:!0});import{openDb as m}from"../../core/canvas/db.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as c}from"../../core/events/operation-id.js";import{processRun as f}from"../../core/import/load/run.js";import{ClaimLostError as d,withRowClaim as _}from"./row-claim.js";const R=2*6e4;class S{static{n(this,"ImportLaneReconciler")}run(e,o){if(!o.lifecycle.acceptsDetachedWork())return;const a=c.fresh(()=>this.pass(e).then(()=>{})).catch(t=>{c.fresh(()=>l({level:"error",event:"import.lane.failed",error:t}))});o.lifecycle.registerDetached(a)}async pass(e){const a=await(await m()).prepare("SELECT * FROM import_runs WHERE (state = 'loading' OR state = 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= ?) ORDER BY created_at").all(new Date(e).toISOString());let t=0;for(const s of a)try{await _("import_runs",s.run_id,R,r=>f(s,r))&&(t+=1)}catch(r){if(!(r instanceof d))throw r}return t}}export{R as IMPORT_LEASE_MS,S as ImportLaneReconciler};
1
+ var p=Object.defineProperty;var a=(n,e)=>p(n,"name",{value:e,configurable:!0});import{openDb as l}from"../../core/canvas/db.js";import{emitEvent as d}from"../../core/events/emit.js";import{operationIdContext as c}from"../../core/events/operation-id.js";import{processRun as m}from"../../core/import/load/run.js";import{ClaimLostError as f,withRowClaim as h}from"./row-claim.js";const _=2*6e4;class g{static{a(this,"ImportLaneReconciler")}options;constructor(e={}){this.options=e}processing=new Set;run(e,s){if(!s.lifecycle.acceptsDetachedWork())return;const i=c.fresh(()=>this.pass(e).then(()=>{})).catch(r=>{c.fresh(()=>d({level:"error",event:"import.lane.failed",error:r}))});s.lifecycle.registerDetached(i)}async pass(e){const i=await(await l()).prepare("SELECT * FROM import_runs WHERE (state = 'loading' OR state = 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= ?) ORDER BY created_at").all(new Date(e).toISOString());let r=0;for(const t of i)if(!this.processing.has(t.run_id)){this.processing.add(t.run_id);try{await h("import_runs",t.run_id,this.options.leaseMs??_,o=>(this.options.process??m)(t,o))&&(r+=1)}catch(o){if(!(o instanceof f))throw o}finally{this.processing.delete(t.run_id)}}return r}}export{_ as IMPORT_LEASE_MS,g as ImportLaneReconciler};
@@ -11,10 +11,17 @@ export declare class ClaimLostError extends Error {
11
11
  }
12
12
  export interface RowClaim {
13
13
  /** Throws `ClaimLostError` unless this claim still owns the row (not taken over, not expired). Called inside a `withCanvasWrite`
14
- * body it locks the row (`FOR UPDATE`) until commit, so a takeover cannot slip in between the check and the writes that follow. */
15
- assertOwned(): Promise<void>;
14
+ * body it locks the row (`FOR UPDATE`) until commit, so a takeover cannot slip in between the check and the writes that follow.
15
+ * Renewals cannot land while that transaction holds the row, so a transaction longer than the lease passes `extendLeaseMs`: the lease
16
+ * is moved that far ahead by the same statement that locks the row (the next renewal after the commit sets it back to the claim's TTL). */
17
+ assertOwned(options?: {
18
+ extendLeaseMs?: number;
19
+ }): Promise<void>;
16
20
  }
17
- /** Runs `work` when this process claims the row; returns false without running it when another process holds the claim. A failed
18
- * `work` releases the claim and rethrows, so the next pass retries it. */
19
- export declare function withRowClaim(table: ClaimableTable, id: string, ttlMs: number, work: (claim: RowClaim) => Promise<void>): Promise<boolean>;
21
+ /** Runs `work` when this process claims the row; returns false without running it when another process holds the claim, or (unless
22
+ * `waitForLock`) when another transaction holds the row lock at that moment. A failed `work` releases the claim and rethrows, so the
23
+ * next pass retries it. `waitForLock` is for a caller nothing re-drives: false then means only that another process holds the claim. */
24
+ export declare function withRowClaim(table: ClaimableTable, id: string, ttlMs: number, work: (claim: RowClaim) => Promise<void>, options?: {
25
+ waitForLock?: boolean;
26
+ }): Promise<boolean>;
20
27
  export {};
@@ -1,2 +1,4 @@
1
- var E=Object.defineProperty;var i=(e,r)=>E(e,"name",{value:r,configurable:!0});import{randomUUID as d}from"node:crypto";import{openDb as _}from"../../core/canvas/db.js";const D={nodes:"node_id",structured_requests:"request_id",human_requests:"request_id",import_runs:"run_id"};class w extends Error{static{i(this,"ClaimLostError")}constructor(r,t){super(`row claim lost: ${r} ${t} is no longer held by this process`)}}async function L(e,r,t,u){const a=D[e],n=d(),o=await _(),p=new Date().toISOString();if((await o.prepare(`UPDATE ${e} SET claimed_by = ?, lease_expires_at = ?
2
- WHERE ${a} = ? AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= ?)`).run(n,new Date(Date.now()+t).toISOString(),r,p)).changes!==1)return!1;let s=!1;const c=setInterval(()=>{o.prepare(`UPDATE ${e} SET lease_expires_at = ? WHERE ${a} = ? AND claimed_by = ? AND lease_expires_at > ?`).run(new Date(Date.now()+t).toISOString(),r,n,new Date().toISOString()).then(l=>{l.changes!==1&&(s=!0)},()=>{s=!0})},Math.max(1,Math.floor(t/3)));c.unref();const m={async assertOwned(){if(s)throw new w(e,r);if(await(await _()).prepare(`SELECT 1 AS held FROM ${e} WHERE ${a} = ? AND claimed_by = ? AND lease_expires_at > ? FOR UPDATE`).get(r,n,new Date().toISOString())===void 0)throw s=!0,new w(e,r)}};try{await u(m)}finally{clearInterval(c),await o.prepare(`UPDATE ${e} SET claimed_by = NULL, lease_expires_at = NULL WHERE ${a} = ? AND claimed_by = ?`).run(r,n)}return!0}i(L,"withRowClaim");export{w as ClaimLostError,L as withRowClaim};
1
+ var R=Object.defineProperty;var i=(e,r)=>R(e,"name",{value:r,configurable:!0});import{randomUUID as L}from"node:crypto";import{openDb as S}from"../../core/canvas/db.js";const N={nodes:"node_id",structured_requests:"request_id",human_requests:"request_id",import_runs:"run_id"};class d extends Error{static{i(this,"ClaimLostError")}constructor(r,n){super(`row claim lost: ${r} ${n} is no longer held by this process`)}}async function y(e,r,n,p,D={}){const t=N[e],a=L(),E=await S(),m=new Date().toISOString();if((await E.prepare(`UPDATE ${e} SET claimed_by = ?, lease_expires_at = ? WHERE ${t} IN
2
+ (SELECT ${t} FROM ${e} WHERE ${t} = ? AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= ?) FOR NO KEY UPDATE${D.waitForLock===!0?"":" SKIP LOCKED"})`).run(a,new Date(Date.now()+n).toISOString(),r,m)).changes!==1)return!1;let s=!1,c=!1;const A=i(async()=>{const o=await E.prepare(`WITH r AS (SELECT ${t}, claimed_by, lease_expires_at FROM ${e} WHERE ${t} = ? FOR NO KEY UPDATE SKIP LOCKED),
3
+ u AS (UPDATE ${e} t SET lease_expires_at = ? FROM r WHERE t.${t} = r.${t} AND r.claimed_by = ? AND r.lease_expires_at > ? RETURNING 1)
4
+ SELECT (SELECT count(*) FROM r) AS seen, (SELECT count(*) FROM u) AS renewed`).get(r,new Date(Date.now()+n).toISOString(),a,new Date().toISOString());Number(o.seen)===1&&Number(o.renewed)!==1&&(s=!0)},"renewOnce"),w=setInterval(()=>{c||(c=!0,A().catch(()=>{s=!0}).finally(()=>{c=!1}))},Math.max(1,Math.floor(n/3)));w.unref();const O={async assertOwned(o){if(s)throw new d(e,r);const l=await S(),_=new Date().toISOString(),u=o?.extendLeaseMs;if((u===void 0?await l.prepare(`SELECT 1 AS held FROM ${e} WHERE ${t} = ? AND claimed_by = ? AND lease_expires_at > ? FOR UPDATE`).get(r,a,_):await l.prepare(`UPDATE ${e} SET lease_expires_at = ? WHERE ${t} = ? AND claimed_by = ? AND lease_expires_at > ? RETURNING 1 AS held`).get(new Date(Date.now()+u).toISOString(),r,a,_))===void 0)throw s=!0,new d(e,r)}};try{await p(O)}finally{clearInterval(w),await E.prepare(`UPDATE ${e} SET claimed_by = NULL, lease_expires_at = NULL WHERE ${t} = ? AND claimed_by = ?`).run(r,a)}return!0}i(y,"withRowClaim");export{d as ClaimLostError,y as withRowClaim};
@@ -11,6 +11,8 @@ interface ToolResultLike {
11
11
  }>;
12
12
  details: unknown;
13
13
  isError?: boolean;
14
+ /** Ends the agent loop after this tool batch — no further model request. */
15
+ terminate?: boolean;
14
16
  }
15
17
  interface SubmitResultParams {
16
18
  request_id: string;
@@ -1,4 +1,4 @@
1
- var b=Object.defineProperty;var o=(e,t)=>b(e,"name",{value:t,configurable:!0});import{Type as i}from"typebox";import{envNodeId as q}from"../shared/env.js";import{localClient as p}from"../api/node-transport.js";import{ApiError as w}from"../api/index.js";import{SUBMIT_RESULT_TOOL as a}from"../core/runtime/structured-output.js";function O(e){const t=JSON.stringify(e.schema,null,2),r=`call the ${`\`${a}\` tool with \`request_id: "${e.request_id}"\``} and the JSON in \`result\``,n=`call \`${a}\` with \`decline: { reason, code }\` instead`;return`<structured-output-request>
1
+ var g=Object.defineProperty;var u=(e,t)=>g(e,"name",{value:t,configurable:!0});import{Type as i}from"typebox";import{envNodeId as q}from"../shared/env.js";import{localClient as p}from"../api/node-transport.js";import{ApiError as w}from"../api/index.js";import{SUBMIT_RESULT_TOOL as c}from"../core/runtime/structured-output.js";function O(e){const t=JSON.stringify(e.schema,null,2),r=`call the ${`\`${c}\` tool with \`request_id: "${e.request_id}"\``} and the JSON in \`result\``,n=`call \`${c}\` with \`decline: { reason, code }\` instead`;return`<structured-output-request>
2
2
  ${e.mode==="terminal"?`This node owes a terminal structured result. When the work is complete, submit it: ${r}. That records it and pushes your final report in one step, finishing this node. Do NOT call \`crtr push final\` yourself; it is blocked while this request is pending. If the schema cannot be honestly satisfied (blocked, unavailable, bad input), ${n} of inventing a value \u2014 that finishes the node with a declined outcome. You cannot stop or go dormant until the result is accepted or declined.`:`This node owes a one-off structured result. Submit it: ${r}. That records it and pushes an update report to your subscribers, then you continue working normally. If the schema cannot be honestly satisfied, ${n} of inventing a value. You cannot stop or go dormant until the result is accepted or declined.`}
3
3
 
4
4
  The submitted JSON is validated against this schema; a mismatch rejects with field errors and records nothing, so fix it and call the tool again.
@@ -8,11 +8,11 @@ Required schema:
8
8
  \`\`\`json
9
9
  ${t}
10
10
  \`\`\`
11
- </structured-output-request>`}o(O,"structuredOutputPromptBlock");function $(e){const t=e.declined,s=e.mode==="terminal"?`${t?"Decline recorded":"Result recorded"} \u2014 node finished; its engine shuts down on next stop. Nothing more to do here: STOP your turn immediately. Reply with just "Done." and nothing else.`:`${t?"One-off request declined":"One-off result recorded"} and pushed \u2014 the structured-output gate is cleared; continue working normally.`,r=t===void 0?"":`
11
+ </structured-output-request>`}u(O,"structuredOutputPromptBlock");function $(e){const t=e.declined,s=e.mode==="terminal"?`${t?"Decline recorded":"Result recorded"} \u2014 node finished; its engine shuts down on next stop.`:`${t?"One-off request declined":"One-off result recorded"} and pushed \u2014 the structured-output gate is cleared; continue working normally.`,r=t===void 0?"":`
12
12
  - code: ${t.code} (${t.retryable?"retryable":"not retryable"})`;return`${s}
13
13
 
14
- - report: ${e.report}${r}`}o($,"submitResultText");async function m(e){return(await p({autostart:!1}).brokerStructuredRequest(e)).request}o(m,"readPendingRequest");function T(e,t){if(typeof t!="string")return t;const s=e?.schema.type;if(s!=="object"&&s!=="array")return t;try{return JSON.parse(t)}catch{return t}}o(T,"normalizeResult");function l(e){return{content:[{type:"text",text:e}],details:void 0,isError:!0}}o(l,"errorResult");function S(e,t=r=>p({autostart:!1}).submitResult(e,r),s=()=>m(e)){return{name:a,label:"Submit result",description:"Answer this node's pending structured-output request. Pass the request id from the structured-output instruction and either `result` (the JSON value matching the required schema) or `decline` when the schema cannot be honestly satisfied. The result is validated against the schema; a mismatch is rejected with field errors and nothing is recorded.",promptSnippet:"Submit the JSON result for a pending structured-output request (or decline it)",parameters:i.Object({request_id:i.String({description:"The request id named in the structured-output instruction."}),result:i.Optional(i.Unknown({description:"The JSON value matching the required schema. Omit when declining."})),decline:i.Optional(i.Object({reason:i.String({description:"One sentence on why the schema cannot be honestly satisfied."}),code:i.String({description:"A whitespace-free token naming the decline class, as the requester documented."}),retryable:i.Optional(i.Boolean({description:"Whether a retry could succeed. Default false."}))},{description:"Decline the request instead of submitting a result."}))}),defaultActive:!1,async execute(r,n){const d=typeof n.request_id=="string"?n.request_id.trim():"";if(d==="")return l("request_id is required: pass the request id named in the structured-output instruction.");const h=Object.hasOwn(n,"result")&&n.result!==void 0,c=n.decline;if(h&&c!==void 0)return l("Pass either `result` or `decline`, not both.");if(!h&&c===void 0)return l("Pass `result` (the JSON value matching the required schema), or `decline` when the schema cannot be honestly satisfied.");const y=c!==void 0?{request_id:d,decline:c.reason,code:c.code,retryable:c.retryable===!0}:{request_id:d,value:T(await s(),n.result)};try{const u=await t(y);return{content:[{type:"text",text:$(u)}],details:u}}catch(u){if(u instanceof w){const f=u.details,g=typeof f?.next=="string"?`
14
+ - report: ${e.report}${r}`}u($,"submitResultText");async function f(e){return(await p({autostart:!1}).brokerStructuredRequest(e)).request}u(f,"readPendingRequest");function T(e,t){if(typeof t!="string")return t;const s=e?.schema.type;if(s!=="object"&&s!=="array")return t;try{return JSON.parse(t)}catch{return t}}u(T,"normalizeResult");function l(e){return{content:[{type:"text",text:e}],details:void 0,isError:!0}}u(l,"errorResult");function S(e,t=r=>p({autostart:!1}).submitResult(e,r),s=()=>f(e)){return{name:c,label:"Submit result",description:"Answer this node's pending structured-output request. Pass the request id from the structured-output instruction and either `result` (the JSON value matching the required schema) or `decline` when the schema cannot be honestly satisfied. The result is validated against the schema; a mismatch is rejected with field errors and nothing is recorded.",promptSnippet:"Submit the JSON result for a pending structured-output request (or decline it)",parameters:i.Object({request_id:i.String({description:"The request id named in the structured-output instruction."}),result:i.Optional(i.Unknown({description:"The JSON value matching the required schema. Omit when declining."})),decline:i.Optional(i.Object({reason:i.String({description:"One sentence on why the schema cannot be honestly satisfied."}),code:i.String({description:"A whitespace-free token naming the decline class, as the requester documented."}),retryable:i.Optional(i.Boolean({description:"Whether a retry could succeed. Default false."}))},{description:"Decline the request instead of submitting a result."}))}),defaultActive:!1,async execute(r,n){const a=typeof n.request_id=="string"?n.request_id.trim():"";if(a==="")return l("request_id is required: pass the request id named in the structured-output instruction.");const h=Object.hasOwn(n,"result")&&n.result!==void 0,d=n.decline;if(h&&d!==void 0)return l("Pass either `result` or `decline`, not both.");if(!h&&d===void 0)return l("Pass `result` (the JSON value matching the required schema), or `decline` when the schema cannot be honestly satisfied.");const y=d!==void 0?{request_id:a,decline:d.reason,code:d.code,retryable:d.retryable===!0}:{request_id:a,value:T(await s(),n.result)};try{const o=await t(y);return{content:[{type:"text",text:$(o)}],details:o,...o.mode==="terminal"?{terminate:!0}:{}}}catch(o){if(o instanceof w){const m=o.details,b=typeof m?.next=="string"?`
15
15
 
16
- ${f.next}`:"";return l(`${u.code}: ${u.message}${g}`)}return l(`The result was not submitted: ${u.message}`)}}}}o(S,"createSubmitResultTool");function x(e){const t=q();if(t===void 0||t.trim()==="")return;e.registerTool(S(t));const s=o(r=>{const n=e.getActiveTools(),d=n.includes(a);r&&!d?e.setActiveTools([...n,a]):!r&&d&&e.setActiveTools(n.filter(h=>h!==a))},"syncTool");e.on("before_agent_start",async r=>{const n=await m(t);if(s(n!==null),n!==null)return{systemPrompt:`${r.systemPrompt}
16
+ ${m.next}`:"";return l(`${o.code}: ${o.message}${b}`)}return l(`The result was not submitted: ${o.message}`)}}}}u(S,"createSubmitResultTool");function x(e){const t=q();if(t===void 0||t.trim()==="")return;e.registerTool(S(t));const s=u(r=>{const n=e.getActiveTools(),a=n.includes(c);r&&!a?e.setActiveTools([...n,c]):!r&&a&&e.setActiveTools(n.filter(h=>h!==c))},"syncTool");e.on("before_agent_start",async r=>{const n=await f(t);if(s(n!==null),n!==null)return{systemPrompt:`${r.systemPrompt}
17
17
 
18
- ${O(n)}`}}),e.on("turn_end",async()=>{s(await m(t)!==null)})}o(x,"registerCanvasStructuredOutput");var J=x;export{a as SUBMIT_RESULT_TOOL,S as createSubmitResultTool,J as default,x as registerCanvasStructuredOutput,O as structuredOutputPromptBlock,$ as submitResultText};
18
+ ${O(n)}`}}),e.on("turn_end",async()=>{await f(t)!==null&&s(!0)})}u(x,"registerCanvasStructuredOutput");var j=x;export{c as SUBMIT_RESULT_TOOL,S as createSubmitResultTool,j as default,x as registerCanvasStructuredOutput,O as structuredOutputPromptBlock,$ as submitResultText};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.614",
3
+ "version": "0.3.616",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.614",
148
+ "@north-light/identity": "0.3.616",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.614",
3
+ "version": "0.3.616",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.614",
3
+ "version": "0.3.616",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.614",
9
+ "version": "0.3.616",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.614",
31
+ "@north-light/identity": "0.3.616",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.614",
11959
+ "version": "0.3.616",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.614",
11964
+ "version": "0.3.616",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.614",
11969
+ "version": "0.3.616",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.614",
11977
+ "version": "0.3.616",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.614",
11981
- "@north-light/identity": "0.3.614"
11980
+ "@north-light/api": "0.3.616",
11981
+ "@north-light/identity": "0.3.616"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.614",
11986
+ "version": "0.3.616",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.614",
11990
- "@north-light/identity": "0.3.614",
11991
- "@north-light/plugin": "0.3.614",
11989
+ "@north-light/api": "0.3.616",
11990
+ "@north-light/identity": "0.3.616",
11991
+ "@north-light/plugin": "0.3.616",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {