@north-light/cli 0.3.611 → 0.3.613

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.
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.46";
2
+ export declare const CONTRACT_LEVEL = "1.47";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1 +1 @@
1
- var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.46",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
1
+ var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.47",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
@@ -9,6 +9,10 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
9
9
 
10
10
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
11
11
 
12
+ ## 0.3.613
13
+
14
+ `oauth.appMember('user:<id>')` asks the directory whether that person is on the team that holds your app, for your app's own staff pages. It answers `{member: true, role: 'admin' | 'member'}` or `{member: false}` (an unknown user is `member: false`) by calling `GET /v1/apps/self/members/:user_id` as the app itself, and caches nothing, so someone removed from the team is refused at their next call. A 401 re-mints the directory token once. Nothing existing changes.
15
+
12
16
  ## 0.3.599
13
17
 
14
18
  `PUT /v1/model-auth/:provider` with `kind: "api_key"` accepts an optional `models: {ultra, strong, medium, light}` for `anthropic`, `openai`, `openrouter` and `moonshotai`. Each value is `<provider>/<model-id>`, a registered chat model of that provider; all four are required. The key is saved with that mapping as the person's model route `key:<provider>`, which is tried after every subscription. An invalid mapping is refused `400 invalid_request`. Without `models` the call behaves as before.
@@ -1 +1 @@
1
- var g=Object.defineProperty;var y=(i,n)=>g(i,"name",{value:n,configurable:!0});import{randomUUID as O}from"node:crypto";import{closeSync as m,existsSync as k,fsyncSync as S,linkSync as b,lstatSync as U,mkdirSync as B,openSync as E,readFileSync as D,readSync as W,readdirSync as $,realpathSync as M,renameSync as P,rmSync as a,rmdirSync as v,statSync as x,writeSync as F}from"node:fs";import{dirname as w,join as d,resolve as X}from"node:path";import{assertBlobKey as Y}from"./index.js";import{blobFault as j}from"./fault.js";function I(i){const n=E(i,"r");try{S(n)}finally{m(n)}}y(I,"syncDir");function J(i,n,f=b){let t;try{t=M(i)}catch(r){if(r.code==="ENOENT")return;throw r}if(t===X(n))return;const e=new Set,o=y((r,c)=>{let u;try{u=$(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}for(const s of u){if(s.name.endsWith(".tmp"))continue;const l=d(r,s.name),N=d(c,s.name);if(s.isDirectory()){o(l,N);try{v(l)}catch(p){if(!["ENOTEMPTY","ENOENT"].includes(p.code??""))throw p}continue}const h=d(n,N);B(w(h),{recursive:!0,mode:448}),e.add(w(h));try{f(l,h)}catch(p){const T=p.code;if(T==="EEXIST"){K(l,h)&&a(l,{force:!0});continue}if(T==="ENOENT"||!L(l,h))continue}a(l,{force:!0})}},"adopt");o(t,"");for(const r of e)I(r);try{v(t)}catch(r){if(!["ENOTEMPTY","ENOENT"].includes(r.code??""))throw r}U(i,{throwIfNoEntry:!1})?.isSymbolicLink()&&!k(i)&&a(i,{force:!0})}y(J,"adoptBlobDirectory");function K(i,n){try{const f=x(i),t=x(n);return f.ino===t.ino&&f.dev===t.dev}catch{return!1}}y(K,"sameFile");function L(i,n){const f=`${n}.${O()}.tmp`;try{const t=E(f,"wx",384);try{let e;try{e=D(i)}catch(r){if(r.code==="ENOENT")return!1;throw r}let o=0;for(;o<e.length;)o+=F(t,e,o);S(t)}finally{m(t)}try{b(f,n)}catch(e){if(e.code==="EEXIST")return!1;throw e}return!0}finally{a(f,{force:!0})}}y(L,"copyInto");function Q(i){const n=y(t=>(Y(t),d(i,...t.split("/"))),"pathOf");function f(t,e,o){let r;try{r=$(t,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}for(const c of r){if(c.name.endsWith(".tmp"))continue;const u=e===""?c.name:`${e}/${c.name}`;c.isDirectory()?f(d(t,c.name),u,o):o.push(u)}}return y(f,"walk"),{async put(t,e){j("put");const o=n(t);B(w(o),{recursive:!0,mode:448});const r=`${o}.${O()}.tmp`,c=E(r,"wx",384);try{const u=typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e);let s=0;for(;s<u.length;)s+=F(c,u,s);S(c)}catch(u){throw m(c),a(r,{force:!0}),u}m(c),P(r,o),I(w(o))},async get(t,e){try{if(!e)return D(n(t));const o=E(n(t),"r");try{const r=Buffer.allocUnsafe(e.length),c=W(o,r,0,e.length,e.start);return r.subarray(0,c)}finally{m(o)}}catch(o){if(o.code==="ENOENT")return null;throw o}},async list(t){const e=[];return f(i,"",e),e.filter(o=>o.startsWith(t)).sort((o,r)=>Buffer.compare(Buffer.from(o),Buffer.from(r)))},async delete(t){a(n(t),{force:!0})}}}y(Q,"createDirectoryBlobStore");export{J as adoptBlobDirectory,Q as createDirectoryBlobStore};
1
+ var k=Object.defineProperty;var y=(i,n)=>k(i,"name",{value:n,configurable:!0});import{createHash as U,randomUUID as b}from"node:crypto";import{closeSync as d,existsSync as W,fsyncSync as S,linkSync as B,lstatSync as M,mkdirSync as g,openSync as p,readFileSync as w,readSync as P,readdirSync as x,realpathSync as X,renameSync as Y,rmSync as a,rmdirSync as D,statSync as $,writeSync as v}from"node:fs";import{dirname as N,join as m,resolve as j}from"node:path";import{assertBlobKey as z}from"./index.js";import{blobFault as F}from"./fault.js";function I(i){const n=p(i,"r");try{S(n)}finally{d(n)}}y(I,"syncDir");function Q(i,n,u=B){let f;try{f=X(i)}catch(t){if(t.code==="ENOENT")return;throw t}if(f===j(n))return;const r=new Set,e=y((t,c)=>{let o;try{o=x(t,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}for(const s of o){if(s.name.endsWith(".tmp"))continue;const l=m(t,s.name),T=m(c,s.name);if(s.isDirectory()){e(l,T);try{D(l)}catch(E){if(!["ENOTEMPTY","ENOENT"].includes(E.code??""))throw E}continue}const h=m(n,T);g(N(h),{recursive:!0,mode:448}),r.add(N(h));try{u(l,h)}catch(E){const O=E.code;if(O==="EEXIST"){H(l,h)&&a(l,{force:!0});continue}if(O==="ENOENT"||!K(l,h))continue}a(l,{force:!0})}},"adopt");e(f,"");for(const t of r)I(t);try{D(f)}catch(t){if(!["ENOTEMPTY","ENOENT"].includes(t.code??""))throw t}M(i,{throwIfNoEntry:!1})?.isSymbolicLink()&&!W(i)&&a(i,{force:!0})}y(Q,"adoptBlobDirectory");function H(i,n){try{const u=$(i),f=$(n);return u.ino===f.ino&&u.dev===f.dev}catch{return!1}}y(H,"sameFile");function K(i,n){const u=`${n}.${b()}.tmp`;try{const f=p(u,"wx",384);try{let r;try{r=w(i)}catch(t){if(t.code==="ENOENT")return!1;throw t}let e=0;for(;e<r.length;)e+=v(f,r,e);S(f)}finally{d(f)}try{B(u,n)}catch(r){if(r.code==="EEXIST")return!1;throw r}return!0}finally{a(u,{force:!0})}}y(K,"copyInto");function R(i){const n=y(r=>(z(r),m(i,...r.split("/"))),"pathOf");function u(r,e,t){let c;try{c=x(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(const o of c){if(o.name.endsWith(".tmp"))continue;const s=e===""?o.name:`${e}/${o.name}`;o.isDirectory()?u(m(r,o.name),s,t):t.push(s)}}y(u,"walk");function f(r,e){g(N(r),{recursive:!0,mode:448});const t=`${r}.${b()}.tmp`,c=p(t,"wx",384);try{let o=0;for(;o<e.length;)o+=v(c,e,o);S(c)}catch(o){throw d(c),a(t,{force:!0}),o}d(c),Y(t,r),I(N(r))}return y(f,"write"),{async put(r,e){F("put"),f(n(r),typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e))},async head(r){let e;try{e=w(n(r))}catch(t){if(t.code==="ENOENT")return null;throw t}return{size:e.length,etag:U("md5").update(e).digest("hex")}},async copy(r,e){F("copy");const t=n(r),c=n(e);let o;try{o=w(t)}catch(s){if(s.code==="ENOENT")return!1;throw s}return f(c,o),!0},async get(r,e){try{if(!e)return w(n(r));const t=p(n(r),"r");try{const c=Buffer.allocUnsafe(e.length),o=P(t,c,0,e.length,e.start);return c.subarray(0,o)}finally{d(t)}}catch(t){if(t.code==="ENOENT")return null;throw t}},async list(r){const e=[];return u(i,"",e),e.filter(t=>t.startsWith(r)).sort((t,c)=>Buffer.compare(Buffer.from(t),Buffer.from(c)))},async delete(r){a(n(r),{force:!0})}}}y(R,"createDirectoryBlobStore");export{Q as adoptBlobDirectory,R as createDirectoryBlobStore};
@@ -1,3 +1,3 @@
1
- /** Fault switch for the blob store (design-fleet, faulting-store seam): `CRTR_FAULT_BLOB=put_fail` makes every `put`
1
+ /** Fault switch for the blob store (design-fleet, faulting-store seam): `CRTR_FAULT_BLOB=put_fail` makes every `put` and `copy`
2
2
  * throw. Read on each call so a seam test can flip it in the serving process's environment. */
3
- export declare function blobFault(op: 'put'): void;
3
+ export declare function blobFault(op: 'put' | 'copy'): void;
@@ -1 +1 @@
1
- var u=Object.defineProperty;var o=(t,r)=>u(t,"name",{value:r,configurable:!0});function p(t){if(t==="put"&&process.env.CRTR_FAULT_BLOB==="put_fail")throw new Error("blob put refused (CRTR_FAULT_BLOB=put_fail)")}o(p,"blobFault");export{p as blobFault};
1
+ var e=Object.defineProperty;var r=(o,t)=>e(o,"name",{value:t,configurable:!0});function u(o){if(process.env.CRTR_FAULT_BLOB==="put_fail")throw new Error("blob put refused (CRTR_FAULT_BLOB=put_fail)")}r(u,"blobFault");export{u as blobFault};
@@ -11,6 +11,13 @@ export interface BlobStore {
11
11
  }): Promise<Buffer | null>;
12
12
  /** Every key beginning with `prefix`, in ascending byte order. */
13
13
  list(prefix: string): Promise<string[]>;
14
+ /** The object's size and content hash without its bytes, or `null` when no object has this key. `etag` is the hex MD5 of the bytes when the store knows it (an object written in one piece), else `null`: equal sizes and equal non-null etags mean equal bytes. */
15
+ head(key: string): Promise<{
16
+ size: number;
17
+ etag: string | null;
18
+ } | null>;
19
+ /** Write the bytes of the object at `from` to `to`, replacing any object at `to`, without the bytes passing through the caller. False when there is no object at `from` (nothing is written). */
20
+ copy(from: string, to: string): Promise<boolean>;
14
21
  /** Remove the object at `key`; removing an absent key is not an error. */
15
22
  delete(key: string): Promise<void>;
16
23
  }
@@ -1,7 +1,7 @@
1
- var q=Object.defineProperty;var c=(e,a)=>q(e,"name",{value:a,configurable:!0});import{createHash as z,createHmac as R}from"node:crypto";import{assertBlobKey as y}from"./index.js";import{blobFault as I}from"./fault.js";const E=c(e=>z("sha256").update(e).digest("hex"),"sha256"),p=c((e,a)=>R("sha256",e).update(a).digest(),"hmac"),f=c(e=>encodeURIComponent(e).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),"encode");function X(e){const a=new URL(e.endpoint);async function i(t,s,n,r,o){const m=`/${f(e.bucket)}${s===""?"":`/${s.split("/").map(f).join("/")}`}`,l=[...n].sort(([h],[C])=>h<C?-1:1).map(([h,C])=>`${f(h)}=${f(C)}`).join("&"),g=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),w=g.slice(0,8),S=E(r??""),d={host:a.host,"x-amz-content-sha256":S,"x-amz-date":g},$=Object.keys(d).sort(),A=$.map(h=>`${h}:${d[h]}
2
- `).join(""),_=$.join(";"),T=`${w}/auto/s3/aws4_request`,B=[t,m,l,A,_,S].join(`
3
- `),K=["AWS4-HMAC-SHA256",g,T,E(B)].join(`
4
- `),H=p(p(p(p(`AWS4${e.secretAccessKey}`,w),"auto"),"s3"),"aws4_request"),j=R("sha256",H).update(K).digest("hex");d.authorization=`AWS4-HMAC-SHA256 Credential=${e.accessKeyId}/${T}, SignedHeaders=${_}, Signature=${j}`;const{host:U,...x}=d;return o&&(x.range=`bytes=${o.start}-${o.start+o.length-1}`),await fetch(`${a.origin}${m}${l?`?${l}`:""}`,{method:t,headers:x,...r?{body:new Uint8Array(r)}:{}})}c(i,"send");async function u(t,s){if(!t.ok)throw new Error(`R2 ${s} failed (${t.status}): ${(await t.text()).slice(0,300)}`);return t}return c(u,"ok"),{async put(t,s){I("put"),y(t),await u(await i("PUT",t,[],typeof s=="string"?Buffer.from(s,"utf8"):Buffer.from(s)),`put ${t}`)},async get(t,s){y(t);const n=await i("GET",t,[],void 0,s);return n.status===416?(await n.arrayBuffer(),Buffer.alloc(0)):n.status===404?(await n.arrayBuffer(),null):Buffer.from(await(await u(n,`get ${t}`)).arrayBuffer())},async list(t){const s=[];let n;do{const r=[["list-type","2"],["prefix",t],...n?[["continuation-token",n]]:[]],o=await(await u(await i("GET","",r),`list ${t}`)).text();for(const m of o.matchAll(/<Key>([^<]*)<\/Key>/g))s.push(m[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'"));n=/<IsTruncated>true<\/IsTruncated>/.test(o)?/<NextContinuationToken>([^<]*)<\/NextContinuationToken>/.exec(o)?.[1]:void 0}while(n);return s.sort((r,o)=>Buffer.compare(Buffer.from(r),Buffer.from(o)))},async delete(t){y(t);const s=await i("DELETE",t,[]);s.status!==404?await u(s,`delete ${t}`):await s.arrayBuffer()}}}c(X,"createR2BlobStore");function O(){const e=process.env.CRTR_R2_BUCKET;if(!e)return null;const a=c(i=>{const u=process.env[i];if(!u)throw new Error(`${i} is required when CRTR_R2_BUCKET is set`);return u},"need");return{bucket:e,endpoint:a("CRTR_R2_ENDPOINT"),accessKeyId:a("CRTR_R2_ACCESS_KEY_ID"),secretAccessKey:a("CRTR_R2_SECRET_ACCESS_KEY")}}c(O,"r2ConfigFromEnv");function P(e,a,i,u=new Date){y(a);const t=new URL(e.endpoint),s=`/${f(e.bucket)}/${a.split("/").map(f).join("/")}`,n=u.toISOString().replace(/[:-]|\.\d{3}/g,""),r=n.slice(0,8),o=`${r}/auto/s3/aws4_request`,l=[["X-Amz-Algorithm","AWS4-HMAC-SHA256"],["X-Amz-Credential",`${e.accessKeyId}/${o}`],["X-Amz-Date",n],["X-Amz-Expires",String(i)],["X-Amz-SignedHeaders","host"]].sort(([$],[A])=>$<A?-1:1).map(([$,A])=>`${f($)}=${f(A)}`).join("&"),g=["PUT",s,l,`host:${t.host}
1
+ var q=Object.defineProperty;var u=(s,a)=>q(s,"name",{value:a,configurable:!0});import{createHash as D,createHmac as C}from"node:crypto";import{assertBlobKey as g}from"./index.js";import{blobFault as H}from"./fault.js";const R=u(s=>D("sha256").update(s).digest("hex"),"sha256"),m=u((s,a)=>C("sha256",s).update(a).digest(),"hmac"),f=u(s=>encodeURIComponent(s).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),"encode"),I=5,P=200;function v(s){const a=new URL(s.endpoint);async function i(t,e,n,r,c,l={}){for(let d=1;;d++){let o,$;try{o=await A(t,e,n,r,c,l)}catch(h){$=h}if(o&&o.status!==429&&o.status<500)return o;if(d===I){if(o)return o;throw $}await o?.arrayBuffer().catch(()=>{}),await new Promise(h=>setTimeout(h,P*2**(d-1)*(.5+Math.random())))}}u(i,"send");async function A(t,e,n,r,c,l){const d=`/${f(s.bucket)}${e===""?"":`/${e.split("/").map(f).join("/")}`}`,o=[...n].sort(([S],[E])=>S<E?-1:1).map(([S,E])=>`${f(S)}=${f(E)}`).join("&"),$=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),h=$.slice(0,8),y=R(r??""),w={host:a.host,"x-amz-content-sha256":y,"x-amz-date":$,...l},T=Object.keys(w).sort(),K=T.map(S=>`${S}:${w[S]}
2
+ `).join(""),_=T.join(";"),x=`${h}/auto/s3/aws4_request`,z=[t,d,o,K,_,y].join(`
3
+ `),b=["AWS4-HMAC-SHA256",$,x,R(z)].join(`
4
+ `),j=m(m(m(m(`AWS4${s.secretAccessKey}`,h),"auto"),"s3"),"aws4_request"),U=C("sha256",j).update(b).digest("hex");w.authorization=`AWS4-HMAC-SHA256 Credential=${s.accessKeyId}/${x}, SignedHeaders=${_}, Signature=${U}`;const{host:M,...B}=w;return c&&(B.range=`bytes=${c.start}-${c.start+c.length-1}`),await fetch(`${a.origin}${d}${o?`?${o}`:""}`,{method:t,headers:B,...r?{body:new Uint8Array(r)}:{}})}u(A,"sendOnce");async function p(t,e){if(!t.ok)throw new Error(`R2 ${e} failed (${t.status}): ${(await t.text()).slice(0,300)}`);return t}return u(p,"ok"),{async put(t,e){H("put"),g(t),await p(await i("PUT",t,[],typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)),`put ${t}`)},async head(t){g(t);const e=await i("HEAD",t,[]);if(e.status===404)return null;await p(e,`head ${t}`);const n=/^"?([0-9a-f]{32})"?$/.exec(e.headers.get("etag")??"")?.[1]??null;return{size:Number(e.headers.get("content-length")),etag:n}},async copy(t,e){H("copy"),g(t),g(e);const n=await i("PUT",e,[],void 0,void 0,{"x-amz-copy-source":`/${f(s.bucket)}/${t.split("/").map(f).join("/")}`});if(n.status===404)return await n.arrayBuffer(),!1;const r=await(await p(n,`copy ${t} to ${e}`)).text();if(/<Error>/.test(r))throw new Error(`R2 copy ${t} to ${e} failed: ${r.slice(0,300)}`);return!0},async get(t,e){g(t);const n=await i("GET",t,[],void 0,e);return n.status===416?(await n.arrayBuffer(),Buffer.alloc(0)):n.status===404?(await n.arrayBuffer(),null):Buffer.from(await(await p(n,`get ${t}`)).arrayBuffer())},async list(t){const e=[];let n;do{const r=[["list-type","2"],["prefix",t],...n?[["continuation-token",n]]:[]],c=await(await p(await i("GET","",r),`list ${t}`)).text();for(const l of c.matchAll(/<Key>([^<]*)<\/Key>/g))e.push(l[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'"));n=/<IsTruncated>true<\/IsTruncated>/.test(c)?/<NextContinuationToken>([^<]*)<\/NextContinuationToken>/.exec(c)?.[1]:void 0}while(n);return e.sort((r,c)=>Buffer.compare(Buffer.from(r),Buffer.from(c)))},async delete(t){g(t);const e=await i("DELETE",t,[]);e.status!==404?await p(e,`delete ${t}`):await e.arrayBuffer()}}}u(v,"createR2BlobStore");function L(){const s=process.env.CRTR_R2_BUCKET;if(!s)return null;const a=u(i=>{const A=process.env[i];if(!A)throw new Error(`${i} is required when CRTR_R2_BUCKET is set`);return A},"need");return{bucket:s,endpoint:a("CRTR_R2_ENDPOINT"),accessKeyId:a("CRTR_R2_ACCESS_KEY_ID"),secretAccessKey:a("CRTR_R2_SECRET_ACCESS_KEY")}}u(L,"r2ConfigFromEnv");function Y(s,a,i,A=new Date){g(a);const p=new URL(s.endpoint),t=`/${f(s.bucket)}/${a.split("/").map(f).join("/")}`,e=A.toISOString().replace(/[:-]|\.\d{3}/g,""),n=e.slice(0,8),r=`${n}/auto/s3/aws4_request`,l=[["X-Amz-Algorithm","AWS4-HMAC-SHA256"],["X-Amz-Credential",`${s.accessKeyId}/${r}`],["X-Amz-Date",e],["X-Amz-Expires",String(i)],["X-Amz-SignedHeaders","host"]].sort(([y],[w])=>y<w?-1:1).map(([y,w])=>`${f(y)}=${f(w)}`).join("&"),d=["PUT",t,l,`host:${p.host}
5
5
  `,"host","UNSIGNED-PAYLOAD"].join(`
6
- `),w=["AWS4-HMAC-SHA256",n,o,E(g)].join(`
7
- `),S=p(p(p(p(`AWS4${e.secretAccessKey}`,r),"auto"),"s3"),"aws4_request"),d=R("sha256",S).update(w).digest("hex");return`${t.origin}${s}?${l}&X-Amz-Signature=${d}`}c(P,"presignPutUrl");export{X as createR2BlobStore,P as presignPutUrl,O as r2ConfigFromEnv};
6
+ `),o=["AWS4-HMAC-SHA256",e,r,R(d)].join(`
7
+ `),$=m(m(m(m(`AWS4${s.secretAccessKey}`,n),"auto"),"s3"),"aws4_request"),h=C("sha256",$).update(o).digest("hex");return`${p.origin}${t}?${l}&X-Amz-Signature=${h}`}u(Y,"presignPutUrl");export{v as createR2BlobStore,Y as presignPutUrl,L as r2ConfigFromEnv};
@@ -6,5 +6,7 @@ export interface MovedBlobs {
6
6
  }
7
7
  /** `created` collects the keys this call wrote, so the caller can delete them if the run fails before its copy commits. */
8
8
  export declare function moveRunBlobs(db: CanvasDb, schema: string, target: string, person: string, blobs: BlobStore, runId: string, created: string[]): Promise<MovedBlobs>;
9
+ /** Delete the keys, concurrently. With `bestEffort`, a key that cannot be deleted is skipped and the rest still go; otherwise the first failure is thrown. */
10
+ export declare function deleteBlobs(blobs: BlobStore, keys: readonly string[], bestEffort?: boolean): Promise<void>;
9
11
  /** Delete the run's uploaded copies (after the run is done). */
10
12
  export declare function deleteRunBlobs(blobs: BlobStore, runId: string): Promise<void>;
@@ -1 +1 @@
1
- var x=Object.defineProperty;var r=(e,n)=>x(e,"name",{value:n,configurable:!0});import{parseBlobKey as _,runBlobPrefix as h}from"../bundle/blob-keys.js";import{q as w}from"./catalog.js";import{ImportLaneError as E}from"./stage.js";const q=8;async function M(e,n,s,g,a,y,v){const R={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${w(n)}.nodes UNION SELECT node_id FROM ${w(s)}.nodes WHERE sub = ?`).all(g)).map(t=>t.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${w(n)}.human_requests`).all()).map(t=>t.v))},p=h(y),i=await a.list(p),l={moved:0,left:0};let f=0;const S=r(async()=>{for(let t=f++;t<i.length;t=f++){const c=i[t],o=c.slice(p.length),u=_(o);if(u===null||!R[u.ownerTable].has(u.owner)){l.left+=1;continue}const d=await a.get(c);if(d===null)throw new E("blobs","bundle_invalid",`${c} was listed and is gone`);const m=await a.get(o);if(m===null)await a.put(o,d),v.push(o);else if(!m.equals(d))throw new E("blobs","unique_conflict",`${o} already exists with other contents; the import does not replace it`,{key:o});l.moved+=1}},"worker");return await Promise.all(Array.from({length:Math.min(q,i.length)},S)),l}r(M,"moveRunBlobs");async function T(e,n){for(const s of await e.list(h(n)))await e.delete(s)}r(T,"deleteRunBlobs");export{T as deleteRunBlobs,M as moveRunBlobs};
1
+ var O=Object.defineProperty;var o=(e,t)=>O(e,"name",{value:t,configurable:!0});import{parseBlobKey as S,runBlobPrefix as E}from"../bundle/blob-keys.js";import{q as h}from"./catalog.js";import{ImportLaneError as y}from"./stage.js";const v=256;function B(){const e=process.env.CRTR_IMPORT_BLOB_WORKERS;if(e===void 0||e==="")return v;const t=Number(e);if(!Number.isInteger(t)||t<1||t>1024)throw new Error(`CRTR_IMPORT_BLOB_WORKERS must be an integer from 1 to 1024, got ${JSON.stringify(e)}`);return t}o(B,"workerLimit");async function p(e,t){if(e.length===0)return;let s=0,n;const i=o(async()=>{for(;n===void 0&&s<e.length;)try{await t(e[s++])}catch(l){n??={error:l}}},"worker");if(await Promise.all(Array.from({length:Math.min(B(),e.length)},i)),n!==void 0)throw n.error}o(p,"forEachBounded");async function N(e,t,s,n,i,l,f){const u={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${h(t)}.nodes UNION SELECT node_id FROM ${h(s)}.nodes WHERE sub = ?`).all(n)).map(a=>a.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${h(t)}.human_requests`).all()).map(a=>a.v))},c=E(l),w={moved:0,left:0},d=[];for(const a of await i.list(c)){const r=S(a.slice(c.length));r===null||!u[r.ownerTable].has(r.owner)?w.left+=1:d.push(a)}const g=new Set,R=new Set(d.map(a=>a.slice(c.length)));return await p([...new Set([...R].map(x))],async a=>{for(const r of await i.list(a))R.has(r)&&g.add(r)}),await p(d,async a=>{const r=a.slice(c.length);if(g.has(r)){if(!await T(i,a,r))throw new y("blobs","unique_conflict",`${r} already exists with other contents; the import does not replace it`,{key:r})}else if(f.push(r),!await i.copy(a,r))throw m(a);w.moved+=1}),w}o(N,"moveRunBlobs");const x=o(e=>e.split("/").slice(0,2).join("/")+"/","ownerPrefix"),m=o(e=>new y("blobs","bundle_invalid",`${e} was listed and is gone`),"gone");async function T(e,t,s){const[n,i]=await Promise.all([e.head(t),e.head(s)]);if(n===null)throw m(t);if(i===null||n.size!==i.size)return!1;if(n.etag!==null&&i.etag!==null)return n.etag===i.etag;for(let l=0;l<n.size;l+=_){const f={start:l,length:Math.min(_,n.size-l)},[u,c]=await Promise.all([e.get(t,f),e.get(s,f)]);if(u===null)throw m(t);if(c===null||!u.equals(c))return!1}return!0}o(T,"sameObject");const _=256*1024;async function L(e,t,s=!1){await p(t,s?n=>e.delete(n).catch(()=>{}):n=>e.delete(n))}o(L,"deleteBlobs");async function $(e,t){await L(e,await e.list(E(t)))}o($,"deleteRunBlobs");export{L as deleteBlobs,$ as deleteRunBlobs,N as moveRunBlobs};
@@ -1,14 +1,14 @@
1
- var h=Object.defineProperty;var l=(n,a)=>h(n,"name",{value:a,configurable:!0});import{createHash as g}from"node:crypto";import{ROOT_PROFILE_ID as j}from"../../profiles/manifest.js";import{substitutePerson as D}from"../../canvas/person.js";import{withCanvasWrite as A}from"../../canvas/db.js";import{ImportLaneError as _}from"./stage.js";import{q as T}from"./catalog.js";const I=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"]],M=[["nodes","grant_id"],["crons","grant_id"]],S={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},H=["app","person","profile","repo"];function W(n){const a=new Map,o=l((c,p)=>{a.has(c)||a.set(c,new Set),a.get(c).add(p)},"add");for(const c of n.foreignKeys)c.parent==="objects"&&c.columns.length===1&&o(c.table,c.columns[0]);for(const[c,p]of I)o(c,p);return a}l(W,"objectIdColumns");const N=l((n,a)=>`${T(n)}.${T(a)}`,"sq"),d=l(async(n,a,...o)=>Number((await n.prepareUncached(a).run(...o)).changes),"run"),O=l(async(n,a,...o)=>await n.prepareUncached(a).all(...o),"rows");async function K(n){n.sourcePerson!==n.targetPerson&&await A(async a=>{await a.exec(`SET LOCAL search_path TO ${T(n.schema)}`),await D(a,n.sourcePerson,n.targetPerson)})}l(K,"rewritePerson");async function C(n,a,o,c,p){return o===null?void 0:(await n.prepareUncached(`SELECT id FROM ${N(a,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,c,p))?.id}l(C,"findFleetGrant");function F(n){return new _("id_map","grant_missing",`no grant in the target for: ${n.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...n]})}l(F,"grantMissing");async function Y(n,a){const{db:o,schema:c,target:p}=n,t=l(e=>N(c,e),"S"),b=l(e=>N(p,e),"T"),m={object:new Map,grant:new Map,kind:new Map};for(const[e,E]of a)m.object.set(e,E);const i=n.targetPerson.replace(/^user:/,"");for(const e of H){const E=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${b("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,f=await O(o,`SELECT i.object AS src, t.object AS dst FROM ${t("identities")} i
1
+ var h=Object.defineProperty;var l=(n,s)=>h(n,"name",{value:s,configurable:!0});import{createHash as D}from"node:crypto";import{ROOT_PROFILE_ID as L}from"../../profiles/manifest.js";import{substitutePerson as A}from"../../canvas/person.js";import{withCanvasWrite as I}from"../../canvas/db.js";import{ImportLaneError as j}from"./stage.js";import{q as T}from"./catalog.js";const M=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"],["waits","target_id"]],H=[["nodes","grant_id"],["crons","grant_id"]],w={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},C=["app","person","profile","repo"];function S(n){const s=new Map,o=l((E,d)=>{s.has(E)||s.set(E,new Set),s.get(E).add(d)},"add");for(const E of n.foreignKeys)E.parent==="objects"&&E.columns.length===1&&o(E.table,E.columns[0]);for(const[E,d]of M)o(E,d);return s}l(S,"objectIdColumns");const N=l((n,s)=>`${T(n)}.${T(s)}`,"sq"),p=l(async(n,s,...o)=>Number((await n.prepareUncached(s).run(...o)).changes),"run"),O=l(async(n,s,...o)=>await n.prepareUncached(s).all(...o),"rows");async function K(n){n.sourcePerson!==n.targetPerson&&await I(async s=>{await s.exec(`SET LOCAL search_path TO ${T(n.schema)}`),await A(s,n.sourcePerson,n.targetPerson)})}l(K,"rewritePerson");async function W(n,s,o,E,d){return o===null?void 0:(await n.prepareUncached(`SELECT id FROM ${N(s,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,E,d))?.id}l(W,"findFleetGrant");function F(n){return new j("id_map","grant_missing",`no grant in the target for: ${n.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...n]})}l(F,"grantMissing");async function Y(n,s){const{db:o,schema:E,target:d}=n,t=l(e=>N(E,e),"S"),m=l(e=>N(d,e),"T"),b={object:new Map,grant:new Map,kind:new Map};for(const[e,r]of s)b.object.set(e,r);const i=n.targetPerson.replace(/^user:/,"");for(const e of C){const r=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${m("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,f=await O(o,`SELECT i.object AS src, t.object AS dst FROM ${t("identities")} i
2
2
  JOIN ${t("objects")} so ON so.id = i.object AND so.type = ?
3
- JOIN ${b("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id
4
- JOIN ${b("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
5
- WHERE ${E}`,e,e==="person"?n.targetPerson:i);for(const{src:$,dst:L}of f)$!==L&&m.object.set($,L)}const R=await O(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${t("objects")} o JOIN ${t("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL`);for(const e of R){const E=await o.prepareUncached(`SELECT o.id FROM ${b("objects")} o JOIN ${b("documents")} d ON d.object = o.id
6
- WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(m.object.get(e.owner)??e.owner,e.name);if(E!==void 0){m.object.set(e.id,E.id);continue}const f=n.shippedBodies[e.id];if(f===void 0)throw new _("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const $=await o.prepareUncached(`SELECT o.id FROM ${b("objects")} o JOIN ${b("identities")} i ON i.object = o.id
3
+ JOIN ${m("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id
4
+ JOIN ${m("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
5
+ WHERE ${r}`,e,e==="person"?n.targetPerson:i);for(const{src:R,dst:_}of f)R!==_&&b.object.set(R,_)}const u=await O(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${t("objects")} o JOIN ${t("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL`);for(const e of u){const r=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("documents")} d ON d.object = o.id
6
+ WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(b.object.get(e.owner)??e.owner,e.name);if(r!==void 0){b.object.set(e.id,r.id);continue}const f=n.shippedBodies[e.id];if(f===void 0)throw new j("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const R=await o.prepareUncached(`SELECT o.id FROM ${m("objects")} o JOIN ${m("identities")} i ON i.object = o.id
7
7
  WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ?
8
8
  UNION ALL SELECT o.id FROM ${t("objects")} o JOIN ${t("identities")} i ON i.object = o.id
9
- WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(n.targetPerson,n.targetPerson);if($===void 0)throw new _("id_map","bundle_invalid",`no person object for ${n.targetPerson}; cannot import shipped document ${e.name}`);await d(o,`UPDATE ${t("objects")} SET owner = ? WHERE id = ?`,$.id,e.id),await d(o,`DELETE FROM ${t("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await d(o,`INSERT INTO ${t("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
10
- VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,i,e.created_at),await d(o,`UPDATE ${t("documents")} SET source_path = NULL WHERE object = ?`,e.id),await d(o,`UPDATE ${t("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${t("revision_parents")} p WHERE p.parent = r.rev_id)`,f,e.id)}const s=await O(o,`SELECT id, sub, grantee FROM ${t("grants")} ORDER BY id`),r=[];for(const e of s){const E=await C(o,p,n.fleetRuntime,e.sub,e.grantee);E===void 0?r.push(e.grantee):m.grant.set(e.id,E)}if(r.length>0)throw F(r);await o.exec(`CREATE TABLE ${t("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,E]of[["object",m.object],["grant",m.grant]])for(const[f,$]of E)await d(o,`INSERT INTO ${t("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,f,$);const u=`(SELECT source FROM ${t("_idmap")} WHERE kind = 'object')`;for(const[e,E]of Object.entries(S))await d(o,`DELETE FROM ${t(e)} WHERE ${E} IN ${u}`);await d(o,`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${u})`),await d(o,`DELETE FROM ${t("revisions")} WHERE document IN ${u}`);for(const[e,E]of W(n.catalog))if(n.catalog.tables.has(e))for(const f of E)await w(o,t(e),f,"object",t("_idmap"));for(const[e,E]of M)await w(o,t(e),E,"grant",t("_idmap"));await d(o,`UPDATE ${t("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
11
- FROM ${t("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await d(o,`DELETE FROM ${t("objects")} WHERE id IN ${u}`),await d(o,`UPDATE ${t("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${t("identities")} WHERE scheme = 'user' AND external_id = ?)`,i,i,n.targetPerson);for(const{name:e}of await O(o,`SELECT k.name FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${b("object_kinds")} t WHERE t.name = k.name)`))m.kind.set(e,e);return await d(o,`DELETE FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${b("object_kinds")} t WHERE t.name = k.name)`),m}l(Y,"rewriteIds");async function B(n){const{db:a,schema:o,target:c,targetPerson:p}=n,t=new Map,b=l(async(i,...R)=>await a.prepareUncached(i).get(...R),"row"),m=l(i=>d(a,`DELETE FROM ${N(o,"profiles")} WHERE id = ?`,i),"dropStaged");for(const{id:i}of await O(a,`SELECT id FROM ${N(o,"profiles")} ORDER BY id`)){let R=i===j?await b(`SELECT id, person FROM ${N(c,"profiles")} WHERE person = ? AND name = 'root'`,p):await b(`SELECT id, person FROM ${N(c,"profiles")} WHERE id = ? AND person = ?`,i,p);if(R===void 0){if(await b(`SELECT id, person FROM ${N(c,"profiles")} WHERE id = ?`,i)===void 0&&i!==j)continue;const u=`${i.replace(/-[0-9a-f]{8}$/,"")}-${g("sha256").update(`${p}\0${i}`).digest("hex").slice(0,8)}`,e=await b(`SELECT id, person FROM ${N(c,"profiles")} WHERE id = ?`,u);if(e!==void 0&&e.person!==p)throw new _("id_map","unique_conflict",`profiles ${u} is held by another person in the target`,{table:"profiles",values:[u]});R=e??{id:u,person:p},e===void 0?await d(a,`UPDATE ${N(o,"profiles")} SET id = ? WHERE id = ?`,u,i):await m(i)}else await m(i);const s=R.id;await d(a,`UPDATE ${N(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${N(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
12
- AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${N(c,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,s,i,s,i),await d(a,`UPDATE ${N(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${N(o,"objects")} WHERE type = 'profile')`,s,i),s!==i&&t.set(i,s)}return t}l(B,"mapProfileIds");async function w(n,a,o,c,p){await d(n,`UPDATE ${a} t SET ${T(o)} = m.target FROM ${p} m WHERE m.kind = ? AND t.${T(o)} = m.source`,c)}l(w,"remap");async function X(n){const{db:a,schema:o,target:c,catalog:p}=n,t=l(s=>N(o,s),"S"),b={},m=l((s,r)=>{r>0&&(b[s]=(b[s]??0)+r)},"count");await a.exec(`CREATE TABLE ${t("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const i=`(SELECT id FROM ${t("objects")} WHERE home_machine IS NOT NULL)`;await d(a,`INSERT INTO ${t("_dropped")} SELECT 'objects', id FROM ${t("objects")} WHERE home_machine IS NOT NULL`);for(const[s,r]of Object.entries(S))m(s,await d(a,`DELETE FROM ${t(s)} WHERE ${r} IN ${i}`));for(m("objects",await d(a,`DELETE FROM ${t("objects")} WHERE home_machine IS NOT NULL`));;){let s=0;for(const r of p.foreignKeys){if(r.columns.length!==1||r.parentColumns.length!==1||!n.catalog.tables.has(r.table))continue;const u=p.tables.get(r.table),e=T(r.columns[0]),E=u.primaryKey.length===1?T(u.primaryKey[0]):null;E!==null&&await d(a,`INSERT INTO ${t("_dropped")} SELECT ?, ${E}::text FROM ${t(r.table)} WHERE ${e} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?) ON CONFLICT DO NOTHING`,r.table,r.parent);const f=await d(a,`DELETE FROM ${t(r.table)} WHERE ${e} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?)`,r.parent);m(r.table,f),s+=f}if(s===0)break}const R=`(SELECT key FROM ${t("_dropped")} WHERE tbl = 'objects')`;m("relations",await d(a,`DELETE FROM ${t("relations")} WHERE resource_id IN ${R} OR subject_id IN ${R}`));for(const s of p.foreignKeys){if(s.columns.length!==1||!p.tables.has(s.table))continue;const r=T(s.columns[0]),u=T(s.parentColumns[0]),e=await O(a,`SELECT DISTINCT c.${r}::text AS value FROM ${t(s.table)} c
13
- WHERE c.${r} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${t(s.parent)} p WHERE p.${u} = c.${r})
14
- AND NOT EXISTS (SELECT 1 FROM ${N(c,s.parent)} p WHERE p.${u} = c.${r}) LIMIT 10`);if(e.length>0)throw new _("drop","bundle_invalid",`${s.table}.${s.columns[0]} names rows that exist nowhere: ${e.map(E=>E.value).join(", ")}`,{table:s.table,column:s.columns[0],values:e.map(E=>E.value)})}return b}l(X,"dropStubRows");export{I as OBJECT_ID_COLUMNS,X as dropStubRows,C as findFleetGrant,F as grantMissing,B as mapProfileIds,W as objectIdColumns,Y as rewriteIds,K as rewritePerson};
9
+ WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(n.targetPerson,n.targetPerson);if(R===void 0)throw new j("id_map","bundle_invalid",`no person object for ${n.targetPerson}; cannot import shipped document ${e.name}`);await p(o,`UPDATE ${t("objects")} SET owner = ? WHERE id = ?`,R.id,e.id),await p(o,`DELETE FROM ${t("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await p(o,`INSERT INTO ${t("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
10
+ VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,i,e.created_at),await p(o,`UPDATE ${t("documents")} SET source_path = NULL WHERE object = ?`,e.id),await p(o,`UPDATE ${t("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${t("revision_parents")} p WHERE p.parent = r.rev_id)`,f,e.id)}const $=await O(o,`SELECT id, sub, grantee FROM ${t("grants")} ORDER BY id`),a=[];for(const e of $){const r=await W(o,d,n.fleetRuntime,e.sub,e.grantee);r===void 0?a.push(e.grantee):b.grant.set(e.id,r)}if(a.length>0)throw F(a);await o.exec(`CREATE TABLE ${t("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,r]of[["object",b.object],["grant",b.grant]])for(const[f,R]of r)await p(o,`INSERT INTO ${t("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,f,R);const c=`(SELECT source FROM ${t("_idmap")} WHERE kind = 'object')`;for(const[e,r]of Object.entries(w))await p(o,`DELETE FROM ${t(e)} WHERE ${r} IN ${c}`);await p(o,`DELETE FROM ${t("revision_parents")} WHERE child IN (SELECT rev_id FROM ${t("revisions")} WHERE document IN ${c})`),await p(o,`DELETE FROM ${t("revisions")} WHERE document IN ${c}`);for(const[e,r]of S(n.catalog))if(n.catalog.tables.has(e))for(const f of r)await g(o,t(e),f,"object",t("_idmap"));for(const[e,r]of H)await g(o,t(e),r,"grant",t("_idmap"));await p(o,`UPDATE ${t("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
11
+ FROM ${t("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(o,`DELETE FROM ${t("objects")} WHERE id IN ${c}`),await p(o,`UPDATE ${t("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${t("identities")} WHERE scheme = 'user' AND external_id = ?)`,i,i,n.targetPerson);for(const{name:e}of await O(o,`SELECT k.name FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`))b.kind.set(e,e);return await p(o,`DELETE FROM ${t("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${m("object_kinds")} t WHERE t.name = k.name)`),b}l(Y,"rewriteIds");async function B(n){const{db:s,schema:o,target:E,targetPerson:d}=n,t=new Map,m=l(async(i,...u)=>await s.prepareUncached(i).get(...u),"row"),b=l(i=>p(s,`DELETE FROM ${N(o,"profiles")} WHERE id = ?`,i),"dropStaged");for(const{id:i}of await O(s,`SELECT id FROM ${N(o,"profiles")} ORDER BY id`)){let u=i===L?await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE person = ? AND name = 'root'`,d):await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ? AND person = ?`,i,d);if(u===void 0){if(await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ?`,i)===void 0&&i!==L)continue;const c=`${i.replace(/-[0-9a-f]{8}$/,"")}-${D("sha256").update(`${d}\0${i}`).digest("hex").slice(0,8)}`,e=await m(`SELECT id, person FROM ${N(E,"profiles")} WHERE id = ?`,c);if(e!==void 0&&e.person!==d)throw new j("id_map","unique_conflict",`profiles ${c} is held by another person in the target`,{table:"profiles",values:[c]});u=e??{id:c,person:d},e===void 0?await p(s,`UPDATE ${N(o,"profiles")} SET id = ? WHERE id = ?`,c,i):await b(i)}else await b(i);const $=u.id;await p(s,`UPDATE ${N(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${N(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
12
+ AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${N(E,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,$,i,$,i),await p(s,`UPDATE ${N(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${N(o,"objects")} WHERE type = 'profile')`,$,i),$!==i&&t.set(i,$)}return t}l(B,"mapProfileIds");async function g(n,s,o,E,d){await p(n,`UPDATE ${s} t SET ${T(o)} = m.target FROM ${d} m WHERE m.kind = ? AND t.${T(o)} = m.source`,E)}l(g,"remap");async function X(n){const{db:s,schema:o,target:E,catalog:d}=n,t=l(a=>N(o,a),"S"),m={},b=l((a,c)=>{c>0&&(m[a]=(m[a]??0)+c)},"count");await s.exec(`CREATE TABLE ${t("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const i=`(SELECT id FROM ${t("objects")} WHERE home_machine IS NOT NULL)`;await p(s,`INSERT INTO ${t("_dropped")} SELECT 'objects', id FROM ${t("objects")} WHERE home_machine IS NOT NULL`);for(const[a,c]of Object.entries(w))b(a,await p(s,`DELETE FROM ${t(a)} WHERE ${c} IN ${i}`));b("objects",await p(s,`DELETE FROM ${t("objects")} WHERE home_machine IS NOT NULL`));const u=new Map;for(const[a,c]of S(d))d.tables.has(a)&&a!=="messages"&&u.set(a,[...c]);const $=`(SELECT key FROM ${t("_dropped")} WHERE tbl = 'objects')`;for(;;){let a=0;const c=l(async(e,r,...f)=>{const R=d.tables.get(e).primaryKey.length===1?T(d.tables.get(e).primaryKey[0]):null;R!==null&&await p(s,`INSERT INTO ${t("_dropped")} SELECT ?, ${R}::text FROM ${t(e)} WHERE ${r} ON CONFLICT DO NOTHING`,e,...f);const _=await p(s,`DELETE FROM ${t(e)} WHERE ${r}`,...f);b(e,_),a+=_},"drop");for(const e of d.foreignKeys)e.columns.length!==1||e.parentColumns.length!==1||!n.catalog.tables.has(e.table)||await c(e.table,`${T(e.columns[0])} IN (SELECT key FROM ${t("_dropped")} WHERE tbl = ?)`,e.parent);for(const[e,r]of u)await c(e,r.map(f=>`${T(f)} IN ${$}`).join(" OR "));if(a===0)break}for(const a of d.foreignKeys){if(a.columns.length!==1||!d.tables.has(a.table))continue;const c=T(a.columns[0]),e=T(a.parentColumns[0]),r=await O(s,`SELECT DISTINCT c.${c}::text AS value FROM ${t(a.table)} c
13
+ WHERE c.${c} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${t(a.parent)} p WHERE p.${e} = c.${c})
14
+ AND NOT EXISTS (SELECT 1 FROM ${N(E,a.parent)} p WHERE p.${e} = c.${c}) LIMIT 10`);if(r.length>0)throw new j("drop","bundle_invalid",`${a.table}.${a.columns[0]} names rows that exist nowhere: ${r.map(f=>f.value).join(", ")}`,{table:a.table,column:a.columns[0],values:r.map(f=>f.value)})}return m}l(X,"dropStubRows");export{M as OBJECT_ID_COLUMNS,X as dropStubRows,W as findFleetGrant,F as grantMissing,B as mapProfileIds,S as objectIdColumns,Y as rewriteIds,K as rewritePerson};
@@ -1,3 +1,3 @@
1
- var Q=Object.defineProperty;var u=(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 N}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 C,encodeKeys as W}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewritePaths as oe,rewriteRequestPaths as de,takeRepoSyncedDocuments as pe}from"./prepare.js";import{boundSub as ce,checkSourcePerson as ue,checkStagedBlobKeys as fe,checkStagedPersons as le,checkStagedReferences as me,checkStagedRequestKeys as _e}from"./bind.js";import{deleteRunBlobs as we,moveRunBlobs as ge}from"./blobs.js";import{dropStubRows as be,findFleetGrant as he,grantMissing as ye,mapProfileIds as Ee,rewriteIds as Se,rewritePerson as ve}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as Re,stagingSchema as Oe,targetSchema as Te}from"./stage.js";import{verifyRun as Pe}from"./verify.js";import{sandboxPathMap as ke,writeNodeFiles as je}from"./path-map.js";import{allStoreKeys as Ie,readPluginsStore as De,recordImportedActivations as Ae,writeStores as Me}from"./stores.js";import{publishImportedPlugins as Ne}from"./publish-plugins.js";import{COPIED_TABLES as Ce}from"../bundle/layout.js";import{ClaimLostError as We}from"../../../daemon/reconcilers/row-claim.js";const L=10*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 Be(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(Be,"readSource");async function Le(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 c=ce(a.sub,r,n.person,"grants.sub");await he(i,s,d,c,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)>=L)throw ye(m);return!1}u(Le,"grantsReady");async function pt(e,i,n={}){const r=n.blobs??await Y(),s=await S(),d=Oe(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 m=[];try{const a=await Be(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 Te(s),b=[...Ce],g=await ae(s,c,[...b,"grants"]);if(!l){const f={},P=[],k=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ue(s,c,a.person,e.person),!await Le(r,s,e,a.person,c,j)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const y=await Ne(await De(r,e.run_id));if(y.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)>=L)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${y.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:y.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}k.push(...y.refused),await t("stage");const K=await Re(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:c,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await le(_)))E(f,o,p);for(const[o,p]of Object.entries(await fe(_)))E(f,o,p);await t("rewrite-person"),await ve(_),await t("prune");const U=await ie(s,d,g,a),I=a.kind==="hosted"?ke(a.pathPrefixes??[]):[];await t("rewrite-paths"),await oe(s,d,I),await de(s,d),await _e(_);const F=await Ee(_);await re(s,d,c,a.installId,e.person),await t("rewrite-ids");const D=await Se(_,F);await t("drop");const J=await pe(s,d,c),q=await be(_);for(const[o,p]of Object.entries({...U}))E(f,o,p);for(const[o,p]of Object.entries(q))E(f,o,p);await me(_),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,c,g,b,new Set,$),await t("blobs"),await ge(s,d,c,e.person,r,e.run_id,m),await t("copy"),await N(async o=>{await i.assertOwned();const p=await ne({db:o,runId:e.run_id,schema:d,target:c,catalog:g,source:a,person:e.person,idMap:D,pathMap:I}),A=await Ue(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await je(o,d,e.run_id,a);const M=await Me({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,z]of Object.entries(M.inserted))p.inserted[G]=z.length;return P.push(...M.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ke(f,p),unresolved_plugins:P,refused_plugins:k}),R(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const h=await Pe(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(h),e.run_id),!h.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:h.differences,invariants:h.invariants});await t("manifest");const T=v.manifest(e.run_id);await r.put(T,await Fe(e.run_id)),await B(s,e.run_id);for(const f of Ie(e.run_id))await r.delete(f);await we(r,e.run_id),await N(async f=>{await Ae(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=He(a);if(await B(s,e.run_id).catch(()=>{}),!l)for(const b of m)await r.delete(b).catch(()=>{});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(pt,"processRun");function He(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(He,"failureOf");function E(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(E,"addDropped");function Ke(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(Ke,"withInserted");async function Ue(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 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(Ue,"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,W(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...C(s.inserted_keys),...r]),i,n)}u(H,"appendManifest");async function Fe(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:C(r.inserted_keys)})).join(`
1
+ var Q=Object.defineProperty;var u=(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 E,withCanvasWrite as N}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as S,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 C,encodeKeys as B}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewritePaths as oe,rewriteRequestPaths as de,takeRepoSyncedDocuments as pe}from"./prepare.js";import{boundSub as ce,checkSourcePerson as ue,checkStagedBlobKeys as fe,checkStagedPersons as le,checkStagedReferences as me,checkStagedRequestKeys as _e}from"./bind.js";import{deleteBlobs as we,deleteRunBlobs as ge,moveRunBlobs as be}from"./blobs.js";import{dropStubRows as he,findFleetGrant as ye,grantMissing as Ee,mapProfileIds as Se,rewriteIds as ve,rewritePerson as Re}from"./rewrite.js";import{dropStaging as W,ImportLaneError as w,stage as Oe,stagingSchema as Te,targetSchema as Pe}from"./stage.js";import{verifyRun as ke}from"./verify.js";import{sandboxPathMap as je,writeNodeFiles as Ie}from"./path-map.js";import{allStoreKeys as De,readPluginsStore as Ae,recordImportedActivations as Me,writeStores as Ne}from"./stores.js";import{publishImportedPlugins as Ce}from"./publish-plugins.js";import{COPIED_TABLES as Be}from"../bundle/layout.js";import{ClaimLostError as We}from"../../../daemon/reconcilers/row-claim.js";const L=10*6e4,v=u(()=>new Date().toISOString(),"now"),R=u(async(e,i)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Le(e,i){const n=await e.get(S.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}u(Le,"readSource");async function He(e,i,n,r,s,d){const t=await e.get(S.rows(n.run_id,"grants")),l=t===null?[]:x(t),m=[];for(const a of l){const c=ce(a.sub,r,n.person,"grants.sub");await ye(i,s,d,c,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)>=L)throw Ee(m);return!1}u(He,"grantsReady");async function ct(e,i,n={}){const r=n.blobs??await Y(),s=await E(),d=Te(e.run_id),t=u(async a=>{await i.assertOwned(),await R(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 c=await Pe(s),O=[...Be],g=await ae(s,c,[...O,"grants"]);if(!l){const f={},P=[],k=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ue(s,c,a.person,e.person),!await He(r,s,e,a.person,c,j)){await i.assertOwned(),await R(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await Ce(await Ae(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)>=L)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 R(e.run_id,"waiting_for_directory");return}k.push(...h.refused),await t("stage");const K=await Oe(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:c,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await le(_)))y(f,o,p);for(const[o,p]of Object.entries(await fe(_)))y(f,o,p);await t("rewrite-person"),await Re(_),await t("prune");const U=await ie(s,d,g,a),I=a.kind==="hosted"?je(a.pathPrefixes??[]):[];await t("rewrite-paths"),await oe(s,d,I),await de(s,d),await _e(_);const F=await Se(_);await re(s,d,c,a.installId,e.person),await t("rewrite-ids");const D=await ve(_,F);await t("drop");const J=await pe(s,d,c),q=await he(_);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(_),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,c,g,O,new Set,$),await t("blobs"),await be(s,d,c,e.person,r,e.run_id,m),await t("copy"),await N(async o=>{await i.assertOwned();const p=await ne({db:o,runId:e.run_id,schema:d,target:c,catalog:g,source:a,person:e.person,idMap:D,pathMap:I}),A=await Fe(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Ie(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,z]of Object.entries(M.inserted))p.inserted[G]=z.length;return P.push(...M.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ue(f,p),unresolved_plugins:P,refused_plugins:k}),v(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const b=await ke(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=S.manifest(e.run_id);await r.put(T,await Je(e.run_id)),await W(s,e.run_id);for(const f of De(e.run_id))await r.delete(f);await ge(r,e.run_id),await N(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(T,v(),e.run_id)})}catch(a){if(a instanceof We)throw a;const c=Ke(a);await W(s,e.run_id).catch(()=>{}),l||await we(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),v(),e.run_id)}}u(ct,"processRun");function Ke(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(Ke,"failureOf");function y(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(y,"addDropped");function Ue(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(Ue,"withInserted");async function Fe(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 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(Fe,"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,B(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...C(s.inserted_keys),...r]),i,n)}u(H,"appendManifest");async function Je(e){const n=await(await E()).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:C(r.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}u(Fe,"manifestFile");export{L as GRANT_WAIT_MS,pt as processRun};
3
+ `))}u(Je,"manifestFile");export{L as GRANT_WAIT_MS,ct as processRun};
@@ -7,6 +7,10 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
7
7
 
8
8
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
9
9
 
10
+ ## 0.3.613
11
+
12
+ `oauth.appMember('user:<id>')` asks the directory whether that person is on the team that holds your app, for your app's own staff pages. It answers `{member: true, role: 'admin' | 'member'}` or `{member: false}` (an unknown user is `member: false`) by calling `GET /v1/apps/self/members/:user_id` as the app itself, and caches nothing, so someone removed from the team is refused at their next call. A 401 re-mints the directory token once. Nothing existing changes.
13
+
10
14
  ## 0.3.599
11
15
 
12
16
  `PUT /v1/model-auth/:provider` with `kind: "api_key"` accepts an optional `models: {ultra, strong, medium, light}` for `anthropic`, `openai`, `openrouter` and `moonshotai`. Each value is `<provider>/<model-id>`, a registered chat model of that provider; all four are required. The key is saved with that mapping as the person's model route `key:<provider>`, which is tried after every subscription. An invalid mapping is refused `400 invalid_request`. Without `models` the call behaves as before.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.611",
3
+ "version": "0.3.613",
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.611",
148
+ "@north-light/identity": "0.3.613",
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.611",
3
+ "version": "0.3.613",
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.611",
3
+ "version": "0.3.613",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.611",
9
+ "version": "0.3.613",
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.611",
31
+ "@north-light/identity": "0.3.613",
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.611",
11959
+ "version": "0.3.613",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.611",
11964
+ "version": "0.3.613",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.611",
11969
+ "version": "0.3.613",
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.611",
11977
+ "version": "0.3.613",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.611",
11981
- "@north-light/identity": "0.3.611"
11980
+ "@north-light/api": "0.3.613",
11981
+ "@north-light/identity": "0.3.613"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.611",
11986
+ "version": "0.3.613",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.611",
11990
- "@north-light/identity": "0.3.611",
11991
- "@north-light/plugin": "0.3.611",
11989
+ "@north-light/api": "0.3.613",
11990
+ "@north-light/identity": "0.3.613",
11991
+ "@north-light/plugin": "0.3.613",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {