@cortexkit/opencode-anthropic-auth 2.5.4 → 2.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/{index-chmd6kg9.js → index-gqgvt8x1.js} +16 -16
- package/dist/index.js +1 -1
- package/dist/transform.d.ts +4 -0
- package/dist/v2/adapter.d.ts +1 -1
- package/dist/v2/server.js +7 -7
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -9,7 +9,7 @@ import{B as _3}from"./index-qqs4ec18.js";import{D as j7,E as M7,F as o$,G as r$,
|
|
|
9
9
|
`;if(_)await r0(I,R);else await m2(I,R)}catch(N){let R=await C1(M,V);if(c2(N)&&!R)return!1;try{await P1(V)}catch{}throw N}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function a0(V){let M;try{M=await A1(O)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(_)try{await a(O,"directory",!0)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(M.mtimeMs+m>X()){let S=!0;try{await A1(I)}catch(h){if(h.code==="ENOENT")S=!1;else return"fresh"}if(S)return"fresh";if(M.mtimeMs+B8>X())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let N=`${O}.${r1()}`;try{await v2(O,N)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if($.onStep)await $.onStep("stale-marker-claimed");let R=_?await J1(N):void 0;return await J0(N,async()=>{if(!R)return!0;let S=await J1(N).catch((h)=>{if(h.code!=="ENOENT")throw h;return});return!!S&&c3(R,S)},V),"recovered"}async function b(V,M){try{if(!await c1(M))return!1}catch(S){if(S.code==="EEXIST"){if(_)try{await a(O,"directory",!0),await z0(I,!0)}catch(h){if(h.code!=="ENOENT")throw h}return!1}throw S}let N=!1,R;try{await V()}catch(S){N=!0,R=S}try{await P1(M)}catch(S){if(l(R,Z)&&l(S,O))throw R;throw S}if(N)throw R;return!0}async function F0(){for(let V=0;V<u;V++){if($.onStep)await $.onStep("relinquish-read");let M;try{M=await F()}catch(N){if(_)throw N;return}if(M?.ownerId!==z)return;try{await _1(Z,{recursive:!0,force:!0});return}catch(N){if(_)throw N;await E()}}}function U2(){if(!$.renew||Q||H)return;let V=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=K8(()=>{G=null;let M=(async()=>{let N=!Q;try{if(!await b(async()=>{let S=await F(),h=X();if(Q||H){N=!1;return}if(S?.ownerId!==z){B("taken-over",S),N=!1;return}if(!(Number(S?.expiresAt)>h)){B("expired",S),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||H){N=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||H){N=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||H){N=!1;return}if(await K(),$.onStep)await $.onStep("renewal-write-finished");if(!await p()){B("marker-lost"),N=!1,await F0();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(R){if(_&&R instanceof w)L=R,B("renewal-failed"),N=!1;try{let S=await F();if(S?.ownerId!==z)B("taken-over",S);else if(!(Number(S?.expiresAt)>X()))B("expired",S)}catch{B("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(N&&!Q&&!H)U2()}})();C=M,M.finally(()=>{if(C===M)C=null})},V),"unref"in G)G.unref();q("scheduled")}function q2(){try{let V=$.onContended?.();if(V&&(typeof V==="object"||typeof V==="function")&&"then"in V&&typeof V.then==="function")Promise.resolve(V).catch(()=>{})}catch{}return null}let T0=await g();if(!T0)for(let V=0;V<u;V++){if(T0=await g(),T0)break;let M=await v();if(M.status==="live")return q2();if(M.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await c1()){await E();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await a0()==="fresh")return null;await E();continue}try{let N=await v();if(N.status==="live")return q2();if(!Z0(M.identity,N))continue;if(!await p())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await p())return null;let R=await v(!1);if(!Z0(M.identity,R))continue;if(await d(Z),!await p())return null;if($.onStep)await $.onStep("stale-lock-removed");if(T0=await g(),!T0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await p())return await F0(),T0=!1,null;break}finally{await P1()}}if(!T0)return null;return U2(),{ownerId:z,whenLost:()=>Y,hasLost:()=>H!==void 0,assertOwned:async()=>{if(L)throw L;let V;try{let M=await F();if(V=M,!Q&&!H&&M?.ownerId===z&&Number(M?.expiresAt)>X())return;B(M?.ownerId!==z?"taken-over":"expired",M)}catch(M){if(B("unreadable"),_&&M instanceof w)throw M}throw new j0({target:$.path,name:$.name,expectedOwnerId:z,...typeof V?.ownerId==="string"?{observedOwnerId:V.ownerId}:{},...typeof V?.expiresAt==="number"?{observedExpiresAt:V.expiresAt}:{}})},release:async(V)=>{if(_&&W)return;Q=!0,D(),await C;let M=performance.now()+m+1000,N=5,R;for(;;){try{let h=!1;if(await b(async()=>{let K2;try{K2=await F()}catch(F2){if(_&&F2.code==="ENOENT"){h=!0;return}throw F2}if(K2?.ownerId!==z){h=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await p())return;await d(Z),h=!0},M)){if(_&&!h)throw new w(Z,"release-not-confirmed",{code:"EIO"});W=h;return}if(V?.aborted)return;await a0(M)}catch(h){if(!l(h,Z)){if(_)throw h;return}R??=h}let S=M-performance.now();if(S<=0)break;if(await new Promise((h)=>setTimeout(h,Math.min(N,S))),_&&performance.now()>=M)break;N=Math.min(N*2,50)}if(_)throw R??new w(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}var R8=1,e1=16384,i2=30000,a3=/^[0-9a-f]{64}$/,o2="unknown_method",r2=new Set([o2,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),t2=new Set(["pending_queue_full"]);function d3($){if(!($ instanceof _8))return;if(r2.has($.code))return{code:$.code,disposition:"terminal"};if(t2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function e2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function t1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function $$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function I1(){return new A("invalid-state","invalid Claustrum enrollment state")}function s3($){if(!e2($)||$.version!==R8||typeof $.proposedName!=="string"||$.proposedName.length===0)throw I1();if($.phase==="pending"){if(!a3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!t1($.createdAt)||!t1($.updatedAt))throw I1();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!$$($.tokenGeneration)||!t1($.updatedAt))throw I1();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!t1($.updatedAt))throw I1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw I1()}function n3($){if(!e2($)||!a3.test(String($.token??""))||!$$($.token_generation))throw new A("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function Z$($){if(!$.isFile())throw new A("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new A("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new A("unsafe-file","Claustrum enrollment file must be owned by the current user")}function d2($){try{return JSON.parse($)}catch{throw new A("invalid-state","Claustrum enrollment file is not valid JSON")}}async function x0($){if(_)try{await W0(f0($));let J=await z0($,!0);if(Buffer.byteLength(J)>e1)throw new A("unsafe-file","Claustrum enrollment file is too large");return d2(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await s2($,p2.O_RDONLY|p2.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new A("unsafe-file","Claustrum enrollment file could not be opened safely")}try{Z$(await Z.stat());let J=Buffer.alloc(e1+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>e1)throw new A("unsafe-file","Claustrum enrollment file is too large");return d2(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function l2($,Z){let J=[];for(let z of $.split(`
|
|
10
10
|
`)){if(z.trim()===""||z.startsWith("#"))continue;let X=z.split(":");if(X.length!==Z||!/^[^\s:,]+$/.test(X[0]??"")||!/^\d+$/.test(X[2]??"")||!Number.isSafeInteger(Number(X[2]))||Z===7&&(!/^\d+$/.test(X[3]??"")||!Number.isSafeInteger(Number(X[3])))||Z===4&&X[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(X[3]??""))return;J.push(X)}return J}async function S8($,Z,J){try{let[z,X]=await Promise.all([p3(J.passwdPath??"/etc/passwd","utf8"),p3(J.groupPath??"/etc/group","utf8")]),G=l2(z,7),Q=l2(X,4);if(!G||!Q)return!1;let W=G.filter((q)=>Number(q[2])===$),H=Q.filter((q)=>Number(q[2])===Z);if(W.length!==1||H.length!==1)return!1;let U=W[0]?.[0],Y=H[0]?.[3]??"";return(Y===""||Y.split(",").every((q)=>q===U))&&!G.some((q)=>Number(q[2])!==$&&Number(q[3])===Z)}catch{return!1}}function J$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>p3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function z$($,Z={}){if(!_){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),X;try{X=await P8($)}catch{return}let G;for(;;){let Q=await n2(X).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=z!==void 0&&await S8(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!G)throw new A("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${X}. Another user could replace it. Run: chmod g-w,o-w ${X}`)}let W=f0(X);if(W===X)return;X=W}}try{await B0($,J$(Z))}catch(J){if(!(J instanceof w))throw J;throw new A("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function z1($,Z={},J="enrollment directory"){if(_){await W0($,!1,J$(Z));return}await L8($,{recursive:!0,mode:448});let z=await n2($),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new A("unsafe-file",`Claustrum ${J} must be owned by the current user`);if((z.mode&63)!==0)await N8($,448)}async function b0($,Z,J={}){let z=f0($);await z1(z,J),await z$(z,J);let X=`${JSON.stringify(Z)}
|
|
11
11
|
`;if(Buffer.byteLength(X)>e1)throw new A("invalid-state","Claustrum enrollment state is too large");if(_)return t0($,X);let G=A8(z,`.${O8($)}.${process.pid}.${D8()}.tmp`),Q,W=!1;try{Q=await s2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await C8(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await l3(G).catch(()=>{})}}var T8=new E0;async function $3($,Z){let J=_?await a2($,Z):await T8.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>a2({tokenPath:X,statePath:G},Z),(X)=>{for(let G of X)if(G!=="absent")Z$(G)}),z={...J.status};if(J.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function a2($,Z){let J=await x0($.tokenPath),z=J===void 0?void 0:n3(J),X=await x0($.statePath),G=X===void 0?void 0:s3(X);if(z)return{usesProposedName:G===void 0,status:{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:z.token_generation}};if(!G)return{status:{state:"idle"},usesProposedName:!1};if(G.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:G.proposedName,code:"missing_token"}};return{status:O0(G),usesProposedName:!1}}async function A0($){let Z=await x0($);if(Z===void 0)throw new A("not-enrolled","Claustrum enrollment is not configured");return n3(Z)}function O0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function X$(){return new A("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class i3{#$;#Z;#X;#Q;#G;#W;#z;constructor($){this.#z=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#X=$.proposedName,this.#Q=$.now??Date.now,this.#G=$.mintSecret??(()=>M8(32).toString("hex")),this.#W=$.writeTokenFile??I8}async status(){return $3(this.#Z,this.#X)}async resetTerminal(){return G$(this.#Z,this.#X)}async#J($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Q()};return await b0(this.#Z.statePath,J,this.#z),O0(J)}async reconcile(){await z1(f0(this.#Z.statePath),this.#z);let $=await M0({name:"ceremony",path:this.#Z.statePath,ttlMs:i2,renew:!0});if(!$)return{state:"busy"};try{let Z=await x0(this.#Z.tokenPath),J=Z===void 0?void 0:n3(Z),z=await x0(this.#Z.statePath),X=z===void 0?void 0:s3(z);if(X&&X.proposedName!==this.#X)throw X$();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#X,tokenGeneration:J.token_generation,updatedAt:this.#Q()};await b0(this.#Z.statePath,Q,this.#z),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#Q()};return await b0(this.#Z.statePath,Q,this.#z),O0(Q)}if(X&&X.phase!=="pending")return O0(X);if(!X){let Q=this.#Q();if(X={version:1,phase:"pending",proposedName:this.#X,requestSecret:this.#G(),createdAt:Q,updatedAt:Q},!a3.test(X.requestSecret))throw new A("invalid-state","invalid minted Claustrum enrollment secret");await b0(this.#Z.statePath,X,this.#z)}if(!X.requestId)try{let Q=j8("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:X.proposedName,requestSecretHash:Q});X={...X,requestId:W.requestId,updatedAt:this.#Q()},await b0(this.#Z.statePath,X,this.#z)}catch(Q){let W=d3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===o2)return await $.assertOwned(),await l3(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#J(X,W.code)}let G=X.requestId;if(!G)return O0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return O0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#Q()};return await b0(this.#Z.statePath,H,this.#z),O0(H)}await z1(f0(this.#Z.tokenPath),this.#z),await z$(f0(this.#Z.tokenPath),this.#z),await this.#W(this.#Z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:X.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#Q()};return await b0(this.#Z.statePath,W,this.#z),O0(W)}catch(Q){let W=d3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code};return this.#J(X,W.code)}}finally{await $.release()}}}async function G$($,Z){await z1(f0($.statePath));let J=await M0({name:"ceremony",path:$.statePath,ttlMs:i2,renew:!0});if(!J)return"busy";try{if(await x0($.tokenPath)!==void 0)return"refused-approved";let z=await x0($.statePath);if(z===void 0)return"idle";let X=s3(z);if(X.proposedName!==Z)throw X$();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await l3($.statePath),"reset"}finally{await J.release()}}var o3="claustrum-tombstone:v1:";function X1($,Z){let J=!1;return(z)=>{if(J)return;if(!Z||Z.aborted)J=!0;$.warn("claustrum shutdown drain timed out",{pendingOperations:z})}}async function G1($,Z){if(!$.size)return;let J,z=!1,X=(async()=>{while(!z&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([X,new Promise((G)=>{J=setTimeout(()=>{z=!0,G()},2000)})]),z&&$.size)Z($.size)}finally{z=!0,clearTimeout(J)}}import{ClaustrumCredentialError as k8}from"@cortexkit/claustrum-client";function Q$($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class r3{options;#$=new Map;#Z=new Map;#X=new Set;#Q;#G;#W=!1;#z=!1;#J=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#G!==void 0,dropped:this.#J}}report($,Z){if(this.#W||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#J++;return}if(!Q$(Z)||"credentialId"in Z||"vouched"in Z)throw Error("invalid reading");let J=JSON.stringify(Z);if(Buffer.byteLength(J,"utf8")>15360)throw Error("oversized reading");let z=JSON.parse(J);if(!Q$(z)||"credentialId"in z||"vouched"in z||typeof z.observedAtMs!=="number"||!Number.isFinite(z.observedAtMs))throw Error("invalid reading");if(z.observedAtMs<=(this.#Z.get($)??-1/0)){this.#J++;return}if(this.#$.has($))this.#J++;if(this.#Z.set($,z.observedAtMs),this.#$.set($,z),!this.#Q&&!this.#G)this.#Q=this.options.setTimeout(()=>{this.#Q=void 0,this.#V()},1000),this.#Q.unref?.()}catch{this.#J++}}forget($){if(this.#$.delete($))this.#J++;this.#Z.delete($)}#V(){if(this.#G||!this.#$.size||this.#z)return this.#G;let $=Promise.resolve().then(async()=>{while(!this.#z&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[J,z]=Z;this.#$.delete(J);try{let X=await this.options.token();if(this.#z||!this.options.owns(J)){if(!this.#z)this.#J++;continue}await this.options.client.reportUsageScoped?.({credentialId:J,reading:z,enrollmentToken:X})}catch(X){if(!this.#z)this.#J++;this.#H(X)}}});return this.#G=$,$.finally(()=>{this.#G=void 0}),$}#H($){let Z="transport_error";try{if($ instanceof k8)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#X.has(Z))return;this.#X.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#W=!0,this.#Q)this.options.clearTimeout(this.#Q);return this.#Q=void 0,this.#V()}drop(){this.#z=!0,this.#J+=this.#$.size+(this.#G?1:0),this.#G=void 0,this.#$.clear(),this.#Z.clear()}}function Y$($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function b8($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var e3=H0("claustrum");function H$($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new A("invalid-token","Invalid Claustrum enrollment token");return $.token}var _0=E8("common-auth.claustrum.phases");function Z9($,Z,J,z=e3){let X=Y$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:b8(Z,J)}),X}var $9=300000,U$=60000;function t3(){return new A("invalid-material","Claustrum returned invalid credential material")}function f8($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw t3()}if(!J||typeof J!=="object")throw t3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(o3))throw t3();return Z}function x8($,Z){let J={kind:"not-mine"};if(!$.operations.includes("read"))return J;if(!$.categories.includes(Z.category))return J;if("classify"in Z){let z=y8($),X;switch(z.authMethod){case"apikey":X="api_key";break;case"chatgpt":case"antigravity":case"oauth":X="oauth";break;default:return{kind:"refused",code:"unknown-auth-method"}}let G={credentialId:$.id,credentialType:X,categories:$.categories,refreshAdapter:$.refreshAdapter,...z};if(G.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let Q=Z.classify(G);if(Q.kind==="not-mine")return J;if(Q.kind==="mine"&&typeof Q.member==="string")return{kind:"mine",type:X,member:Q.member};if(Q.kind==="refused"&&typeof Q.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(Q.code)&&!Q.code.includes(`
|
|
12
|
-
`)&&Z.refusalCodes.includes(Q.code))return{kind:"refused",code:Q.code}}catch{}return{kind:"refused",code:"unclassified"}}if($.credentialType!=="oauth"&&$.credentialType!=="api_key")return J;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?{kind:"mine",type:"oauth"}:J;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?{kind:"mine",type:"api_key"}:J;return J}function y8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function g8($){let{grants:Z,grantTuples:J}=$;if(Z===void 0||J===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(J.map(({selectorKind:z,selector:X,operation:G})=>Object.freeze({selectorKind:z,selector:X,operation:G})))})}class Q1{#$;#Z;#X;#Q;#G;#W;#z;#J=new WeakMap;#V=new WeakMap;#H=new Map;#Y=new WeakMap;#U;#F=new Map;#q;#B;#D=!1;#C=new t;#P;#O=!1;#K=-1/0;#M=2000;#_=!1;#j;#L=new Set;#A=new Set;#R;#E;#N;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>A0(Z);else throw new A("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#Q=$.family,this.#G=$.parseIdentity,this.#W=$.requireAssertion??!1,this.#X=$.now??Date.now,this.#z=$.logger??e3,this.#R=X1(this.#z),this.#q=$.setTimeoutImpl??setTimeout,this.#B=$.clearTimeoutImpl??clearTimeout,this.#U=new r3({client:this.#$,owns:(J)=>this.#F.has(J),token:async()=>H$(await this.#Z()),logger:this.#z,setTimeout:this.#q,clearTimeout:this.#B})}transportLost($){if(this.#_||this.#D)return;this.#D=!0,this.#C=$ instanceof W$?$:new t,this.#z.warn("serving kept vault receipt",{reason:"unreachable"}),this.#S()}reachable(){if(this.#_||!this.#D)return;if(this.#D=!1,this.#P)this.#B(this.#P);this.#P=void 0,this.#M=2000;for(let $ of this.#H.values())$.since=null;(this.#z.info??e3.info)("vault receipt serving resumed",{reason:"reachable"})}#S(){if(this.#_||!this.#D||this.#P||this.#O)return;this.#P=this.#q(()=>{this.#P=void 0,this.#k(!0)},this.#M),this.#P.unref?.()}#k($=!1){if(this.#_||!this.#D||this.#O)return;if(this.#X()-this.#K<1000){this.#S();return}this.#K=this.#X(),this.#O=!0,this.#f().catch(()=>{if($&&this.#D)this.#M=Math.min(this.#M*2,30000)}).finally(()=>{this.#O=!1,this.#S()})}#I($){if(this.#_)throw new A("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#I($),_0.hasSubscribers)_0.publish({logger:this.#z,phase:"token read begin"});let Z=this.#Z();this.#A.add(Z);let J;try{J=await Z}finally{if(this.#A.delete(Z),_0.hasSubscribers)_0.publish({logger:this.#z,phase:"token read end"})}return this.#I($),H$(J)}async#b($,Z){this.#I(Z);let J,z;try{let X=$();J=Z?await Promise.race([X,new Promise((G,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await X}catch(X){if(this.#I(Z),L0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof W$)throw X;if(L0(X)==="unreachable")throw new t;throw new A("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#I(Z),this.reachable(),J}async discover($){let Z=await this.#f($);return this.#j=Z.view,Z}async#f($){let Z,J;try{J=await this.#y($)}catch(Y){throw this.#H.clear(),this.#g(),Y}if(_0.hasSubscribers)_0.publish({logger:this.#z,phase:"list scoped begin"});try{Z=await this.#b(()=>this.#$.listScoped(J),$)}catch(Y){throw this.listFailed(Y),Y}finally{if(_0.hasSubscribers)_0.publish({logger:this.#z,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let Y of Z.rows){let q=x8(Y,this.#Q);if(q.kind==="not-mine"){G++;continue}if(q.kind==="refused"){X.push({...Y.id.trim()&&{credentialId:Y.id},code:q.code});continue}Q.push({row:Y,type:q.type,...q.member!==void 0&&{member:q.member}}),W.set(Y.id,(W.get(Y.id)??0)+1)}let H=[];for(let{row:Y,type:q,member:D}of Q){let B;if(!Y.id.trim())B="empty credential id";else if((W.get(Y.id)??0)>1)B="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())B="blank account identity";else if(!Y.state.trim())B="empty state";if(B){z.push({...Y.id.trim()&&{credentialId:Y.id},...D!==void 0&&{member:D},reason:B});continue}H.push(Object.freeze({credentialId:Y.id,credentialType:q,...D!==void 0&&{member:D},...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of z)this.#z.warn("skipped malformed vault record",Y);let U=g8(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),..."classify"in this.#Q&&{refused:Object.freeze(X),notMine:G},...U&&{grantReach:U}}}listFailed($){if(L0($)==="unreachable")this.transportLost($);else this.reachable(),this.#H.clear(),this.#g()}forget($){this.#H.delete($),this.#F.delete($),this.#U.forget($)}#g(){for(let $ of this.#F.keys())this.#U.forget($);this.#F.clear()}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#H){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}for(let[J,z]of this.#F){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.credentialType||X.accountIdentity!==z.accountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#H){if(!this.#x(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#x($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#X()>U$}async authorize($,Z,J="vault"){this.#I(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#H.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#y(Z)}catch(H){throw this.#H.clear(),this.#g(),H}if(this.#D&&Q)return this.#k(),this.#v(z,Q,W,J);try{let H=await this.#T({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#H.set(z,{attempt:H,routeId:J,since:null}),this.#F.set(z,{...$}),H}catch(H){if(this.#I(Z),L0(H)!=="unreachable")throw this.forget(z),H;return this.#v(z,Q,W,J,H)}}#v($,Z,J,z,X=this.#C){if(!Z||this.#H.get($)!==Z||!this.#x(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#X();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#J.set(G,J),this.#Y.set(G,z),G}async#T($,Z,J){if(!$.credentialId)throw new A("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#W&&G===void 0)throw new A("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#b(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:$9}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new A("identity-changed","Claustrum served credential identity changed");let W=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||W===null&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#X()<$9))throw new A("insufficient-validity","Claustrum served credential has insufficient validity");let H=f8(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#W&&(Q.credentialId===void 0||U===void 0))throw new A("identity-unasserted","Claustrum served credential did not assert its identity");let Y=U===void 0?this.#G?.(H):void 0,q=U??Y;if(G!==void 0&&q!==void 0&&q!==G)throw new A("identity-changed","Claustrum served credential identity changed");let D=q??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...D!==void 0&&{accountIdentity:D},accountIdentitySource:U!==void 0?"asserted":Y!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...U!==void 0&&{assertedAccountIdentity:U},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#J.set(L,Z),L}async reportFailure($,Z,J){if(Z!==401)return;this.#I();let z=this.#J.get($);if(!z)throw new A("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Y.get($);if(X!==void 0){this.forget($.credentialId),this.#z.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#H.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#V.get($);if(Q)return Q;let W=this.#b(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#V.set($,W);try{await W,this.#z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#V.delete($),H}}watchRoster($){this.#I();let Z=new l1({client:this.#$,enrollmentToken:()=>this.#y(),view:$.view??(()=>this.#j),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#z,now:this.#X,setTimeoutImpl:this.#q,clearTimeoutImpl:this.#B});return this.#L.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#L.delete(Z),Z.stop()}}}reportUsage($){if(this.#_)return;try{this.#U.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#U.state()}close(){if(this.#_)return;if(this.#_=!0,this.#P)this.#B(this.#P);this.#P=void 0;for(let Z of this.#L)Z.stop();this.#L.clear(),this.#H.clear();let $=this.#U.close();if($)this.#A.add($),$.then(()=>this.#A.delete($));else this.#$.close();this.#N=G1(this.#A,(Z)=>(this.#E??this.#R)(Z)).finally(()=>{if(this.#U.drop(),this.#F.clear(),$)this.#$.close()})}async dispose($=this.#R){this.#E=$,this.close(),await this.#N}}import{resolve as Q3}from"node:path";var J9=30000,z9={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var y0="all",v8=Object.freeze(["primary"]);function K$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function H1($,Z){return JSON.stringify([$,Z])}function I0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function s($){return typeof $==="number"&&Number.isFinite($)}function q$($){return typeof $==="string"&&$.length>0}function n($,Z,J){return $[Z]===void 0||J($[Z])}function h8($){return s($)&&$>0}function X9($){return typeof $==="string"}function m8($){if(!I0($)||!q$($.scope)||!q$($.label))return!1;switch($.kind){case"reading":return s($.checkedAt)&&s($.usedPercent)&&n($,"resetsAt",X9)&&n($,"windowMinutes",h8);case"retired":return s($.retiredAt);case"absent":return s($.checkedAt);default:return!1}}function w8($){if(!I0($)||!s($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&n($,"remainingPercent",s)&&n($,"usedPercent",s)&&n($,"resetsAt",X9)&&n($,"limit",s)&&n($,"used",s)&&n($,"remaining",s)&&n($,"unit",X9)}function F$($){return I0($)&&s($.value)&&Number.isInteger($.value)&&$.value>=0&&s($.checkedAt)}function G9($){return I0($)&&Object.values($).every(F$)}function u8($){return typeof $==="boolean"}function Y1($){return I0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&n($,"balance",s)&&n($,"overageLimitReached",u8)&&s($.checkedAt)}function B$($){if(!I0($))return;let Z=Object.entries($).filter(([,J])=>F$(J));return Z.length===0?void 0:Object.fromEntries(Z)}function g0($){if(W1($))return $;if(!I0($))return;let{counters:Z,credits:J,...z}=$;if(!W1(z))return;let X=B$(Z),G=Y1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function W1($){if(!I0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!m8(J))return!1;let z=H1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return n($,"budget",w8)&&n($,"counters",G9)&&n($,"credits",Y1)}class Z3 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function z3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J3($){return typeof $==="number"&&Number.isFinite($)}function V$($){return $===void 0||typeof $==="string"&&$!==""}function j$($){return typeof $==="string"&&$!==""}function R1($,Z){return $[Z]===void 0||J3($[Z])}function Q9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function c8($){return z3($)&&V$($.scope)&&j$($.label)&&J3($.usedPercent)&&Q9($,"resetsAt")&&($.windowMinutes===void 0||J3($.windowMinutes)&&$.windowMinutes>0)}function p8($){return z3($)&&V$($.scope)&&j$($.label)}function d8($){if(!z3($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&R1($,"remainingPercent")&&R1($,"usedPercent")&&Q9($,"resetsAt")&&R1($,"limit")&&R1($,"used")&&R1($,"remaining")&&Q9($,"unit")}function U1($){if(!z3($)||!J3($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let X of Z){if(!c8(X))return!1;let G=H1(X.scope??y0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(p8))return!1;return($.budget===void 0||d8($.budget))&&($.counters===void 0||G9($.counters))&&($.credits===void 0||Y1($.credits))}function l8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function a8($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function s8($,Z){let J=new Map(Object.entries($??{}));for(let[z,X]of Object.entries(Z??{})){let G=J.get(z);if(G===void 0||X.checkedAt>=G.checkedAt)J.set(z,X)}return J.size===0?void 0:Object.fromEntries(J)}function n8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function S1($,Z){let J=$===void 0?void 0:g0($);if($!==void 0&&J===void 0)throw new Z3("stored quota map is malformed");if(!U1(Z))throw new Z3("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let O of z.limits)G.set(H1(O.scope,O.label),O);let Q=(O)=>{let I=G.get(O);return I===void 0||X>=K$(I)},W=new Set;for(let O of Z.readings??[]){let I=O.scope??y0,T=H1(I,O.label);if(W.add(T),!Q(T))continue;G.set(T,{scope:I,label:O.label,kind:"reading",checkedAt:X,usedPercent:O.usedPercent,...O.resetsAt===void 0?{}:{resetsAt:O.resetsAt},...O.windowMinutes===void 0?{}:{windowMinutes:O.windowMinutes}})}for(let O of Z.coverage??[]){let I=O.scope??y0,T=H1(I,O.label);if(W.has(T)||!Q(T))continue;let m=G.get(T);G.set(T,m===void 0||m.kind==="absent"?{scope:I,label:O.label,kind:"absent",checkedAt:X}:{scope:I,label:O.label,kind:"retired",retiredAt:X})}let{limits:H,budget:U,counters:Y,credits:q,...D}=z,B=a8(z.budget,Z.budget,X),L=s8(z.counters,Z.counters),C=n8(z.credits,Z.credits);return{...D,limits:[...G.values()].sort(l8),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var i8=Object.freeze({validate:W1,decode:g0,merge:S1});function M$($,Z=""){let J=new Map,{observation:z}=$,X=(W,H,U)=>J.set(`${Z}:${W}`,{at:H,order:0,publication:{...$,observation:U}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of z.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...W}]})}for(let W of z.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...W}]})}if(z.budget)X("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[W,H]of Object.entries(z.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[W]:{...H}}});if(z.credits)X("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!J.size)X("empty",z.checkedAt,{checkedAt:z.checkedAt});return J}import{createHash as e8}from"node:crypto";import{stat as $6}from"node:fs/promises";import{resolve as T1}from"node:path";function D$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function W9($,Z,J){return $.some((z)=>D$(z,Z,J))}function H9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function Y9($,Z,J){return $.filter((z)=>!Z.some((X)=>D$(z,X,J)))}function q9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>Y0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function Z6($,Z){let J=Y0(Z),z=Z.accountIdentity===void 0?-1:$.order.findIndex((G)=>G.accountIdentity===Z.accountIdentity),X=z>=0?z:$.order.findIndex((G)=>J.includes(G.credentialId));return X>=0?X:1/0}var G3="vault:";function J6($){return e8("sha256").update($).digest("hex")}function z6($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function X6($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function Y0($){return[$.credentialId,...$.aliases??[]]}function P$($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??G3,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,H=[...$?.declined??W?.declined??[]],U=Z.skipped.length===0,Y=new Set(Z.credentials.map((F)=>F.credentialId)),q=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),D=Z.skipped.some((F)=>F.credentialId===void 0),B=(F)=>!Y.has(F)&&(q.has(F)||D),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let K of Y0(F))if(!L.has(K))L.set(K,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let K=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},j=X6(K),P=C.get(j)??[];P.push(K),C.set(j,P)}let O=new Set,I=new Set(G),T=[],m=(F,K)=>F.credential.credentialId.localeCompare(K.credential.credentialId),u=[...C.values()].map((F)=>F.toSorted(m)).sort((F,K)=>F[0]&&K[0]?m(F[0],K[0]):0);for(let F of u){let K=F[0]?.identity,j=F.filter((b)=>b.credential.state==="active"),P=j.length?j:F,g=P.filter((b)=>b.claimed),E=g.length?g:P,v=new Set(F.map((b)=>b.credential.credentialId)),Z0=Q.find((b)=>!O.has(b)&&Y0(b).some((F0)=>v.has(F0))&&(b.accountIdentity===void 0||b.accountIdentity===K)),p=E.find((b)=>b.credential.credentialId===Z0?.credentialId)??E[0];if(!p)continue;let d=p.credential,l=Z0??(K===void 0?void 0:Q.find((b)=>!O.has(b)&&b.accountIdentity===K));if(l)O.add(l);let J0=l?.routeId;if(!J0||G.has(J0)){let b=`${X}${d.credentialId}${K===void 0?"":`~${J6(K).slice(0,10)}`}`;J0=b;for(let F0=2;I.has(J0);F0++)J0=`${b}~${F0}`}I.add(J0);let P1=l?Y0(l).filter(B):[],C1=[...new Set([...F.map((b)=>b.credential.credentialId),...P1])].filter((b)=>b!==d.credentialId).sort((b,F0)=>b.localeCompare(F0)),c1=J.mapAccount?.(d)??{};T.push({previousIndex:l?Q.indexOf(l):1/0,row:{routeId:J0,credentialId:d.credentialId,credentialType:d.credentialType,...K!==void 0&&{accountIdentity:K},...C1.length&&{aliases:C1},state:d.state,label:c1.label?.trim()||z6(d),...d.email!==void 0&&{email:d.email},...d.orgName!==void 0&&{orgName:d.orgName},enabled:![d.credentialId,...C1].some((b)=>W9(H,b,K)),addedAt:l?.addedAt??z,...l?.quota!==void 0&&{quota:l.quota},...!p.claimed&&K!==void 0&&{unclaimed:!0}}});let a0=T.at(-1);if(W&&a0)a0.previousIndex=Z6(W,a0.row)}return Q.forEach((F,K)=>{if(O.has(F)||!Y0(F).some(B))return;if(I.has(F.routeId))return;let[j,...P]=Y0(F).filter((v)=>!Y.has(v));if(j===void 0)return;I.add(F.routeId);let{aliases:g,...E}=F;T.push({previousIndex:K,row:{...E,credentialId:j,...P.length&&{aliases:P},stale:!0}})}),T.sort((F,K)=>F.previousIndex===K.previousIndex?F.row.credentialId.localeCompare(K.row.credentialId):F.previousIndex-K.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:U,...!U&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:T.map((F)=>F.row),declined:H}}function K9($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function k1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function q1($){return $===void 0||typeof $==="string"}function G6($){let Z=k1($)?g0($.quota):void 0;if(!k1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!q1($.accountIdentity)||!q1($.email)||!q1($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((J)=>typeof J==="string"))||$.quota!==void 0&&Z===void 0||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return{...$,...Z===void 0?{}:{quota:Z}}}var Q6=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function N$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!k1(J)||!q1(J.credentialId)||typeof J.reason!=="string"||!Q6.has(J.reason))return;Z.push(J)}return Z}function C$($){if(!k1($)||$.version!==1||!q1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!N$($.rejected))throw new A("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=G6(X);if(!G)throw new A("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!k1(X)||typeof X.credentialId!=="string"||!q1(X.accountIdentity))throw new A("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=N$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},...$.limits!==void 0&&{limits:$.limits},rows:Z,declined:J}}function F9($){return C$(JSON.parse(JSON.stringify($)))}var W6=new E0({followSymlinks:!0});async function c($){if(_)return U9($);let Z=await W6.read([$],([J=$])=>U9(J));return structuredClone(Z)}async function U9($){let Z;try{Z=await z0($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new A("invalid-state","Claustrum roster file is not valid")}return C$(J)}var O$={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},A$={name:"claustrum-roster",ttlMs:30000};async function v0($,Z,J={}){return w3($,{...O$,signal:J.signal},async(z)=>{let X=await U9($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await $1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function B9($,Z){return v0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");let X=H9(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:X,rows:J.rows.map((G)=>G===z?{...G,enabled:!1}:G)},result:void 0}})}function V9($,Z){return v0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:Y9(J.declined,Y0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function H6($){return new A("invalid-order",$)}function Y6($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let J=new Set($.map((G)=>G.routeId)),z=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(z.has(G))return`route id ${G} appears more than once`;if(!J.has(G))return`route id ${G} is not in the roster`;z.add(G)}let X=[...J].filter((G)=>!z.has(G)).length;if(X>0)return`the order leaves out ${X} roster route id${X===1?"":"s"}`;return}function j9($,Z,J={}){return v0($,(z)=>{let X=z?.rows??[],G=Y6(X,Z);if(G)throw H6(G);let Q=new Map;for(let U of X){let Y=Q.get(U.routeId);if(Y)Y.push(U);else Q.set(U.routeId,[U])}let W=[...Z],H=W.flatMap((U)=>Q.get(U)??[]);if(!z||H.every((U,Y)=>U===X[Y]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function U6($,Z){if(!Y0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&Y0($).length===1)return"bind";return"refuse"}async function M9($,Z){let{routeId:J,observation:z,...X}=Z;return _$($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function _$($,Z){if(!U1(Z.observation))return!1;let J=r($,await c($));if(!R0(J,Z).kept)return!1;return R$($,Z)}function D9($,Z){return _$($,Z)}function R0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?U6(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=S1(J.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((Q)=>Q===J?{...Q,...G,quota:X}:Q)},kept:!0}}var X3=new Map;function E1($){X3.delete(T1($))}function I$($,Z){let J=T1($);if(Z instanceof A)return Z.kind==="roster-busy";if(Z instanceof C0||Z instanceof j0)return T1(Z.details.target)===J;if(Z instanceof w){let z=T1(Z.path);return[O$.name,A$.name].some((X)=>{let G=Z1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var q6=4;async function L$($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await $6($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function K6($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function F6($,Z,J){for(let z=0;z<q6;z++){let X=await L$($),G=await c($),Q,W,H;try{({target:Q,local:W}=Z(G));let U=JSON.stringify(J(Q));H=JSON.stringify(Q)!==U||W!==void 0&&JSON.stringify(W)!==U}catch{return"commit"}if(!K6(X,await L$($)))continue;if(H)return"commit";return S$($)?"commit":"unchanged"}return"commit"}async function b1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){E1($.path);return}let J=await M0({...A$,path:$.path,renew:!0});if(!J){let Q=await c($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new A("roster-busy","Claustrum account discovery is already in progress");return Q}let z=T1($.path),X=$.listedOver,G;try{let Q=await c($.path),W=X?void 0:X3.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},X3.delete(z);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let U=typeof $.projection==="function"?$.projection():$.projection,Y=(B)=>P$(B,H,U),q=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await F6($.path,(B)=>{if(X)return{target:B};let L=r($.path,B);return{target:B,...L!==B&&{local:L}}},Y)==="unchanged"){if(!await q())return;return await c($.path)}return await v0($.path,async(B)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&B?.view!==X.view&&B?.view!==H.view)return{result:B};let L=Y(B);return{...JSON.stringify(B)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof C0&&G&&!X&&!$.signal?.aborted&&await Z())X3.set(z,G);throw Q}finally{await J.release($.signal)}}var h0=new Map,B6=H0("claustrum"),k$=100;function E$($,Z=z9){let J=Q3($),z=h0.get(J);if(!z)z={path:J,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},h0.set(J,z);return z}function b$($,Z,J){let z=E$($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():N9($)})()}function V6($){return M$($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function R$($,Z){if(!U1(Z.observation))return Promise.resolve(!1);let J=E$($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),X=J.pending.get(z)??new Map;for(let[G,Q]of V6(Z)){let W=X.get(G);if(!W||Q.at>=W.at){if(Q.order=++J.order,Q.publication.observation.coverage)Q.priorReading=W?.publication.observation.readings?W.publication:W?.priorReading;X.set(G,Q)}}if(X.size)J.pending.set(z,X);for(let G of J.listeners)G(Z);return x$(J,k$),Promise.resolve(!0)}function f$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function r($,Z){let J=h0.get(Q3($));if(J)for(let z of f$(J.pending)){if(z.priorReading)Z=R0(Z,z.priorReading).roster;Z=R0(Z,z.publication).roster}return Z}function S$($){return!!h0.get(Q3($))?.pending.size}function x$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+J9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,y$($)}),!$.draining)$.timer.unref?.()}function T$($){$.timer?.cancel(),$.timer=void 0}function y$($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([J,z])=>[J,new Map(z)]));return $.running=(async()=>{try{if(await v0($.path,(z)=>{let X=z;for(let Q of f$(Z)){if(Q.priorReading)X=R0(X,Q.priorReading).roster;X=R0(X,Q.publication).roster}let G=JSON.stringify(X)!==JSON.stringify(z);return{...G&&{next:X},result:G}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[z,X]of Z){let G=$.pending.get(z);for(let[Q,W]of X)if(G?.get(Q)===W)G.delete(Q);if(!G?.size)$.pending.delete(z)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)B6.warn("vault quota publication delayed; retrying",{error:J instanceof Error?J.message:String(J)})}finally{$.running=void 0;for(let z of $.wake)z();let J=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):k$;x$($,J)}})(),$.running}async function N9($,Z=1000){let J=Q3($),z=h0.get(J);if(!z)return;z.draining=!0,T$(z);let X,G,Q=new Promise((W)=>{G=()=>{if(!z.pending.size||z.abort.signal.aborted)W()},z.wake.add(G),G()});try{if(z.pending.size)y$(z);await Promise.race([Q,new Promise((W)=>{X=setTimeout(W,Math.max(0,Z))})])}finally{if(clearTimeout(X),G)z.wake.delete(G);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),T$(z),z.pending.clear(),h0.get(J)===z)h0.delete(J)}}}var W3=1e4;function g$(){return new t}var L9;function h$($,Z){if(!L9)throw Error("ClaustrumConsumer is not initialized");return L9($,Z)}function v$(){return new A("not-active","Claustrum scoped custody is not active")}class P9{#$;#Z=new AbortController;#X;#Q;#G;#W;#z;#J;#V;#H;#Y=!1;#U=new Set;#F;#q;#B;#D;#C=new Map;#P;#O;#K;#M;#_=new WeakMap;static{L9=($,Z)=>{let J=new P9(Z);return J.#K=$,{consumer:J,hooks:J.#g()}}}constructor($){this.#$=$,this.#X=$.logger??H0("claustrum"),this.#Q=X1(this.#X,this.#Z.signal),this.#O=b$($.rosterPath,(Z)=>{this.#J=R0(this.#J,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#L($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#A(){return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=k0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#E(){if(this.#j(),this.#G)return this.#G;if(!this.#W){let $={timedOut:!1};this.#W=this.#N($),this.#L(this.#W)}return this.#R(this.#W)}#N($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=this.#$.connect().then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#j();throw g$()}if(this.#G=new Q1({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#X,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#q=x3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#X.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#S()}),W(g$())},this.#S()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#W=void 0})}#S(){return this.#$.connectTimeoutMs??W3}snapshot(){return this.#J}grantReach(){if(this.#K)return this.#K.grantReach(this.#J?.view);let $=this.#V;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){if(this.#K)return Object.freeze({vault:this.#K.watchMode()});return Object.freeze({vault:this.#B?.mode??"polling",...this.#$.insula&&{insula:this.#q?.source.watchMode()??"polling"}})}#k(){this.#B?.close(),this.#B=void 0,this.#D?.(),this.#D=void 0}keptReceiptState(){if(this.#K){let $=this.#M;return $&&this.#K.leaseLive($)?$.custody.keptReceiptState():this.#K.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return K9(this.#J)}refresh(){if(this.#j(),this.#K)return this.#L(this.#x(this.#K));if(this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#A()){if(this.#J=void 0,this.#V=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#G=void 0,this.#q?.release(),this.#q=void 0;return}let $=await this.#E(),Z,J=await b1({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},isActive:()=>this.#A(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#j();let z=J?.view!==this.#J?.view;if(this.#J=r(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#V=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#P=(this.#$.now??Date.now)(),J})().finally(()=>{this.#z=void 0}),this.#L(this.#z),this.#I(this.#z),this.#z}#I($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#Y)return;if(this.#j(),this.#Y=!0,this.#K){this.#K.start();return}let $=async()=>{try{if(await this.#y())await this.refresh();await this.refreshInsulaQuota(),this.#b()}catch(J){if(!this.#Z.signal.aborted)this.#$.onError?.(J)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#H=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#H=void 0,this.#L($())},Z),this.#H.unref?.()};this.#L($())}async#y(){if(this.#B?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#P===void 0||$-this.#P>=n0)return!0;return!await this.#A()}#b(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#B??=$.watchRoster({view:()=>this.#J?.view,onView:()=>this.#L((async()=>{while(this.#z)await this.#z.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#q&&!this.#D)this.#D=this.#q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await A0(this.#$.tokenPath),await this.#E(),await this.#q?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{return await A0(this.#$.tokenPath),this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await A0(this.#$.tokenPath);let J=r(this.#$.rosterPath,await c(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#f(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#A())return{miss:"unreachable"};try{await A0(this.#$.tokenPath);let z=r(this.#$.rosterPath,await c(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#q)return{miss:"unreachable"};let X=this.#q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#C.get($)!==J.miss)this.#C.set($,J.miss),this.#X.warn("skipped insula provider poll",{reason:J.miss});return}return this.#C.delete($),J.miss?Z():J.reading}#f($){if(!this.#$.insula||!$)return;let Z=this.#q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#K)return this.#h(this.#K,$,Z);this.#j(Z);let J=this.#J??await this.#R(this.refresh(),Z);if(!J||!await this.#A())throw this.#G?.close(),this.#G=void 0,this.#k(),this.#q?.release(),this.#q=void 0,new A("not-active","Claustrum scoped custody is not active");let z=r(this.#$.rosterPath,await c(this.#$.rosterPath));this.#j(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#G?.forget(X.credentialId);throw new A("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#G?.forget(X.credentialId);throw new A("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#R(this.#E(),Z),W=k0([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}#g(){return{discovery:($)=>{let Z=this.#K;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#L($.then((z)=>this.#v(Z,z)));this.#I(J)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#J?.view;if(this.#J=r(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(J){this.#$.onError?.(J)}},reset:()=>{this.#J=void 0},roster:()=>this.#J,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#x($){let Z=await $.refresh();return this.#v($,Z)}#v($,Z){if(this.#j(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#J}#T($){if($&&this.#M!==$)return;this.#M?.release(),this.#M=void 0}async#u($,Z){let J=this.#M;if(J&&$.leaseLive(J))return J;this.#T();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#j();let X=this.#M;if(X&&$.leaseLive(X))return z.release(),X;return this.#M=z,z}async#h($,Z,J){if(this.#j(J),!this.#J)await this.#R($.refresh(),J);let z=this.#J;if(!await $.readAuthority())throw this.#T(),v$();if(this.#j(J),!z)throw new A("route-unavailable","Claustrum has no roster for this provider yet");let X=r(this.#$.rosterPath,await c(this.#$.rosterPath));this.#j(J);let G=z.rows.find((U)=>U.routeId===Z),Q=X?.rows.find((U)=>U.routeId===Z);if(Q&&!Q.enabled){if(G)$.forget(G.credentialId);throw new A("route-declined","Claustrum route is disabled")}if(!G||!Q||Q.state!=="active"||Q.credentialId!==G.credentialId||Q.accountIdentity!==G.accountIdentity||Q.credentialType!==G.credentialType){if(G)$.forget(G.credentialId);throw new A("route-unavailable","Claustrum route is disabled, removed or changed")}let W={credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},H=k0([this.#Z.signal,...J?[J]:[]]);try{for(let U=0;;U++){let Y=await this.#u($,H.signal);try{let q=await Y.custody.authorize(W,H.signal,Z);return this.#_.set(q,Y),q}catch(q){if(U>0||H.signal.aborted||$.leaseLive(Y)||!(q instanceof A)||q.kind!=="closed")throw q;if(this.#T(Y),!await $.readAuthority())throw v$()}}}finally{H.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#J?.rows.find((J)=>J.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#K){if(this.#M&&this.#K.leaseLive(this.#M))this.#M.custody.reportUsage($)}else this.#G?.reportUsage($)}catch{}}usageReportState(){try{return(this.#K?this.#M?.custody:this.#G)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,J){if(this.#j(),this.#K){let z=this.#_.get($);if(!z)throw new A("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new A("no-receipt","Claustrum dispatch receipt has no active owner");await this.#G.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z),z?.throwIfAborted()}catch(W){if(z?.aborted)throw W}if(Z9(J.site,X,Q,this.#X))await G.body?.cancel().catch(()=>{}),X=Q,G=await Z(Q,z)}if(G.status===401)await this.reportFailure(X,401,J.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){if(this.#j(),await B9(this.#$.rosterPath,$),this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J);if(this.#K)this.#K.retainUnion();else this.#G?.retain(this.#J?.rows??[])}async accept($){if(this.#j(),await V9(this.#$.rosterPath,$),this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J)}async reorder($){this.#j();let Z=await j9(this.#$.rosterPath,$);if(this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J);return Z}async recordQuota($,Z,J){return this.#j(),M9(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:J.credentialId,accountIdentitySource:J.accountIdentitySource,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity},...J.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:J.expectedAccountIdentity}})}async recordAccountQuota($,Z,J){return this.#j(),D9(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new A("closed","Claustrum consumer is closed")),this.#H)(this.#$.clearTimeoutImpl??clearTimeout)(this.#H);if(this.#H=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#M?.release(),this.#M=void 0,this.#K?.detach(),this.#q?.release(),this.#q=void 0,this.#J=void 0,this.#V=void 0,this.#O(),E1(this.#$.rosterPath)}async dispose(){this.close(),this.#F??=Promise.all([G1(this.#U,this.#Q),this.#O()]).then(()=>{}),await this.#F}}import{createHash as j6}from"node:crypto";import{channel as M6}from"node:diagnostics_channel";import{readdir as D6,stat as N6}from"node:fs/promises";import{dirname as L6,join as K1,resolve as m$}from"node:path";var H3=new Map,P6=/^[a-z0-9][a-z0-9._-]{0,63}$/,C6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,O6=/^[0-9a-f]{16}$/,w$=3;function O9($,Z=new Set){if($===null)return"null";if(typeof $==="string"||typeof $==="boolean")return JSON.stringify($);if(typeof $==="number")return Number.isFinite($)?JSON.stringify($):void 0;if(typeof $!=="object"||Z.has($))return;let J=new Set(Z).add($),z=[];if(Array.isArray($)){for(let G=0;G<$.length;G++){let Q=O9($[G],J);if(Q===void 0)return;z.push(Q)}return`[${z.join(",")}]`}let X=Object.getPrototypeOf($);if(X!==Object.prototype&&X!==null)return;for(let G of Object.keys($).sort()){let Q=O9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function A6($,Z){let J=O9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??G3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new A("invalid-state","Claustrum hub classifierInput must be plain JSON");return j6("sha256").update(J).digest("hex").slice(0,16)}function u$($,Z){if(typeof $!=="string"||!P6.test($)||C6.test($))throw new A("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function S0($="Claustrum custody lease is closed"){return new A("closed",$)}function C9(){return new A("not-active","Claustrum scoped custody is not active")}function c$(){return new t}function _6($,Z){return new Promise((J,z)=>{let X=()=>z(Z.reason);if(Z.addEventListener("abort",X,{once:!0}),$.then((G)=>{Z.removeEventListener("abort",X),J(G)},(G)=>{Z.removeEventListener("abort",X),z(G)}),Z.aborted)X()})}function p$($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class d${#$;#Z;#X;#Q=new AbortController;#G=new Map;#W=new WeakMap;#z=0;#J;#V;#H;#Y;#U;#F;#q=0;#B;#D;#C;#P=!1;#O=new Set;#K;#M;#_;constructor($){if(!$.family||!("classify"in $.family))throw new A("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=u$($.hostGeneration,"host generation"),J=$.members.map((X)=>u$(X,"member"));if(new Set(J).size!==J.length)throw new A("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??H0("claustrum"),this.#X=X1(this.#Z,this.#Q.signal),this.#M=K1($.stateDir,"rosters",Z),this.#_=A6($,J);let z=K1(this.#M,this.#_);for(let X of J)this.#G.set(X,{provider:X,path:K1(z,`${X}.json`),closed:!1})}#j($){return this.#O.add($),$.then(()=>this.#O.delete($),()=>this.#O.delete($)),$}#L(){if(this.#Q.signal.aborted)throw S0("Claustrum discovery hub is closed")}#A($){let Z=this.#G.get($);if(!Z)throw new A("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#A($).path}member($,Z){this.#L();let J=this.#A($);if(J.hooks)throw new A("wrong-consumer","Claustrum hub member was already built");for(let q of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(q in Z)throw new A("wrong-consumer",`Claustrum hub members cannot take ${q}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#h(),readAuthority:()=>this.#x(),acquire:(q)=>this.acquire(q),leaseLive:(q)=>this.#S(q),grantReach:(q)=>q!==void 0&&this.#B?.view===q?this.#B.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#w(),publishRoster:(q)=>this.#R(J,q),forget:(q)=>this.#J?.custody?.forget(q),detach:()=>{J.closed=!0,J.releaseRoster?.()}},X={rosterPath:J.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:G,hooks:Q}=h$(z,X);J.hooks=Q;let W=m$(J.path),H=H3.get(W)??new Set,U=(q)=>{if(J.closed||this.#F!==!0||!this.#J||!this.#N(this.#J)||!Q.roster()||this.#c(Q,q))return;if(J.seen=JSON.stringify(F9(q)),Q.install(q),q.view!==this.#B?.view)J.pending??={failures:0,wait:0};this.#w()};H.add(U),J.receiveRoster=U,H3.set(W,H);let Y=!0;return J.releaseRoster=()=>{if(!Y)return;if(Y=!1,H.delete(U),!H.size)H3.delete(W)},G}#R($,Z){let J=this.#J;if($.closed||!J||!this.#N(J))return;$.seen=JSON.stringify(F9(Z)),$.hooks?.install(Z);for(let z of H3.get(m$($.path))??[]){if(!this.#N(J))return;if(z!==$.receiveRoster)z(Z)}}#E(){let $={id:++this.#z,count:0,ended:!1,controller:new AbortController};return this.#J=$,$}#N($){return!$.ended&&this.#J===$&&!this.#Q.signal.aborted}#S($){let Z=this.#W.get($);return!!Z&&!Z.released&&!Z.generation.ended}#k($,Z=S0()){if($.ended)return;if($.ended=!0,$.count=0,this.#J===$)this.#J=void 0;if(this.#H&&this.#W.get(this.#H)?.generation===$)this.#H=void 0;if(this.#Y?.generation===$)this.#Y.watch.close(),this.#Y=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#j($.custody.dispose(this.#X))}#I($){if($.ended)return;if($.count--,$.count<=0)this.#k($)}#y($){let Z=this.#V;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??W3,X,G=this.#$.connect().then((H)=>{if(J.timedOut)throw H.close(),c$();if(!this.#N($)||$.count<=0)throw H.close(),S0("Claustrum connection is no longer wanted");return $.custody=new Q1({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),Q=new Promise((H,U)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#N($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),U(c$())},z),X.unref?.()});return J.promise=this.#j(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#V===J)this.#V=void 0}).catch(()=>{}),this.#V=J,J.promise}acquire($){try{if(this.#L(),$?.throwIfAborted(),this.#F===!1)throw C9()}catch(J){return Promise.reject(J)}let Z=this.#J??this.#E();return Z.count++,this.#b(Z,$,!0)}async#b($,Z,J){let z=$.custody;if(!z){let X=k0([$.controller.signal,...Z?[Z]:[]]);try{z=await _6(this.#y($),X.signal)}catch(G){if(!$.ended)throw this.#I($),G;return this.#f(Z,J)}finally{X.dispose()}}if($.ended)return this.#f(Z,J);if(Z?.aborted)throw this.#I($),Z.reason;return this.#g($,z)}#f($,Z){if($?.throwIfAborted(),this.#L(),this.#F===!1)throw C9();if(!Z)throw S0();let J=this.#J??this.#E();return J.count++,this.#b(J,$,!1)}#g($,Z){let J={generation:$,custody:Z,released:!1},z=()=>{if(J.released||$.ended)throw S0()},X=Object.freeze({authorize:async(Q,W,H)=>{z();let U=k0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,U.signal,H)}finally{U.dispose()}},reportFailure:async(Q,W,H)=>{return z(),Z.reportFailure(Q,W,H)},reportUsage:(Q)=>{if(!J.released&&!$.ended)Z.reportUsage(Q)},usageReportState:()=>{return z(),Z.usageReportState()},forget:(Q)=>{z(),Z.forget(Q)},keptReceiptState:()=>{return z(),Z.keptReceiptState()}}),G=Object.freeze({custody:X,generation:$.id,release:()=>{if(J.released)return;J.released=!0,this.#I($)}});return this.#W.set(G,J),G}leaseState(){let $=this.#J;return Object.freeze({generation:$?.id,count:$?.count??0})}async#x(){let $=await this.#$.isCustodyActive?.()??!0;if(this.#Q.signal.aborted)return!1;let Z=this.#F;if(this.#F=$,!$&&Z!==!1)this.#v();return $}#v(){this.#q++;let $=this.#J;if($)this.#k($,C9());this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0,this.#B=void 0,this.#D=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),E1(Z.path)}#T(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#H,Z=$&&this.#W.get($);if($&&Z&&this.#S($))return Z;this.#H=void 0;let J=await this.acquire(this.#Q.signal),z=this.#H&&this.#W.get(this.#H);if(this.#H&&z&&this.#S(this.#H))return J.release(),z;this.#H=J;let X=this.#W.get(J);if(!X)throw S0();return X}#h(){try{this.#L()}catch(z){return Promise.reject(z)}let $=this.#U;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#j(this.#n(Z).finally(()=>{if(this.#U===Z)this.#U=void 0}));Z.promise=J,this.#U=Z;for(let z of this.#T())z.hooks?.discovery(J);return J}async#n($){if(!await this.#x())return;let Z=await this.#u(),J=Z.generation;if($.generation=J,!this.#N(J))return;let z=await this.#o().then(()=>{return},(Y)=>Y instanceof Error?Y:Error(String(Y))),X=new Map(await Promise.all([...this.#G.values()].map(async(Y)=>[Y,await c(Y.path).then((q)=>q?{file:q}:{},(q)=>q instanceof Error?q:Error(String(q)))])));if(!this.#N(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(Y){if(!this.#N(J))return;for(let q of this.#G.values())if(q.pending)this.#m(q);throw Y}if(!this.#N(J))return;let Q=this.#T(),W=await Promise.all(Q.map((Y)=>Y.hooks&&!Y.closed?this.#i(Y,Y.hooks,G,z??X.get(Y),J):void 0));if(!this.#N(J))return;let H=new Map,U=!0;for(let[Y,q]of Q.entries()){let D=q.hooks,B=W[Y];if(!D||!B)continue;if("error"in B){let{error:C}=B;if(U=!1,this.#m(q),I$(q.path,C))this.#Z.debug("claustrum hub member commit refused",{member:q.provider});else H.set(q.provider,C);continue}let{roster:L}=B;if(!this.#N(J))return;if(L?.view!==G.view)U=!1,this.#m(q);else q.pending=void 0;if(!L)continue;if(this.#c(D,L)){U=!1,this.#m(q);continue}this.#R(q,L)}if(!this.#N(J))return;if(this.#w(),U)this.#B=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#D=(this.#$.now??Date.now)(),{errors:H}}async#i($,Z,J,z,X){let G={...J,credentials:J.credentials.filter((Q)=>Q.member===$.provider),skipped:J.skipped.filter((Q)=>Q.member===$.provider)};try{if(!z)throw S0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let H=M6("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{Q=await this.#r($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await b1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#N(X)&&this.#F===!0,signal:X.controller.signal,projection:()=>({...Z.projection(),...Q&&{seed:Q}}),listedOver:{view:z.file?.view}})}}catch(Q){return{error:Q}}}async#o(){for(let $ of[L6(this.#M),this.#M,K1(this.#M,this.#_)])await z1($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[K1(this.#M,Z)];try{for(let X of await D6(this.#M))if(X!==this.#_&&O6.test(X))J.push(K1(this.#M,X,Z))}catch{}let z;for(let X of J)try{let G=(await N6(X)).mtimeMs,Q=await c(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&q9(z.roster)}#c($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#m($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(n0/J)),X=Z<=w$?1:Math.min(2**(Z-w$),z);$.pending={failures:Z,wait:X-1}}#w(){let $=this.#J?.custody;if(!$)return;$.retain(this.#T().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#q;for(let Z of this.#T()){let J;try{J=await c(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#q||this.#F!==!0)return;let z=Z.hooks;if(!J||!z||Z.closed)continue;let X=JSON.stringify(J);if(X===Z.seen)continue;let G=z.roster();if(!G||G.view!==J.view||this.#c(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=p$(G);if(Z.seen=X,this.#R(Z,J),p$(z.roster())!==Q)this.#w()}}#e(){let $=!1;for(let J of this.#G.values()){if(!J.pending)continue;if(J.pending.wait<=0)$=!0;else J.pending.wait--}if(this.#Y?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#D===void 0||Z-this.#D>=n0}#$0(){let $=this.#H,Z=$&&this.#W.get($);if(!$||!Z||!this.#S($)||this.#F!==!0)return;let J=Z.generation;if(!this.#N(J)||this.#Y?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#B?.view,onView:()=>this.#j((async()=>{while(this.#U)await this.#U.promise.catch(()=>{});if(!this.#N(J))return;await this.#a()})()),onRefused:(X)=>this.#d(X),onError:(X)=>this.#p(X)});this.#Y={generation:J,watch:z}}#p($){if(!this.#Q.signal.aborted)this.#$.onError?.($)}#d($){if(this.#Q.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#T())Z.hooks?.onError($)}#l($){for(let[Z,J]of $?.errors??[])this.#G.get(Z)?.hooks?.onError(J)}async#a(){let $;try{$=await this.#h()}catch(Z){this.#d(Z);return}this.#l($)}async#s(){try{if(await this.#x()){if(await this.#t(),this.#e())await this.#a();this.#$0()}}catch(Z){this.#p(Z)}if(this.#Q.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#C=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#C=void 0,this.#j(this.#s())},$),this.#C.unref?.()}start(){if(this.#P)return;this.#L(),this.#P=!0,this.#j(this.#s())}async refresh(){this.#l(await this.#h())}refusals(){let $=this.#B;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#B?.reach}watchState(){let $=this.#Y;return $&&this.#N($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#J?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#Q.signal.aborted)return;this.#Q.abort(S0("Claustrum discovery hub is closed"));for(let Z of this.#G.values())Z.releaseRoster?.();if(this.#C)(this.#$.clearTimeoutImpl??clearTimeout)(this.#C);this.#C=void 0;let $=this.#J;if($)this.#k($);this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0}async dispose(){this.close(),this.#K??=G1(this.#O,this.#X),await this.#K}}var w0={opencode:S6,pi:T6};function A9($,Z){let{tokenPath:J}=l$($,Z);return{stateDir:R6(J),host:$,override:J}}function _9($,Z){return k6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class m0 extends Error{code;constructor($){super($==="permission-refused"?"Native vault setup: permission-refused. Could not grant this host read access to native Claude accounts. An older ck may refuse a grant that already exists. Update CortexKit tools and run setup again.":`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}function I9($,Z){let J=Z??w0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new m0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function a$($,Z){try{await Z.processFence();let J=await $3(Z.paths??l$($,Z.env),w0[$]);if(J.state==="blocked")throw new m0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=I9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new m0("permission-refused");return z}catch{throw new m0("permission-refused")}}import{createHash as v6}from"node:crypto";import{lstat as h6,mkdir as m6,readFile as z4}from"node:fs/promises";import{dirname as w6}from"node:path";import{assertHostsStopped as u6,canonicalPath as S9,createNativeAccountRuntime as c6,custodyTombstoneOAuth as p6,inspectNativeHostAuthEntry as X4,NativeMigrationError as u0,nativeJournalMayAdoptLaterHostLogin as d6,nativePoolHoldsAccountData as l6,prepareNativeMigration as a6,readNativeEnrollmentMode as G4,readNativeMigrationJournal as s6,releaseNativeMigrationPreflight as n6,requireNoSupervisedAuthContentSnapshot as i6,runNativeMigration as o6,writeNativeHostAuth as r6}from"@cortexkit/anthropic-auth-core";import{dirname as E6,join as s$,resolve as R9}from"node:path";import{ACCOUNT_FILE_NAME as n$,ACCOUNT_STATE_FILE_NAME as b6,canonicalPath as i$,getStickyRoutingStatePath as f6,resolveLocalRoutingDestination as x6,resolveNativePoolPaths as y6}from"@cortexkit/anthropic-auth-core";async function D0($,Z){let J=$==="pi"?t$(Z):o$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=R9(z||s$(J,n$)),G=R9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(n$)?s$(E6(X),b6):`${X}.state.json`)),Q=await y6(X,G),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:Q,legacyConfigPath:X,legacyStatePath:G,hostAuthPath:$==="pi"?e$(Z):r$(Z),routingSourcePath:R9(W||f6(X)),routingDestinationPath:x6($,Q,Z)}}async function $4($){let Z=new Map;for(let J of $){let z=new Set;for(let[X,G]of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath].entries()){let Q=await i$(G);if(z.has(Q)&&!(X===9&&Q===await i$(J.routingSourcePath)))throw Error("Native setup storage paths overlap");let W=Z.get(Q);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(Q,J.host),z.add(Q)}}}import{types as g6}from"node:util";var Z4=new WeakMap;function J4($){return typeof $==="object"&&$!==null?Z4.get($):void 0}function F1($){if(!$||typeof $!=="object"||g6.isProxy($))return;if(Object.getOwnPropertyDescriptor($,"name")?.value==="ProcessInspectionError"&&Object.getOwnPropertyDescriptor($,"code")?.value==="process-inspection-failed")return"Process inspection failed; setup cannot prove hosts are stopped.";return}class i extends Error{constructor($){super($);this.name="SetupRefusal",Z4.set(this,$)}}var T9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function Q4($){let Z=$==="opencode"?"OpenCode":"Pi";return`${Z} is still connected to the vault. Old local settings do not disconnect it. In ${Z}, run /claude → Accounts → Disconnect from the vault. Then run local setup again.`}async function k9($,Z){let J=[];for(let z of $)if(await G4(z,Z)!=="local")J.push(Q4(z));if(J.length)throw new i(J.join(`
|
|
12
|
+
`)&&Z.refusalCodes.includes(Q.code))return{kind:"refused",code:Q.code}}catch{}return{kind:"refused",code:"unclassified"}}if($.credentialType!=="oauth"&&$.credentialType!=="api_key")return J;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?{kind:"mine",type:"oauth"}:J;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?{kind:"mine",type:"api_key"}:J;return J}function y8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function g8($){let{grants:Z,grantTuples:J}=$;if(Z===void 0||J===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(J.map(({selectorKind:z,selector:X,operation:G})=>Object.freeze({selectorKind:z,selector:X,operation:G})))})}class Q1{#$;#Z;#X;#Q;#G;#W;#z;#J=new WeakMap;#V=new WeakMap;#H=new Map;#Y=new WeakMap;#U;#F=new Map;#q;#B;#D=!1;#C=new t;#P;#O=!1;#K=-1/0;#M=2000;#_=!1;#j;#L=new Set;#A=new Set;#R;#E;#N;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>A0(Z);else throw new A("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#Q=$.family,this.#G=$.parseIdentity,this.#W=$.requireAssertion??!1,this.#X=$.now??Date.now,this.#z=$.logger??e3,this.#R=X1(this.#z),this.#q=$.setTimeoutImpl??setTimeout,this.#B=$.clearTimeoutImpl??clearTimeout,this.#U=new r3({client:this.#$,owns:(J)=>this.#F.has(J),token:async()=>H$(await this.#Z()),logger:this.#z,setTimeout:this.#q,clearTimeout:this.#B})}transportLost($){if(this.#_||this.#D)return;this.#D=!0,this.#C=$ instanceof W$?$:new t,this.#z.warn("serving kept vault receipt",{reason:"unreachable"}),this.#S()}reachable(){if(this.#_||!this.#D)return;if(this.#D=!1,this.#P)this.#B(this.#P);this.#P=void 0,this.#M=2000;for(let $ of this.#H.values())$.since=null;(this.#z.info??e3.info)("vault receipt serving resumed",{reason:"reachable"})}#S(){if(this.#_||!this.#D||this.#P||this.#O)return;this.#P=this.#q(()=>{this.#P=void 0,this.#k(!0)},this.#M),this.#P.unref?.()}#k($=!1){if(this.#_||!this.#D||this.#O)return;if(this.#X()-this.#K<1000){this.#S();return}this.#K=this.#X(),this.#O=!0,this.#f().catch(()=>{if($&&this.#D)this.#M=Math.min(this.#M*2,30000)}).finally(()=>{this.#O=!1,this.#S()})}#I($){if(this.#_)throw new A("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#I($),_0.hasSubscribers)_0.publish({logger:this.#z,phase:"token read begin"});let Z=this.#Z();this.#A.add(Z);let J;try{J=await Z}finally{if(this.#A.delete(Z),_0.hasSubscribers)_0.publish({logger:this.#z,phase:"token read end"})}return this.#I($),H$(J)}async#b($,Z){this.#I(Z);let J,z;try{let X=$();J=Z?await Promise.race([X,new Promise((G,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await X}catch(X){if(this.#I(Z),L0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof W$)throw X;if(L0(X)==="unreachable")throw new t;throw new A("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#I(Z),this.reachable(),J}async discover($){let Z=await this.#f($);return this.#j=Z.view,Z}async#f($){let Z,J;try{J=await this.#y($)}catch(Y){throw this.#H.clear(),this.#g(),Y}if(_0.hasSubscribers)_0.publish({logger:this.#z,phase:"list scoped begin"});try{Z=await this.#b(()=>this.#$.listScoped(J),$)}catch(Y){throw this.listFailed(Y),Y}finally{if(_0.hasSubscribers)_0.publish({logger:this.#z,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let Y of Z.rows){let q=x8(Y,this.#Q);if(q.kind==="not-mine"){G++;continue}if(q.kind==="refused"){X.push({...Y.id.trim()&&{credentialId:Y.id},code:q.code});continue}Q.push({row:Y,type:q.type,...q.member!==void 0&&{member:q.member}}),W.set(Y.id,(W.get(Y.id)??0)+1)}let H=[];for(let{row:Y,type:q,member:D}of Q){let B;if(!Y.id.trim())B="empty credential id";else if((W.get(Y.id)??0)>1)B="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())B="blank account identity";else if(!Y.state.trim())B="empty state";if(B){z.push({...Y.id.trim()&&{credentialId:Y.id},...D!==void 0&&{member:D},reason:B});continue}H.push(Object.freeze({credentialId:Y.id,credentialType:q,...D!==void 0&&{member:D},...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of z)this.#z.warn("skipped malformed vault record",Y);let U=g8(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),..."classify"in this.#Q&&{refused:Object.freeze(X),notMine:G},...U&&{grantReach:U}}}listFailed($){if(L0($)==="unreachable")this.transportLost($);else this.reachable(),this.#H.clear(),this.#g()}forget($){this.#H.delete($),this.#F.delete($),this.#U.forget($)}#g(){for(let $ of this.#F.keys())this.#U.forget($);this.#F.clear()}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#H){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}for(let[J,z]of this.#F){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.credentialType||X.accountIdentity!==z.accountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#H){if(!this.#x(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#x($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#X()>U$}async authorize($,Z,J="vault"){this.#I(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#H.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#y(Z)}catch(H){throw this.#H.clear(),this.#g(),H}if(this.#D&&Q)return this.#k(),this.#v(z,Q,W,J);try{let H=await this.#T({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#H.set(z,{attempt:H,routeId:J,since:null}),this.#F.set(z,{...$}),H}catch(H){if(this.#I(Z),L0(H)!=="unreachable")throw this.forget(z),H;return this.#v(z,Q,W,J,H)}}#v($,Z,J,z,X=this.#C){if(!Z||this.#H.get($)!==Z||!this.#x(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#X();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#J.set(G,J),this.#Y.set(G,z),G}async#T($,Z,J){if(!$.credentialId)throw new A("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#W&&G===void 0)throw new A("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#b(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:$9}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new A("identity-changed","Claustrum served credential identity changed");let W=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||W===null&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#X()<$9))throw new A("insufficient-validity","Claustrum served credential has insufficient validity");let H=f8(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#W&&(Q.credentialId===void 0||U===void 0))throw new A("identity-unasserted","Claustrum served credential did not assert its identity");let Y=U===void 0?this.#G?.(H):void 0,q=U??Y;if(G!==void 0&&q!==void 0&&q!==G)throw new A("identity-changed","Claustrum served credential identity changed");let D=q??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...D!==void 0&&{accountIdentity:D},accountIdentitySource:U!==void 0?"asserted":Y!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...U!==void 0&&{assertedAccountIdentity:U},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#J.set(L,Z),L}async reportFailure($,Z,J){if(Z!==401)return;this.#I();let z=this.#J.get($);if(!z)throw new A("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Y.get($);if(X!==void 0){this.forget($.credentialId),this.#z.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#H.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#V.get($);if(Q)return Q;let W=this.#b(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#V.set($,W);try{await W,this.#z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#V.delete($),H}}watchRoster($){this.#I();let Z=new l1({client:this.#$,enrollmentToken:()=>this.#y(),view:$.view??(()=>this.#j),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#z,now:this.#X,setTimeoutImpl:this.#q,clearTimeoutImpl:this.#B});return this.#L.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#L.delete(Z),Z.stop()}}}reportUsage($){if(this.#_)return;try{this.#U.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#U.state()}close(){if(this.#_)return;if(this.#_=!0,this.#P)this.#B(this.#P);this.#P=void 0;for(let Z of this.#L)Z.stop();this.#L.clear(),this.#H.clear();let $=this.#U.close();if($)this.#A.add($),$.then(()=>this.#A.delete($));else this.#$.close();this.#N=G1(this.#A,(Z)=>(this.#E??this.#R)(Z)).finally(()=>{if(this.#U.drop(),this.#F.clear(),$)this.#$.close()})}async dispose($=this.#R){this.#E=$,this.close(),await this.#N}}import{resolve as Q3}from"node:path";var J9=30000,z9={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var y0="all",v8=Object.freeze(["primary"]);function K$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function H1($,Z){return JSON.stringify([$,Z])}function I0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function s($){return typeof $==="number"&&Number.isFinite($)}function q$($){return typeof $==="string"&&$.length>0}function n($,Z,J){return $[Z]===void 0||J($[Z])}function h8($){return s($)&&$>0}function X9($){return typeof $==="string"}function m8($){if(!I0($)||!q$($.scope)||!q$($.label))return!1;switch($.kind){case"reading":return s($.checkedAt)&&s($.usedPercent)&&n($,"resetsAt",X9)&&n($,"windowMinutes",h8);case"retired":return s($.retiredAt);case"absent":return s($.checkedAt);default:return!1}}function w8($){if(!I0($)||!s($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&n($,"remainingPercent",s)&&n($,"usedPercent",s)&&n($,"resetsAt",X9)&&n($,"limit",s)&&n($,"used",s)&&n($,"remaining",s)&&n($,"unit",X9)}function F$($){return I0($)&&s($.value)&&Number.isInteger($.value)&&$.value>=0&&s($.checkedAt)}function G9($){return I0($)&&Object.values($).every(F$)}function u8($){return typeof $==="boolean"}function Y1($){return I0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&n($,"balance",s)&&n($,"overageLimitReached",u8)&&s($.checkedAt)}function B$($){if(!I0($))return;let Z=Object.entries($).filter(([,J])=>F$(J));return Z.length===0?void 0:Object.fromEntries(Z)}function g0($){if(W1($))return $;if(!I0($))return;let{counters:Z,credits:J,...z}=$;if(!W1(z))return;let X=B$(Z),G=Y1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function W1($){if(!I0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!m8(J))return!1;let z=H1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return n($,"budget",w8)&&n($,"counters",G9)&&n($,"credits",Y1)}class Z3 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function z3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J3($){return typeof $==="number"&&Number.isFinite($)}function V$($){return $===void 0||typeof $==="string"&&$!==""}function j$($){return typeof $==="string"&&$!==""}function R1($,Z){return $[Z]===void 0||J3($[Z])}function Q9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function c8($){return z3($)&&V$($.scope)&&j$($.label)&&J3($.usedPercent)&&Q9($,"resetsAt")&&($.windowMinutes===void 0||J3($.windowMinutes)&&$.windowMinutes>0)}function p8($){return z3($)&&V$($.scope)&&j$($.label)}function d8($){if(!z3($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&R1($,"remainingPercent")&&R1($,"usedPercent")&&Q9($,"resetsAt")&&R1($,"limit")&&R1($,"used")&&R1($,"remaining")&&Q9($,"unit")}function U1($){if(!z3($)||!J3($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let X of Z){if(!c8(X))return!1;let G=H1(X.scope??y0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(p8))return!1;return($.budget===void 0||d8($.budget))&&($.counters===void 0||G9($.counters))&&($.credits===void 0||Y1($.credits))}function l8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function a8($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function s8($,Z){let J=new Map(Object.entries($??{}));for(let[z,X]of Object.entries(Z??{})){let G=J.get(z);if(G===void 0||X.checkedAt>=G.checkedAt)J.set(z,X)}return J.size===0?void 0:Object.fromEntries(J)}function n8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function S1($,Z){let J=$===void 0?void 0:g0($);if($!==void 0&&J===void 0)throw new Z3("stored quota map is malformed");if(!U1(Z))throw new Z3("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let O of z.limits)G.set(H1(O.scope,O.label),O);let Q=(O)=>{let I=G.get(O);return I===void 0||X>=K$(I)},W=new Set;for(let O of Z.readings??[]){let I=O.scope??y0,T=H1(I,O.label);if(W.add(T),!Q(T))continue;G.set(T,{scope:I,label:O.label,kind:"reading",checkedAt:X,usedPercent:O.usedPercent,...O.resetsAt===void 0?{}:{resetsAt:O.resetsAt},...O.windowMinutes===void 0?{}:{windowMinutes:O.windowMinutes}})}for(let O of Z.coverage??[]){let I=O.scope??y0,T=H1(I,O.label);if(W.has(T)||!Q(T))continue;let m=G.get(T);G.set(T,m===void 0||m.kind==="absent"?{scope:I,label:O.label,kind:"absent",checkedAt:X}:{scope:I,label:O.label,kind:"retired",retiredAt:X})}let{limits:H,budget:U,counters:Y,credits:q,...D}=z,B=a8(z.budget,Z.budget,X),L=s8(z.counters,Z.counters),C=n8(z.credits,Z.credits);return{...D,limits:[...G.values()].sort(l8),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var i8=Object.freeze({validate:W1,decode:g0,merge:S1});function M$($,Z=""){let J=new Map,{observation:z}=$,X=(W,H,U)=>J.set(`${Z}:${W}`,{at:H,order:0,publication:{...$,observation:U}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of z.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...W}]})}for(let W of z.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...W}]})}if(z.budget)X("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[W,H]of Object.entries(z.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[W]:{...H}}});if(z.credits)X("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!J.size)X("empty",z.checkedAt,{checkedAt:z.checkedAt});return J}import{createHash as e8}from"node:crypto";import{stat as $6}from"node:fs/promises";import{resolve as T1}from"node:path";function D$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function W9($,Z,J){return $.some((z)=>D$(z,Z,J))}function H9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function Y9($,Z,J){return $.filter((z)=>!Z.some((X)=>D$(z,X,J)))}function q9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>Y0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function Z6($,Z){let J=Y0(Z),z=Z.accountIdentity===void 0?-1:$.order.findIndex((G)=>G.accountIdentity===Z.accountIdentity),X=z>=0?z:$.order.findIndex((G)=>J.includes(G.credentialId));return X>=0?X:1/0}var G3="vault:";function J6($){return e8("sha256").update($).digest("hex")}function z6($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function X6($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function Y0($){return[$.credentialId,...$.aliases??[]]}function P$($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??G3,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,H=[...$?.declined??W?.declined??[]],U=Z.skipped.length===0,Y=new Set(Z.credentials.map((F)=>F.credentialId)),q=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),D=Z.skipped.some((F)=>F.credentialId===void 0),B=(F)=>!Y.has(F)&&(q.has(F)||D),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let K of Y0(F))if(!L.has(K))L.set(K,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let K=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},j=X6(K),P=C.get(j)??[];P.push(K),C.set(j,P)}let O=new Set,I=new Set(G),T=[],m=(F,K)=>F.credential.credentialId.localeCompare(K.credential.credentialId),u=[...C.values()].map((F)=>F.toSorted(m)).sort((F,K)=>F[0]&&K[0]?m(F[0],K[0]):0);for(let F of u){let K=F[0]?.identity,j=F.filter((b)=>b.credential.state==="active"),P=j.length?j:F,g=P.filter((b)=>b.claimed),E=g.length?g:P,v=new Set(F.map((b)=>b.credential.credentialId)),Z0=Q.find((b)=>!O.has(b)&&Y0(b).some((F0)=>v.has(F0))&&(b.accountIdentity===void 0||b.accountIdentity===K)),p=E.find((b)=>b.credential.credentialId===Z0?.credentialId)??E[0];if(!p)continue;let d=p.credential,l=Z0??(K===void 0?void 0:Q.find((b)=>!O.has(b)&&b.accountIdentity===K));if(l)O.add(l);let J0=l?.routeId;if(!J0||G.has(J0)){let b=`${X}${d.credentialId}${K===void 0?"":`~${J6(K).slice(0,10)}`}`;J0=b;for(let F0=2;I.has(J0);F0++)J0=`${b}~${F0}`}I.add(J0);let P1=l?Y0(l).filter(B):[],C1=[...new Set([...F.map((b)=>b.credential.credentialId),...P1])].filter((b)=>b!==d.credentialId).sort((b,F0)=>b.localeCompare(F0)),c1=J.mapAccount?.(d)??{};T.push({previousIndex:l?Q.indexOf(l):1/0,row:{routeId:J0,credentialId:d.credentialId,credentialType:d.credentialType,...K!==void 0&&{accountIdentity:K},...C1.length&&{aliases:C1},state:d.state,label:c1.label?.trim()||z6(d),...d.email!==void 0&&{email:d.email},...d.orgName!==void 0&&{orgName:d.orgName},enabled:![d.credentialId,...C1].some((b)=>W9(H,b,K)),addedAt:l?.addedAt??z,...l?.quota!==void 0&&{quota:l.quota},...!p.claimed&&K!==void 0&&{unclaimed:!0}}});let a0=T.at(-1);if(W&&a0)a0.previousIndex=Z6(W,a0.row)}return Q.forEach((F,K)=>{if(O.has(F)||!Y0(F).some(B))return;if(I.has(F.routeId))return;let[j,...P]=Y0(F).filter((v)=>!Y.has(v));if(j===void 0)return;I.add(F.routeId);let{aliases:g,...E}=F;T.push({previousIndex:K,row:{...E,credentialId:j,...P.length&&{aliases:P},stale:!0}})}),T.sort((F,K)=>F.previousIndex===K.previousIndex?F.row.credentialId.localeCompare(K.row.credentialId):F.previousIndex-K.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:U,...!U&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:T.map((F)=>F.row),declined:H}}function K9($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function k1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function q1($){return $===void 0||typeof $==="string"}function G6($){let Z=k1($)?g0($.quota):void 0;if(!k1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!q1($.accountIdentity)||!q1($.email)||!q1($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((J)=>typeof J==="string"))||$.quota!==void 0&&Z===void 0||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return{...$,...Z===void 0?{}:{quota:Z}}}var Q6=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function N$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!k1(J)||!q1(J.credentialId)||typeof J.reason!=="string"||!Q6.has(J.reason))return;Z.push(J)}return Z}function C$($){if(!k1($)||$.version!==1||!q1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!N$($.rejected))throw new A("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=G6(X);if(!G)throw new A("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!k1(X)||typeof X.credentialId!=="string"||!q1(X.accountIdentity))throw new A("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=N$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},...$.limits!==void 0&&{limits:$.limits},rows:Z,declined:J}}function F9($){return C$(JSON.parse(JSON.stringify($)))}var W6=new E0({followSymlinks:!0});async function c($){if(_)return U9($);let Z=await W6.read([$],([J=$])=>U9(J));return structuredClone(Z)}async function U9($){let Z;try{Z=await z0($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new A("invalid-state","Claustrum roster file is not valid")}return C$(J)}var O$={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},A$={name:"claustrum-roster",ttlMs:30000};async function v0($,Z,J={}){return w3($,{...O$,signal:J.signal},async(z)=>{let X=await U9($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G){await z.assertOwned();try{await $1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}})}catch(W){if(W&&typeof W==="object"&&"published"in W&&W.published===!0)J.onPublished?.();throw W}J.onPublished?.()}return Q})}function B9($,Z){return v0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");let X=H9(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:X,rows:J.rows.map((G)=>G===z?{...G,enabled:!1}:G)},result:void 0}})}function V9($,Z){return v0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:Y9(J.declined,Y0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function H6($){return new A("invalid-order",$)}function Y6($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let J=new Set($.map((G)=>G.routeId)),z=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(z.has(G))return`route id ${G} appears more than once`;if(!J.has(G))return`route id ${G} is not in the roster`;z.add(G)}let X=[...J].filter((G)=>!z.has(G)).length;if(X>0)return`the order leaves out ${X} roster route id${X===1?"":"s"}`;return}function j9($,Z,J={}){return v0($,(z)=>{let X=z?.rows??[],G=Y6(X,Z);if(G)throw H6(G);let Q=new Map;for(let U of X){let Y=Q.get(U.routeId);if(Y)Y.push(U);else Q.set(U.routeId,[U])}let W=[...Z],H=W.flatMap((U)=>Q.get(U)??[]);if(!z||H.every((U,Y)=>U===X[Y]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function U6($,Z){if(!Y0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&Y0($).length===1)return"bind";return"refuse"}async function M9($,Z){let{routeId:J,observation:z,...X}=Z;return _$($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function _$($,Z){if(!U1(Z.observation))return!1;let J=r($,await c($));if(!R0(J,Z).kept)return!1;return R$($,Z)}function D9($,Z){return _$($,Z)}function R0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?U6(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=S1(J.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((Q)=>Q===J?{...Q,...G,quota:X}:Q)},kept:!0}}var X3=new Map;function E1($){X3.delete(T1($))}function I$($,Z){let J=T1($);if(Z instanceof A)return Z.kind==="roster-busy";if(Z instanceof C0||Z instanceof j0)return T1(Z.details.target)===J;if(Z instanceof w){let z=T1(Z.path);return[O$.name,A$.name].some((X)=>{let G=Z1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var q6=4;async function L$($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await $6($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function K6($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function F6($,Z,J){for(let z=0;z<q6;z++){let X=await L$($),G=await c($),Q,W,H;try{({target:Q,local:W}=Z(G));let U=JSON.stringify(J(Q));H=JSON.stringify(Q)!==U||W!==void 0&&JSON.stringify(W)!==U}catch{return"commit"}if(!K6(X,await L$($)))continue;if(H)return"commit";return S$($)?"commit":"unchanged"}return"commit"}async function b1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){E1($.path);return}let J=await M0({...A$,path:$.path,renew:!0});if(!J){let Q=await c($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new A("roster-busy","Claustrum account discovery is already in progress");return Q}let z=T1($.path),X=$.listedOver,G;try{let Q=await c($.path),W=X?void 0:X3.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},X3.delete(z);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let U=typeof $.projection==="function"?$.projection():$.projection,Y=(B)=>P$(B,H,U),q=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await F6($.path,(B)=>{if(X)return{target:B};let L=r($.path,B);return{target:B,...L!==B&&{local:L}}},Y)==="unchanged"){if(!await q())return;return await c($.path)}return await v0($.path,async(B)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&B?.view!==X.view&&B?.view!==H.view)return{result:B};let L=Y(B);return{...JSON.stringify(B)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof C0&&G&&!X&&!$.signal?.aborted&&await Z())X3.set(z,G);throw Q}finally{await J.release($.signal)}}var h0=new Map,B6=H0("claustrum"),k$=100;function E$($,Z=z9){let J=Q3($),z=h0.get(J);if(!z)z={path:J,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},h0.set(J,z);return z}function b$($,Z,J){let z=E$($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():N9($)})()}function V6($){return M$($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function R$($,Z){if(!U1(Z.observation))return Promise.resolve(!1);let J=E$($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),X=J.pending.get(z)??new Map;for(let[G,Q]of V6(Z)){let W=X.get(G);if(!W||Q.at>=W.at){if(Q.order=++J.order,Q.publication.observation.coverage)Q.priorReading=W?.publication.observation.readings?W.publication:W?.priorReading;X.set(G,Q)}}if(X.size)J.pending.set(z,X);for(let G of J.listeners)G(Z);return x$(J,k$),Promise.resolve(!0)}function f$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function r($,Z){let J=h0.get(Q3($));if(J)for(let z of f$(J.pending)){if(z.priorReading)Z=R0(Z,z.priorReading).roster;Z=R0(Z,z.publication).roster}return Z}function S$($){return!!h0.get(Q3($))?.pending.size}function x$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+J9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,y$($)}),!$.draining)$.timer.unref?.()}function T$($){$.timer?.cancel(),$.timer=void 0}function y$($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([J,z])=>[J,new Map(z)]));return $.running=(async()=>{try{if(await v0($.path,(z)=>{let X=z;for(let Q of f$(Z)){if(Q.priorReading)X=R0(X,Q.priorReading).roster;X=R0(X,Q.publication).roster}let G=JSON.stringify(X)!==JSON.stringify(z);return{...G&&{next:X},result:G}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[z,X]of Z){let G=$.pending.get(z);for(let[Q,W]of X)if(G?.get(Q)===W)G.delete(Q);if(!G?.size)$.pending.delete(z)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)B6.warn("vault quota publication delayed; retrying",{error:J instanceof Error?J.message:String(J)})}finally{$.running=void 0;for(let z of $.wake)z();let J=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):k$;x$($,J)}})(),$.running}async function N9($,Z=1000){let J=Q3($),z=h0.get(J);if(!z)return;z.draining=!0,T$(z);let X,G,Q=new Promise((W)=>{G=()=>{if(!z.pending.size||z.abort.signal.aborted)W()},z.wake.add(G),G()});try{if(z.pending.size)y$(z);await Promise.race([Q,new Promise((W)=>{X=setTimeout(W,Math.max(0,Z))})])}finally{if(clearTimeout(X),G)z.wake.delete(G);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),T$(z),z.pending.clear(),h0.get(J)===z)h0.delete(J)}}}var W3=1e4;function g$(){return new t}var L9;function h$($,Z){if(!L9)throw Error("ClaustrumConsumer is not initialized");return L9($,Z)}function v$(){return new A("not-active","Claustrum scoped custody is not active")}class P9{#$;#Z=new AbortController;#X;#Q;#G;#W;#z;#J;#V;#H;#Y=!1;#U=new Set;#F;#q;#B;#D;#C=new Map;#P;#O;#K;#M;#_=new WeakMap;static{L9=($,Z)=>{let J=new P9(Z);return J.#K=$,{consumer:J,hooks:J.#g()}}}constructor($){this.#$=$,this.#X=$.logger??H0("claustrum"),this.#Q=X1(this.#X,this.#Z.signal),this.#O=b$($.rosterPath,(Z)=>{this.#J=R0(this.#J,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#L($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#A(){return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=k0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#E(){if(this.#j(),this.#G)return this.#G;if(!this.#W){let $={timedOut:!1};this.#W=this.#N($),this.#L(this.#W)}return this.#R(this.#W)}#N($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=this.#$.connect().then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#j();throw g$()}if(this.#G=new Q1({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#X,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#q=x3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#X.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#S()}),W(g$())},this.#S()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#W=void 0})}#S(){return this.#$.connectTimeoutMs??W3}snapshot(){return this.#J}grantReach(){if(this.#K)return this.#K.grantReach(this.#J?.view);let $=this.#V;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){if(this.#K)return Object.freeze({vault:this.#K.watchMode()});return Object.freeze({vault:this.#B?.mode??"polling",...this.#$.insula&&{insula:this.#q?.source.watchMode()??"polling"}})}#k(){this.#B?.close(),this.#B=void 0,this.#D?.(),this.#D=void 0}keptReceiptState(){if(this.#K){let $=this.#M;return $&&this.#K.leaseLive($)?$.custody.keptReceiptState():this.#K.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return K9(this.#J)}refresh(){if(this.#j(),this.#K)return this.#L(this.#x(this.#K));if(this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#A()){if(this.#J=void 0,this.#V=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#G=void 0,this.#q?.release(),this.#q=void 0;return}let $=await this.#E(),Z,J=await b1({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},isActive:()=>this.#A(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#j();let z=J?.view!==this.#J?.view;if(this.#J=r(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#V=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#P=(this.#$.now??Date.now)(),J})().finally(()=>{this.#z=void 0}),this.#L(this.#z),this.#I(this.#z),this.#z}#I($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#Y)return;if(this.#j(),this.#Y=!0,this.#K){this.#K.start();return}let $=async()=>{try{if(await this.#y())await this.refresh();await this.refreshInsulaQuota(),this.#b()}catch(J){if(!this.#Z.signal.aborted)this.#$.onError?.(J)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#H=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#H=void 0,this.#L($())},Z),this.#H.unref?.()};this.#L($())}async#y(){if(this.#B?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#P===void 0||$-this.#P>=n0)return!0;return!await this.#A()}#b(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#B??=$.watchRoster({view:()=>this.#J?.view,onView:()=>this.#L((async()=>{while(this.#z)await this.#z.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#q&&!this.#D)this.#D=this.#q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await A0(this.#$.tokenPath),await this.#E(),await this.#q?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{return await A0(this.#$.tokenPath),this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await A0(this.#$.tokenPath);let J=r(this.#$.rosterPath,await c(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#f(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#A())return{miss:"unreachable"};try{await A0(this.#$.tokenPath);let z=r(this.#$.rosterPath,await c(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#q)return{miss:"unreachable"};let X=this.#q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#C.get($)!==J.miss)this.#C.set($,J.miss),this.#X.warn("skipped insula provider poll",{reason:J.miss});return}return this.#C.delete($),J.miss?Z():J.reading}#f($){if(!this.#$.insula||!$)return;let Z=this.#q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#K)return this.#h(this.#K,$,Z);this.#j(Z);let J=this.#J??await this.#R(this.refresh(),Z);if(!J||!await this.#A())throw this.#G?.close(),this.#G=void 0,this.#k(),this.#q?.release(),this.#q=void 0,new A("not-active","Claustrum scoped custody is not active");let z=r(this.#$.rosterPath,await c(this.#$.rosterPath));this.#j(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#G?.forget(X.credentialId);throw new A("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#G?.forget(X.credentialId);throw new A("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#R(this.#E(),Z),W=k0([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}#g(){return{discovery:($)=>{let Z=this.#K;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#L($.then((z)=>this.#v(Z,z)));this.#I(J)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#J?.view;if(this.#J=r(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(J){this.#$.onError?.(J)}},reset:()=>{this.#J=void 0},roster:()=>this.#J,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#x($){let Z=await $.refresh();return this.#v($,Z)}#v($,Z){if(this.#j(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#J}#T($){if($&&this.#M!==$)return;this.#M?.release(),this.#M=void 0}async#u($,Z){let J=this.#M;if(J&&$.leaseLive(J))return J;this.#T();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#j();let X=this.#M;if(X&&$.leaseLive(X))return z.release(),X;return this.#M=z,z}async#h($,Z,J){if(this.#j(J),!this.#J)await this.#R($.refresh(),J);let z=this.#J;if(!await $.readAuthority())throw this.#T(),v$();if(this.#j(J),!z)throw new A("route-unavailable","Claustrum has no roster for this provider yet");let X=r(this.#$.rosterPath,await c(this.#$.rosterPath));this.#j(J);let G=z.rows.find((U)=>U.routeId===Z),Q=X?.rows.find((U)=>U.routeId===Z);if(Q&&!Q.enabled){if(G)$.forget(G.credentialId);throw new A("route-declined","Claustrum route is disabled")}if(!G||!Q||Q.state!=="active"||Q.credentialId!==G.credentialId||Q.accountIdentity!==G.accountIdentity||Q.credentialType!==G.credentialType){if(G)$.forget(G.credentialId);throw new A("route-unavailable","Claustrum route is disabled, removed or changed")}let W={credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},H=k0([this.#Z.signal,...J?[J]:[]]);try{for(let U=0;;U++){let Y=await this.#u($,H.signal);try{let q=await Y.custody.authorize(W,H.signal,Z);return this.#_.set(q,Y),q}catch(q){if(U>0||H.signal.aborted||$.leaseLive(Y)||!(q instanceof A)||q.kind!=="closed")throw q;if(this.#T(Y),!await $.readAuthority())throw v$()}}}finally{H.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#J?.rows.find((J)=>J.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#K){if(this.#M&&this.#K.leaseLive(this.#M))this.#M.custody.reportUsage($)}else this.#G?.reportUsage($)}catch{}}usageReportState(){try{return(this.#K?this.#M?.custody:this.#G)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,J){if(this.#j(),this.#K){let z=this.#_.get($);if(!z)throw new A("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new A("no-receipt","Claustrum dispatch receipt has no active owner");await this.#G.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z),z?.throwIfAborted()}catch(W){if(z?.aborted)throw W}if(Z9(J.site,X,Q,this.#X))await G.body?.cancel().catch(()=>{}),X=Q,G=await Z(Q,z)}if(G.status===401)await this.reportFailure(X,401,J.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){if(this.#j(),await B9(this.#$.rosterPath,$),this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J);if(this.#K)this.#K.retainUnion();else this.#G?.retain(this.#J?.rows??[])}async accept($){if(this.#j(),await V9(this.#$.rosterPath,$),this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J)}async reorder($){this.#j();let Z=await j9(this.#$.rosterPath,$);if(this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J);return Z}async recordQuota($,Z,J){return this.#j(),M9(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:J.credentialId,accountIdentitySource:J.accountIdentitySource,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity},...J.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:J.expectedAccountIdentity}})}async recordAccountQuota($,Z,J){return this.#j(),D9(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new A("closed","Claustrum consumer is closed")),this.#H)(this.#$.clearTimeoutImpl??clearTimeout)(this.#H);if(this.#H=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#M?.release(),this.#M=void 0,this.#K?.detach(),this.#q?.release(),this.#q=void 0,this.#J=void 0,this.#V=void 0,this.#O(),E1(this.#$.rosterPath)}async dispose(){this.close(),this.#F??=Promise.all([G1(this.#U,this.#Q),this.#O()]).then(()=>{}),await this.#F}}import{createHash as j6}from"node:crypto";import{channel as M6}from"node:diagnostics_channel";import{readdir as D6,stat as N6}from"node:fs/promises";import{dirname as L6,join as K1,resolve as m$}from"node:path";var H3=new Map,P6=/^[a-z0-9][a-z0-9._-]{0,63}$/,C6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,O6=/^[0-9a-f]{16}$/,w$=3;function O9($,Z=new Set){if($===null)return"null";if(typeof $==="string"||typeof $==="boolean")return JSON.stringify($);if(typeof $==="number")return Number.isFinite($)?JSON.stringify($):void 0;if(typeof $!=="object"||Z.has($))return;let J=new Set(Z).add($),z=[];if(Array.isArray($)){for(let G=0;G<$.length;G++){let Q=O9($[G],J);if(Q===void 0)return;z.push(Q)}return`[${z.join(",")}]`}let X=Object.getPrototypeOf($);if(X!==Object.prototype&&X!==null)return;for(let G of Object.keys($).sort()){let Q=O9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function A6($,Z){let J=O9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??G3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new A("invalid-state","Claustrum hub classifierInput must be plain JSON");return j6("sha256").update(J).digest("hex").slice(0,16)}function u$($,Z){if(typeof $!=="string"||!P6.test($)||C6.test($))throw new A("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function S0($="Claustrum custody lease is closed"){return new A("closed",$)}function C9(){return new A("not-active","Claustrum scoped custody is not active")}function c$(){return new t}function _6($,Z){return new Promise((J,z)=>{let X=()=>z(Z.reason);if(Z.addEventListener("abort",X,{once:!0}),$.then((G)=>{Z.removeEventListener("abort",X),J(G)},(G)=>{Z.removeEventListener("abort",X),z(G)}),Z.aborted)X()})}function p$($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class d${#$;#Z;#X;#Q=new AbortController;#G=new Map;#W=new WeakMap;#z=0;#J;#V;#H;#Y;#U;#F;#q=0;#B;#D;#C;#P=!1;#O=new Set;#K;#M;#_;constructor($){if(!$.family||!("classify"in $.family))throw new A("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=u$($.hostGeneration,"host generation"),J=$.members.map((X)=>u$(X,"member"));if(new Set(J).size!==J.length)throw new A("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??H0("claustrum"),this.#X=X1(this.#Z,this.#Q.signal),this.#M=K1($.stateDir,"rosters",Z),this.#_=A6($,J);let z=K1(this.#M,this.#_);for(let X of J)this.#G.set(X,{provider:X,path:K1(z,`${X}.json`),closed:!1})}#j($){return this.#O.add($),$.then(()=>this.#O.delete($),()=>this.#O.delete($)),$}#L(){if(this.#Q.signal.aborted)throw S0("Claustrum discovery hub is closed")}#A($){let Z=this.#G.get($);if(!Z)throw new A("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#A($).path}member($,Z){this.#L();let J=this.#A($);if(J.hooks)throw new A("wrong-consumer","Claustrum hub member was already built");for(let q of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(q in Z)throw new A("wrong-consumer",`Claustrum hub members cannot take ${q}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#h(),readAuthority:()=>this.#x(),acquire:(q)=>this.acquire(q),leaseLive:(q)=>this.#S(q),grantReach:(q)=>q!==void 0&&this.#B?.view===q?this.#B.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#w(),publishRoster:(q)=>this.#R(J,q),forget:(q)=>this.#J?.custody?.forget(q),detach:()=>{J.closed=!0,J.releaseRoster?.()}},X={rosterPath:J.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:G,hooks:Q}=h$(z,X);J.hooks=Q;let W=m$(J.path),H=H3.get(W)??new Set,U=(q)=>{if(J.closed||this.#F!==!0||!this.#J||!this.#N(this.#J)||!Q.roster()||this.#c(Q,q))return;if(J.seen=JSON.stringify(F9(q)),Q.install(q),q.view!==this.#B?.view)J.pending??={failures:0,wait:0};this.#w()};H.add(U),J.receiveRoster=U,H3.set(W,H);let Y=!0;return J.releaseRoster=()=>{if(!Y)return;if(Y=!1,H.delete(U),!H.size)H3.delete(W)},G}#R($,Z){let J=this.#J;if($.closed||!J||!this.#N(J))return;$.seen=JSON.stringify(F9(Z)),$.hooks?.install(Z);for(let z of H3.get(m$($.path))??[]){if(!this.#N(J))return;if(z!==$.receiveRoster)z(Z)}}#E(){let $={id:++this.#z,count:0,ended:!1,controller:new AbortController};return this.#J=$,$}#N($){return!$.ended&&this.#J===$&&!this.#Q.signal.aborted}#S($){let Z=this.#W.get($);return!!Z&&!Z.released&&!Z.generation.ended}#k($,Z=S0()){if($.ended)return;if($.ended=!0,$.count=0,this.#J===$)this.#J=void 0;if(this.#H&&this.#W.get(this.#H)?.generation===$)this.#H=void 0;if(this.#Y?.generation===$)this.#Y.watch.close(),this.#Y=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#j($.custody.dispose(this.#X))}#I($){if($.ended)return;if($.count--,$.count<=0)this.#k($)}#y($){let Z=this.#V;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??W3,X,G=this.#$.connect().then((H)=>{if(J.timedOut)throw H.close(),c$();if(!this.#N($)||$.count<=0)throw H.close(),S0("Claustrum connection is no longer wanted");return $.custody=new Q1({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),Q=new Promise((H,U)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#N($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),U(c$())},z),X.unref?.()});return J.promise=this.#j(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#V===J)this.#V=void 0}).catch(()=>{}),this.#V=J,J.promise}acquire($){try{if(this.#L(),$?.throwIfAborted(),this.#F===!1)throw C9()}catch(J){return Promise.reject(J)}let Z=this.#J??this.#E();return Z.count++,this.#b(Z,$,!0)}async#b($,Z,J){let z=$.custody;if(!z){let X=k0([$.controller.signal,...Z?[Z]:[]]);try{z=await _6(this.#y($),X.signal)}catch(G){if(!$.ended)throw this.#I($),G;return this.#f(Z,J)}finally{X.dispose()}}if($.ended)return this.#f(Z,J);if(Z?.aborted)throw this.#I($),Z.reason;return this.#g($,z)}#f($,Z){if($?.throwIfAborted(),this.#L(),this.#F===!1)throw C9();if(!Z)throw S0();let J=this.#J??this.#E();return J.count++,this.#b(J,$,!1)}#g($,Z){let J={generation:$,custody:Z,released:!1},z=()=>{if(J.released||$.ended)throw S0()},X=Object.freeze({authorize:async(Q,W,H)=>{z();let U=k0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,U.signal,H)}finally{U.dispose()}},reportFailure:async(Q,W,H)=>{return z(),Z.reportFailure(Q,W,H)},reportUsage:(Q)=>{if(!J.released&&!$.ended)Z.reportUsage(Q)},usageReportState:()=>{return z(),Z.usageReportState()},forget:(Q)=>{z(),Z.forget(Q)},keptReceiptState:()=>{return z(),Z.keptReceiptState()}}),G=Object.freeze({custody:X,generation:$.id,release:()=>{if(J.released)return;J.released=!0,this.#I($)}});return this.#W.set(G,J),G}leaseState(){let $=this.#J;return Object.freeze({generation:$?.id,count:$?.count??0})}async#x(){let $=await this.#$.isCustodyActive?.()??!0;if(this.#Q.signal.aborted)return!1;let Z=this.#F;if(this.#F=$,!$&&Z!==!1)this.#v();return $}#v(){this.#q++;let $=this.#J;if($)this.#k($,C9());this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0,this.#B=void 0,this.#D=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),E1(Z.path)}#T(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#H,Z=$&&this.#W.get($);if($&&Z&&this.#S($))return Z;this.#H=void 0;let J=await this.acquire(this.#Q.signal),z=this.#H&&this.#W.get(this.#H);if(this.#H&&z&&this.#S(this.#H))return J.release(),z;this.#H=J;let X=this.#W.get(J);if(!X)throw S0();return X}#h(){try{this.#L()}catch(z){return Promise.reject(z)}let $=this.#U;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#j(this.#n(Z).finally(()=>{if(this.#U===Z)this.#U=void 0}));Z.promise=J,this.#U=Z;for(let z of this.#T())z.hooks?.discovery(J);return J}async#n($){if(!await this.#x())return;let Z=await this.#u(),J=Z.generation;if($.generation=J,!this.#N(J))return;let z=await this.#o().then(()=>{return},(Y)=>Y instanceof Error?Y:Error(String(Y))),X=new Map(await Promise.all([...this.#G.values()].map(async(Y)=>[Y,await c(Y.path).then((q)=>q?{file:q}:{},(q)=>q instanceof Error?q:Error(String(q)))])));if(!this.#N(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(Y){if(!this.#N(J))return;for(let q of this.#G.values())if(q.pending)this.#m(q);throw Y}if(!this.#N(J))return;let Q=this.#T(),W=await Promise.all(Q.map((Y)=>Y.hooks&&!Y.closed?this.#i(Y,Y.hooks,G,z??X.get(Y),J):void 0));if(!this.#N(J))return;let H=new Map,U=!0;for(let[Y,q]of Q.entries()){let D=q.hooks,B=W[Y];if(!D||!B)continue;if("error"in B){let{error:C}=B;if(U=!1,this.#m(q),I$(q.path,C))this.#Z.debug("claustrum hub member commit refused",{member:q.provider});else H.set(q.provider,C);continue}let{roster:L}=B;if(!this.#N(J))return;if(L?.view!==G.view)U=!1,this.#m(q);else q.pending=void 0;if(!L)continue;if(this.#c(D,L)){U=!1,this.#m(q);continue}this.#R(q,L)}if(!this.#N(J))return;if(this.#w(),U)this.#B=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#D=(this.#$.now??Date.now)(),{errors:H}}async#i($,Z,J,z,X){let G={...J,credentials:J.credentials.filter((Q)=>Q.member===$.provider),skipped:J.skipped.filter((Q)=>Q.member===$.provider)};try{if(!z)throw S0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let H=M6("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{Q=await this.#r($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await b1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#N(X)&&this.#F===!0,signal:X.controller.signal,projection:()=>({...Z.projection(),...Q&&{seed:Q}}),listedOver:{view:z.file?.view}})}}catch(Q){return{error:Q}}}async#o(){for(let $ of[L6(this.#M),this.#M,K1(this.#M,this.#_)])await z1($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[K1(this.#M,Z)];try{for(let X of await D6(this.#M))if(X!==this.#_&&O6.test(X))J.push(K1(this.#M,X,Z))}catch{}let z;for(let X of J)try{let G=(await N6(X)).mtimeMs,Q=await c(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&q9(z.roster)}#c($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#m($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(n0/J)),X=Z<=w$?1:Math.min(2**(Z-w$),z);$.pending={failures:Z,wait:X-1}}#w(){let $=this.#J?.custody;if(!$)return;$.retain(this.#T().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#q;for(let Z of this.#T()){let J;try{J=await c(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#q||this.#F!==!0)return;let z=Z.hooks;if(!J||!z||Z.closed)continue;let X=JSON.stringify(J);if(X===Z.seen)continue;let G=z.roster();if(!G||G.view!==J.view||this.#c(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=p$(G);if(Z.seen=X,this.#R(Z,J),p$(z.roster())!==Q)this.#w()}}#e(){let $=!1;for(let J of this.#G.values()){if(!J.pending)continue;if(J.pending.wait<=0)$=!0;else J.pending.wait--}if(this.#Y?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#D===void 0||Z-this.#D>=n0}#$0(){let $=this.#H,Z=$&&this.#W.get($);if(!$||!Z||!this.#S($)||this.#F!==!0)return;let J=Z.generation;if(!this.#N(J)||this.#Y?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#B?.view,onView:()=>this.#j((async()=>{while(this.#U)await this.#U.promise.catch(()=>{});if(!this.#N(J))return;await this.#a()})()),onRefused:(X)=>this.#d(X),onError:(X)=>this.#p(X)});this.#Y={generation:J,watch:z}}#p($){if(!this.#Q.signal.aborted)this.#$.onError?.($)}#d($){if(this.#Q.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#T())Z.hooks?.onError($)}#l($){for(let[Z,J]of $?.errors??[])this.#G.get(Z)?.hooks?.onError(J)}async#a(){let $;try{$=await this.#h()}catch(Z){this.#d(Z);return}this.#l($)}async#s(){try{if(await this.#x()){if(await this.#t(),this.#e())await this.#a();this.#$0()}}catch(Z){this.#p(Z)}if(this.#Q.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#C=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#C=void 0,this.#j(this.#s())},$),this.#C.unref?.()}start(){if(this.#P)return;this.#L(),this.#P=!0,this.#j(this.#s())}async refresh(){this.#l(await this.#h())}refusals(){let $=this.#B;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#B?.reach}watchState(){let $=this.#Y;return $&&this.#N($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#J?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#Q.signal.aborted)return;this.#Q.abort(S0("Claustrum discovery hub is closed"));for(let Z of this.#G.values())Z.releaseRoster?.();if(this.#C)(this.#$.clearTimeoutImpl??clearTimeout)(this.#C);this.#C=void 0;let $=this.#J;if($)this.#k($);this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0}async dispose(){this.close(),this.#K??=G1(this.#O,this.#X),await this.#K}}var w0={opencode:S6,pi:T6};function A9($,Z){let{tokenPath:J}=l$($,Z);return{stateDir:R6(J),host:$,override:J}}function _9($,Z){return k6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class m0 extends Error{code;constructor($){super($==="permission-refused"?"Native vault setup: permission-refused. Could not grant this host read access to native Claude accounts. An older ck may refuse a grant that already exists. Update CortexKit tools and run setup again.":`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}function I9($,Z){let J=Z??w0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new m0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function a$($,Z){try{await Z.processFence();let J=await $3(Z.paths??l$($,Z.env),w0[$]);if(J.state==="blocked")throw new m0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=I9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new m0("permission-refused");return z}catch{throw new m0("permission-refused")}}import{createHash as v6}from"node:crypto";import{lstat as h6,mkdir as m6,readFile as z4}from"node:fs/promises";import{dirname as w6}from"node:path";import{assertHostsStopped as u6,canonicalPath as S9,createNativeAccountRuntime as c6,custodyTombstoneOAuth as p6,inspectNativeHostAuthEntry as X4,NativeMigrationError as u0,nativeJournalMayAdoptLaterHostLogin as d6,nativePoolHoldsAccountData as l6,prepareNativeMigration as a6,readNativeEnrollmentMode as G4,readNativeMigrationJournal as s6,releaseNativeMigrationPreflight as n6,requireNoSupervisedAuthContentSnapshot as i6,runNativeMigration as o6,writeNativeHostAuth as r6}from"@cortexkit/anthropic-auth-core";import{dirname as E6,join as s$,resolve as R9}from"node:path";import{ACCOUNT_FILE_NAME as n$,ACCOUNT_STATE_FILE_NAME as b6,canonicalPath as i$,getStickyRoutingStatePath as f6,resolveLocalRoutingDestination as x6,resolveNativePoolPaths as y6}from"@cortexkit/anthropic-auth-core";async function D0($,Z){let J=$==="pi"?t$(Z):o$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=R9(z||s$(J,n$)),G=R9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(n$)?s$(E6(X),b6):`${X}.state.json`)),Q=await y6(X,G),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:Q,legacyConfigPath:X,legacyStatePath:G,hostAuthPath:$==="pi"?e$(Z):r$(Z),routingSourcePath:R9(W||f6(X)),routingDestinationPath:x6($,Q,Z)}}async function $4($){let Z=new Map;for(let J of $){let z=new Set;for(let[X,G]of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath].entries()){let Q=await i$(G);if(z.has(Q)&&!(X===9&&Q===await i$(J.routingSourcePath)))throw Error("Native setup storage paths overlap");let W=Z.get(Q);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(Q,J.host),z.add(Q)}}}import{types as g6}from"node:util";var Z4=new WeakMap;function J4($){return typeof $==="object"&&$!==null?Z4.get($):void 0}function F1($){if(!$||typeof $!=="object"||g6.isProxy($))return;if(Object.getOwnPropertyDescriptor($,"name")?.value==="ProcessInspectionError"&&Object.getOwnPropertyDescriptor($,"code")?.value==="process-inspection-failed")return"Process inspection failed; setup cannot prove hosts are stopped.";return}class i extends Error{constructor($){super($);this.name="SetupRefusal",Z4.set(this,$)}}var T9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function Q4($){let Z=$==="opencode"?"OpenCode":"Pi";return`${Z} is still connected to the vault. Old local settings do not disconnect it. In ${Z}, run /claude → Accounts → Disconnect from the vault. Then run local setup again.`}async function k9($,Z){let J=[];for(let z of $)if(await G4(z,Z)!=="local")J.push(Q4(z));if(J.length)throw new i(J.join(`
|
|
13
13
|
`))}function c0($,Z){return async()=>{i6(Z.env);try{await u6(Z.fence,Z.env)}catch(J){let z=F1(J);if(z)throw new i(z);throw J}await k9([$],Z.env)}}async function E9($){try{return v6("sha256").update(await z4($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new u0("unsafe-source")}}async function f1($,Z){let J;try{J=JSON.parse(await z4(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new u0("unsafe-source")}let z=X4($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function Y3($,Z){let{paths:J}=$,z=$.generation2?void 0:await f1(J.host,J.hostAuthPath),X=await Promise.all([J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.routingDestinationPath].map(E9));return JSON.stringify([await G4(J.host,Z),z?.digest,...X])}async function b9($,Z,J){let z=Z.paths??await D0($,Z.env),X=c0($,Z);await X();let G=await s6(z.paths);if(G&&G.host!==$)throw new u0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await S9(z.hostAuthPath)||G.routingPaths.source!==await S9(z.routingSourcePath)||G.routingPaths.destination!==await S9(z.routingDestinationPath)))throw new u0("invalid-source");let W={paths:z,generation2:J,action:"migration",notice:!1,fingerprint:"",authorityPhase:G?.phase??"absent",poolPopulation:"not-evaluated"};if(J){if(G&&!Q)throw new u0("invalid-source");if(W.action=G?"reuse":"empty-init",!G){let H=[z.paths.config,z.paths.state,z.paths.runtime,z.paths.roster];if(!Z.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE)H.push(z.routingDestinationPath);for(let U of H){try{await h6(U)}catch(Y){if(Y.code==="ENOENT")continue;throw new u0("unsafe-source")}throw new u0("invalid-source")}}}else{W.slot=await f1($,z.hostAuthPath);let H=d6(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||H?await l6({paths:z.paths}):"not-evaluated";let U=W.poolPopulation===!0;if($==="opencode"&&(U||Q&&G?.kind!=="empty-init"&&!H&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await a6({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await Y3(W,Z.env),W}async function B1($,Z){await c0($.paths.host,Z)();let J=await b9($.paths.host,{...Z,paths:$.paths},$.generation2);try{if(J.fingerprint!==$.fingerprint||J.action!==$.action)throw new i("Setup inputs changed. Rerun setup with all hosts stopped.")}finally{if(J.preflight)n6(J.preflight)}}async function f9($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=c0("opencode",Z);await J(),await m6(w6($.paths.hostAuthPath),{recursive:!0,mode:448}),await r6({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:X4("opencode",{anthropic:p6("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function W4($,Z){let J={...Z.env},z=c0($,{...Z,env:J});await z();let X=Z.paths??await D0($,J),G=await Z.login?.($);if(G&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(G.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await z(),await Z.beforeCommit?.(),!Z.skipMigration)await o6({paths:X.paths,legacyConfigPath:X.legacyConfigPath,legacyStatePath:X.legacyStatePath,host:$,hostAuthPath:X.hostAuthPath,routingSourcePath:X.routingSourcePath,routingDestinationPath:X.routingDestinationPath,env:J,processFence:z,removePiAnthropicAuth:Z.removePiAnthropicAuth,preflight:Z.preflight});if(G){let Q=c6({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new i(Q4($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{await Q.close()}}if(Z.skipMigration){let Q=await f1($,X.hostAuthPath);await f9({paths:X,slot:Q},Z)}}var H4={opencode:"OpenCode",pi:"Pi"};function Q5($,Z,J){switch($){case"auth-content-refused":return"Run setup without OPENCODE_AUTH_CONTENT in the environment.";case"host-auth-invalid":return"The host auth file could not be read safely.";case"primary-conflict":return"Pi has a stored Anthropic API key, which would take precedence over the vault account. Remove it in Pi, then rerun setup.";case"consent-required":return"Pi has stored Anthropic authentication. Explicit consent is required to move it aside for vault use.";case"primary-unverified":return"The vault has no verified default Claude account. Sign in through the vault and rerun setup.";case"no-read-grant":return`${H4[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...I9(Z,J)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${H4[Z]}'s vault read grant reaches no Claude login: no vault login carries the anthropic-native category, which logins saved before vault categories existed lack. Run ck auth reclassify --from-registry, check the logins with ck auth status, then rerun setup.`}}class X0 extends Error{host;approvedName;code;constructor($,Z="opencode",J){super(Q5($,Z,J));this.host=Z;this.approvedName=J;this.name="NativeVaultActivationError",this.code=$}}function W5($){let Z=$?.grantReach;if(!Z||$.credentials.length>0||$.skipped.length>0)return"primary-unverified";return Z.grants===0?"no-read-grant":"grant-reaches-nothing"}async function y9($){try{return JSON.parse(await t6($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new X0("host-auth-invalid")}}async function x1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await D0($,Z.env),z=x9($,await y9(J.hostAuthPath)),X=g9({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=z5({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await E9(G)])}async function Y4($){try{G5($.env)}catch{throw new X0("auth-content-refused")}try{await e6($.fence,$.env)}catch(Z){let J=F1(Z);if(J)throw new i(J);throw Z}}async function U4($,Z){let J={...Z.env};await(()=>Y4({...Z,env:J}))();let X=Z.paths??await D0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&x9("opencode",await y9(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=x9("pi",await y9(X.hostAuthPath)),W=await g9({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new J5("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new X0("consent-required")}return{priorMode:await X5($,J),fingerprint:await x1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function q4($,Z,J){let z={...Z.env},X=()=>Y4({...Z,env:z});await X();let G=Z.paths??await D0($,z);if(await x1($,Z)!==J.fingerprint)throw new X0("host-auth-invalid");let Q=await a$($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary,paths:Z.enrollment?.paths}),W=Z.discover??(()=>Z5({paths:G.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),H,U=async()=>{return H=await W(),H},Y=$5({paths:G.paths,host:$,vault:{env:z,discover:U}});try{await X(),await Y.vault.refresh();let q=await Y.read(),D=q.accounts.find((B)=>B.id==="main");if(q.mode!=="claustrum"||!D?.accountIdentity||D.source!=="vault"){let B=W5(H);throw B==="primary-unverified"?new X0(B):new X0(B,$,Q)}if(await X(),$==="pi")await g9({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{await Y.close()}}var H5=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class v9 extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:H5.exec(z.command)?.[1]??"host"})),J=Z.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
14
14
|
`);super(`OpenCode or Pi processes are currently running:
|
|
15
15
|
${J}
|