@cortexkit/opencode-openai-auth 1.8.5 → 1.9.0
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/bin.js +2 -2
- package/dist/index-0vvxnhd3.js +76 -0
- package/dist/{index-byz2j6hz.js → index-2f9w48sc.js} +1 -1
- package/dist/{index-jh90fx7y.js → index-2sb7q9wr.js} +2 -2
- package/dist/{index-zf649dj2.js → index-7bgst9rd.js} +2 -2
- package/dist/{index-kphzmgq6.js → index-96971sba.js} +1 -1
- package/dist/{index-5wgxt362.js → index-bvswyxpt.js} +1 -1
- package/dist/{index-g5hv0tda.js → index-e32hgdk4.js} +2 -2
- package/dist/index-ececstzk.js +91 -0
- package/dist/{index-95s2mw9w.js → index-jenb51ww.js} +2 -2
- package/dist/{index-zah8t2d2.js → index-v0y4hv4r.js} +2 -2
- package/dist/{index-rmc6hwg6.js → index-vkg5pw57.js} +1 -1
- package/dist/{index-n12zjwh9.js → index-wkn4d21h.js} +2 -2
- package/dist/index-yw0wnqjq.js +63 -0
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-ybe08zph.js +1 -0
- package/dist/{token-j2jmx8k7.js → token-y2zkdr5m.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +25 -0
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +20 -1
- package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +262 -129
- package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +6 -0
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +25 -0
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +20 -1
- package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +338 -222
- package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +6 -0
- package/dist/index-8x42xzxb.js +0 -74
- package/dist/index-a7xv52hy.js +0 -63
- package/dist/index-zne9tzy9.js +0 -91
- package/dist/token-util-7n2nfbyc.js +0 -1
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import{Ie as d,Le as b,Me as W3,Ne as U$,Oe as Q3,Pe as U3}from"./index-wkn4d21h.js";import{gf as c$,hf as A,jf as c6,nf as K6}from"./index-7bgst9rd.js";import{Af as K4,qf as Z0,rf as v0,tf as H4,vf as R3,wf as S$}from"./index-jenb51ww.js";var P="all",r$=Object.freeze(["primary"]);function WZ($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function x0($,Z){return JSON.stringify([$,Z])}function n($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function S($){return typeof $==="number"&&Number.isFinite($)}function KZ($){return typeof $==="string"&&$.length>0}function T($,Z,z){return $[Z]===void 0||z($[Z])}function s6($){return S($)&&$>0}function o$($){return typeof $==="string"}function a6($){if(!n($)||!KZ($.scope)||!KZ($.label))return!1;switch($.kind){case"reading":return S($.checkedAt)&&S($.usedPercent)&&T($,"resetsAt",o$)&&T($,"windowMinutes",s6);case"retired":return S($.retiredAt);case"absent":return S($.checkedAt);default:return!1}}function n6($){if(!n($)||!S($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&T($,"remainingPercent",S)&&T($,"usedPercent",S)&&T($,"resetsAt",o$)&&T($,"limit",S)&&T($,"used",S)&&T($,"remaining",S)&&T($,"unit",o$)}function QZ($){return n($)&&S($.value)&&Number.isInteger($.value)&&$.value>=0&&S($.checkedAt)}function t$($){return n($)&&Object.values($).every(QZ)}function o6($){return typeof $==="boolean"}function l($){return n($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&T($,"balance",S)&&T($,"overageLimitReached",o6)&&S($.checkedAt)}function e$($){if(!n($))return;let Z=Object.entries($).filter(([,z])=>QZ(z));return Z.length===0?void 0:Object.fromEntries(Z)}function K0($){if(H0($))return $;if(!n($))return;let{counters:Z,credits:z,...X}=$;if(!H0(X))return;let Y=e$(Z),J=l(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...J===void 0?{}:{credits:J}}}function H0($){if(!n($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let z of $.limits){if(!a6(z))return!1;let X=x0(z.scope,z.label);if(Z.has(X))return!1;Z.add(X)}return T($,"budget",n6)&&T($,"counters",t$)&&T($,"credits",l)}var qZ=900000,FZ="no quota reading yet",NZ="no limits reported";function MZ($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let Y=Math.floor(Z/60),J=Z%60;return J===0?`${Y}h`:`${Y}h${J}m`}let z=Math.floor(Z/1440),X=Math.floor(Z%1440/60);return X===0?`${z}d`:`${z}d${X}h`}function jZ($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function _Z($){if($.scope!==P||$.windowMinutes===void 0)return $.label;return jZ($.windowMinutes)}function $3($){return Math.min(100,Math.max(0,$))}function J$($){return Math.round($3($))}function UZ($){return`${J$($)}% left`}function VZ($,Z,z){let X=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(X)&&X>z?{resetIn:MZ(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>Z&&X<=z}}function r6($,Z){let z=$.windowMinutes,X=Z.windowMinutes;if(z!==void 0&&X!==void 0&&z!==X)return z-X;if(z===void 0!==(X===void 0))return z===void 0?1:-1;if($.scope!==Z.scope){if($.scope===P)return-1;if(Z.scope===P)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function OZ($,Z){let{windows:z,age:X}=Z3($,Z),Y=z.map(({part:J})=>J);return X===void 0?{windows:Y}:{windows:Y,age:X}}function t6($){let Z=PZ($.filter(({part:z,scope:X})=>z.kind==="window"&&X!==P).map(({scope:z})=>z));for(let z of $)z.part.short=z.part.kind==="budget"?"cr":z.scope===P?z.part.name:Z.get(z.scope)??z.scope;return $}function Z3($,Z){if(!$)return{windows:[]};let{now:z}=Z,Y=$.limits.filter((G)=>G.kind==="reading"&&G.remainingPercent!==void 0).sort(r6).map((G)=>{let B=$3(G.remainingPercent??0);return{scope:G.scope,...G.windowMinutes===void 0?{}:{windowMinutes:G.windowMinutes},part:{kind:"window",name:_Z(G),short:"",figure:UZ(G.remainingPercent??0),remainingPercent:B,checkedAt:G.checkedAt,...VZ(G.resetsAt,G.checkedAt,z)}}}),J=$.budget;if(J){let G=J.remainingPercent,B=J.reached?"credits spent":G!==void 0?`credits ${UZ(G)}`:"credits available";Y.push({scope:P,spent:J.reached,part:{kind:"budget",name:"credits",short:"",figure:B,...G===void 0?{}:{remainingPercent:$3(G)},checkedAt:J.checkedAt,...VZ(J.resetsAt,J.checkedAt,z)}})}if(t6(Y),Y.length>0){let G=z-Math.min(...Y.map(({part:B})=>B.checkedAt));if(G>(Z.staleAfterMs??qZ))return{windows:Y,age:`checked ${MZ(G)} ago`}}return{windows:Y}}function e6($,Z){return Z3($,Z).age!==void 0}function DZ($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function PZ($){let Z=[...new Set($.map(DZ))],z=new Map(Z.map((Y)=>[Y,2])),X=(Y)=>Y.slice(0,z.get(Y));for(;;){let Y=new Map;for(let G of Z)Y.set(X(G),[...Y.get(X(G))??[],G]);let J=!1;for(let G of Y.values()){if(G.length<2)continue;for(let B of G){let H=z.get(B)??2;if(H<B.length)z.set(B,H+1),J=!0}}if(!J)break}return new Map($.map((Y)=>[Y,X(DZ(Y))]))}var $8=2;function Z8($){let Z=$.map((X)=>X.label.trim()||X.scope),z=PZ(Z);return Z.map((X)=>z.get(X)??X)}function z8($,Z){if(!$||$.length===0)return;let z=Z.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===P))return;let X=$.flatMap((B,H)=>{let K=z.filter(({scope:W})=>W===B.scope).reduce((W,U)=>W===void 0||(U.part.remainingPercent??0)<(W.part.remainingPercent??0)?U:W,void 0);return K?[{group:B,listed:H,window:K}]:[]});if(X.length===0)return;let Y=Z8($),J=(B)=>B.window.part.remainingPercent??0,G=[...X].sort((B,H)=>J(B)-J(H)||B.listed-H.listed).slice(0,$8).sort((B,H)=>B.listed-H.listed);return G.map((B,H)=>{let{windowMinutes:Q}=B.window,K=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[jZ(Q)],`${J$(J(B))}%`].join(" ");return H===G.length-1?`${K} left`:K})}function X8($,Z){let{windows:z}=Z3($,Z),X=z8($?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:U})=>W.kind==="window"&&U===P),J=z.filter(({part:W,scope:U})=>W.kind==="window"&&U!==P),G=z.find(({part:W})=>W.kind==="budget"),B=G?.spent?0:G?.part.remainingPercent,Q=[...J.map(({part:W})=>({label:W.short,remaining:W.remainingPercent??0})),...B===void 0||G===void 0?[]:[{label:G.part.short,remaining:B}]].reduce((W,U)=>W===void 0||U.remaining<W.remaining?U:W,void 0),K=Y.map(({part:W})=>`${W.name} ${J$(W.remainingPercent??0)}%`);if(Q)K.push(`${Q.label} ${J$(Q.remaining)}%`);if(K.length===0)return z.map(({part:W})=>W.figure);return K.map((W,U)=>U===K.length-1?`${W} left`:W)}function LZ($,Z){if(Z.form==="narrow")return X8($,Z);let z=OZ($,Z),X=(Z.form??"full")==="full",Y=z.windows.map((J)=>{let G=X&&J.resetIn?`, resets ${J.resetIn}`:"";return`${J.kind==="budget"?"":`${J.name} `}${J.figure}${G}`});return z.age===void 0?Y:[...Y,z.age]}function Y8($,Z){let z=LZ($,Z);if(z.length>0)return z.join(" · ");return $&&$.limits.length>0?NZ:FZ}function J8($){if($===void 0)return;if($.unlimited)return"Unlimited";if(!$.hasCredits)return;let{balance:Z}=$;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?`${Math.round(Z)} credits`:"Available"}function G8($){if($.kind==="retired")return{scope:$.scope,label:$.label,kind:"retired",checkedAt:$.retiredAt};if($.kind==="absent")return{scope:$.scope,label:$.label,kind:"absent",checkedAt:$.checkedAt};return{scope:$.scope,label:$.label,kind:"reading",checkedAt:$.checkedAt,usedPercent:$.usedPercent,remainingPercent:100-$.usedPercent,...$.windowMinutes===void 0?{}:{windowMinutes:$.windowMinutes},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function B8($,Z){let z=$.windowMinutes!==void 0,X=Z.windowMinutes!==void 0;if(z!==X)return z?-1:1;if(z&&X&&$.windowMinutes!==Z.windowMinutes)return(Z.windowMinutes??0)-($.windowMinutes??0);if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function H8($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function f($,Z=P){let z=new Map;for(let K of $?.limits??[]){if(K.scope!==Z&&K.scope!==P)continue;let W=z.get(K.label);if(W===void 0){z.set(K.label,K);continue}let U=K.scope===P?W:K,D=K.scope===P?K:W;z.set(K.label,U.kind==="reading"?U:D)}let X=[...z.values()].map(G8).sort(B8),Y=X.filter((K)=>K.kind==="reading"),J=Y.length>0?Y:X,G=J.length>0?Math.min(...J.map((K)=>K.checkedAt)):void 0,B=$?.budget?.kind==="reading"?H8($.budget):void 0,H=e$($?.counters),Q=l($?.credits)?$.credits:void 0;return{scope:Z,limits:X,...G===void 0?{}:{checkedAt:G},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H},...Q===void 0?{}:{credits:Q}}}function W0($,Z){let z=$?.budget;if(z?.reached!==!0||typeof z.resetsAt!=="string")return;let X=Date.parse(z.resetsAt);if(!Number.isFinite(X)||X<=Z)return;return{resetsAt:z.resetsAt,resetAtMs:X}}function z3($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function G$($,Z){if(typeof $.resetsAt!=="string")return;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z>Z?z:void 0}class B$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function K$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H$($){return typeof $==="number"&&Number.isFinite($)}function xZ($){return $===void 0||typeof $==="string"&&$!==""}function RZ($){return typeof $==="string"&&$!==""}function w0($,Z){return $[Z]===void 0||H$($[Z])}function X3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function K8($){return K$($)&&xZ($.scope)&&RZ($.label)&&H$($.usedPercent)&&X3($,"resetsAt")&&($.windowMinutes===void 0||H$($.windowMinutes)&&$.windowMinutes>0)}function W8($){return K$($)&&xZ($.scope)&&RZ($.label)}function Q8($){if(!K$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&w0($,"remainingPercent")&&w0($,"usedPercent")&&X3($,"resetsAt")&&w0($,"limit")&&w0($,"used")&&w0($,"remaining")&&X3($,"unit")}function R0($){if(!K$($)||!H$($.checkedAt))return!1;let Z=$.readings??[],z=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(z))return!1;let X=new Set;for(let Y of Z){if(!K8(Y))return!1;let J=x0(Y.scope??P,Y.label);if(X.has(J))return!1;X.add(J)}if(!z.every(W8))return!1;return($.budget===void 0||Q8($.budget))&&($.counters===void 0||t$($.counters))&&($.credits===void 0||l($.credits))}function U8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function V8($,Z,z){if(Z===void 0)return $;if($!==void 0&&z<$.checkedAt)return $;return{...Z,checkedAt:z}}function D8($,Z){let z=new Map(Object.entries($??{}));for(let[X,Y]of Object.entries(Z??{})){let J=z.get(X);if(J===void 0||Y.checkedAt>=J.checkedAt)z.set(X,Y)}return z.size===0?void 0:Object.fromEntries(z)}function q8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function h0($,Z){let z=$===void 0?void 0:K0($);if($!==void 0&&z===void 0)throw new B$("stored quota map is malformed");if(!R0(Z))throw new B$("quota observation is malformed");let X=z??{limits:[]},Y=Z.checkedAt,J=new Map;for(let M of X.limits)J.set(x0(M.scope,M.label),M);let G=(M)=>{let L=J.get(M);return L===void 0||Y>=WZ(L)},B=new Set;for(let M of Z.readings??[]){let L=M.scope??P,R=x0(L,M.label);if(B.add(R),!G(R))continue;J.set(R,{scope:L,label:M.label,kind:"reading",checkedAt:Y,usedPercent:M.usedPercent,...M.resetsAt===void 0?{}:{resetsAt:M.resetsAt},...M.windowMinutes===void 0?{}:{windowMinutes:M.windowMinutes}})}for(let M of Z.coverage??[]){let L=M.scope??P,R=x0(L,M.label);if(B.has(R)||!G(R))continue;let p=J.get(R);J.set(R,p===void 0||p.kind==="absent"?{scope:L,label:M.label,kind:"absent",checkedAt:Y}:{scope:L,label:M.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:Q,counters:K,credits:W,...U}=X,D=V8(X.budget,Z.budget,Y),V=D8(X.counters,Z.counters),j=q8(X.credits,Z.credits);return{...U,limits:[...J.values()].sort(U8),...D===void 0?{}:{budget:D},...V===void 0?{}:{counters:V},...j===void 0?{}:{credits:j}}}var F8=Object.freeze({validate:H0,decode:K0,merge:h0});function SZ($,Z,z){let X=Z.rateLimitMarks?.get($);if(X!==void 0&&z<X)return{id:$,reason:"rate-limited",until:X};let Y=Z.refreshBackoff?.get($);if(Y!==void 0&&z<Y)return{id:$,reason:"refresh-backoff",until:Y};return}function N8($,Z,z,X){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let J of z)if(!Z.limits.some((G)=>G.label===J))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:J},pullRequested:!0};let Y=Z.limits.filter(z3);for(let J of Y)if(G$(J,X)===void 0)return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:J.scope,label:J.label},pullRequested:!0};for(let J of Y){let G=G$(J,X);if(G!==void 0&&typeof J.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:J.scope,label:J.label},resetsAt:J.resetsAt,resetAtMs:G}}return}function m($){let Z=$.scope??P,z=$.requiredLabels??r$,X=[],Y=[],J=[];for(let U of $.rows){let D=SZ(U.id,$,$.now);if(D){X.push(D);continue}if(U.kind==="api-key"){J.push({id:U.id,kind:U.kind});continue}let V=f(U.quota,Z),j=N8(U.id,V,z,$.now);if(j){Y.push(j);continue}J.push({id:U.id,kind:U.kind,projection:V})}let G=new Map(J.flatMap((U)=>{let D=W0(U.projection,$.now);return D?[[U.id,D]]:[]})),B=G.size>0&&G.size===J.length,H=[];for(let U of J){let D=G.get(U.id);if(D===void 0)H.push(U);else if(B)H.push({...U,lastPath:!0});else Y.push({id:U.id,stage:2,reason:"budget-spent",...D})}let Q=new Map($.rows.map((U,D)=>[U.id,D])),K=(U,D)=>(Q.get(U.id)??0)-(Q.get(D.id)??0);Y.sort(K);let W=Y.filter((U)=>("pullRequested"in U)).map((U)=>U.id);for(let U of W)$.requestPull?.(U);return{admitted:H,refused:Y,excluded:X,pulls:W}}var TZ="main";function M8($){switch($){case"sticky-balanced":return{mode:"sticky-balanced",placement:"roster"};case"main-first":return{mode:"ordered",placement:"main-first"};case"fallback-first":return{mode:"ordered",placement:"fallback-first"};default:return{mode:"ordered",placement:"roster"}}}function W$($,Z,z=TZ){if(Z==="roster"||!$.includes(z))return[...$];let X=$.filter((Y)=>Y!==z);return Z==="main-first"?[z,...X]:[...X,z]}function Y3($){let Z=m($),z=new Set(Z.admitted.map((Y)=>Y.id));return{order:W$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>z.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function j8($,Z,z){let X=Z.at(-1);if(X!==void 0){if(X.status===void 0||!z.includes(X.status))return}let Y=new Set(Z.map((J)=>J.id));return $.find((J)=>!Y.has(J))}function J3($,Z,z){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof z==="string"&&$.wireIdentity!==z)}function _8($,Z,z){let X=new Map;for(let[Y,J]of $){if(Y===z)continue;if(J.quotaCheckedAt!==Z.get(J.accountId))continue;X.set(J.accountId,(X.get(J.accountId)??0)+(J.inputBytes??0))}return X}var m0=900000,EZ=0.016666666666666666,G3=0.000001;function Q$($,Z){for(let z of[$?.checkedAt,Z])if(typeof z==="number"&&Number.isFinite(z))return z;return}function CZ($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function IZ($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,z)=>{let X=Z.windowMinutes!==void 0,Y=z.windowMinutes!==void 0;if(X!==Y)return X?-1:1;if(X&&Y)return(z.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function H3($){let Z=($.classifyStatus??CZ)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let z=Q$($.quota,$.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||$.now-z>m0)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of IZ($.quota)){let J=Y.remainingPercent;if(typeof J==="number"&&Number.isFinite(J)&&J<=0)return{action:"migrate",reason:"exhausted",window:{scope:Y.scope,label:Y.label},...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{}}}let X=W0($.quota,$.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:Z}}function B3($,Z,z){let X=Math.max(0,$.remainingPercent-Z);if(X<=0)return 0;if(!$.resetsAt)return X;let Y=Date.parse($.resetsAt);if(!Number.isFinite(Y)||Y<=z)return X;let J=Math.max((Y-z)/3600000,EZ);return X/J}function AZ($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function O8($,Z){if(!$.quota)return;let z=Q$($.quota,$.quotaCheckedAt);if(z===void 0||Z-z>m0)return;let X=IZ($.quota).map((G)=>B3({remainingPercent:G.remainingPercent??Number.NaN,...G.resetsAt===void 0?{}:{resetsAt:G.resetsAt}},$.reservePercent[G.label]??0,Z)),Y=$.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))X.push(B3({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,Z));let J=X.length>0?Math.min(...X):0;return J>0?{candidate:$,quotaCheckedAt:z,weight:J}:void 0}function kZ($){let Z=$.candidates.filter((Y)=>Y.killswitchPasses!==!1);if($.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(Z.length===0)return;let z=Z.map((Y)=>O8(Y,$.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((J,G)=>{let B=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,G3),H=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,G3);return B-H||J.candidate.configuredOrder-G.candidate.configuredOrder||AZ(J.candidate.accountId,G.candidate.accountId)});let Y=z[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let X=[...Z].sort((Y,J)=>{let G=(Y.resetCreditsApplicable??0)>0?1:0;return((J.resetCreditsApplicable??0)>0?1:0)-G||Y.configuredOrder-J.configuredOrder||AZ(Y.accountId,J.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:Q$(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function K3($){let Z=m($),z=new Map(Z.admitted.map((V)=>[V.id,V])),X=new Map(Z.refused.map((V)=>[V.id,V])),Y=new Set(Z.excluded.map((V)=>V.id)),J=new Set($.rows.map((V)=>V.id)),G=$.pin!==void 0&&J3($.pin,J,$.identities?.get($.pin.accountId));if(G&&$.pin){let V=z.get($.pin.accountId);if(V&&$.killswitch?.get(V.id)!==!1)return{outcome:"dispatch",accountId:V.id,source:"pin",...V.projection?.checkedAt===void 0?{}:{quotaCheckedAt:V.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?X.get($.pin.accountId):void 0,H=G&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Q=(V)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(V):$.rowReservePercent?.get(V.id))??$.reservePercent??{}},K=$.scope,W=$.rows.map((V,j)=>({row:V,configuredOrder:j})).filter(({row:V})=>!Y.has(V.id)).map(({row:V,configuredOrder:j})=>{let M=$.killswitch?.get(V.id),L=$.resetCreditsApplicable?.get(V.id);return{accountId:V.id,quota:V.kind==="api-key"?void 0:z.get(V.id)?.projection??f(V.quota,K),reservePercent:Q(V),configuredOrder:j,...L===void 0?{}:{resetCreditsApplicable:L},...M===void 0?{}:{killswitchPasses:M}}}),U=[],D=G?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let V=kZ({candidates:W,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!V)break;let j=X.get(V.accountId);if(j){U.push(j),W=W.filter((L)=>L.accountId!==V.accountId);continue}let M=$.identities?.get(V.accountId);return{outcome:"dispatch",accountId:V.accountId,source:V.source,...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt},pin:G&&!H?{action:"retain"}:{action:"assign",pin:{accountId:V.accountId,inputBytes:$.requestBytes,...M===void 0?{}:{wireIdentity:M},...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt}}},refusedSelections:U,admission:Z}}return{outcome:"no-admissible-account",pin:D,refusedSelections:U,admission:Z}}import{createHash as P8}from"node:crypto";var L8=86400000,x8=300000,R8=3600000,S8=60000,T8=900000,A8=300000;function V3($){return $ instanceof Error?$.message:String($)}function E8($){let Z=$?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.name==="TimeoutError"||$.message.includes("fetch failed")||"code"in $&&($.code==="ECONNRESET"||$.code==="ECONNREFUSED"||$.code==="ETIMEDOUT"||$.code==="UND_ERR_CONNECT_TIMEOUT")}function D3($){let Z=V3($),z=$?.status;if(typeof z==="number")return z===429||z>=500;if(!($ instanceof Error))return!1;let X=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function fZ($){return P8("sha256").update($).digest("hex")}function bZ($){let Z=fZ($.refreshToken),X=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,Y,J=$.error?.retryAfter;if(typeof J==="number"&&J>0)Y=J*1000;else if(E8($.error))Y=Math.min(R8,x8*2**Math.min(X-1,6));else Y=L8;return{message:V3($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:X,tokenHash:Z}}function Q0($,Z,z){if(!$?.nextRetryAt||$.nextRetryAt<=z)return!1;if(!Z)return!0;return $.tokenHash===fZ(Z)}function V$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function g0($){let z=($.previous?.retryCount??0)+1,X,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(D3($.error))X=Math.min(T8,S8*2**Math.min(z-1,6));else X=A8;return{message:V3($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function S0($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function q3($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let z=Date.parse($);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{createServer as yZ}from"node:http";import{setTimeout as C8}from"node:timers/promises";var N$="app_EMoamEEZ73f0CkXaXp7hrann",D0="https://auth.openai.com",l0=1455,I8=3000,k8="cortexkit-opencode-openai-auth";function vZ($){return`${k8}/${$}`}var gZ="main",f8=`"${gZ}" is a reserved account id; choose a different label.`;function pZ($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function b8(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=pZ(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function wZ($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let z=Z[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function hZ($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let z=$["https://api.openai.com/auth"];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.chatgpt_account_id==="string"&&z.chatgpt_account_id.length>0)return z.chatgpt_account_id;let X=$.organizations;if(Array.isArray(X)){let Y=X[0];if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string"&&Y.id.length>0)return Y.id}return}function q$($){if($.id_token){let Z=wZ($.id_token),z=Z&&hZ(Z);if(z)return z}if($.access_token){let Z=wZ($.access_token);return Z?hZ(Z):void 0}return}function y8($){return typeof $==="string"&&$.toLowerCase()===gZ}function F3($){if(y8($))throw Error(f8);return $}function w8($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:N$,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${D0}/oauth/authorize?${X.toString()}`}async function h8($,Z,z){let X=await fetch(`${D0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:N$,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function m8($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var v8=`<!doctype html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<title>CortexKit OpenAI Auth - Authorization Successful</title>
|
|
5
|
+
<style>
|
|
6
|
+
body {
|
|
7
|
+
font-family:
|
|
8
|
+
system-ui,
|
|
9
|
+
-apple-system,
|
|
10
|
+
sans-serif;
|
|
11
|
+
display: flex;
|
|
12
|
+
justify-content: center;
|
|
13
|
+
align-items: center;
|
|
14
|
+
height: 100vh;
|
|
15
|
+
margin: 0;
|
|
16
|
+
background: #131010;
|
|
17
|
+
color: #f1ecec;
|
|
18
|
+
}
|
|
19
|
+
.container {
|
|
20
|
+
text-align: center;
|
|
21
|
+
padding: 2rem;
|
|
22
|
+
}
|
|
23
|
+
h1 {
|
|
24
|
+
color: #f1ecec;
|
|
25
|
+
margin-bottom: 1rem;
|
|
26
|
+
}
|
|
27
|
+
p {
|
|
28
|
+
color: #b7b1b1;
|
|
29
|
+
}
|
|
30
|
+
</style>
|
|
31
|
+
</head>
|
|
32
|
+
<body>
|
|
33
|
+
<div class="container">
|
|
34
|
+
<h1>Authorization Successful</h1>
|
|
35
|
+
<p>You can close this window and return to OpenCode.</p>
|
|
36
|
+
</div>
|
|
37
|
+
<script>
|
|
38
|
+
setTimeout(() => window.close(), 2000)
|
|
39
|
+
</script>
|
|
40
|
+
</body>
|
|
41
|
+
</html>`,D$=($)=>`<!doctype html>
|
|
42
|
+
<html>
|
|
43
|
+
<head>
|
|
44
|
+
<title>CortexKit OpenAI Auth - Authorization Failed</title>
|
|
45
|
+
<style>
|
|
46
|
+
body {
|
|
47
|
+
font-family:
|
|
48
|
+
system-ui,
|
|
49
|
+
-apple-system,
|
|
50
|
+
sans-serif;
|
|
51
|
+
display: flex;
|
|
52
|
+
justify-content: center;
|
|
53
|
+
align-items: center;
|
|
54
|
+
height: 100vh;
|
|
55
|
+
margin: 0;
|
|
56
|
+
background: #131010;
|
|
57
|
+
color: #f1ecec;
|
|
58
|
+
}
|
|
59
|
+
.container {
|
|
60
|
+
text-align: center;
|
|
61
|
+
padding: 2rem;
|
|
62
|
+
}
|
|
63
|
+
h1 {
|
|
64
|
+
color: #fc533a;
|
|
65
|
+
margin-bottom: 1rem;
|
|
66
|
+
}
|
|
67
|
+
p {
|
|
68
|
+
color: #b7b1b1;
|
|
69
|
+
}
|
|
70
|
+
.error {
|
|
71
|
+
color: #ff917b;
|
|
72
|
+
font-family: monospace;
|
|
73
|
+
margin-top: 1rem;
|
|
74
|
+
padding: 1rem;
|
|
75
|
+
background: #3c140d;
|
|
76
|
+
border-radius: 0.5rem;
|
|
77
|
+
}
|
|
78
|
+
</style>
|
|
79
|
+
</head>
|
|
80
|
+
<body>
|
|
81
|
+
<div class="container">
|
|
82
|
+
<h1>Authorization Failed</h1>
|
|
83
|
+
<p>An error occurred during authorization.</p>
|
|
84
|
+
<div class="error">${m8($)}</div>
|
|
85
|
+
</div>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`,F$=[],p0,c=new Map;function mZ($,Z){return new Promise((z,X)=>{let Y=(G)=>{$.off("listening",J),X(G)},J=()=>{$.off("error",Y),z()};$.once("error",Y),$.once("listening",J),$.listen(l0,Z)})}function lZ($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function U0(){return c.size}function q0($){if(c.delete($),U0()===0)V0()}async function g8(){let $=`http://localhost:${l0}/auth/callback`;if(F$.length>0)return{port:l0,redirectUri:$};if(p0)return p0;p0=(async()=>{let Z=(J,G)=>{let B=new URL(J.url||"/",`http://127.0.0.1:${l0}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),Q=B.searchParams.get("state"),K=B.searchParams.get("error"),W=B.searchParams.get("error_description");if(K){let D=W||K;if(Q){let V=c.get(Q);if(V)V.reject(Error(D)),q0(Q);else if(U0()===0)V0()}else if(U0()===0)V0();G.writeHead(200,{"Content-Type":"text/html"}),G.end(D$(D));return}if(!Q){if(U0()===0)V0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(D$("Missing state parameter"));return}if(!H){if(U0()===0)V0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(D$("Missing authorization code"));return}let U=c.get(Q);if(!U){if(U0()===0)V0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(D$("Unknown state — authorization may have expired"));return}q0(Q),h8(H,$,U.pkce).then((D)=>U.resolve(D)).catch((D)=>U.reject(D)),G.writeHead(200,{"Content-Type":"text/html"}),G.end(v8);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),Q=H?[H]:[...c.keys()];G.writeHead(200),G.end("Login cancelled");for(let K of Q){let W=c.get(K);if(!W)continue;W.reject(Error("Login cancelled")),q0(K)}if(U0()===0)V0();return}G.writeHead(404),G.end("Not found")},z=yZ(Z);await mZ(z,"127.0.0.1");let X=[z],Y=yZ(Z);try{await mZ(Y,"::1"),X.push(Y)}catch(J){let G=J.code;if(G!=="EADDRNOTAVAIL"&&G!=="EAFNOSUPPORT")throw lZ(z),J}return F$=X,{port:l0,redirectUri:$}})();try{return await p0}finally{p0=void 0}}function V0(){let $=F$;F$=[];for(let Z of $)lZ(Z)}function p8($,Z,z=300000,X){return new Promise((Y,J)=>{if(X?.aborted){q0(Z),J(Error("Login cancelled"));return}let G=setTimeout(()=>{if(c.get(Z))q0(Z),J(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(G),c.get(Z))q0(Z),J(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);c.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(G),X)X.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(G),X)X.removeEventListener("abort",B);J(H)}})})}async function l8($){let Z=await fetch(`${D0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":vZ($)},body:JSON.stringify({client_id:N$})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${D0}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function d8($,Z,z){let X=Math.max(parseInt($.interval,10)||5,1)*1000,Y=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),J=!Number.isNaN(Y)&&Y>0?Y*1000:900000,G=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>J)throw Error("Device authorization expired");let B=await fetch(`${D0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":vZ(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let K=await B.json(),W=await fetch(`${D0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:K.authorization_code,redirect_uri:`${D0}/deviceauth/callback`,client_id:N$,code_verifier:K.code_verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let H=J-(Date.now()-G);if(H<=0)throw Error("Device authorization expired");let Q=Math.min(X+I8,H);try{await C8(Q,void 0,{signal:z})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw Error("Device authorization cancelled");throw K}}}async function H7($){let{label:Z,headless:z=!1,signal:X,version:Y}=$;if(F3(Z),z){let{deviceData:K,url:W,instructions:U}=await l8(Y),D=(async()=>{let V=await d8(K,Y,X),j=Date.now(),M=q$(V);return{id:F3(Z||M||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:j+(V.expires_in??3600)*1000,enabled:!0,addedAt:j,lastUsed:j,lastRefreshedAt:j,accountId:M}})();return{url:W,instructions:U,completion:D}}let{redirectUri:J}=await g8(),G=await b8(),B=pZ(crypto.getRandomValues(new Uint8Array(32)).buffer),H=w8(J,G,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let K=await p8(G,B,void 0,X),W=Date.now(),U=q$(K);return{id:F3(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:W+(K.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:U}}finally{q0(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function M$($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let X=Z<100000000000?Z*1000:Z,Y=new Date(X);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let z=new Date($);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function N3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function dZ($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function cZ($,Z){let z=$.get(Z);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let Y=Z.slice(0,-13),J=N3($.get(`${Y}-window-minutes`)),G=M$($.get(`${Y}-reset-at`)??void 0);if(X===0&&$.get(`${Y}-window-minutes`)==="0"&&!G)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:G,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}var aZ=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function nZ($,Z){let z=$.get(Z);if(z===null)return"absent";if(z.trim()==="")return"invalid";let X=Number(z);return Number.isFinite(X)&&X>=0&&X<=100?"valid":"invalid"}function W7($){if(aZ.some((J)=>nZ($,J)==="invalid"))return{};let Z={},z=cZ($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=cZ($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;let Y=c8($);if(Y)Z.credits=Y;return Z}function uZ($,Z){let z=$.get(Z)?.trim();if(z===void 0)return;if(z.toLowerCase()==="true"||z==="1")return!0;if(z.toLowerCase()==="false"||z==="0")return!1;return}function c8($){let Z=uZ($,"x-codex-credits-has-credits"),z=uZ($,"x-codex-credits-unlimited");if(Z===void 0||z===void 0)return;let X=o($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:z,...X!==void 0?{balance:X}:{},checkedAt:Date.now()}}function Q7($){let Z=aZ.map((z)=>nZ($,z));return Z.includes("valid")&&!Z.includes("invalid")}function iZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=N3($.window_minutes),z=M$($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function U7($){let Z={},z=iZ($.rate_limits?.primary);if(z)Z.primary=z;let X=iZ($.rate_limits?.secondary);if(X)Z.secondary=X;let Y=u8($.credits);if(Y)Z.credits=Y;return Z}function u8($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let z=o(typeof Z.balance==="string"?Z.balance.trim():Z.balance);return{hasCredits:Z.has_credits,unlimited:Z.unlimited,...z!==void 0?{balance:z}:{},...typeof Z.overage_limit_reached==="boolean"?{overageLimitReached:Z.overage_limit_reached}:{},checkedAt:Date.now()}}function o($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function sZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=N3($.limit_window_seconds),z=M$($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function oZ($){let Z={},z=sZ($.rate_limit?.primary_window);if(z)Z.primary=z;let X=sZ($.rate_limit?.secondary_window);if(X)Z.secondary=X;let Y=dZ($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let J=dZ($.rate_limit_reset_credits?.applicable_available_count);if(J!==void 0)Z.resetCreditsApplicable=J;let G=$.spend_control?.individual_limit;if($.spend_control===null||G===null)Z.spendControlCleared=!0;if(G&&typeof $.spend_control?.reached==="boolean"){let H=o(G.limit),Q=o(G.used),K=o(G.remaining),W=o(G.used_percent),U=o(G.remaining_percent);if(H!==void 0&&Q!==void 0&&K!==void 0&&W!==void 0&&U!==void 0)Z.spendControl={limit:H,used:Q,remaining:K,usedPercent:W,remainingPercent:U,resetsAt:M$(G.reset_at),unit:G.unit,source:G.source,reached:$.spend_control.reached}}let B=$.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let H=o(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as Z1}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as i8}from"@cortexkit/claustrum-client";import{SocketClosedError as s8,SocketTimeoutError as a8,SubcCallError as n8}from"@cortexkit/subc-client";class q extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var M3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class C extends q{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function r($){if($ instanceof C||$ instanceof s8||$ instanceof a8)return"unreachable";let Z=$ instanceof i8||$ instanceof n8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(M3,Z))return"answered";return M3[Z]}import{resolve as rZ}from"node:path";import{storeIdentity as o8}from"@cortexkit/claustrum-client";import{SubcClient as tZ}from"@cortexkit/subc-client";var T0=300000,j$=300000,j3=1000;class d0{#$;#Z=0;restart(){this.#Z=0}continuous($){let Z=$.kind==="changed"&&$.seq===this.#Z+1&&(this.#$===void 0||$.epoch===this.#$);return this.#$=$.epoch,this.#Z=$.seq,Z}}class _${#$;#Z;#G;#B=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#G}request(){if(this.#G)return this.#B=!0,this.#G;return this.#G=(async()=>{do{this.#B=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#B)})().finally(()=>{this.#G=void 0}),this.#G}}class O${#$;#Z=new d0;#G;#B="polling";#Y;#W;#X=!1;#z;#M=!1;#J=0;constructor($){this.#$=$,this.#G=new _$(async()=>{let Z=this.#M;if(this.#M=!1,Z||this.#z!==this.#$.view())await this.#$.discover(this.#z??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#B}start(){if(this.#X||this.#Y||this.#W)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Q("fallback","client-without-watch");return}this.#q(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#W)(this.#$.clearTimeoutImpl??clearTimeout)(this.#W);this.#W=void 0;let $=this.#Y;this.#Y=void 0,$?.handle.stop()}#Q($,Z){if(this.#B===$)return;this.#B=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#D($,Z){this.#W=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#W=void 0,!this.#X)Z()},$),this.#W.unref?.()}async#q($){let Z;try{Z=await this.#$.enrollmentToken()}catch(G){if(this.#X)return;this.#$.onError?.(G),this.#F("token-unreadable");return}let z=this.#$.client.watchScoped;if(this.#X||this.#Y||!z)return;this.#Z.restart(),this.#M=$;let X,Y;try{Y=z.call(this.#$.client,(G)=>{if(this.#X||!X||this.#Y!==X)return;if(X.notices++,X.notices===1)this.#$.onReachable?.(),X.acceptedAt=(this.#$.now??Date.now)(),this.#Q("watching","accepted");if(!this.#Z.continuous(G))this.#M=!0;this.#z=G.view,this.#G.request()},{enrollmentToken:Z})}catch(G){this.#$.onError?.(G),this.#F("watch-failed");return}X={handle:Y,notices:0},this.#Y=X,this.#Q("polling",$?"resubscribing":"opening");let J=X;Y.closed.then((G)=>this.#H(J,G),(G)=>this.#H(J,{kind:"transport_lost",error:G}))}#H($,Z){if(this.#X||this.#Y!==$)return;if(this.#Y=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#Q("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("refused");try{this.#$.onRefused(Z.error)}catch(z){this.#$.onError?.(z)}return}if($.notices>0){let z=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&z-$.acceptedAt>=300000)this.#J=0;let X=Math.min(1000*2**Math.min(this.#J,16),300000);this.#J++,this.#Q("polling","resubscribing"),this.#D(X,()=>void this.#q(!0));return}this.#F(Z.kind)}#F($){this.#Q("fallback",$),this.#D(300000,()=>void this.#q(!1))}}function $4($){let Z=$.identity??o8($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let z,X=!1,Y,J=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),G=(async()=>{if(z=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await tZ.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),X)throw z.close(),Error("insula usage timeout");let B=await z.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await z.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([G,J])}finally{X=!0,clearTimeout(Y),z?.close()}},watchUsage(z){let X,Y,J=!1,G=(async()=>{let B,H=new Promise((K,W)=>{B=setTimeout(()=>W(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),Q=(async()=>{let K=Math.min($.handshakeTimeoutMs??3000,3000),W=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:K}):await tZ.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:K});if(X=W,J){W.close();return}let U=await W.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(J){W.close();return}Y=W.subscribe(U,{method:"usage.watch"},z)})();try{await Promise.race([Q,H])}catch(K){throw J=!0,K}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{J=!0,X?.close()});return{stop(){if(J)return;J=!0,Y?.unsubscribe(),X?.close()},closed:G}}}}var L$=60000,eZ=4*L$,r8=2*L$,_3=new Map,P$=new Map;function A0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function t8($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!A0(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function e8($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class Z4{transport;key;#$=[];#Z=!1;#G=new Set;#B=new Map;#Y=new _$(async()=>{try{let $=await this.transport.getUsage();if(!A0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>A0(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#G=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#G)this.#B.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#G.clear()}},()=>{});#W=new d0;#X="polling";#z=0;#M=0;#J=new Map;#Q;#D;#q={};#H=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Y.running)return this.#Y.running;if(this.#X==="watching")return Promise.resolve();for(let[z,X]of P$)if($-X>=L$)P$.delete(z);let Z=P$.get(this.key);if(Z!==void 0&&$-Z<L$)return Promise.resolve();return P$.set(this.key,$),this.#Y.request()}watchMode(){return this.#X}watch($={}){this.#z++;let Z=$.provider;if(Z===void 0)this.#M++;else this.#J.set(Z,(this.#J.get(Z)??0)+1);if(this.#z===1)this.#q=$,this.#_();let z=!1;return()=>{if(z)return;if(z=!0,Z===void 0)this.#M--;else{let X=(this.#J.get(Z)??1)-1;if(X>0)this.#J.set(Z,X);else this.#J.delete(Z)}if(--this.#z===0)this.#F()}}#F(){if(this.#D)(this.#q.clearTimeoutImpl??clearTimeout)(this.#D);this.#D=void 0;let $=this.#Q;this.#Q=void 0,$?.handle?.stop(),this.#X="polling"}#N($){this.#D=(this.#q.setTimeoutImpl??setTimeout)(()=>{if(this.#D=void 0,this.#z>0&&!this.#Q)this.#_()},$),this.#D.unref?.()}#_(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#W.restart();let Z={notices:0};this.#Q=Z;let z;try{z=$.call(this.transport,(X)=>this.#S(Z,X))}catch(X){this.#P(Z,X);return}Z.handle=z,z.closed.then(()=>this.#P(Z,void 0),(X)=>this.#P(Z,X))}#S($,Z){if(this.#Q!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#H=0;let z=t8(Z);if(!z)this.#W.restart();if(!(z?this.#W.continuous(z):!1)||z?.provider===void 0||this.#M>0||this.#J.has(z.provider))this.#Y.request()}#P($,Z){if(this.#Q!==$)return;this.#Q=void 0;let z=e8(Z);if(z==="unknown_method"||z==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let X=Math.min(j3*2**Math.min(this.#H,16),j$);this.#H++,this.#X="polling",this.#N(X);return}if(this.#X="fallback",this.#Y.request(),Z===void 0||r(Z)==="unreachable")this.#N(j$)}current($,Z,z){for(let X of this.#$){if(X.provider!==$||typeof X.account!=="string"||X.account.trim()!==Z)continue;if(X.stale!==void 0||X.errorClass!==void 0||!A0(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=eZ)continue;return{entry:X,context:{fetchedAt:Y,...typeof X.source==="string"&&{source:X.source}}}}return}lookup($,Z,z){if(!this.#Z)return{miss:"unreachable"};let X=this.#$.find((G)=>G.provider===$&&typeof G.account==="string"&&G.account.trim()===Z),Y=(X??this.#$.find((G)=>G.provider===$&&G.account===void 0&&G.errorClass!==void 0))?.errorClass;if(Y==="upstream_failed")return{miss:"upstream-failed"};if(Y==="credential_absent"||Y==="credential_unusable"||Y==="credential_rejected")return{miss:"credential"};if(Y!==void 0)return{miss:"unreachable"};if(X){let G=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!A0(X.usage)||!Number.isFinite(G))return{miss:"unreachable"};let B={entry:X,context:{fetchedAt:G,...typeof X.source==="string"&&{source:X.source}}};if(X.stale!==void 0&&(!A0(X.stale)||X.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:B};return z>=G+eZ||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#G.has($))return{miss:"absent"};let J=this.#B.get($)??z;return this.#B.set($,J),{miss:z-J>=r8?"unreachable":"cold"}}}function O3($,Z){let z=JSON.stringify([rZ($.connectionFile),rZ(Z)]),X=_3.get(z);if(!X)X={source:new Z4($,z),refs:0},_3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)_3.delete(z)}}}import{ClaustrumCredentialError as Xz}from"@cortexkit/claustrum-client";function F0($){let Z=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:B,listener:H}of z)B.removeEventListener("abort",H);z.length=0},J=(B)=>{if(X||Z.signal.aborted)return;Z.abort(B),Y()},G=$.find((B)=>B.aborted);if(G)return Z.abort(G.reason),{signal:Z.signal,dispose:Y};for(let B of $){if(Z.signal.aborted)break;let H=()=>J(B.reason);if(z.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)J(B.reason)}return{signal:Z.signal,dispose:Y}}import{channel as L9}from"node:diagnostics_channel";import{ClaustrumCredentialError as A4}from"@cortexkit/claustrum-client";import{createHash as Y9,randomBytes as J9,randomUUID as G9}from"node:crypto";import{constants as z4}from"node:fs";import{chmod as B9,mkdir as H9,open as W4,readFile as L3,realpath as K9,rename as W9,stat as Q4,unlink as S3}from"node:fs/promises";import{basename as U4,dirname as e,extname as X4,isAbsolute as Y4,join as T3,resolve as Q9}from"node:path";import{ClaustrumCredentialError as U9,ClaustrumClient as V9,writeEnrollmentTokenFile as D9}from"@cortexkit/claustrum-client";import{lstat as $9}from"node:fs/promises";import{resolve as Z9}from"node:path";async function z9($){try{let Z=await $9($);return Z.isFile()?Z:void 0}catch(Z){return Z.code==="ENOENT"?"absent":void 0}}function X9($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class P3{#$=new Map;async read($,Z,z){let X=$.map((Q)=>Z9(Q)),Y=JSON.stringify(X),J=await Promise.all(X.map(z9)),G=J.every((Q)=>Q!==void 0)?J:void 0,B=this.#$.get(Y);if(G&&B&&G.every((Q,K)=>{let W=B.identities[K];return W!==void 0&&X9(Q,W)}))return z?.(G),B.value;this.#$.delete(Y);let H=await Z(X);if(G){if(this.#$.size>=64){let Q=this.#$.keys().next().value;if(Q!==void 0)this.#$.delete(Q)}this.#$.set(Y,{identities:G,value:H})}return H}}var q9=1,R$=16384,V4=30000,A3=/^[0-9a-f]{64}$/,D4="unknown_method",q4=new Set([D4,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),F4=new Set(["pending_queue_full"]);function x3($){if(!($ instanceof U9))return;if(q4.has($.code))return{code:$.code,disposition:"terminal"};if(F4.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function F9($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new q("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function N9($){return V9.connect($)}function N4($){let Z=X4($)||".json",z=U4($,X4($));return{statePath:T3(e($),`${z}-state${Z}`),tokenPath:$}}function M9($){let Z=$.override?.trim();if(Z&&!Y4(Z)&&!$.cwd)throw new q("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=Z?Y4(Z)?Z:Q9($.cwd,Z):T3($.stateDir,`${$.host}-enrollment.json`);return N4(z)}function M4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function x$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function j4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function c0(){return new q("invalid-state","invalid Claustrum enrollment state")}function T$($){if(!M4($)||$.version!==q9||typeof $.proposedName!=="string"||$.proposedName.length===0)throw c0();if($.phase==="pending"){if(!A3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!x$($.createdAt)||!x$($.updatedAt))throw c0();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)||!j4($.tokenGeneration)||!x$($.updatedAt))throw c0();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"||!x$($.updatedAt))throw c0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw c0()}function E3($){if(!M4($)||!A3.test(String($.token??""))||!j4($.token_generation))throw new q("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function _4($){if(!$.isFile())throw new q("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new q("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new q("unsafe-file","Claustrum enrollment file must be owned by the current user")}function J4($){try{return JSON.parse($)}catch{throw new q("invalid-state","Claustrum enrollment file is not valid JSON")}}async function $0($){if(Z0)try{await R3(e($));let z=await S$($,!0);if(Buffer.byteLength(z)>R$)throw new q("unsafe-file","Claustrum enrollment file is too large");return J4(z)}catch(z){if(z.code==="ENOENT")return;throw z}let Z;try{Z=await W4($,z4.O_RDONLY|z4.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new q("unsafe-file","Claustrum enrollment file could not be opened safely")}try{_4(await Z.stat());let z=Buffer.alloc(R$+1),{bytesRead:X}=await Z.read(z,0,z.byteLength,0);if(X>R$)throw new q("unsafe-file","Claustrum enrollment file is too large");return J4(z.subarray(0,X).toString("utf8"))}finally{await Z.close()}}function G4($,Z){let z=[];for(let X of $.split(`
|
|
88
|
+
`)){if(X.trim()===""||X.startsWith("#"))continue;let Y=X.split(":");if(Y.length!==Z||!/^[^\s:,]+$/.test(Y[0]??"")||!/^\d+$/.test(Y[2]??"")||!Number.isSafeInteger(Number(Y[2]))||Z===7&&(!/^\d+$/.test(Y[3]??"")||!Number.isSafeInteger(Number(Y[3])))||Z===4&&Y[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(Y[3]??""))return;z.push(Y)}return z}async function j9($,Z,z){try{let[X,Y]=await Promise.all([L3(z.passwdPath??"/etc/passwd","utf8"),L3(z.groupPath??"/etc/group","utf8")]),J=G4(X,7),G=G4(Y,4);if(!J||!G)return!1;let B=J.filter((W)=>Number(W[2])===$),H=G.filter((W)=>Number(W[2])===Z);if(B.length!==1||H.length!==1)return!1;let Q=B[0]?.[0],K=H[0]?.[3]??"";return(K===""||K.split(",").every((W)=>W===Q))&&!J.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function O4($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>L3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function P4($,Z={}){if(!Z0){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await K9($)}catch{return}let J;for(;;){let G=await Q4(Y).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(J===void 0)J=X!==void 0&&await j9(z,X,Z);if((G.mode&2)!==0||G.uid!==z||G.gid!==X||!J)throw new q("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=e(Y);if(B===Y)return;Y=B}}try{await H4($,O4(Z))}catch(z){if(!(z instanceof v0))throw z;throw new q("unsafe-file",`Claustrum enrollment parent refused: ${z.path} (${z.reason??z.code}). Use a folder that other users cannot write or replace.`)}}async function E0($,Z={},z="enrollment directory"){if(Z0){await R3($,!1,O4(Z));return}await H9($,{recursive:!0,mode:448});let X=await Q4($),Y=process.geteuid?.();if(Y!==void 0&&X.uid!==Y)throw new q("unsafe-file",`Claustrum ${z} must be owned by the current user`);if((X.mode&63)!==0)await B9($,448)}async function N0($,Z,z={}){let X=e($);await E0(X,z),await P4(X,z);let Y=`${JSON.stringify(Z)}
|
|
89
|
+
`;if(Buffer.byteLength(Y)>R$)throw new q("invalid-state","Claustrum enrollment state is too large");if(Z0)return K4($,Y);let J=T3(X,`.${U4($)}.${process.pid}.${G9()}.tmp`),G,B=!1;try{G=await W4(J,"wx",384),B=!0,await G.writeFile(Y,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await W9(J,$),B=!1}finally{if(await G?.close().catch(()=>{}),B)await S3(J).catch(()=>{})}}var _9=new P3;async function C3($,Z){let z=Z0?await B4($,Z):await _9.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,J=$.statePath])=>B4({tokenPath:Y,statePath:J},Z),(Y)=>{for(let J of Y)if(J!=="absent")_4(J)}),X={...z.status};if(z.usesProposedName&&X.state==="approved")X.proposedName=Z;return X}async function B4($,Z){let z=await $0($.tokenPath),X=z===void 0?void 0:E3(z),Y=await $0($.statePath),J=Y===void 0?void 0:T$(Y);if(X)return{usesProposedName:J===void 0,status:{state:"approved",proposedName:J?.proposedName??Z,...J?.phase==="approved"&&J.approvedName!==void 0&&{approvedName:J.approvedName},tokenGeneration:X.token_generation}};if(!J)return{status:{state:"idle"},usesProposedName:!1};if(J.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:J.proposedName,code:"missing_token"}};return{status:t(J),usesProposedName:!1}}async function O9($,Z){let z;try{z=await C3($,Z)}catch(X){if(!(X instanceof q)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await $0($.statePath);if(Y===void 0)return"unreadable";let J=T$(Y);return J.phase==="approved"&&J.proposedName===Z?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in z&&z.proposedName!==Z)return"unreadable";if(z.state==="approved"||z.state==="blocked"&&z.code==="missing_token")return"vault";return"local"}async function z0($){let Z=await $0($);if(Z===void 0)throw new q("not-enrolled","Claustrum enrollment is not configured");return E3(Z)}function t($){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 L4(){return new q("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class x4{#$;#Z;#G;#B;#Y;#W;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#G=$.proposedName,this.#B=$.now??Date.now,this.#Y=$.mintSecret??(()=>J9(32).toString("hex")),this.#W=$.writeTokenFile??D9}async status(){return C3(this.#Z,this.#G)}async resetTerminal(){return R4(this.#Z,this.#G)}async#z($,Z){let z={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#B()};return await N0(this.#Z.statePath,z,this.#X),t(z)}async reconcile(){await E0(e(this.#Z.statePath),this.#X);let $=await b({name:"ceremony",path:this.#Z.statePath,ttlMs:V4,renew:!0});if(!$)return{state:"busy"};try{let Z=await $0(this.#Z.tokenPath),z=Z===void 0?void 0:E3(Z),X=await $0(this.#Z.statePath),Y=X===void 0?void 0:T$(X);if(Y&&Y.proposedName!==this.#G)throw L4();if(z){if(!Y||Y.phase==="pending"){let G={version:1,phase:"approved",proposedName:Y?.proposedName??this.#G,tokenGeneration:z.token_generation,updatedAt:this.#B()};await N0(this.#Z.statePath,G,this.#X),Y=G}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:z.token_generation}}if(Y?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#B()};return await N0(this.#Z.statePath,G,this.#X),t(G)}if(Y&&Y.phase!=="pending")return t(Y);if(!Y){let G=this.#B();if(Y={version:1,phase:"pending",proposedName:this.#G,requestSecret:this.#Y(),createdAt:G,updatedAt:G},!A3.test(Y.requestSecret))throw new q("invalid-state","invalid minted Claustrum enrollment secret");await N0(this.#Z.statePath,Y,this.#X)}if(!Y.requestId)try{let G=Y9("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B=await this.#$.enrollPropose({name:Y.proposedName,requestSecretHash:G});Y={...Y,requestId:B.requestId,updatedAt:this.#B()},await N0(this.#Z.statePath,Y,this.#X)}catch(G){let B=x3(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};if(B.code===D4)return await $.assertOwned(),await S3(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#z(Y,B.code)}let J=Y.requestId;if(!J)return t(Y);try{let G=await this.#$.enrollPoll({requestId:J,requestSecret:Y.requestSecret});if(G.status==="pending")return t(Y);if(G.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#B()};return await N0(this.#Z.statePath,H,this.#X),t(H)}await E0(e(this.#Z.tokenPath),this.#X),await P4(e(this.#Z.tokenPath),this.#X),await this.#W(this.#Z.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,updatedAt:this.#B()};return await N0(this.#Z.statePath,B,this.#X),t(B)}catch(G){let B=x3(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:J,retryCode:B.code};return this.#z(Y,B.code)}}finally{await $.release()}}}async function R4($,Z){await E0(e($.statePath));let z=await b({name:"ceremony",path:$.statePath,ttlMs:V4,renew:!0});if(!z)return"busy";try{if(await $0($.tokenPath)!==void 0)return"refused-approved";let X=await $0($.statePath);if(X===void 0)return"idle";let Y=T$(X);if(Y.proposedName!==Z)throw L4();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await S3($.statePath),"reset"}finally{await z.release()}}var u0="claustrum-tombstone:v1:";function A$($){return`${u0}${$}`}function I3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function E$($){return typeof $==="string"&&$.startsWith(u0)}function S4($,Z){if(!I3($)||$.type!=="oauth")return!1;return $.refresh===A$(Z)}function T4($,Z){if(S4($,Z))return"placeholder";if(I3($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!E$($.refresh))return"login";if(I3($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function P9($){let Z=T4($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new q("host-slot-login",`${$.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if($.mode==="local"&&Z==="placeholder")throw new q("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function C0($,Z){let z=!1;return(X)=>{if(z)return;if(!Z||Z.aborted)z=!0;$.warn("claustrum shutdown drain timed out",{pendingOperations:X})}}async function I0($,Z){if(!$.size)return;let z,X=!1,Y=(async()=>{while(!X&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([Y,new Promise((J)=>{z=setTimeout(()=>{X=!0,J()},2000)})]),X&&$.size)Z($.size)}finally{X=!0,clearTimeout(z)}}function E4($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function x9($,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 f3=A("claustrum"),X0=L9("common-auth.claustrum.phases");function y3($,Z,z,X=f3){let Y=E4(Z,z);return X.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:x9(Z,z)}),Y}var b3=300000,C4=60000;function k3(){return new q("invalid-material","Claustrum returned invalid credential material")}function R9($){let Z=$.trim();if(Z.startsWith("{")){let z;try{z=JSON.parse(Z)}catch{throw k3()}if(!z||typeof z!=="object")throw k3();let X=z,Y=X.access_token??X.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(u0))throw k3();return Z}function S9($,Z){let z={kind:"not-mine"};if(!$.operations.includes("read"))return z;if(!$.categories.includes(Z.category))return z;if("classify"in Z){let X=T9($),Y;switch(X.authMethod){case"apikey":Y="api_key";break;case"chatgpt":case"antigravity":case"oauth":Y="oauth";break;default:return{kind:"refused",code:"unknown-auth-method"}}let J={credentialId:$.id,credentialType:Y,categories:$.categories,refreshAdapter:$.refreshAdapter,...X};if(J.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let G=Z.classify(J);if(G.kind==="not-mine")return z;if(G.kind==="mine"&&typeof G.member==="string")return{kind:"mine",type:Y,member:G.member};if(G.kind==="refused"&&typeof G.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(G.code)&&!G.code.includes(`
|
|
90
|
+
`)&&Z.refusalCodes.includes(G.code))return{kind:"refused",code:G.code}}catch{}return{kind:"refused",code:"unclassified"}}if($.credentialType!=="oauth"&&$.credentialType!=="api_key")return z;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?{kind:"mine",type:"oauth"}:z;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?{kind:"mine",type:"api_key"}:z;return z}function T9($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function A9($){let{grants:Z,grantTuples:z}=$;if(Z===void 0||z===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(z.map(({selectorKind:X,selector:Y,operation:J})=>Object.freeze({selectorKind:X,selector:Y,operation:J})))})}class k0{#$;#Z;#G;#B;#Y;#W;#X;#z=new WeakMap;#M=new WeakMap;#J=new Map;#Q=new WeakMap;#D;#q;#H=!1;#F=new C;#N;#_=!1;#S=-1/0;#P=2000;#K=!1;#j;#x=new Set;#U=new Set;#O;#L;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>z0(Z);else throw new q("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#B=$.family,this.#Y=$.parseIdentity,this.#W=$.requireAssertion??!1,this.#G=$.now??Date.now,this.#X=$.logger??f3,this.#O=C0(this.#X),this.#D=$.setTimeoutImpl??setTimeout,this.#q=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#K||this.#H)return;this.#H=!0,this.#F=$ instanceof A4?$:new C,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#R()}reachable(){if(this.#K||!this.#H)return;if(this.#H=!1,this.#N)this.#q(this.#N);this.#N=void 0,this.#P=2000;for(let $ of this.#J.values())$.since=null;(this.#X.info??f3.info)("vault receipt serving resumed",{reason:"reachable"})}#R(){if(this.#K||!this.#H||this.#N||this.#_)return;this.#N=this.#D(()=>{this.#N=void 0,this.#E(!0)},this.#P),this.#N.unref?.()}#E($=!1){if(this.#K||!this.#H||this.#_)return;if(this.#G()-this.#S<1000){this.#R();return}this.#S=this.#G(),this.#_=!0,this.#C().catch(()=>{if($&&this.#H)this.#P=Math.min(this.#P*2,30000)}).finally(()=>{this.#_=!1,this.#R()})}#V($){if(this.#K)throw new q("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#T($){if(this.#V($),X0.hasSubscribers)X0.publish({logger:this.#X,phase:"token read begin"});let Z=this.#Z();this.#U.add(Z);let z;try{z=await Z}finally{if(this.#U.delete(Z),X0.hasSubscribers)X0.publish({logger:this.#X,phase:"token read end"})}if(this.#V($),!/^[0-9a-f]{64}$/.test(z.token)||!Number.isSafeInteger(z.token_generation)||z.token_generation<1)throw new q("invalid-token","Invalid Claustrum enrollment token");return z.token}async#A($,Z){this.#V(Z);let z,X;try{let Y=$();z=Z?await Promise.race([Y,new Promise((J,G)=>{let B=()=>G(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),X=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await Y}catch(Y){if(this.#V(Z),r(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof A4)throw Y;if(r(Y)==="unreachable")throw new C;throw new q("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#V(Z),this.reachable(),z}async discover($){let Z=await this.#C($);return this.#j=Z.view,Z}async#C($){let Z,z;try{z=await this.#T($)}catch(K){throw this.#J.clear(),K}if(X0.hasSubscribers)X0.publish({logger:this.#X,phase:"list scoped begin"});try{Z=await this.#A(()=>this.#$.listScoped(z),$)}catch(K){throw this.listFailed(K),K}finally{if(X0.hasSubscribers)X0.publish({logger:this.#X,phase:"list scoped end"})}let X=[],Y=[],J=0,G=[],B=new Map;for(let K of Z.rows){let W=S9(K,this.#B);if(W.kind==="not-mine"){J++;continue}if(W.kind==="refused"){Y.push({...K.id.trim()&&{credentialId:K.id},code:W.code});continue}G.push({row:K,type:W.type,...W.member!==void 0&&{member:W.member}}),B.set(K.id,(B.get(K.id)??0)+1)}let H=[];for(let{row:K,type:W,member:U}of G){let D;if(!K.id.trim())D="empty credential id";else if((B.get(K.id)??0)>1)D="duplicate credential id";else if(K.accountId!==void 0&&!K.accountId.trim())D="blank account identity";else if(!K.state.trim())D="empty state";if(D){X.push({...K.id.trim()&&{credentialId:K.id},...U!==void 0&&{member:U},reason:D});continue}H.push(Object.freeze({credentialId:K.id,credentialType:W,...U!==void 0&&{member:U},...K.accountId!==void 0&&{accountIdentity:K.accountId},state:K.state,...K.email!==void 0&&{email:K.email},...K.orgName!==void 0&&{orgName:K.orgName}}))}for(let K of X)this.#X.warn("skipped malformed vault record",K);let Q=A9(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(X),..."classify"in this.#B&&{refused:Object.freeze(Y),notMine:J},...Q&&{grantReach:Q}}}listFailed($){if(r($)==="unreachable")this.transportLost($);else this.reachable(),this.#J.clear()}forget($){this.#J.delete($)}retain($){let Z=new Map($.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#J){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}}keptReceiptState(){let $=null;for(let[Z,z]of this.#J){if(!this.#b(z.attempt)){this.forget(Z);continue}if(z.since!==null)$=Math.min($??z.since,z.since)}return Object.freeze({active:$!==null,since:$})}#b($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#G()>C4}async authorize($,Z,z="vault"){this.#V(Z);let{credentialId:X,credentialType:Y,accountIdentity:J}=$,G=this.#J.get(X);if(G&&(G.attempt.credentialType!==Y||G.attempt.expectedAccountIdentity!==J))this.forget(X),G=void 0;let B;try{B=await this.#T(Z)}catch(H){throw this.#J.clear(),H}if(this.#H&&G)return this.#E(),this.#k(X,G,B,z);try{let H=await this.#f({credentialId:X,credentialType:Y,accountIdentity:J},B,Z);return this.#J.set(X,{attempt:H,routeId:z,since:null}),H}catch(H){if(this.#V(Z),r(H)!=="unreachable")throw this.forget(X),H;return this.#k(X,G,B,z,H)}}#k($,Z,z,X,Y=this.#F){if(!Z||this.#J.get($)!==Z||!this.#b(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#G();let J=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#z.set(J,z),this.#Q.set(J,X),J}async#f($,Z,z){if(!$.credentialId)throw new q("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:J}=$;if(this.#W&&J===void 0)throw new q("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#A(()=>this.#$.getScoped({credentialId:X,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:b3}}),z);if(G.credentialId!==void 0&&G.credentialId!==X)throw new q("identity-changed","Claustrum served credential identity changed");let B=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#G()<b3))throw new q("insufficient-validity","Claustrum served credential has insufficient validity");let H=R9(G.material),Q=G.accountId?.trim()?G.accountId:void 0;if(this.#W&&(G.credentialId===void 0||Q===void 0))throw new q("identity-unasserted","Claustrum served credential did not assert its identity");let K=Q===void 0?this.#Y?.(H):void 0,W=Q??K;if(J!==void 0&&W!==void 0&&W!==J)throw new q("identity-changed","Claustrum served credential identity changed");let U=W??J,V=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":K!==void 0?"parsed":J!==void 0?"expected":"none",...J!==void 0&&{expectedAccountIdentity:J},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#z.set(V,Z),V}async reportFailure($,Z,z){if(Z!==401)return;this.#V();let X=this.#z.get($);if(!X)throw new q("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#Q.get($);if(Y!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let J=this.#J.get($.credentialId);if(J&&J.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let G=this.#M.get($);if(G)return G;let B=this.#A(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:$.recordVersion,reporterSource:z}));this.#M.set($,B);try{await B,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:z})}catch(H){throw this.#M.delete($),H}}watchRoster($){this.#V();let Z=new O$({client:this.#$,enrollmentToken:()=>this.#T(),view:$.view??(()=>this.#j),discover:async(z)=>{await $.onView(z)},onRefused:(z)=>{this.listFailed(z),$.onRefused?.(z)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#X,now:this.#G,setTimeoutImpl:this.#D,clearTimeoutImpl:this.#q});return this.#x.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#x.delete(Z),Z.stop()}}}close(){if(this.#K)return;if(this.#K=!0,this.#N)this.#q(this.#N);this.#N=void 0;for(let $ of this.#x)$.stop();this.#x.clear(),this.#J.clear(),this.#$.close()}async dispose($=this.#O){this.close(),this.#L??=I0(this.#U,$),await this.#L}}import{resolve as k$}from"node:path";var I4=30000,k4={now:()=>performance.now(),schedule($,Z){let z=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(z),unref:()=>z.unref?.()}}};function f4($,Z=""){let z=new Map,{observation:X}=$,Y=(B,H,Q)=>z.set(`${Z}:${B}`,{at:H,order:0,publication:{...$,observation:Q}}),J=(B,H)=>JSON.stringify([B??"all",H]),G=new Set;for(let B of X.readings??[]){let H=J(B.scope,B.label);G.add(H),Y(H,X.checkedAt,{checkedAt:X.checkedAt,readings:[{...B}]})}for(let B of X.coverage??[]){let H=J(B.scope,B.label);if(!G.has(H))Y(H,X.checkedAt,{checkedAt:X.checkedAt,coverage:[{...B}]})}if(X.budget)Y("budget",X.checkedAt,{checkedAt:X.checkedAt,budget:{...X.budget}});for(let[B,H]of Object.entries(X.counters??{}))Y(`counter:${B}`,H.checkedAt,{checkedAt:X.checkedAt,counters:{[B]:{...H}}});if(X.credits)Y("credits",X.credits.checkedAt,{checkedAt:X.checkedAt,credits:{...X.credits}});if(!z.size)Y("empty",X.checkedAt,{checkedAt:X.checkedAt});return z}import{createHash as E9}from"node:crypto";import{stat as C9}from"node:fs/promises";import{resolve as i0}from"node:path";function b4($,Z,z){if($.accountIdentity!==void 0&&z!==void 0)return $.accountIdentity===z;return $.credentialId===Z}function w3($,Z,z){return $.some((X)=>b4(X,Z,z))}function h3($,Z,z){let X={credentialId:Z,...z!==void 0&&{accountIdentity:z}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==z),X]}function m3($,Z,z){return $.filter((X)=>!Z.some((Y)=>b4(X,Y,z)))}function v3($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>v(Z).map((z)=>({credentialId:z,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function I9($,Z){let z=v(Z),X=Z.accountIdentity===void 0?-1:$.order.findIndex((J)=>J.accountIdentity===Z.accountIdentity),Y=X>=0?X:$.order.findIndex((J)=>z.includes(J.credentialId));return Y>=0?Y:1/0}var I$="vault:";function k9($){return E9("sha256").update($).digest("hex")}function f9($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function b9($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function v($){return[$.credentialId,...$.aliases??[]]}function h4($,Z,z={}){let X=z.now??Date.now(),Y=z.routePrefix??I$,J=z.reservedRouteIds??new Set,G=$?.rows??[],B=$?void 0:z.seed,H=[...$?.declined??B?.declined??[]],Q=Z.skipped.length===0,K=new Set(Z.credentials.map((N)=>N.credentialId)),W=new Set(Z.skipped.flatMap((N)=>N.credentialId===void 0?[]:[N.credentialId])),U=Z.skipped.some((N)=>N.credentialId===void 0),D=(N)=>!K.has(N)&&(W.has(N)||U),V=new Map;for(let N of G){if(N.accountIdentity===void 0)continue;for(let _ of v(N))if(!V.has(_))V.set(_,N.accountIdentity)}let j=new Map;for(let N of Z.credentials){let _=N.accountIdentity!==void 0?{credential:N,identity:N.accountIdentity,claimed:!0}:{credential:N,identity:V.get(N.credentialId),claimed:!1},s=b9(_),a=j.get(s)??[];a.push(_),j.set(s,a)}let M=new Set,L=new Set(J),R=[],p=(N,_)=>N.credential.credentialId.localeCompare(_.credential.credentialId),w=[...j.values()].map((N)=>N.toSorted(p)).sort((N,_)=>N[0]&&_[0]?p(N[0],_[0]):0);for(let N of w){let _=N[0]?.identity,s=N.filter((O)=>O.credential.state==="active"),a=s.length?s:N,u$=a.filter((O)=>O.claimed),Y$=u$.length?u$:a,i$=new Set(N.map((O)=>O.credential.credentialId)),HZ=G.find((O)=>!M.has(O)&&v(O).some((L0)=>i$.has(L0))&&(O.accountIdentity===void 0||O.accountIdentity===_)),s$=Y$.find((O)=>O.credential.credentialId===HZ?.credentialId)??Y$[0];if(!s$)continue;let k=s$.credential,h=HZ??(_===void 0?void 0:G.find((O)=>!M.has(O)&&O.accountIdentity===_));if(h)M.add(h);let B0=h?.routeId;if(!B0||J.has(B0)){let O=`${Y}${k.credentialId}${_===void 0?"":`~${k9(_).slice(0,10)}`}`;B0=O;for(let L0=2;L.has(B0);L0++)B0=`${O}~${L0}`}L.add(B0);let u6=h?v(h).filter(D):[],a$=[...new Set([...N.map((O)=>O.credential.credentialId),...u6])].filter((O)=>O!==k.credentialId).sort((O,L0)=>O.localeCompare(L0)),i6=z.mapAccount?.(k)??{};R.push({previousIndex:h?G.indexOf(h):1/0,row:{routeId:B0,credentialId:k.credentialId,credentialType:k.credentialType,..._!==void 0&&{accountIdentity:_},...a$.length&&{aliases:a$},state:k.state,label:i6.label?.trim()||f9(k),...k.email!==void 0&&{email:k.email},...k.orgName!==void 0&&{orgName:k.orgName},enabled:![k.credentialId,...a$].some((O)=>w3(H,O,_)),addedAt:h?.addedAt??X,...h?.quota!==void 0&&{quota:h.quota},...!s$.claimed&&_!==void 0&&{unclaimed:!0}}});let n$=R.at(-1);if(B&&n$)n$.previousIndex=I9(B,n$.row)}return G.forEach((N,_)=>{if(M.has(N)||!v(N).some(D))return;if(L.has(N.routeId))return;let[s,...a]=v(N).filter((i$)=>!K.has(i$));if(s===void 0)return;L.add(N.routeId);let{aliases:u$,...Y$}=N;R.push({previousIndex:_,row:{...Y$,credentialId:s,...a.length&&{aliases:a},stale:!0}})}),R.sort((N,_)=>N.previousIndex===_.previousIndex?N.row.credentialId.localeCompare(_.row.credentialId):N.previousIndex-_.previousIndex),{version:1,view:Z.view,complete:Q,...!Q&&{rejected:Z.skipped.map((N)=>({...N.credentialId!==void 0&&{credentialId:N.credentialId},reason:N.reason}))},rows:R.map((N)=>N.row),declined:H}}function g3($){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 s0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function f0($){return $===void 0||typeof $==="string"}function y9($){let Z=s0($)?K0($.quota):void 0;if(!s0($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!f0($.accountIdentity)||!f0($.email)||!f0($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((z)=>typeof z==="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 w9=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function y4($){if(!Array.isArray($))return;let Z=[];for(let z of $){if(!s0(z)||!f0(z.credentialId)||typeof z.reason!=="string"||!w9.has(z.reason))return;Z.push(z)}return Z}function m4($){if(!s0($)||$.version!==1||!f0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!y4($.rejected))throw new q("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let J=y9(Y);if(!J)throw new q("invalid-state","Claustrum roster file is not valid");Z.push(J)}let z=[];for(let Y of $.declined){if(!s0(Y)||typeof Y.credentialId!=="string"||!f0(Y.accountIdentity))throw new q("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=y4($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...X&&{rejected:X},rows:Z,declined:z}}function p3($){return m4(JSON.parse(JSON.stringify($)))}async function x($){let Z;try{Z=await S$($,Z0)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse(Z)}catch{throw new q("invalid-state","Claustrum roster file is not valid")}return m4(z)}var v4={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},g4={name:"claustrum-roster",ttlMs:30000};async function M0($,Z,z={}){return U3($,{...v4,signal:z.signal},async(X)=>{let Y=await x($),{next:J,result:G}=await Z(Y,{assertOwned:()=>X.assertOwned()});if(J)await X.assertOwned(),await d($,J,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}});return G})}function l3($,Z){return M0($,(z)=>{let X=z?.rows.find((J)=>J.routeId===Z);if(!z||!X)throw new q("route-unavailable","Claustrum route is not in the roster");let Y=h3(z.declined,X.credentialId,X.accountIdentity);return{next:{...z,declined:Y,rows:z.rows.map((J)=>J===X?{...J,enabled:!1}:J)},result:void 0}})}function d3($,Z){return M0($,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===Z);if(!z||!X)throw new q("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:m3(z.declined,v(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function h9($){return new q("invalid-order",$)}function m9($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let z=new Set($.map((J)=>J.routeId)),X=new Set;for(let J of Z){if(typeof J!=="string")return"route ids must be an array of route ids";if(X.has(J))return`route id ${J} appears more than once`;if(!z.has(J))return`route id ${J} is not in the roster`;X.add(J)}let Y=[...z].filter((J)=>!X.has(J)).length;if(Y>0)return`the order leaves out ${Y} roster route id${Y===1?"":"s"}`;return}function c3($,Z,z={}){return M0($,(X)=>{let Y=X?.rows??[],J=m9(Y,Z);if(J)throw h9(J);let G=new Map;for(let Q of Y){let K=G.get(Q.routeId);if(K)K.push(Q);else G.set(Q.routeId,[Q])}let B=[...Z],H=B.flatMap((Q)=>G.get(Q)??[]);if(!X||H.every((Q,K)=>Q===Y[K]))return{result:{ids:B,outcome:"unchanged"}};return{next:{...X,rows:H},result:{ids:B,outcome:"reordered"}}},{...z.signal&&{signal:z.signal}})}function v9($,Z){if(!v($).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")&&v($).length===1)return"bind";return"refuse"}async function u3($,Z){let{routeId:z,observation:X,...Y}=Z;return p4($,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function p4($,Z){if(!R0(Z.observation))return!1;let z=I($,await x($));if(!Y0(z,Z).kept)return!1;return d4($,Z)}function i3($,Z){return p4($,Z)}function Y0($,Z){let z=$?.rows.find((G)=>G.routeId===Z.routeId),X=!z?"refuse":Z.receipt?v9(z,Z.receipt):z.accountIdentity!==void 0&&z.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!z||X==="refuse")return{roster:$,kept:!1};let Y=h0(z.quota,Z.observation),J=X==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((G)=>G===z?{...G,...J,quota:Y}:G)},kept:!0}}var C$=new Map;function a0($){C$.delete(i0($))}function l4($,Z){let z=i0($);if(Z instanceof q)return Z.kind==="roster-busy";if(Z instanceof U$||Z instanceof Q3)return i0(Z.details.target)===z;if(Z instanceof v0){let X=i0(Z.path);return[v4.name,g4.name].some((Y)=>{let J=W3(z,Y);return X===J||X.startsWith(`${J}.`)})}return!1}var g9=4;async function w4($){try{let{dev:Z,ino:z,size:X,mtimeMs:Y}=await C9($);return{dev:Z,ino:z,size:X,mtimeMs:Y}}catch{return}}function p9($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function l9($,Z,z){for(let X=0;X<g9;X++){let Y=await w4($),J=await x($),G,B,H;try{({target:G,local:B}=Z(J));let Q=JSON.stringify(z(G));H=JSON.stringify(G)!==Q||B!==void 0&&JSON.stringify(B)!==Q}catch{return"commit"}if(!p9(Y,await w4($)))continue;if(H)return"commit";return c4($)?"commit":"unchanged"}return"commit"}async function n0($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){a0($.path);return}let z=await b({...g4,path:$.path,renew:!0});if(!z){let G=await x($.path);if($.signal?.throwIfAborted(),!G?.view)throw new q("roster-busy","Claustrum account discovery is already in progress");return G}let X=i0($.path),Y=$.listedOver,J;try{let G=await x($.path),B=Y?void 0:C$.get(X);J=B&&(B.previousView===G?.view||B.inventory.view===G?.view)?B:{inventory:await $.custody.discover($.signal),previousView:G?.view},C$.delete(X);let{inventory:H}=J;$.onInventory?.(H),$.signal?.throwIfAborted();let Q=typeof $.projection==="function"?$.projection():$.projection,K=(D)=>h4(D,H,Q),W=async()=>{return $.signal?.throwIfAborted(),await z.assertOwned(),Z()};if(await l9($.path,(D)=>{if(Y)return{target:D};let V=I($.path,D);return{target:D,...V!==D&&{local:V}}},K)==="unchanged"){if(!await W())return;return await x($.path)}return await M0($.path,async(D)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await z.assertOwned(),Y&&D?.view!==Y.view&&D?.view!==H.view)return{result:D};let V=K(D);return{...JSON.stringify(D)!==JSON.stringify(V)&&{next:V},result:V}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await z.assertOwned()}})}catch(G){if(G instanceof U$&&J&&!Y&&!$.signal?.aborted&&await Z())C$.set(X,J);throw G}finally{await z.release($.signal)}}var j0=new Map,d9=A("claustrum"),i4=100;function s4($,Z=k4){let z=k$($),X=j0.get(z);if(!X)X={path:z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},j0.set(z,X);return X}function a4($,Z,z){let X=s4($,z);X.listeners.add(Z);let Y;return()=>Y??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():s3($)})()}function c9($){return f4($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function d4($,Z){if(!R0(Z.observation))return Promise.resolve(!1);let z=s4($),X=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),Y=z.pending.get(X)??new Map;for(let[J,G]of c9(Z)){let B=Y.get(J);if(!B||G.at>=B.at){if(G.order=++z.order,G.publication.observation.coverage)G.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(J,G)}}if(Y.size)z.pending.set(X,Y);for(let J of z.listeners)J(Z);return o4(z,i4),Promise.resolve(!0)}function n4($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,z)=>Z.order-z.order)}function I($,Z){let z=j0.get(k$($));if(z)for(let X of n4(z.pending)){if(X.priorReading)Z=Y0(Z,X.priorReading).roster;Z=Y0(Z,X.publication).roster}return Z}function c4($){return!!j0.get(k$($))?.pending.size}function o4($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let z=$.draining?0:($.committedAt??-1/0)+I4-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,z),()=>{return $.timer=void 0,r4($)}),!$.draining)$.timer.unref?.()}function u4($){$.timer?.cancel(),$.timer=void 0}function r4($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([z,X])=>[z,new Map(X)]));return $.running=(async()=>{try{if(await M0($.path,(X)=>{let Y=X;for(let G of n4(Z)){if(G.priorReading)Y=Y0(Y,G.priorReading).roster;Y=Y0(Y,G.publication).roster}let J=JSON.stringify(Y)!==JSON.stringify(X);return{...J&&{next:Y},result:J}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[X,Y]of Z){let J=$.pending.get(X);for(let[G,B]of Y)if(J?.get(G)===B)J.delete(G);if(!J?.size)$.pending.delete(X)}$.failures=0}catch(z){if(!$.abort.signal.aborted&&$.failures++===0)d9.warn("vault quota publication delayed; retrying",{error:z instanceof Error?z.message:String(z)})}finally{$.running=void 0;for(let X of $.wake)X();let z=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):i4;o4($,z)}})(),$.running}async function s3($,Z=1000){let z=k$($),X=j0.get(z);if(!X)return;X.draining=!0,u4(X);let Y,J,G=new Promise((B)=>{J=()=>{if(!X.pending.size||X.abort.signal.aborted)B()},X.wake.add(J),J()});try{if(X.pending.size)r4(X);await Promise.race([G,new Promise((B)=>{Y=setTimeout(B,Math.max(0,Z))})])}finally{if(clearTimeout(Y),J)X.wake.delete(J);if(X.draining=!1,!X.listeners.size){if(X.abort.abort(),u4(X),X.pending.clear(),j0.get(z)===X)j0.delete(z)}}}var f$=1e4;function t4(){return new C}var a3;function $6($,Z){if(!a3)throw Error("ClaustrumConsumer is not initialized");return a3($,Z)}function e4(){return new q("not-active","Claustrum scoped custody is not active")}class n3{#$;#Z=new AbortController;#G;#B;#Y;#W;#X;#z;#M;#J;#Q=!1;#D=new Set;#q;#H;#F;#N;#_=new Map;#S;#P;#K;#j;#x=new WeakMap;static{a3=($,Z)=>{let z=new n3(Z);return z.#K=$,{consumer:z,hooks:z.#g()}}}constructor($){this.#$=$,this.#G=$.logger??A("claustrum"),this.#B=C0(this.#G,this.#Z.signal),this.#P=a4($.rosterPath,(Z)=>{this.#z=Y0(this.#z,Z).roster})}#U($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#O($){return this.#D.add($),$.then(()=>this.#D.delete($),()=>this.#D.delete($)),$}async#L(){return await this.#$.isCustodyActive?.()??!0}#R($,Z){let z=F0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((X,Y)=>{let J=()=>{z.signal.removeEventListener("abort",G),z.dispose()},G=()=>{J(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",G,{once:!0}),$.then((B)=>{if(J(),z.signal.aborted)Y(z.signal.reason);else X(B)},(B)=>{J(),Y(B)}),z.signal.aborted)G()})}async#E(){if(this.#U(),this.#Y)return this.#Y;if(!this.#W){let $={timedOut:!1};this.#W=this.#V($),this.#O(this.#W)}return this.#R(this.#W)}#V($){let Z=this.#$.setTimeoutImpl??setTimeout,z=this.#$.clearTimeoutImpl??clearTimeout,X=this.#$.connect().then((G)=>{if(this.#Z.signal.aborted||$.timedOut){if(G.close(),!$.timedOut)this.#U();throw t4()}if(this.#Y=new k0({client:G,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#G,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&G.insula)this.#H=O3(G.insula,this.#$.tokenPath);return this.#Y}),Y,J=new Promise((G,B)=>{Y=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#G.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#T()}),B(t4())},this.#T()),Y.unref?.()});return Promise.race([X,J]).finally(()=>{if(Y)z(Y);this.#W=void 0})}#T(){return this.#$.connectTimeoutMs??f$}snapshot(){return this.#z}grantReach(){if(this.#K)return this.#K.grantReach(this.#z?.view);let $=this.#M;return $&&this.#z?.view===$.view?$.reach:void 0}watchState(){if(this.#K)return Object.freeze({vault:this.#K.watchMode()});return Object.freeze({vault:this.#F?.mode??"polling",...this.#$.insula&&{insula:this.#H?.source.watchMode()??"polling"}})}#A(){this.#F?.close(),this.#F=void 0,this.#N?.(),this.#N=void 0}keptReceiptState(){if(this.#K){let $=this.#j;return $&&this.#K.leaseLive($)?$.custody.keptReceiptState():this.#K.keptReceiptState()}return this.#Y?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return g3(this.#z)}refresh(){if(this.#U(),this.#K)return this.#O(this.#y(this.#K));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#L()){if(this.#z=void 0,this.#M=void 0,this.#A(),this.#Y)this.#Y.close(),this.#O(this.#Y.dispose(this.#B));this.#Y=void 0,this.#H?.release(),this.#H=void 0;return}let $=await this.#E(),Z,z=await n0({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#L(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#U();let X=z?.view!==this.#z?.view;if(this.#z=I(this.#$.rosterPath,z),$.retain(z?.rows??[]),Z&&z?.view!==void 0)this.#M=Z.grantReach?{view:z.view,reach:Z.grantReach}:void 0;if(z&&X)this.#$.onRoster?.(z);return this.#S=(this.#$.now??Date.now)(),z})().finally(()=>{this.#X=void 0}),this.#O(this.#X),this.#C(this.#X),this.#X}#C($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#Q)return;if(this.#U(),this.#Q=!0,this.#K){this.#K.start();return}let $=async()=>{try{if(await this.#b())await this.refresh();await this.refreshInsulaQuota(),this.#k()}catch(z){if(!this.#Z.signal.aborted)this.#$.onError?.(z)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#J=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#J=void 0,this.#O($())},Z),this.#J.unref?.()};this.#O($())}async#b(){if(this.#F?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#S===void 0||$-this.#S>=T0)return!0;return!await this.#L()}#k(){let $=this.#Y;if(this.#Z.signal.aborted||!$)return;if(this.#F??=$.watchRoster({view:()=>this.#z?.view,onView:()=>this.#O((async()=>{while(this.#X)await this.#X.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.#H&&!this.#N)this.#N=this.#H.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{await z0(this.#$.tokenPath),await this.#E(),await this.#H?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{return await z0(this.#$.tokenPath),this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{await z0(this.#$.tokenPath);let z=I(this.#$.rosterPath,await x(this.#$.rosterPath))?.rows.find((X)=>X.routeId===$);return this.#f(z?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#L())return{miss:"unreachable"};try{await z0(this.#$.tokenPath);let X=I(this.#$.rosterPath,await x(this.#$.rosterPath))?.rows.find((G)=>G.routeId===$)?.accountIdentity;if(!X||!this.#H)return{miss:"unreachable"};let Y=this.#H.source.lookup(Z.provider,X,(this.#$.now??Date.now)()),J=Y.reading&&Z.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...J!==void 0&&{reading:J}};return J===void 0?{miss:"unreachable"}:{reading:J}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let z=await this.lookupInsulaQuotaForRoute($);if(z.miss==="cold"||z.miss==="upstream-failed"){if(this.#_.get($)!==z.miss)this.#_.set($,z.miss),this.#G.warn("skipped insula provider poll",{reason:z.miss});return}return this.#_.delete($),z.miss?Z():z.reading}#f($){if(!this.#$.insula||!$)return;let Z=this.#H?.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.#w(this.#K,$,Z);this.#U(Z);let z=this.#z??await this.#R(this.refresh(),Z);if(!z||!await this.#L())throw this.#Y?.close(),this.#Y=void 0,this.#A(),this.#H?.release(),this.#H=void 0,new q("not-active","Claustrum scoped custody is not active");let X=I(this.#$.rosterPath,await x(this.#$.rosterPath));this.#U(Z);let Y=z.rows.find((H)=>H.routeId===$),J=X?.rows.find((H)=>H.routeId===$);if(J&&!J.enabled){if(Y)this.#Y?.forget(Y.credentialId);throw new q("route-declined","Claustrum route is disabled")}if(!Y||!J||J.state!=="active"||J.credentialId!==Y.credentialId||J.accountIdentity!==Y.accountIdentity||J.credentialType!==Y.credentialType){if(Y)this.#Y?.forget(Y.credentialId);throw new q("route-unavailable","Claustrum route is disabled, removed or changed")}let G=await this.#R(this.#E(),Z),B=F0([this.#Z.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:J.credentialId,credentialType:J.credentialType,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity}},B.signal,$)}finally{B.dispose()}}#g(){return{discovery:($)=>{let Z=this.#K;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let z=this.#O($.then((X)=>this.#h(Z,X)));this.#C(z)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#z?.view;if(this.#z=I(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(z){this.#$.onError?.(z)}},reset:()=>{this.#z=void 0},roster:()=>this.#z,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#y($){let Z=await $.refresh();return this.#h($,Z)}#h($,Z){if(this.#U(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#z}#I($){if($&&this.#j!==$)return;this.#j?.release(),this.#j=void 0}async#p($,Z){let z=this.#j;if(z&&$.leaseLive(z))return z;this.#I();let X=await $.acquire(Z);if(this.#Z.signal.aborted)X.release(),this.#U();let Y=this.#j;if(Y&&$.leaseLive(Y))return X.release(),Y;return this.#j=X,X}async#w($,Z,z){if(this.#U(z),!this.#z)await this.#R($.refresh(),z);let X=this.#z;if(!await $.readAuthority())throw this.#I(),e4();if(this.#U(z),!X)throw new q("route-unavailable","Claustrum has no roster for this provider yet");let Y=I(this.#$.rosterPath,await x(this.#$.rosterPath));this.#U(z);let J=X.rows.find((Q)=>Q.routeId===Z),G=Y?.rows.find((Q)=>Q.routeId===Z);if(G&&!G.enabled){if(J)$.forget(J.credentialId);throw new q("route-declined","Claustrum route is disabled")}if(!J||!G||G.state!=="active"||G.credentialId!==J.credentialId||G.accountIdentity!==J.accountIdentity||G.credentialType!==J.credentialType){if(J)$.forget(J.credentialId);throw new q("route-unavailable","Claustrum route is disabled, removed or changed")}let B={credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},H=F0([this.#Z.signal,...z?[z]:[]]);try{for(let Q=0;;Q++){let K=await this.#p($,H.signal);try{let W=await K.custody.authorize(B,H.signal,Z);return this.#x.set(W,K),W}catch(W){if(Q>0||H.signal.aborted||$.leaseLive(K)||!(W instanceof q)||W.kind!=="closed")throw W;if(this.#I(K),!await $.readAuthority())throw e4()}}}finally{H.dispose()}}async reportFailure($,Z,z){if(this.#U(),this.#K){let X=this.#x.get($);if(!X)throw new q("no-receipt","Claustrum dispatch receipt has no active owner");await X.custody.reportFailure($,Z,z);return}if(!this.#Y)throw new q("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Y.reportFailure($,Z,z)}async send($,Z,z){let X=z.signal,Y=await this.authorize($,X),J=await Z(Y,X);if(J.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,z.reporterSource??"direct"),J;if(J.status===401&&!X?.aborted){let G;try{G=await this.authorize($,X),X?.throwIfAborted()}catch(B){if(X?.aborted)throw B}if(y3(z.site,Y,G,this.#G))await J.body?.cancel().catch(()=>{}),Y=G,J=await Z(G,X)}if(J.status===401)await this.reportFailure(Y,401,z.reporterSource??"direct").catch((G)=>this.#$.onError?.(G)),Promise.resolve().then(()=>this.refresh()).catch((G)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(G)});return J}async decline($){if(this.#U(),await l3(this.#$.rosterPath,$),this.#z=I(this.#$.rosterPath,await x(this.#$.rosterPath)),this.#z)this.#K?.publishRoster(this.#z);if(this.#K)this.#K.retainUnion();else this.#Y?.retain(this.#z?.rows??[])}async accept($){if(this.#U(),await d3(this.#$.rosterPath,$),this.#z=I(this.#$.rosterPath,await x(this.#$.rosterPath)),this.#z)this.#K?.publishRoster(this.#z)}async reorder($){this.#U();let Z=await c3(this.#$.rosterPath,$);if(this.#z=I(this.#$.rosterPath,await x(this.#$.rosterPath)),this.#z)this.#K?.publishRoster(this.#z);return Z}async recordQuota($,Z,z){return this.#U(),u3(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:z.credentialId,accountIdentitySource:z.accountIdentitySource,...z.accountIdentity!==void 0&&{accountIdentity:z.accountIdentity},...z.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:z.expectedAccountIdentity}})}async recordAccountQuota($,Z,z){return this.#U(),i3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:z})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new q("closed","Claustrum consumer is closed")),this.#J)(this.#$.clearTimeoutImpl??clearTimeout)(this.#J);if(this.#J=void 0,this.#A(),this.#Y)this.#Y.close(),this.#O(this.#Y.dispose(this.#B));this.#j?.release(),this.#j=void 0,this.#K?.detach(),this.#H?.release(),this.#H=void 0,this.#z=void 0,this.#M=void 0,this.#P(),a0(this.#$.rosterPath)}async dispose(){this.close(),this.#q??=Promise.all([I0(this.#D,this.#B),this.#P()]).then(()=>{}),await this.#q}}import{createHash as u9}from"node:crypto";import{channel as i9}from"node:diagnostics_channel";import{readdir as s9,stat as a9}from"node:fs/promises";import{dirname as n9,join as b0,resolve as Z6}from"node:path";var b$=new Map,o9=/^[a-z0-9][a-z0-9._-]{0,63}$/,r9=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,t9=/^[0-9a-f]{16}$/,z6=3;function r3($,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 z=new Set(Z).add($),X=[];if(Array.isArray($)){for(let J=0;J<$.length;J++){let G=r3($[J],z);if(G===void 0)return;X.push(G)}return`[${X.join(",")}]`}let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return;for(let J of Object.keys($).sort()){let G=r3($[J],z);if(G===void 0)return;X.push(`${JSON.stringify(J)}:${G}`)}return`{${X.join(",")}}`}function e9($,Z){let z=r3({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??I$,mapAccount:$.mapAccount?String($.mapAccount):null});if(z===void 0)throw new q("invalid-state","Claustrum hub classifierInput must be plain JSON");return u9("sha256").update(z).digest("hex").slice(0,16)}function X6($,Z){if(typeof $!=="string"||!o9.test($)||r9.test($))throw new q("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function J0($="Claustrum custody lease is closed"){return new q("closed",$)}function o3(){return new q("not-active","Claustrum scoped custody is not active")}function Y6(){return new C}function $1($,Z){return new Promise((z,X)=>{let Y=()=>X(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),$.then((J)=>{Z.removeEventListener("abort",Y),z(J)},(J)=>{Z.removeEventListener("abort",Y),X(J)}),Z.aborted)Y()})}function J6($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class G6{#$;#Z;#G;#B=new AbortController;#Y=new Map;#W=new WeakMap;#X=0;#z;#M;#J;#Q;#D;#q;#H=0;#F;#N;#_;#S=!1;#P=new Set;#K;#j;#x;constructor($){if(!$.family||!("classify"in $.family))throw new q("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=X6($.hostGeneration,"host generation"),z=$.members.map((Y)=>X6(Y,"member"));if(new Set(z).size!==z.length)throw new q("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??A("claustrum"),this.#G=C0(this.#Z,this.#B.signal),this.#j=b0($.stateDir,"rosters",Z),this.#x=e9($,z);let X=b0(this.#j,this.#x);for(let Y of z)this.#Y.set(Y,{provider:Y,path:b0(X,`${Y}.json`),closed:!1})}#U($){return this.#P.add($),$.then(()=>this.#P.delete($),()=>this.#P.delete($)),$}#O(){if(this.#B.signal.aborted)throw J0("Claustrum discovery hub is closed")}#L($){let Z=this.#Y.get($);if(!Z)throw new q("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#L($).path}member($,Z){this.#O();let z=this.#L($);if(z.hooks)throw new q("wrong-consumer","Claustrum hub member was already built");for(let W of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(W in Z)throw new q("wrong-consumer",`Claustrum hub members cannot take ${W}`);let X={provider:z.provider,start:()=>this.start(),refresh:()=>this.#w(),readAuthority:()=>this.#y(),acquire:(W)=>this.acquire(W),leaseLive:(W)=>this.#T(W),grantReach:(W)=>W!==void 0&&this.#F?.view===W?this.#F.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#v(),publishRoster:(W)=>this.#R(z,W),forget:(W)=>this.#z?.custody?.forget(W),detach:()=>{z.closed=!0,z.releaseRoster?.()}},Y={rosterPath:z.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:J,hooks:G}=$6(X,Y);z.hooks=G;let B=Z6(z.path),H=b$.get(B)??new Set,Q=(W)=>{if(z.closed||this.#q!==!0||!this.#z||!this.#V(this.#z)||!G.roster()||this.#l(G,W))return;if(z.seen=JSON.stringify(p3(W)),G.install(W),W.view!==this.#F?.view)z.pending??={failures:0,wait:0};this.#v()};H.add(Q),z.receiveRoster=Q,b$.set(B,H);let K=!0;return z.releaseRoster=()=>{if(!K)return;if(K=!1,H.delete(Q),!H.size)b$.delete(B)},J}#R($,Z){let z=this.#z;if($.closed||!z||!this.#V(z))return;$.seen=JSON.stringify(p3(Z)),$.hooks?.install(Z);for(let X of b$.get(Z6($.path))??[]){if(!this.#V(z))return;if(X!==$.receiveRoster)X(Z)}}#E(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#z=$,$}#V($){return!$.ended&&this.#z===$&&!this.#B.signal.aborted}#T($){let Z=this.#W.get($);return!!Z&&!Z.released&&!Z.generation.ended}#A($,Z=J0()){if($.ended)return;if($.ended=!0,$.count=0,this.#z===$)this.#z=void 0;if(this.#J&&this.#W.get(this.#J)?.generation===$)this.#J=void 0;if(this.#Q?.generation===$)this.#Q.watch.close(),this.#Q=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#U($.custody.dispose(this.#G))}#C($){if($.ended)return;if($.count--,$.count<=0)this.#A($)}#b($){let Z=this.#M;if(Z?.generation===$&&Z.promise)return Z.promise;let z={generation:$,timedOut:!1},X=this.#$.connectTimeoutMs??f$,Y,J=this.#$.connect().then((H)=>{if(z.timedOut)throw H.close(),Y6();if(!this.#V($)||$.count<=0)throw H.close(),J0("Claustrum connection is no longer wanted");return $.custody=new k0({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}),G=new Promise((H,Q)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(z.timedOut=!0,!this.#V($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:X}),Q(Y6())},X),Y.unref?.()});return z.promise=this.#U(Promise.race([J,G]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),z.promise.finally(()=>{if(this.#M===z)this.#M=void 0}).catch(()=>{}),this.#M=z,z.promise}acquire($){try{if(this.#O(),$?.throwIfAborted(),this.#q===!1)throw o3()}catch(z){return Promise.reject(z)}let Z=this.#z??this.#E();return Z.count++,this.#k(Z,$,!0)}async#k($,Z,z){let X=$.custody;if(!X){let Y=F0([$.controller.signal,...Z?[Z]:[]]);try{X=await $1(this.#b($),Y.signal)}catch(J){if(!$.ended)throw this.#C($),J;return this.#f(Z,z)}finally{Y.dispose()}}if($.ended)return this.#f(Z,z);if(Z?.aborted)throw this.#C($),Z.reason;return this.#g($,X)}#f($,Z){if($?.throwIfAborted(),this.#O(),this.#q===!1)throw o3();if(!Z)throw J0();let z=this.#z??this.#E();return z.count++,this.#k(z,$,!1)}#g($,Z){let z={generation:$,custody:Z,released:!1},X=()=>{if(z.released||$.ended)throw J0()},Y=Object.freeze({authorize:async(G,B,H)=>{X();let Q=F0([$.controller.signal,...B?[B]:[]]);try{return await Z.authorize(G,Q.signal,H)}finally{Q.dispose()}},reportFailure:async(G,B,H)=>{return X(),Z.reportFailure(G,B,H)},forget:(G)=>{X(),Z.forget(G)},keptReceiptState:()=>{return X(),Z.keptReceiptState()}}),J=Object.freeze({custody:Y,generation:$.id,release:()=>{if(z.released)return;z.released=!0,this.#C($)}});return this.#W.set(J,z),J}leaseState(){let $=this.#z;return Object.freeze({generation:$?.id,count:$?.count??0})}async#y(){let $=await this.#$.isCustodyActive?.()??!0;if(this.#B.signal.aborted)return!1;let Z=this.#q;if(this.#q=$,!$&&Z!==!1)this.#h();return $}#h(){this.#H++;let $=this.#z;if($)this.#A($,o3());this.#J=void 0,this.#Q?.watch.close(),this.#Q=void 0,this.#F=void 0,this.#N=void 0;for(let Z of this.#Y.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),a0(Z.path)}#I(){return[...this.#Y.values()].filter(($)=>$.hooks&&!$.closed)}async#p(){let $=this.#J,Z=$&&this.#W.get($);if($&&Z&&this.#T($))return Z;this.#J=void 0;let z=await this.acquire(this.#B.signal),X=this.#J&&this.#W.get(this.#J);if(this.#J&&X&&this.#T(this.#J))return z.release(),X;this.#J=z;let Y=this.#W.get(z);if(!Y)throw J0();return Y}#w(){try{this.#O()}catch(X){return Promise.reject(X)}let $=this.#D;if($&&!$.generation?.ended)return $.promise;let Z={},z=this.#U(this.#a(Z).finally(()=>{if(this.#D===Z)this.#D=void 0}));Z.promise=z,this.#D=Z;for(let X of this.#I())X.hooks?.discovery(z);return z}async#a($){if(!await this.#y())return;let Z=await this.#p(),z=Z.generation;if($.generation=z,!this.#V(z))return;let X=await this.#o().then(()=>{return},(K)=>K instanceof Error?K:Error(String(K))),Y=new Map(await Promise.all([...this.#Y.values()].map(async(K)=>[K,await x(K.path).then((W)=>W?{file:W}:{},(W)=>W instanceof Error?W:Error(String(W)))])));if(!this.#V(z))return;let J;try{J=await Z.custody.discover(z.controller.signal)}catch(K){if(!this.#V(z))return;for(let W of this.#Y.values())if(W.pending)this.#m(W);throw K}if(!this.#V(z))return;let G=this.#I(),B=await Promise.all(G.map((K)=>K.hooks&&!K.closed?this.#n(K,K.hooks,J,X??Y.get(K),z):void 0));if(!this.#V(z))return;let H=new Map,Q=!0;for(let[K,W]of G.entries()){let U=W.hooks,D=B[K];if(!U||!D)continue;if("error"in D){let{error:j}=D;if(Q=!1,this.#m(W),l4(W.path,j))this.#Z.debug("claustrum hub member commit refused",{member:W.provider});else H.set(W.provider,j);continue}let{roster:V}=D;if(!this.#V(z))return;if(V?.view!==J.view)Q=!1,this.#m(W);else W.pending=void 0;if(!V)continue;if(this.#l(U,V)){Q=!1,this.#m(W);continue}this.#R(W,V)}if(!this.#V(z))return;if(this.#v(),Q)this.#F=Object.freeze({view:J.view,...J.grantReach&&{reach:J.grantReach},refused:Object.freeze([...J.refused??[]]),notMine:J.notMine??0});return this.#N=(this.#$.now??Date.now)(),{errors:H}}async#n($,Z,z,X,Y){let J={...z,credentials:z.credentials.filter((G)=>G.member===$.provider),skipped:z.skipped.filter((G)=>G.member===$.provider)};try{if(!X)throw J0("Claustrum hub member has no base view");if(X instanceof Error)throw X;let G;if(!X.file){let H=i9("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{G=await this.#r($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await n0({path:$.path,custody:{discover:async()=>J},isActive:()=>this.#V(Y)&&this.#q===!0,signal:Y.controller.signal,projection:()=>({...Z.projection(),...G&&{seed:G}}),listedOver:{view:X.file?.view}})}}catch(G){return{error:G}}}async#o(){for(let $ of[n9(this.#j),this.#j,b0(this.#j,this.#x)])await E0($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,z=[b0(this.#j,Z)];try{for(let Y of await s9(this.#j))if(Y!==this.#x&&t9.test(Y))z.push(b0(this.#j,Y,Z))}catch{}let X;for(let Y of z)try{let J=(await a9(Y)).mtimeMs,G=await x(Y);if(G&&(!X||J>X.modified))X={modified:J,roster:G}}catch{}return X&&v3(X.roster)}#l($,Z){let z=$.projection().reservedRouteIds;return!!z?.size&&Z.rows.some((X)=>z.has(X.routeId))}#m($){let Z=($.pending?.failures??0)+1,z=Math.max(1,this.#$.pollIntervalMs??5000),X=Math.max(1,Math.ceil(T0/z)),Y=Z<=z6?1:Math.min(2**(Z-z6),X);$.pending={failures:Z,wait:Y-1}}#v(){let $=this.#z?.custody;if(!$)return;$.retain(this.#I().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#H;for(let Z of this.#I()){let z;try{z=await x(Z.path)}catch(B){Z.hooks?.onError(B);continue}if($!==this.#H||this.#q!==!0)return;let X=Z.hooks;if(!z||!X||Z.closed)continue;let Y=JSON.stringify(z);if(Y===Z.seen)continue;let J=X.roster();if(!J||J.view!==z.view||this.#l(X,z)){Z.pending??={failures:0,wait:0};continue}let G=J6(J);if(Z.seen=Y,this.#R(Z,z),J6(X.roster())!==G)this.#v()}}#e(){let $=!1;for(let z of this.#Y.values()){if(!z.pending)continue;if(z.pending.wait<=0)$=!0;else z.pending.wait--}if(this.#Q?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#N===void 0||Z-this.#N>=T0}#$0(){let $=this.#J,Z=$&&this.#W.get($);if(!$||!Z||!this.#T($)||this.#q!==!0)return;let z=Z.generation;if(!this.#V(z)||this.#Q?.generation===z)return;let X=Z.custody.watchRoster({view:()=>this.#F?.view,onView:()=>this.#U((async()=>{while(this.#D)await this.#D.promise.catch(()=>{});if(!this.#V(z))return;await this.#i()})()),onRefused:(Y)=>this.#c(Y),onError:(Y)=>this.#d(Y)});this.#Q={generation:z,watch:X}}#d($){if(!this.#B.signal.aborted)this.#$.onError?.($)}#c($){if(this.#B.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#I())Z.hooks?.onError($)}#u($){for(let[Z,z]of $?.errors??[])this.#Y.get(Z)?.hooks?.onError(z)}async#i(){let $;try{$=await this.#w()}catch(Z){this.#c(Z);return}this.#u($)}async#s(){try{if(await this.#y()){if(await this.#t(),this.#e())await this.#i();this.#$0()}}catch(Z){this.#d(Z)}if(this.#B.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#_=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#_=void 0,this.#U(this.#s())},$),this.#_.unref?.()}start(){if(this.#S)return;this.#O(),this.#S=!0,this.#U(this.#s())}async refresh(){this.#u(await this.#w())}refusals(){let $=this.#F;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#F?.reach}watchState(){let $=this.#Q;return $&&this.#V($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#z?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#B.signal.aborted)return;this.#B.abort(J0("Claustrum discovery hub is closed"));for(let Z of this.#Y.values())Z.releaseRoster?.();if(this.#_)(this.#$.clearTimeoutImpl??clearTimeout)(this.#_);this.#_=void 0;let $=this.#z;if($)this.#A($);this.#J=void 0,this.#Q?.watch.close(),this.#Q=void 0}async dispose(){this.close(),this.#K??=I0(this.#P,this.#G),await this.#K}}var z1=1e4;async function $z($){let{connectTimeoutMs:Z,...z}=$,X=Z??z1,Y=Z1.connect(z),J=!1,G,B=new Promise((H,Q)=>{G=setTimeout(()=>{J=!0,Q(new C)},X),G.unref?.()});try{let H=await Promise.race([Y,B]);return Object.assign(H,{insula:$4($)})}catch(H){throw Y.then((Q)=>Q.close(),()=>{}),H}finally{if(!J&&G)clearTimeout(G)}}var B6=A$("openai");function H6($){return E$($)}function _0($){if(!$||$.corrupt===!0)return!1;return H6($.refresh)}class o0 extends Error{code="tombstone-refresh";constructor(){super("This OpenAI account was moved into the Claustrum vault by an older version of OpenAI auth and holds no local credential. Connect the vault, or sign in to the account again.");this.name="TombstoneRefreshError"}}function y$($){if(H6($))throw new o0}var X1=A("quota"),t3="primary",e3="secondary",Y1="app_EMoamEEZ73f0CkXaXp7hrann",J1="https://auth.openai.com";async function Lz($){y$($.refreshToken);let Z=await $.fetchImpl(`${J1}/oauth/token`,{method:"POST",signal:AbortSignal.timeout(15000),headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:Y1}).toString()});if(!Z.ok){let Y=q3(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:Y,isRefreshError:!0})}let z=await Z.json();if(!z||typeof z.access_token!=="string"||!z.access_token||typeof z.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});if(z.refresh_token!==void 0&&typeof z.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});let X=typeof z.refresh_token==="string"&&z.refresh_token?z.refresh_token:$.refreshToken;return{access:z.access_token,refresh:X,expires:$.now()+z.expires_in*1000,expiresIn:z.expires_in}}var G1="https://chatgpt.com/backend-api/wham/usage";async function xz($){let Z=$.logger??X1,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await $.fetchImpl(G1,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Y.ok){let G=q3(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:G})}let J=oZ(await Y.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:Y.status,elapsedMs:Date.now()-X}),J}catch(Y){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof Y?.status==="number"?Y.status:"error",elapsedMs:Date.now()-X,error:K6(Y)}),Y}}import{createHash as B1}from"node:crypto";var H1=globalThis.setTimeout,K1=5;function r0($){let Z=$?.quota?.checkIntervalMinutes??K1;return Math.max(1,Z)*60000}function W1($){return $?.quota?.enabled!==!1}function w$($,Z){if(!$?.resetsAt)return!1;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z<=Z}function Iz($,Z,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let J=Z===t3?$?.primary:Z===e3?$?.secondary:void 0,G=J?.resetsAt?Date.parse(J.resetsAt):NaN;if(Number.isFinite(G)&&G>z)return G;return z+X}function Q1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function W6($,Z,z){if(!W1(Z))return z+r0(Z);let X=Q1(Z),Y=[];for(let J of["primary","secondary"]){let G=$?.[J];if(!G)continue;if(G.remainingPercent>=X[J])continue;let B=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=z)return z+r0(Z);Y.push(B)}if(!Y.length)return z+r0(Z);return Math.min(...Y)+60000}function U1($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function V1($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function y($){return B1("sha256").update($).digest("hex").slice(0,16)}class G0{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;configPath;constructor($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath,this.now=$.now??Date.now,this.fetchQuotaFn=$.fetchQuotaFn,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==y($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let z=this.fallbacks.get($)??null;if(!Z||!z)return z;if(this.fallbackTokenFps.get($)!==y(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!Q6(Z.quota))return;if(this.mainTokenFp=y($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,$Z(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let z=this.fallbacks.get($)??null;if(Z&&z?.accountId&&z.accountId!==Z)return null;return z}setFallback($,Z,z,X=!1,Y){if(!X&&!Q6(Z.quota))return;let J=this.fallbacks.get($)?.accountId;if(Y&&J&&Y!==J)this.clearRateLimited($);let G=Y??J;if(this.fallbacks.set($,{...Z,accountId:G}),z)this.fallbackTokenFps.set($,y(z));else this.fallbackTokenFps.delete($);if($Z(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let z=this.rateLimitedUntilMap.get($);if(z!==void 0&&z>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=y($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let z=G0.fallbackInflightKey($,Z),X=this.inflightFallbacks.get(z);if(X)return X;if(this.isFallbackBackedOff($,Z)){let J=this.getFallback($,Z);if(J)return J.quota;throw Error("Quota API rate-limited — try again later")}let Y=this._fetchFallback($,Z);return this.inflightFallbacks.set(z,Y),Y}async refreshAllFallbacks($){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;if(_0(z)||!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground($){let Z=y($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale($,Z){let z=this.getFallback($,Z);if(!z)return!0;return this.now()>=z.refreshAfter}shouldRefreshOnRequestCount($){let Z=V1(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let z=U1($);if(!z)return;let X=Z?y(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:W6(z.quota,$,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=Y.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=Y,this.mainTokenFp=z.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&S0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=r0(this.storage);for(let z of $){if(z.enabled===!1)continue;if(!z.quota)continue;let X=Math.max(z.quota.primary?.checkedAt??0,z.quota.secondary?.checkedAt??0);if(X<=0)continue;let Y=this.getFallback(z.id,z.access);if(Y&&Y.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+Z,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return S0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==y(Z))return!1}return S0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,y(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let X=this.now()-this.lastApiCallAt;if(X<G0.API_CALL_GAP_MS)await new Promise((Y)=>{let J=H1(Y,G0.API_CALL_GAP_MS-X);if(typeof J==="object"&&"unref"in J)J.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=y($);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let z=await b({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!z){let X=this.main;if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=this.now(),Y=await this._fetchQuota($),J=this.now();if(this.mainTokenFp=y($),this.main={quota:Y,refreshAfter:W6(Y,this.storage,J),checkedAt:J},$Z(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,J,this.mainTokenFp,X),Y}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,Z)){let X=this.getFallback($,Z);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=await b({name:G0.quotaLockName($),ttlMs:30000,path:this.configPath});if(!z){let X=this.getFallback($,Z);if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=await this._fetchQuota(Z),Y=this.now();return this.setFallback($,{quota:X,refreshAfter:Y+r0(this.storage),checkedAt:Y},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError($,Z,z),z}finally{this.inflightFallbacks.delete(G0.fallbackInflightKey($,Z))}})}async _fetchQuota($){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:$,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError($){return $?.status===401}_handleMainFetchError($){if(G0.isAuthError($))return;this.mainLastApiError=g0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(G0.isAuthError(z))return;let X=y(Z),Y=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,g0({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,X)}}function Q6($){return Boolean($.primary||$.secondary)}function $Z($){let{primary:Z,secondary:z}=$;if(!Z&&!z)return!1;if(Z&&Z.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{createHash as D1,randomUUID as q1}from"node:crypto";import{setTimeout as F1}from"node:timers/promises";import{readFile as E1}from"node:fs/promises";var O0=A("refresh"),Z$=A("accounts"),N1=1e4,M1=15000,ZZ=50;function u($){return $.type==="oauth"&&$.corrupt!==!0}function j1($){let Z=$?.trim();if(!Z)return!1;try{let z=new URL(Z);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}var _1="floors-v1";function iz($){return $.costZeroing?.enabled!==!1}class m$ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var O1=[401,403,429],U6={primary:0,secondary:0},P1=!1,XZ={primary:5,secondary:10};function F($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var L1=new Set(["__proto__","constructor","prototype"]);function x1($){return $.length>0&&!L1.has($)}function R1($){return $ instanceof m$||F($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function h$($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():q1(),label:typeof $.label==="string"?$.label:void 0,enabled:typeof $.enabled==="boolean"?$.enabled:void 0,addedAt:typeof $.addedAt==="number"?$.addedAt:void 0,lastUsed:typeof $.lastUsed==="number"?$.lastUsed:void 0,accountId:typeof $.accountId==="string"?$.accountId:void 0}}function V6($){if(!F($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function S1($){if(!F($))return;let Z={};for(let Y of["primary","secondary"]){let J=$[Y];if(!F(J))continue;let G=Number(J.usedPercent),B=Number(J.remainingPercent),H=Number(J.checkedAt);if(!Number.isFinite(G)||!Number.isFinite(B)||!Number.isFinite(H))continue;let Q=typeof J.windowMinutes==="number"?J.windowMinutes:Number.NaN;Z[Y]={usedPercent:G,remainingPercent:B,checkedAt:H,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let J=typeof $[Y]==="number"?$[Y]:Number.NaN;if(Number.isFinite(J)&&J>=0)Z[Y]=J}let z=$.spendControl;if(F(z)){let Y=Number(z.limit),J=Number(z.used),G=Number(z.remaining),B=Number(z.usedPercent),H=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof z.reached==="boolean")Z.spendControl={limit:Y,used:J,remaining:G,usedPercent:B,remainingPercent:H,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=$.credits;if(F(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&(X.overageLimitReached===void 0||typeof X.overageLimitReached==="boolean")){let Y=Number(X.balance),J=typeof X.checkedAt==="number"?X.checkedAt:Number.NaN;Z.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,...typeof X.overageLimitReached==="boolean"?{overageLimitReached:X.overageLimitReached}:{},...Number.isFinite(Y)?{balance:Y}:{},...Number.isFinite(J)?{checkedAt:J}:{}}}return Object.keys(Z).length?Z:void 0}function T1($){if(!F($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!j1(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...h$($),type:"api",apiKey:z||void 0,baseURL:Z,authHeader:X}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...h$($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...h$($),type:"oauth",corrupt:!0}}return{...h$($),type:"oauth",access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:V6($.lastRefreshError),lastQuotaRefreshError:V6($.lastQuotaRefreshError),quota:S1($.quota)}}function A1($){if(!F($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!x1(z)||!F(X))continue;let Y={};if(F(X.inFlight))Y.inFlight={...X.inFlight};if(F(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))Y.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...F(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))Y.cooldownUntil=X.cooldownUntil;if(Object.keys(Y).length>0)Z[z]=Y}return Object.keys(Z).length>0?Z:void 0}var D6=new Set;function P6($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(D6.has(Z))return;D6.add(Z),Z$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function L6($){if(!F($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(T1).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let G of Z)if(F(G)&&typeof G.id==="string"&&G.id.trim())X.add(G.id.trim());let Y=new Set(z.map((G)=>G.id)),J=[];for(let G of X)if(!Y.has(G))J.push(G);P6(J)}return{version:1,main:{type:"opencode",provider:"openai"},routing:F($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:F($.refresh)?$.refresh:void 0,quota:F($.quota)?$.quota:void 0,reset:A1($.reset),dump:F($.dump)?$.dump:void 0,costZeroing:F($.costZeroing)?$.costZeroing:void 0,killswitch:F($.killswitch)?$.killswitch:void 0,logging:F($.logging)?$.logging:void 0,cachekeep:F($.cachekeep)?$.cachekeep:void 0,cacheKeep:F($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:z}}function x6($){if(!("claustrum"in $))return $;let{claustrum:Z,...z}=$;return z}async function i($){try{return{exists:!0,value:JSON.parse(await E1($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function g($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function C1($){let Z;try{Z=(await i($)).value}catch{return null}return BZ(Z)}function R6($,Z){if(!F($))return $;let z=F(Z)?Z:{},X=F(z.main)?z.main:void 0,Y=F(z.accounts)?z.accounts:{},J=F($.quota)?$.quota:{},G=F($.refresh)?$.refresh:{},B=X??J,H=X??G,K=G.mainRefreshLeaseId!==void 0?{id:G.mainRefreshLeaseId,until:G.mainRefreshLeaseUntil,tokenHash:G.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!F(D))return D;let V=typeof D.id==="string"&&F(Y[D.id])?Y[D.id]:{};return{...D,...V}}):void 0;return S6({...$,refresh:g({...G,mainLastRefreshError:G.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:K.id,mainRefreshLeaseUntil:K.until,mainRefreshLeaseTokenHash:K.tokenHash}),quota:g({...J,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:U})}async function I1($){let Z=await i($.configPath);if(!Z.exists)return null;let z=await i($.statePath);return L6(R6(Z.value,z.value))}var q6=new Set;async function az($){try{let{exists:Z,value:z}=await i($.configPath);if(!Z)return null;if(!F(z))throw Error("settings must be an object");let X=F(z.refresh)?z.refresh:{},Y=F(z.quota)?z.quota:{};return{version:1,accounts:[],routing:F(z.routing)?z.routing:void 0,fallbackOn:Array.isArray(z.fallbackOn)?z.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:g({enabled:X.enabled,refreshBeforeExpiryMinutes:X.refreshBeforeExpiryMinutes}),quota:g({enabled:Y.enabled,checkIntervalMinutes:Y.checkIntervalMinutes,refreshEveryNRequests:Y.refreshEveryNRequests,minimumRemaining:Y.minimumRemaining,failClosedOnUnknownQuota:Y.failClosedOnUnknownQuota}),dump:F(z.dump)?z.dump:void 0,costZeroing:F(z.costZeroing)?z.costZeroing:void 0,killswitch:F(z.killswitch)?z.killswitch:void 0,logging:F(z.logging)?z.logging:void 0,cachekeep:F(z.cachekeep)?z.cachekeep:void 0,cacheKeep:F(z.cacheKeep)?z.cacheKeep:void 0}}catch{if(!q6.has($.configPath))q6.add($.configPath),Z$.warn("could not read OpenAI auth settings; using defaults",{path:$.configPath});return null}}function S6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function k1($){return g({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function T6($){if($.type==="api")return g({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return g({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function v$($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function t0($,Z,z){if(z in Z)$[z]=Z[z];else delete $[z]}function f1($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function b1($,Z){if(!f1($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var y1=300000;function F6($,Z){if($===void 0)return 0;return $>Z+y1?0:$}function w1($,Z,z){let X=Date.now(),Y=F6(Z.lastRefreshedAt,X),J=F6(z.lastRefreshedAt,X),G=Z.expires??0,B=z.expires??0,H=J>Y?z:Y>J?Z:B>G?z:G>B?Z:b1(Z,z);t0($,H,"access"),t0($,H,"refresh"),t0($,H,"expires"),t0($,H,"lastRefreshedAt"),t0($,H,"lastRefreshError")}function h1($,Z){if(!F($))return Z;let z=$,X=v$(z.quota),Y=v$(Z.quota),J=X>Y,G=J?{...z,...Z,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...Z};if(!J&&!("lastQuotaRefreshError"in Z))delete G.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete G.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||z.lastUsed>Z.lastUsed))G.lastUsed=z.lastUsed;return w1(G,z,Z),G}function A6($){let Z=$.refresh?g({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?g({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return S6({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:z,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,cacheKeep:$.cacheKeep,mainAccountId:$.mainAccountId,accounts:$.accounts.map(k1)})}async function z$($,Z=!1){let z=Date.now(),X=z+M1,Y=0;while(Date.now()<=X){Y++;let B=await b({name:"save",ttlMs:N1,path:$,renew:Z});if(B)return B;let H=X-Date.now();if(H<=0)break;await F1(Math.min(ZZ+f6(ZZ),H))}let J=Date.now()-z,G=Math.round(J/Math.max(1,Y));throw Error(`Timed out after ${J}ms waiting for the account store lock on ${$} (${Y} attempts, ~${G}ms apart; retry interval is ${ZZ}ms). A gap near the retry interval means lock contention; a much larger one means this process's event loop was saturated and the wait expired without getting scheduled.`)}function E6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,T6(z)]));return{version:1,main:g({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function BZ($){if(!F($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!F(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function m1($,Z,z,X){if(!F($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],J=[];for(let G of Z){if(z.has(G))continue;if(X.has(G))continue;let B=$.accounts.find((H)=>F(H)&&typeof H.id==="string"&&H.id.trim()===G);if(!B)continue;Y.push(B),J.push(G)}return{preservedRawEntries:Y,preservedIds:J}}function v1($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!F(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function g1($,Z,z){let X=BZ($);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:J}=m1($,X,Z,z);return P6(J),Y}async function nz($,Z,z={}){let{configPath:X,statePath:Y}=Z,J=await z$(X);try{let G=await z$(Y);try{let B=await i(X),H=await i(Y),Q=(B.exists?L6(R6(B.value,H.value)):null)??p1(),K=new Set(Q.accounts.map((w)=>w.id)),W=BZ(B.value)??new Set,U=$(Q,{rawRosterIds:[...W],loadedRosterIds:[...K]})??Q,D=new Set(z.allowDrop??[]),V=g1(B.value,K,D),j=A6(U),M=new Set((Array.isArray(j.accounts)?j.accounts:[]).map((w)=>F(w)&&typeof w.id==="string"?w.id.trim():"").filter(Boolean)),L=V.filter((w)=>{if(!F(w))return!1;if(typeof w.id!=="string")return!1;return!M.has(w.id.trim())}),R=F(B.value)?B.value:{},p={...x6(R),...j,accounts:[...Array.isArray(j.accounts)?j.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return Q;if(await d(X,p),z.canWrite&&!z.canWrite())return Q;return await d(Y,E6(U)),Z$.debug("account config written",{accountCount:p.accounts.length,accountIds:v1(p.accounts)}),U}finally{await G.release()}}finally{await J.release()}}function p1(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function l1($,Z){$.main=$.main??{};let z=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:v$($.main.quota),X=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:v$(Z.quota?.mainQuota);if(z>X)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function d1($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function YZ($){if(Array.isArray($))return $.map(YZ);if(!F($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,z])=>[Z,YZ(z)]))}async function c1($,Z,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=Z.statePath,J=await z$(Y);try{let G=(await i(Y)).value,B=F(G)?{...G,version:1}:{version:1};if(z.mainQuota)l1(B,$);if(z.mainRefresh)d1(B,$);if(z.accounts){let H=z.accounts===!0?null:new Set(z.accounts),Q=await C1(Z.configPath);B.accounts={...F(B.accounts)?B.accounts:{}};for(let K of $.accounts){if(H&&!H.has(K.id))continue;if(Q&&!Q.has(K.id))continue;B.accounts[K.id]=h1(B.accounts[K.id],T6(K))}if(H){for(let K of H)if(!$.accounts.some((W)=>W.id===K))delete B.accounts[K]}if(Q){for(let K of Object.keys(B.accounts))if(!Q.has(K))delete B.accounts[K]}}if(X&&!X())return;await d(Y,YZ(B))}finally{await J.release()}}function u1($){return $?.fallbackOn?.length?$.fallbackOn:O1}function oz($,Z){return u1(Z).includes($)}function i1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??U6.primary,secondary:Z.secondary??Z["1w"]??U6.secondary}}function JZ($){return $?.quota?.enabled!==!1}function X$($){return $?.quota?.failClosedOnUnknownQuota??P1}function C6($,Z,z=Date.now()){if(!JZ(Z))return!0;if(!$)return!X$(Z);let X=i1(Z),Y=X$(Z);for(let J of["primary","secondary"]){let G=$[J];if(!G)continue;if(w$(G,z)){if(Y)return!1;continue}if(G.remainingPercent<X[J])return!1}return!0}function g$($){return $?.killswitch?.enabled===!0}function N6($){return{primary:$?.primary??$?.["5h"]??XZ.primary,secondary:$?.secondary??$?.["1w"]??XZ.secondary}}function rz($){return $?.cacheKeep??$?.cachekeep}function M6($){return typeof $==="number"&&Number.isFinite($)?$:0}function I6($,Z){if(!$?.killswitch)return XZ;if($.killswitch.schema===_1){let{accounts:z,defaults:X}=$.killswitch,Y=Z??"main",J=F(z)&&Object.hasOwn(z,Y)&&F(z[Y])?z[Y]:F(X)?X:void 0;return{primary:M6(J?.primary),secondary:M6(J?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return N6($.killswitch.accounts[Z]);return N6($.killswitch.main)}function k6($,Z,z,X=Date.now()){if(!g$(Z))return!0;if(!$)return!X$(Z);let Y=I6(Z,z),J=X$(Z);for(let G of["primary","secondary"]){let B=$[G];if(!B)continue;if(w$(B,X)){if(J)return!1;continue}if(B.remainingPercent<Y[G])return!1}return!0}function tz($,Z,z,X){if(!g$(X))return 300;let Y=[],J=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:H}of J){if(!H)continue;let Q=I6(X,B),K=[],W=!1;for(let U of["primary","secondary"]){let D=H[U];if(!D||w$(D,z))continue;if(D.remainingPercent>=Q[U])continue;let V=D.resetsAt?Date.parse(D.resetsAt):NaN;if(!Number.isFinite(V)||V<=z){W=!0;break}K.push(V)}if(W||K.length===0)continue;Y.push(Math.max(...K))}if(Y.length===0)return 300;let G=Math.min(...Y);return Math.max(1,Math.ceil((G-z)/1000))}function j6($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function ez($,Z){let{configPath:z,statePath:X}=Z;if(!$)return;try{let J=await i(z);if(J.exists&&F(J.value)&&j6(J.value))return}catch{}let Y=await z$(z);try{let J=await z$(X);try{let G=await i(z);if(G.exists&&F(G.value)){if(j6(G.value))return}if(!$)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let K=q$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(K)B.mainAccountId=K}let H=G.exists&&F(G.value)?G.value:{},Q={...x6(H),...A6(B)};await d(z,Q),await d(X,E6(B))}finally{await J.release()}}finally{await Y.release()}}function s1($){return $?.refresh?.enabled!==!1}function a1($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function f6($){return Math.floor(Math.random()*($+1))}function P0($,Z,z){return!$.access||!$.expires||$.expires-z<=a1(Z)}function n1($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function e0($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class b6 extends Error{constructor($){super(`Refusing to refresh account ${$}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}var o1="common-auth-placeholder:v1:openai",y6="main";function $X($){return F($)&&$.type==="oauth"&&($.refresh===o1||$.refresh===B6)}function ZX($){return $?.accounts.find((Z)=>Z.id===y6&&Z.enabled!==!1&&u(Z))}function zX($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==y6)}}function E($,Z){let z=$.accounts.findIndex((X)=>X.id===Z.id);if(z!==-1)$.accounts[z]=Z}function $$($){return $ instanceof Error?$.message:String($)}function GZ($,Z,z){if(Z instanceof o0)return;$.lastRefreshError=bZ({error:Z,now:z,refreshToken:$.refresh,previous:$.lastRefreshError})}function zZ($,Z,z){if(Z instanceof o0)return;if($.lastQuotaRefreshError=g0({error:Z,now:z,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)GZ($,Z,z)}function _6($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return Number.isFinite(z)?z>Z:!0}function r1($,Z){if(!$)return!1;return _6($.primary,Z)||_6($.secondary,Z)}function t1($,Z,z){if(!$)return!1;let X=Z?.quota?.checkIntervalMinutes??5,Y=Math.max(1,X)*60000,J=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return z-J<Y}function O6($,Z,z){return!t1($.quota,Z,z)}function e1($,Z,z,X){return D3(z)&&C6($.quota,Z,X)&&r1($.quota,X)}function $2($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var Z2=60000,z2=60000,X2=600000;function Y2($){return`fallback-oauth-refresh-${D1("sha256").update($).digest("base64url").slice(0,16)}`}var J2=1e4,G2=100;class B2{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor($){this.options=$,this.now=$.now??Date.now,this.fetchImpl=$.fetchImpl??fetch,this.paths=$.paths,this.quotaManager=$.quotaManager??null,this.onFallbackStorageChanged=$.onFallbackStorageChanged}assertNotTombstoned($){if($)y$($.refresh)}seedFallbackQuota($,Z){if(!this.quotaManager)return;if(!$.quota)return;let z=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(z<=0)return;let X=this.quotaManager.getFallback($.id,$.access);if(X&&X.checkedAt>=z)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:z+$2(Z),checkedAt:z},$.access,!1,$.accountId)}async load(){return I1(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await c1($,this.paths,{accounts:Z??!0},this.options.canWrite)}startBackgroundRefresh(){let $=async()=>{if(await this.options.backgroundRefreshPaused?.())return;if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if($().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{$().catch(()=>{})},Z2+f6(z2)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($){let Z=$!==void 0?$:await this.load();if(!Z)return[];let z=[],X=!1;for(let Y of Z.accounts){if(Y.enabled===!1||!u(Y))continue;if(e0(Z,Y))continue;if(_0(Y))continue;let J=!1,G=Y;try{if(P0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&Q0(B,G.refresh,this.now()))throw J=!0,Error(V$(B,this.now()));try{G=await this.refreshAccount(G,Z),X=!0}catch(H){if(R1(H))continue;J=!0;let Q=Z.accounts.find((K)=>K.id===Y.id&&u(K));if(Q&&!Q0(Q.lastRefreshError,Q.refresh,this.now()))GZ(Q,H,this.now()),E(Z,Q),X=!0;throw H}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))z.push(G)}catch(B){let H=n1(G,this.now());if(J){if(!H)continue}else if(!H)continue;if(e1(G,Z,B,this.now()))O0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:$$(B)}),z.push(G);else if(!X$(Z))z.push(G)}}if(X){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((J)=>{Z$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:$$(J)})})}return z}async markUsed($){try{let Z=await this.load();if(!Z)return;let z=Z.accounts.find((X)=>X.id===$.id);if(!z)return;z.lastUsed=this.now(),await this.save(Z,[z.id])}catch(Z){Z$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:$$(Z)})}}accountPassesQuotaPolicy($,Z){return C6($.quota,Z,this.now())}quotaPolicyAccount($){if(!this.quotaManager)return $;let Z=this.quotaManager.getFallback($.id,$.access)?.quota;return Z?{...$,quota:Z}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!s1($))return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!u(z))continue;if(e0($,z))continue;if(_0(z))continue;if(!P0(z,$,this.now()))continue;if(Q0(z.lastRefreshError,z.refresh,this.now()))continue;try{O0.debug("fallback oauth background due",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),await this.refreshAccount(z,$),Z=!0}catch(X){O0.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:$$(X)}),GZ(z,X,this.now()),E($,z),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!JZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!u(z))continue;if(e0($,z))continue;if(_0(z))continue;let X=z;try{if(P0(X,$,this.now())){if(Q0(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,$),Z=!0}if(S0(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,$),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):O6(X,$,this.now())))continue;await this.refreshAccountQuota(X,$),Z=!0}catch(Y){zZ(z,Y,this.now()),E($,z),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),z=[];if(!Z||!JZ(Z))return{storage:Z,errors:z};if(!this.options.fetchQuotaFn)return{storage:Z,errors:z};let X=$.force??!1,Y=!1;for(let J of Z.accounts){if(J.enabled===!1||!u(J))continue;if(e0(Z,J))continue;if(_0(J))continue;let G=J;try{if(P0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&Q0(B,G.refresh,this.now()))throw Error(V$(B,this.now()));G=await this.refreshAccount(G,Z),Y=!0}if(!X&&!O6(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,E(Z,G),Y=!0;continue}await this.refreshAccountQuota(G,Z),Y=!0}catch(B){zZ(J,B,this.now()),E(Z,J),Y=!0,z.push({accountId:J.id,message:$$(B)})}}if(Y)await this.save(Z);return{storage:Z,errors:z}}async refreshAccount($,Z,z={}){let X=this.refreshPromises.get($.id);if(X){let G=await X;return E(Z,G),G}let Y=this.refreshAccountNow($,Z,z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let J=await Y;return E(Z,J),J}async waitForConcurrentFallbackRefresh($,Z,z,X){let Y=Date.now()+J2;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,G2));let J=await this.load(),G=J?.accounts.find((Q)=>Q.id===$.id&&u(Q));if(!G)continue;if(this.assertNotTombstoned(G),(G.access!==z.access||G.refresh!==z.refresh||(G.expires??0)>(z.expires??0)+60000)&&(X.force||!P0(G,J,this.now())))return E(Z,G),O0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G;let H=G.lastRefreshError;if(H&&Q0(H,G.refresh,this.now()))throw E(Z,G),Error(V$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,z){if(z.asPoolMain||!Z)return;if(e0($,Z))throw new b6(Z.id)}async refreshAccountNow($,Z,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===$.id&&u(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!P0(Y,X,this.now()))return E(Z,Y),Y;let J=Y??$,G=await b({name:Y2(J.id),ttlMs:X2,path:this.paths.configPath,renew:!0});if(!G){O0.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:J.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,J,z);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),Y=X?.accounts.find((K)=>K.id===$.id&&u(K)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!P0(Y,X,this.now()))return E(Z,Y),Y;if(!Y)throw new m$($.id);J=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});O0.debug("fallback oauth refresh request start",{pid:process.pid,accountId:J.id,force:z.force===!0,expiresInMs:J.expires?J.expires-this.now():void 0});let H=await B({refreshToken:J.refresh,fetchImpl:this.fetchImpl,now:this.now});if(J.access=H.access,J.refresh=H.refresh,J.expires=H.expires,J.lastRefreshedAt=H.expires-H.expiresIn*1000,J.lastRefreshError=void 0,E(Z,J),await this.save(Z),!(await this.load())?.accounts.some((K)=>K.id===$.id))throw new m$($.id);return O0.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J}finally{await G.release()}}async refreshAccountQuota($,Z){let z=$;if(this.assertNotTombstoned(z),!z.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let X=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(J)=>this.quotaManager?this.quotaManager.refreshFallback(z.id,J):X({accessToken:J,fetchImpl:this.fetchImpl,now:this.now});try{if(!z.access)throw Error(`Fallback account ${$.id} has no access token`);let J=await Y(z.access);z.quota=J,z.lastQuotaRefreshError=void 0,E(Z,z),await this.save(Z)}catch(J){throw zZ($,J,this.now()),E(Z,$),J}}}var w6=["primary","secondary"];function p$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function y0($){return typeof $==="number"&&Number.isFinite($)}function H2($,Z){if(!p$(Z))return;let z=Z.usedPercent;if(!y0(z)||z<0||z>100)return;return{label:$,usedPercent:z,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...y0(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function K2($){let Z=$.spendControl;if(p$(Z)&&typeof Z.reached==="boolean"){let z=(X)=>y0(Z[X])?{[X]:Z[X]}:{};return{kind:"reading",reached:Z.reached,...z("remainingPercent"),...z("usedPercent"),...z("limit"),...z("used"),...z("remaining"),...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...typeof Z.unit==="string"?{unit:Z.unit}:{}}}if($.spendControlCleared===!0)return{kind:"cleared"};return}function W2($,Z){if(!p$($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...y0($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function JX($,Z,z){if(!p$($)||!y0(Z))return;let X=[],Y=[];for(let Q of w6){let K=H2(Q,$[Q]);if(K)X.push(K);else if(z)Y.push({label:Q})}let J=K2($),G=$.resetCreditsAvailable,B=typeof G==="number"&&Number.isSafeInteger(G)&&G>=0?{resetCredits:{value:G,checkedAt:Z}}:void 0,H=W2($.credits,Z);if(X.length===0&&Y.length===0&&!J&&!B&&!H)return;return{checkedAt:Z,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...J?{budget:J}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function h6($){if(!H0($))return;let Z=f($),z={};for(let X of w6){let Y=Z.limits.find((G)=>G.label===X&&G.kind==="reading");if(!Y||!y0(Y.usedPercent))continue;let J={usedPercent:Y.usedPercent,remainingPercent:100-Y.usedPercent,checkedAt:Y.checkedAt,...Y.resetsAt!==void 0?{resetsAt:Y.resetsAt}:{},...Y.windowMinutes!==void 0?{windowMinutes:Y.windowMinutes}:{}};z[X]=J}return z.primary||z.secondary?z:void 0}var v6="main";function QX($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function UX($,Z,z){let X=new Map;if(g$(Z))for(let Y of $)X.set(Y.id,k6(h6(Y.quota),Z,Y.id===v6?void 0:Y.id,z));return X}var VX=5,Q2=5000;function DX($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function qX($,Z=Q2){let z=$.rows.filter((G)=>G.kind==="oauth"&&$.killswitch.get(G.id)!==!1&&f(G.quota).limits.length===0);if(z.length===0)return;if(m({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((G)=>$.killswitch.get(G.id)!==!1))return;let Y=[];if(m({rows:z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(G)=>{let B=$.requestPull(G);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let J;return Promise.race([Promise.all(Y),new Promise((G)=>{J=setTimeout(G,Z)})]).then(()=>{}).finally(()=>clearTimeout(J))}function l$($){return $.reason==="exhausted"||$.reason==="budget-spent"}function U2($,Z){if(!l($))return!1;let z=$;if(!(Z-z.checkedAt<=m0))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function d$($,Z,z){let X=(B)=>Z.killswitch.get(B)!==!1,Y=new Set(z.admitted.filter((B)=>B.lastPath!==!0&&X(B.id)).map((B)=>B.id)),J=new Map(z.refused.map((B)=>[B.id,B])),G=$.filter((B)=>{if(B.kind!=="oauth"||!X(B.id))return!1;if(J.get(B.id)?.reason!=="exhausted")return!1;let H=f(B.quota);if(W0(H,Z.now))return!1;return U2(H.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:G}}function V2($,Z=$.rows){return m({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class D2{#$=new Set;served($,Z,z){let X=V2($),Y=d$($.rows,$,X),J=new Set(Y.credits);if(Y.free.has(Z)){this.#$.clear();return}for(let G of[...this.#$])if(!J.has(G))this.#$.delete(G);if(!J.has(Z)||this.#$.has(Z))return;this.#$.add(Z),z?.info("serving requests on prepaid credits",{accountId:Z,reason:"free quota used up"})}has($){return this.#$.has($)}ids(){return new Set(this.#$)}}function g6($,Z,z){if($===void 0)return{reason:"no-credential"};if(z.get($)===!1)return{reason:"killswitch"};let X=Z.excluded.find((J)=>J.id===$);if(X?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:X.until};if(X)return{reason:"no-credential"};let Y=Z.refused.find((J)=>J.id===$);if(Y&&"resetAtMs"in Y)return{reason:"quota-exhausted",resetAtMs:Y.resetAtMs};if(Y)return{reason:"quota-unknown"};return{reason:"no-credential"}}function m6($,Z,z){if(Z.refused.find((Y)=>!l$(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return g6($[0],Z,z)}function FX($){let Z=$.replayable!==!1,z=$.mainId===void 0?v6:$.mainId??"",X=Z?$.placement:"main-first",Y=Y3({rows:$.rows,placement:X,formerMainId:z,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),J=W$($.rows.map((W)=>W.id),X,z),G=new Set(Y.admission.refused.filter((W)=>l$(W)&&$.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=J.filter((W)=>G.has(W)),H=d$($.rows,$,Y.admission),Q=Y.order.filter((W)=>H.free.has(W)),K=J.filter((W)=>H.credits.includes(W));if(!Z){let W=J.includes(z),U=W?z:Q[0]??K[0]??Y.order[0]??B[0];if(U!==void 0&&Y.order.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&K.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&G.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:W?g6(z,Y.admission,$.killswitch):m6(J,Y.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(K.length>0){let W=Y.order.length>0?Y.order:B;return{kind:"send",order:[...K,...W.filter((U)=>!K.includes(U))],lastPath:!1}}if(Y.order.length>0)return{kind:"send",order:Y.order,lastPath:!1};if(B.length>0)return{kind:"send",order:B,lastPath:!0};return{kind:"block",block:m6(J,Y.admission,$.killswitch)}}function NX($){let Z=m({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=new Map;for(let X of $.rows)z.set(X.id,f(X.quota));for(let X of Z.admitted)if(X.projection)z.set(X.id,X.projection);return{projections:z,excluded:new Set(Z.excluded.map((X)=>X.id))}}function p6($,Z,z){let X=z.exclude,Y=X?$.rows.filter((G)=>!X.has(G.id)):$.rows,J=new Map;for(let G of Y){let B=Z.resetCredits(G.id);if(B!==void 0)J.set(G.id,B)}return K3({rows:Y,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...z.pendingBytes?{pendingBytes:z.pendingBytes}:{},rowReservePercent:(G)=>Z.reservePercent(G.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:J,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function MX($,Z,z,X){let Y=p6($,Z,{exclude:z,pendingBytes:X}),J=$.rows.filter((K)=>!z.has(K.id)),G=d$(J,$,Y.admission),B=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(B&&G.free.has(B.accountId))return B;let H=G.credits[0];if(H===void 0)return B;let Q=f(J.find((K)=>K.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function jX($,Z,z){let X=$.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},J=p6($,Z,{pin:z}),G=d$($.rows,$,J.admission),B=G.credits.includes(z),H=G.credits.some((W)=>W!==z);if(J.outcome==="dispatch"){let W=!G.free.has(J.accountId);if(J.pin.action==="assign"){if(W&&B)return{kind:"serve"};return Y}if(J.accountId!==z)return{kind:"detour"};if(W&&H)return Y;return{kind:"serve"}}let Q=J.admission.refused.find((W)=>W.id===z),K=X||Q!==void 0&&l$(Q);if(B)return{kind:"serve"};if(H)return K?Y:{kind:"detour"};if(!X&&Q&&l$(Q))return{kind:"last-path"};return{kind:"none"}}function _X($,Z,z,X){let Y=$.killswitch.get(z);return H3({quota:Z.projections.get(z),now:$.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as l6}from"node:os";import{join as d6}from"node:path";var q2=["error","warn","info","debug","trace"];function F2(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?d6(l6(),"opencode-openai-auth","opencode-openai-auth.log"):d6(l6(),"opencode-openai-auth.log"))}function N2(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&q2.includes($)?$:void 0}c6({file:F2,level:N2});if(process.once("beforeExit",async()=>{try{await c$()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>c$());
|
|
91
|
+
export{H0 as Mc,h0 as Nc,F8 as Oc,_Z as Pc,e6 as Qc,LZ as Rc,Y8 as Sc,J8 as Tc,f as Uc,TZ as Vc,M8 as Wc,W$ as Xc,j8 as Yc,J3 as Zc,_8 as _c,I4 as $c,k4 as ad,P3 as bd,L8 as cd,E8 as dd,fZ as ed,bZ as fd,Q0 as gd,V$ as hd,vZ as id,pZ as jd,b8 as kd,wZ as ld,hZ as md,q$ as nd,w8 as od,q0 as pd,g8 as qd,p8 as rd,l8 as sd,d8 as td,H7 as ud,W7 as vd,Q7 as wd,U7 as xd,q as yd,F0 as zd,D4 as Ad,F9 as Bd,N9 as Cd,M9 as Dd,C3 as Ed,O9 as Fd,x4 as Gd,P9 as Hd,x as Id,n3 as Jd,$z as Kd,_0 as Ld,o0 as Md,Lz as Nd,xz as Od,Iz as Pd,y as Qd,G0 as Rd,u as Sd,_1 as Td,iz as Ud,XZ as Vd,x1 as Wd,C1 as Xd,I1 as Yd,az as Zd,nz as _d,c1 as $d,u1 as ae,oz as be,C6 as ce,g$ as de,rz as ee,I6 as fe,k6 as ge,tz as he,ez as ie,a1 as je,e0 as ke,y6 as le,$X as me,ZX as ne,zX as oe,X2 as pe,Y2 as qe,B2 as re,JX as se,h6 as te,v6 as ue,QX as ve,UX as we,VX as xe,DX as ye,qX as ze,U2 as Ae,D2 as Be,FX as Ce,NX as De,MX as Ee,jX as Fe,_X as Ge};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{O as
|
|
1
|
+
import{Hf as F}from"./index-2f9w48sc.js";import{randomUUID as k}from"node:crypto";import{lstat as N,readFile as f,rename as y,unlink as I}from"node:fs/promises";import{tmpdir as P}from"node:os";import{dirname as W,join as E,resolve as K}from"node:path";var O=process.platform==="win32",L=new Set;function V(j){if(j?.reason==="io-error"){if(j.win32Code===2||j.win32Code===3)return"ENOENT";if(j.win32Code===80||j.win32Code===183)return"EEXIST"}return j?.code??"ERR_PRIVATE_FILE"}var _;var v="native-addon-unavailable";function b(j){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:j}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:v})}function g(j,x){return x instanceof j.PrivateFilesUnavailableError||x?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function m(j){try{await j.verifyPrivatePath(E(P(),`.common-auth-private-files-probe-${k()}`),"file")}catch(x){if(g(j,x))throw b(x)}}function $(){return _??=import("@cortexkit/private-files").then(async(j)=>{if(O)await m(j);return j},(j)=>{throw O?b(j):j}),_}class Q extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor(j,x,z){let q=z;super(q?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${x}: ${j} (${v}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${x}: ${j} (${q?.reason??q?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:z});this.path=j,this.stage=x,this.name="PrivateFileError",this.code=V(q),this.win32Code=q?.win32Code,this.reason=q?.reason}}async function T(j,x,z){try{return await z()}catch(q){if(q instanceof Q)throw q;throw new Q(j,x,q)}}var c;async function Y(j,x){j=K(j),x??=c,await T(j,"safe-parent",async()=>{let z=await(await $()).verifySafeParent(j,x);if(z.ok===!1){if(z.reason==="io-error"||z.reason==="wrong-kind")await N(j);throw new Q(z.level??z.path,"safe-parent",{...z,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function S(j,x,z=!1){if(j=K(j),x==="directory")return Y(j);await T(j,"verify",async()=>{let q=await $(),H=await q.verifyOwnerOnly(j),C=!1;if(!H.ok){let{reason:J}=H.refusal;if(J==="io-error")await q.verifyPrivatePath(j,x);if(z&&[q.EXTRA_ACE,q.NOT_PROTECTED,q.NULL_DACL,q.EMPTY_DACL].includes(J))await Y(W(j)),await q.securePrivatePath(j,x),C=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:J,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await q.verifyPrivatePath(j,x),C&&!L.has(j))L.add(j),process.emitWarning(`Private permissions tightened: ${j}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function w(j,x=!1,z){j=K(j),await T(j,"directory",async()=>{let q=await $();try{return await N(j),await Y(j,z)}catch(C){if(V(C)!=="ENOENT")throw C}let H=W(j);if(H===j)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await w(H,!1,z);try{await q.createOwnerOnly(j,{kind:"dir"})}catch(C){if(V(C)!=="EEXIST")throw C}await Y(j,z)})}async function p(j,x=!1){if(!O)return f(j,"utf8");return(await u(j,x)).toString("utf8")}async function u(j,x=!1){if(!O)return f(j);if(j=K(j),x)await Y(W(j)),await S(j,"file",!0);return T(j,"read",async()=>(await $()).readOwnerOnly(j))}async function d(j,x){await Y(W(K(j))),await T(j,"create",async()=>{await(await $()).createPrivateFile(K(j),x)})}async function r(j){await Y(W(K(j))),await T(j,"directory-create",async()=>{await(await $()).createOwnerOnly(K(j),{kind:"dir"})})}async function l(j,x,z={}){j=K(j),x=K(x);let q=z.now??(()=>performance.now()),H=q(),C=z.deadline??1/0,J,Z=[0,10,20,40,80,100],U,G=0;for(let D of Z){let R=Math.min(J??1/0,C);if(q()>=R)break;if(D)await(z.sleep??((B)=>new Promise((X)=>setTimeout(X,B))))(Math.min(D,Math.max(0,R-q())));if(q()>=R)break;let A=q();if(await z.beforeRename?.(),J!==void 0)J+=q()-A;if(q()>=C)break;G++;try{return await(z.rename??y)(j,x),{attempts:G,elapsedMs:q()-H}}catch(B){U??=B;let X=B;if(!(X.win32Code!==void 0?X.win32Code===32||X.win32Code===33:["EBUSY","EPERM","EACCES"].includes(X.code??"")&&!X.reason))break;J??=q()+500}}let M=new Q(x,"rename",U??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw M.attempts=G,M.elapsedMs=q()-H,M}async function e(j,x,z={}){j=K(j),await w(W(j));try{await S(j,"file",!0)}catch(G){if(G.code!=="ENOENT")throw G}let q=K(z.stagePath??`${j}.${k()}.tmp`);if(W(q)!==W(j))throw new Q(j,"stage-directory",{code:"EXDEV"});let H=!1,C=!1,J={attempts:0,elapsedMs:0},Z="stage-create",U=(G)=>{try{z.onOutcome?.({path:j,stage:G?.stage??"published",published:C,fileDurable:C,durabilityConfirmed:!1,attempts:G?.attempts??J.attempts,elapsedMs:G?.elapsedMs??J.elapsedMs,...G&&{code:G.code,win32Code:G.win32Code}})}catch{}};try{if(await d(q,x),H=!0,Z="before-rename",J=await l(q,j,z),H=!1,C=!0,Z="published-callback",z.onRenamed?.(),Z="published-verify",await S(j,"file"),z.durable&&z.durability!=="file-only-on-windows")throw new Q(j,"directory-sync-unsupported",{code:"ENOTSUP"});U()}catch(G){let M=G instanceof Q?G:new Q(j,Z,G);if(M.published=C,M.fileDurable=C,C)Object.assign(M,J);if(H){try{await I(q)}catch{M.orphanPath=q}H=!1}throw U(M),M}finally{if(H)await I(q).catch(()=>{})}}
|
|
2
|
+
export{O as qf,Q as rf,T as sf,Y as tf,S as uf,w as vf,p as wf,d as xf,r as yf,l as zf,e as Af};
|