@cortexkit/opencode-openai-auth 1.9.5 → 1.10.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.
Files changed (43) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-CZ16goZ6.d.ts → codex-request-BLzSBegI.d.ts} +4 -0
  3. package/dist/{index-4gnwkw3a.js → index-17rh67pr.js} +1 -1
  4. package/dist/{index-npj40h62.js → index-29ztc0ay.js} +2 -2
  5. package/dist/{index-f1cqptqa.js → index-361xxyg2.js} +2 -2
  6. package/dist/index-3p1tc2e2.js +91 -0
  7. package/dist/index-3r9thx6n.js +76 -0
  8. package/dist/{index-mcy24ej8.js → index-95z5dpe1.js} +2 -2
  9. package/dist/index-dcyhv7eh.js +8 -0
  10. package/dist/{index-y4j7y8b8.js → index-dkhy2peg.js} +1 -1
  11. package/dist/{index-7qxa018z.js → index-fd3f8vw2.js} +2 -2
  12. package/dist/{index-s2vrkdj4.js → index-mf3dqvbn.js} +2 -2
  13. package/dist/{index-cf0mrvqj.js → index-mkda7acs.js} +1 -1
  14. package/dist/{index-s52j2h64.js → index-w37815v4.js} +1 -1
  15. package/dist/index-ya96m6wr.js +64 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.js +1 -1
  18. package/dist/rpc/port-file.js +1 -1
  19. package/dist/rpc/protocol.js +1 -1
  20. package/dist/rpc/rpc-client.js +1 -1
  21. package/dist/rpc/rpc-dir.js +1 -1
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/{token-djwdynff.js → token-pd3t5f20.js} +1 -1
  24. package/dist/token-util-807rzwws.js +1 -0
  25. package/dist/tui-preferences.js +1 -1
  26. package/dist/v2/server.d.ts +1 -2
  27. package/dist/v2/server.js +3 -3
  28. package/package.json +6 -6
  29. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +32 -8
  30. package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
  31. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +10 -5
  32. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
  33. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
  34. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +32 -8
  35. package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
  36. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +10 -5
  37. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
  38. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
  39. package/dist/index-1nrre3d8.js +0 -91
  40. package/dist/index-41yn5c02.js +0 -8
  41. package/dist/index-8rj2xddq.js +0 -63
  42. package/dist/index-h3vtzckv.js +0 -76
  43. package/dist/token-util-0xt1ws82.js +0 -1
@@ -1,91 +0,0 @@
1
- import{Je as d,Me as y,Ne as Q3,Oe as V$,Pe as U3,Qe as V3}from"./index-41yn5c02.js";import{hf as u$,if as A,kf as s6,of as U6}from"./index-s2vrkdj4.js";import{Cf as W4,rf as Z0,sf as g0,vf as K4,xf as S3,yf as T$}from"./index-mcy24ej8.js";var L="all",t$=Object.freeze(["primary"]);function UZ($){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 QZ($){return typeof $==="string"&&$.length>0}function T($,Z,z){return $[Z]===void 0||z($[Z])}function o6($){return S($)&&$>0}function r$($){return typeof $==="string"}function r6($){if(!n($)||!QZ($.scope)||!QZ($.label))return!1;switch($.kind){case"reading":return S($.checkedAt)&&S($.usedPercent)&&T($,"resetsAt",r$)&&T($,"windowMinutes",o6);case"retired":return S($.retiredAt);case"absent":return S($.checkedAt);default:return!1}}function t6($){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",r$)&&T($,"limit",S)&&T($,"used",S)&&T($,"remaining",S)&&T($,"unit",r$)}function VZ($){return n($)&&S($.value)&&Number.isInteger($.value)&&$.value>=0&&S($.checkedAt)}function e$($){return n($)&&Object.values($).every(VZ)}function e6($){return typeof $==="boolean"}function l($){return n($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&T($,"balance",S)&&T($,"overageLimitReached",e6)&&S($.checkedAt)}function $3($){if(!n($))return;let Z=Object.entries($).filter(([,z])=>VZ(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=$3(Z),G=l(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...G===void 0?{}:{credits:G}}}function H0($){if(!n($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let z of $.limits){if(!r6(z))return!1;let X=x0(z.scope,z.label);if(Z.has(X))return!1;Z.add(X)}return T($,"budget",t6)&&T($,"counters",e$)&&T($,"credits",l)}var MZ=900000,_Z="no quota reading yet",jZ="no limits reported";function OZ($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let Y=Math.floor(Z/60),G=Z%60;return G===0?`${Y}h`:`${Y}h${G}m`}let z=Math.floor(Z/1440),X=Math.floor(Z%1440/60);return X===0?`${z}d`:`${z}d${X}h`}function PZ($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function Z3($){if($.scope!==L||$.windowMinutes===void 0)return $.label;return PZ($.windowMinutes)}function z3($){return Math.min(100,Math.max(0,$))}function G$($){return Math.round(z3($))}function DZ($){return`${G$($)}% left`}function FZ($,Z,z){let X=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(X)&&X>z?{resetIn:OZ(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>Z&&X<=z}}function $8($,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===L)return-1;if(Z.scope===L)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function Z8($){let Z=LZ($.filter(({part:z,scope:X})=>z.kind==="window"&&X!==L).map(({scope:z})=>z));for(let z of $)z.part.short=z.part.kind==="budget"?"cr":z.scope===L?z.part.name:Z.get(z.scope)??z.scope;return $}function qZ($){return Number.isFinite($.remainingPercent)&&Number.isFinite($.checkedAt)}function X3($,Z,z=!1){if(!$)return{windows:[]};let{now:X}=Z,G=$.limits.filter((H)=>H.kind==="reading"&&(z||qZ(H))).sort($8).map((H)=>{let Q=qZ(H)?{kind:"window",reading:"known",name:Z3(H),short:"",figure:DZ(H.remainingPercent),remainingPercent:z3(H.remainingPercent),checkedAt:H.checkedAt,...FZ(H.resetsAt,H.checkedAt,X)}:{kind:"window",reading:"unknown",name:Z3(H),short:"",figure:"no reading",resetSinceReading:!1};return{scope:H.scope,...H.windowMinutes===void 0?{}:{windowMinutes:H.windowMinutes},part:Q}}),J=$.budget;if(J){let H=J.remainingPercent,Q=J.reached?"credits spent":H!==void 0?`credits ${DZ(H)}`:"credits available";G.push({scope:L,spent:J.reached,part:{kind:"budget",reading:"known",name:"credits",short:"",figure:Q,...H===void 0?{}:{remainingPercent:z3(H)},checkedAt:J.checkedAt,...FZ(J.resetsAt,J.checkedAt,X)}})}Z8(G);let B=G.flatMap(({part:H})=>H.reading==="known"&&H.checkedAt!==void 0?[H.checkedAt]:[]);if(B.length>0){let H=X-Math.min(...B);if(H>(Z.staleAfterMs??MZ))return{windows:G,age:`checked ${OZ(H)} ago`}}return{windows:G}}function z8($,Z){return X3($,Z).age!==void 0}function NZ($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function LZ($){let Z=[...new Set($.map(NZ))],z=new Map(Z.map((Y)=>[Y,2])),X=(Y)=>Y.slice(0,z.get(Y));for(;;){let Y=new Map;for(let J of Z)Y.set(X(J),[...Y.get(X(J))??[],J]);let G=!1;for(let J of Y.values()){if(J.length<2)continue;for(let B of J){let H=z.get(B)??2;if(H<B.length)z.set(B,H+1),G=!0}}if(!G)break}return new Map($.map((Y)=>[Y,X(NZ(Y))]))}var X8=2;function Y8($){let Z=$.map((X)=>X.label.trim()||X.scope),z=LZ(Z);return Z.map((X)=>z.get(X)??X)}function J8($,Z){if(!$||$.length===0)return;let z=Z.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===L))return;let X=$.flatMap((B,H)=>{let K=z.filter(({scope:W})=>W===B.scope).reduce((W,D)=>W===void 0||(D.part.remainingPercent??0)<(W.part.remainingPercent??0)?D:W,void 0);return K?[{group:B,listed:H,window:K}]:[]});if(X.length===0)return;let Y=Y8($),G=(B)=>B.window.part.remainingPercent??0,J=[...X].sort((B,H)=>G(B)-G(H)||B.listed-H.listed).slice(0,X8).sort((B,H)=>B.listed-H.listed);return J.map((B,H)=>{let{windowMinutes:Q}=B.window,K=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[PZ(Q)],`${G$(G(B))}%`].join(" ");return H===J.length-1?`${K} left`:K})}function G8($,Z){let{windows:z}=X3($,Z),X=J8($?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:D})=>W.kind==="window"&&D===L),G=z.filter(({part:W,scope:D})=>W.kind==="window"&&D!==L),J=z.find(({part:W})=>W.kind==="budget"),B=J?.spent?0:J?.part.remainingPercent,Q=[...G.map(({part:W})=>({label:W.short,remaining:W.remainingPercent??0})),...B===void 0||J===void 0?[]:[{label:J.part.short,remaining:B}]].reduce((W,D)=>W===void 0||D.remaining<W.remaining?D:W,void 0),K=Y.map(({part:W})=>`${W.name} ${G$(W.remainingPercent??0)}%`);if(Q)K.push(`${Q.label} ${G$(Q.remaining)}%`);if(K.length===0)return z.map(({part:W})=>W.figure);return K.map((W,D)=>D===K.length-1?`${W} left`:W)}function xZ($,Z){if(Z.form==="narrow")return G8($,Z);let{windows:z,age:X}=X3($,Z),Y=(Z.form??"full")==="full",G=z.map(({part:J})=>{let B=Y&&J.resetIn?`, resets ${J.resetIn}`:"";return`${J.kind==="budget"?"":`${J.name} `}${J.figure}${B}`});return X===void 0?G:[...G,X]}function B8($,Z){let z=xZ($,Z);if(z.length>0)return z.join(" · ");return $&&$.limits.length>0?jZ:_Z}function H8($){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 K8($){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 W8($,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 Q8($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function b($,Z=L){let z=new Map;for(let K of $?.limits??[]){if(K.scope!==Z&&K.scope!==L)continue;let W=z.get(K.label);if(W===void 0){z.set(K.label,K);continue}let D=K.scope===L?W:K,V=K.scope===L?K:W;z.set(K.label,D.kind==="reading"?D:V)}let X=[...z.values()].map(K8).sort(W8),Y=X.filter((K)=>K.kind==="reading"),G=Y.length>0?Y:X,J=G.length>0?Math.min(...G.map((K)=>K.checkedAt)):void 0,B=$?.budget?.kind==="reading"?Q8($.budget):void 0,H=$3($?.counters),Q=l($?.credits)?$.credits:void 0;return{scope:Z,limits:X,...J===void 0?{}:{checkedAt:J},...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 B$($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function h0($,Z){if(typeof $.resetsAt!=="string")return;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z>Z?z:void 0}class H$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function W$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function K$($){return typeof $==="number"&&Number.isFinite($)}function RZ($){return $===void 0||typeof $==="string"&&$!==""}function SZ($){return typeof $==="string"&&$!==""}function w0($,Z){return $[Z]===void 0||K$($[Z])}function Y3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function U8($){return W$($)&&RZ($.scope)&&SZ($.label)&&K$($.usedPercent)&&Y3($,"resetsAt")&&($.windowMinutes===void 0||K$($.windowMinutes)&&$.windowMinutes>0)}function V8($){return W$($)&&RZ($.scope)&&SZ($.label)}function D8($){if(!W$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&w0($,"remainingPercent")&&w0($,"usedPercent")&&Y3($,"resetsAt")&&w0($,"limit")&&w0($,"used")&&w0($,"remaining")&&Y3($,"unit")}function R0($){if(!W$($)||!K$($.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(!U8(Y))return!1;let G=x0(Y.scope??L,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(V8))return!1;return($.budget===void 0||D8($.budget))&&($.counters===void 0||e$($.counters))&&($.credits===void 0||l($.credits))}function F8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function q8($,Z,z){if(Z===void 0)return $;if($!==void 0&&z<$.checkedAt)return $;return{...Z,checkedAt:z}}function N8($,Z){let z=new Map(Object.entries($??{}));for(let[X,Y]of Object.entries(Z??{})){let G=z.get(X);if(G===void 0||Y.checkedAt>=G.checkedAt)z.set(X,Y)}return z.size===0?void 0:Object.fromEntries(z)}function M8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function m0($,Z){let z=$===void 0?void 0:K0($);if($!==void 0&&z===void 0)throw new H$("stored quota map is malformed");if(!R0(Z))throw new H$("quota observation is malformed");let X=z??{limits:[]},Y=Z.checkedAt,G=new Map;for(let M of X.limits)G.set(x0(M.scope,M.label),M);let J=(M)=>{let P=G.get(M);return P===void 0||Y>=UZ(P)},B=new Set;for(let M of Z.readings??[]){let P=M.scope??L,x=x0(P,M.label);if(B.add(x),!J(x))continue;G.set(x,{scope:P,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 P=M.scope??L,x=x0(P,M.label);if(B.has(x)||!J(x))continue;let k=G.get(x);G.set(x,k===void 0||k.kind==="absent"?{scope:P,label:M.label,kind:"absent",checkedAt:Y}:{scope:P,label:M.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:Q,counters:K,credits:W,...D}=X,V=q8(X.budget,Z.budget,Y),U=N8(X.counters,Z.counters),_=M8(X.credits,Z.credits);return{...D,limits:[...G.values()].sort(F8),...V===void 0?{}:{budget:V},...U===void 0?{}:{counters:U},..._===void 0?{}:{credits:_}}}var _8=Object.freeze({validate:H0,decode:K0,merge:m0});function TZ($,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 j8($,Z,z,X,Y){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((B)=>B.label===J))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:J},pullRequested:!0};let G=Z.limits.filter(B$);for(let J of G)if(h0(J,X)===void 0&&!Y.some((B)=>B.scope===J.scope&&B.label===J.label))return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:J.scope,label:J.label},pullRequested:!0};for(let J of G){let B=h0(J,X);if(B!==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:B}}return}function v($){let Z=$.scope??L,z=$.requiredLabels??t$,X=[],Y=[],G=[],J=new Set;for(let V of $.rows){let U=TZ(V.id,$,$.now);if(U){X.push(U);continue}if(V.kind==="api-key"){G.push({id:V.id,kind:V.kind});continue}let _=b(V.quota,Z),M=$.liftedWindows?.get(V.id)??[];if(_.limits.some((x)=>B$(x)&&h0(x,$.now)===void 0&&M.some((k)=>k.scope===x.scope&&k.label===x.label)))J.add(V.id);let P=j8(V.id,_,z,$.now,M);if(P){Y.push(P);continue}G.push({id:V.id,kind:V.kind,projection:_})}let B=new Map(G.flatMap((V)=>{let U=W0(V.projection,$.now);return U?[[V.id,U]]:[]})),H=B.size>0&&B.size===G.length,Q=[];for(let V of G){let U=B.get(V.id);if(U===void 0)Q.push(V);else if(H)Q.push({...V,lastPath:!0});else Y.push({id:V.id,stage:2,reason:"budget-spent",...U})}let K=new Map($.rows.map((V,U)=>[V.id,U])),W=(V,U)=>(K.get(V.id)??0)-(K.get(U.id)??0);Y.sort(W);for(let V of Y)if("pullRequested"in V)J.add(V.id);let D=$.rows.filter((V)=>J.has(V.id)).map((V)=>V.id);for(let V of D)$.requestPull?.(V);return{admitted:Q,refused:Y,excluded:X,pulls:D}}var AZ="main";function O8($){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 Q$($,Z,z=AZ){if(Z==="roster"||!$.includes(z))return[...$];let X=$.filter((Y)=>Y!==z);return Z==="main-first"?[z,...X]:[...X,z]}function J3($){let Z=v($),z=new Set(Z.admitted.map((Y)=>Y.id));return{order:Q$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>z.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function P8($,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((G)=>G.id));return $.find((G)=>!Y.has(G))}function G3($,Z,z){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof z==="string"&&$.wireIdentity!==z)}function L8($,Z,z){let X=new Map;for(let[Y,G]of $){if(Y===z)continue;if(G.quotaCheckedAt!==Z.get(G.accountId))continue;X.set(G.accountId,(X.get(G.accountId)??0)+(G.inputBytes??0))}return X}var v0=900000,CZ=0.016666666666666666,B3=0.000001;function U$($,Z){for(let z of[$?.checkedAt,Z])if(typeof z==="number"&&Number.isFinite(z))return z;return}function IZ($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function kZ($){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 K3($){let Z=($.classifyStatus??IZ)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let z=U$($.quota,$.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||$.now-z>v0)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of kZ($.quota)){let G=Y.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=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 H3($,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 G=Math.max((Y-z)/3600000,CZ);return X/G}function EZ($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function x8($,Z){if(!$.quota)return;let z=U$($.quota,$.quotaCheckedAt);if(z===void 0||Z-z>v0)return;let X=kZ($.quota).map((J)=>H3({remainingPercent:J.remainingPercent??Number.NaN,...J.resetsAt===void 0?{}:{resetsAt:J.resetsAt}},$.reservePercent[J.label]??0,Z)),Y=$.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))X.push(H3({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,Z));let G=X.length>0?Math.min(...X):0;return G>0?{candidate:$,quotaCheckedAt:z,weight:G}:void 0}function fZ($){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)=>x8(Y,$.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((G,J)=>{let B=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,B3),H=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,B3);return B-H||G.candidate.configuredOrder-J.candidate.configuredOrder||EZ(G.candidate.accountId,J.candidate.accountId)});let Y=z[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let X=[...Z].sort((Y,G)=>{let J=(Y.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-J||Y.configuredOrder-G.configuredOrder||EZ(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:U$(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function W3($){let Z=v($),z=new Map(Z.admitted.map((U)=>[U.id,U])),X=new Map(Z.refused.map((U)=>[U.id,U])),Y=new Set(Z.excluded.map((U)=>U.id)),G=new Set($.rows.map((U)=>U.id)),J=$.pin!==void 0&&G3($.pin,G,$.identities?.get($.pin.accountId));if(J&&$.pin){let U=z.get($.pin.accountId);if(U&&$.killswitch?.get(U.id)!==!1)return{outcome:"dispatch",accountId:U.id,source:"pin",...U.projection?.checkedAt===void 0?{}:{quotaCheckedAt:U.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?X.get($.pin.accountId):void 0,H=J&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Q=(U)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(U):$.rowReservePercent?.get(U.id))??$.reservePercent??{}},K=$.scope,W=$.rows.map((U,_)=>({row:U,configuredOrder:_})).filter(({row:U})=>!Y.has(U.id)).map(({row:U,configuredOrder:_})=>{let M=$.killswitch?.get(U.id),P=$.resetCreditsApplicable?.get(U.id);return{accountId:U.id,quota:U.kind==="api-key"?void 0:z.get(U.id)?.projection??b(U.quota,K),reservePercent:Q(U),configuredOrder:_,...P===void 0?{}:{resetCreditsApplicable:P},...M===void 0?{}:{killswitchPasses:M}}}),D=[],V=J?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let U=fZ({candidates:W,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!U)break;let _=X.get(U.accountId);if(_){D.push(_),W=W.filter((P)=>P.accountId!==U.accountId);continue}let M=$.identities?.get(U.accountId);return{outcome:"dispatch",accountId:U.accountId,source:U.source,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},pin:J&&!H?{action:"retain"}:{action:"assign",pin:{accountId:U.accountId,inputBytes:$.requestBytes,...M===void 0?{}:{wireIdentity:M},...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt}}},refusedSelections:D,admission:Z}}return{outcome:"no-admissible-account",pin:V,refusedSelections:D,admission:Z}}import{createHash as R8}from"node:crypto";var S8=86400000,T8=300000,A8=3600000,E8=60000,C8=900000,I8=300000;function D3($){return $ instanceof Error?$.message:String($)}function k8($){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 F3($){let Z=D3($),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 bZ($){return R8("sha256").update($).digest("hex")}function yZ($){let Z=bZ($.refreshToken),X=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,Y,G=$.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(k8($.error))Y=Math.min(A8,T8*2**Math.min(X-1,6));else Y=S8;return{message:D3($.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===bZ(Z)}function D$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function p0($){let z=($.previous?.retryCount??0)+1,X,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(F3($.error))X=Math.min(C8,E8*2**Math.min(z-1,6));else X=I8;return{message:D3($.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 hZ}from"node:http";import{setTimeout as f8}from"node:timers/promises";var M$="app_EMoamEEZ73f0CkXaXp7hrann",D0="https://auth.openai.com",d0=1455,b8=3000,y8="cortexkit-opencode-openai-auth";function gZ($){return`${y8}/${$}`}var pZ="main",h8=`"${pZ}" is a reserved account id; choose a different label.`;function lZ($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function w8(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=lZ(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 mZ($){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&&mZ(Z);if(z)return z}if($.access_token){let Z=wZ($.access_token);return Z?mZ(Z):void 0}return}function m8($){return typeof $==="string"&&$.toLowerCase()===pZ}function N3($){if(m8($))throw Error(h8);return $}function v8($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:M$,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 g8($,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:M$,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function p8($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var l8=`<!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>`,F$=($)=>`<!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">${p8($)}</div>
85
- </div>
86
- </body>
87
- </html>`,N$=[],l0,c=new Map;function vZ($,Z){return new Promise((z,X)=>{let Y=(J)=>{$.off("listening",G),X(J)},G=()=>{$.off("error",Y),z()};$.once("error",Y),$.once("listening",G),$.listen(d0,Z)})}function dZ($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function U0(){return c.size}function F0($){if(c.delete($),U0()===0)V0()}async function d8(){let $=`http://localhost:${d0}/auth/callback`;if(N$.length>0)return{port:d0,redirectUri:$};if(l0)return l0;l0=(async()=>{let Z=(G,J)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${d0}`);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 V=W||K;if(Q){let U=c.get(Q);if(U)U.reject(Error(V)),F0(Q);else if(U0()===0)V0()}else if(U0()===0)V0();J.writeHead(200,{"Content-Type":"text/html"}),J.end(F$(V));return}if(!Q){if(U0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(F$("Missing state parameter"));return}if(!H){if(U0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(F$("Missing authorization code"));return}let D=c.get(Q);if(!D){if(U0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(F$("Unknown state — authorization may have expired"));return}F0(Q),g8(H,$,D.pkce).then((V)=>D.resolve(V)).catch((V)=>D.reject(V)),J.writeHead(200,{"Content-Type":"text/html"}),J.end(l8);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),Q=H?[H]:[...c.keys()];J.writeHead(200),J.end("Login cancelled");for(let K of Q){let W=c.get(K);if(!W)continue;W.reject(Error("Login cancelled")),F0(K)}if(U0()===0)V0();return}J.writeHead(404),J.end("Not found")},z=hZ(Z);await vZ(z,"127.0.0.1");let X=[z],Y=hZ(Z);try{await vZ(Y,"::1"),X.push(Y)}catch(G){let J=G.code;if(J!=="EADDRNOTAVAIL"&&J!=="EAFNOSUPPORT")throw dZ(z),G}return N$=X,{port:d0,redirectUri:$}})();try{return await l0}finally{l0=void 0}}function V0(){let $=N$;N$=[];for(let Z of $)dZ(Z)}function c8($,Z,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){F0(Z),G(Error("Login cancelled"));return}let J=setTimeout(()=>{if(c.get(Z))F0(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(J),c.get(Z))F0(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);c.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);G(H)}})})}async function u8($){let Z=await fetch(`${D0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":gZ($)},body:JSON.stringify({client_id:M$})});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 i8($,Z,z){let X=Math.max(parseInt($.interval,10)||5,1)*1000,Y=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(Y)&&Y>0?Y*1000:900000,J=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-J>G)throw Error("Device authorization expired");let B=await fetch(`${D0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":gZ(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:M$,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=G-(Date.now()-J);if(H<=0)throw Error("Device authorization expired");let Q=Math.min(X+b8,H);try{await f8(Q,void 0,{signal:z})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw Error("Device authorization cancelled");throw K}}}async function V7($){let{label:Z,headless:z=!1,signal:X,version:Y}=$;if(N3(Z),z){let{deviceData:K,url:W,instructions:D}=await u8(Y),V=(async()=>{let U=await i8(K,Y,X),_=Date.now(),M=q$(U);return{id:N3(Z||M||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:U.access_token,refresh:U.refresh_token,expires:_+(U.expires_in??3600)*1000,enabled:!0,addedAt:_,lastUsed:_,lastRefreshedAt:_,accountId:M}})();return{url:W,instructions:D,completion:V}}let{redirectUri:G}=await d8(),J=await w8(),B=lZ(crypto.getRandomValues(new Uint8Array(32)).buffer),H=v8(G,J,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let K=await c8(J,B,void 0,X),W=Date.now(),D=q$(K);return{id:N3(Z||D||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:D}}finally{F0(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function _$($){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 M3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function cZ($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function uZ($,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),G=M3($.get(`${Y}-window-minutes`)),J=_$($.get(`${Y}-reset-at`)??void 0);if(X===0&&$.get(`${Y}-window-minutes`)==="0"&&!J)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:J,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var nZ=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function oZ($,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 F7($){if(nZ.some((G)=>oZ($,G)==="invalid"))return{};let Z={},z=uZ($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=uZ($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;let Y=s8($);if(Y)Z.credits=Y;return Z}function iZ($,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 s8($){let Z=iZ($,"x-codex-credits-has-credits"),z=iZ($,"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=nZ.map((z)=>oZ($,z));return Z.includes("valid")&&!Z.includes("invalid")}function sZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=M3($.window_minutes),z=_$($.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 N7($){let Z={},z=sZ($.rate_limits?.primary);if(z)Z.primary=z;let X=sZ($.rate_limits?.secondary);if(X)Z.secondary=X;let Y=a8($.credits);if(Y)Z.credits=Y;return Z}function a8($){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 aZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=M3($.limit_window_seconds),z=_$($.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 rZ($){let Z={},z=aZ($.rate_limit?.primary_window);if(z)Z.primary=z;let X=aZ($.rate_limit?.secondary_window);if(X)Z.secondary=X;let Y=cZ($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let G=cZ($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let J=$.spend_control?.individual_limit;if($.spend_control===null||J===null)Z.spendControlCleared=!0;if(J&&typeof $.spend_control?.reached==="boolean"){let H=o(J.limit),Q=o(J.used),K=o(J.remaining),W=o(J.used_percent),D=o(J.remaining_percent);if(H!==void 0&&Q!==void 0&&K!==void 0&&W!==void 0&&D!==void 0)Z.spendControl={limit:H,used:Q,remaining:K,usedPercent:W,remainingPercent:D,resetsAt:_$(J.reset_at),unit:J.unit,source:J.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 J1}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as n8}from"@cortexkit/claustrum-client";import{SocketClosedError as o8,SocketTimeoutError as r8,SubcCallError as t8}from"@cortexkit/subc-client";class F extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var _3=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 F{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function r($){if($ instanceof C||$ instanceof o8||$ instanceof r8)return"unreachable";let Z=$ instanceof n8||$ instanceof t8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(_3,Z))return"answered";return _3[Z]}import{resolve as tZ}from"node:path";import{storeIdentity as e8}from"@cortexkit/claustrum-client";import{SubcClient as eZ}from"@cortexkit/subc-client";var T0=300000,j$=300000,j3=1000;class c0{#$;#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 O${#$;#Z;#B;#J=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#B}request(){if(this.#B)return this.#J=!0,this.#B;return this.#B=(async()=>{do{this.#J=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#J)})().finally(()=>{this.#B=void 0}),this.#B}}class P${#$;#Z=new c0;#B;#J="polling";#Y;#H;#X=!1;#z;#N=!1;#G=0;constructor($){this.#$=$,this.#B=new O$(async()=>{let Z=this.#N;if(this.#N=!1,Z||this.#z!==this.#$.view())await this.#$.discover(this.#z??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#J}start(){if(this.#X||this.#Y||this.#H)return;if(typeof this.#$.client.watchScoped!=="function"){this.#K("fallback","client-without-watch");return}this.#D(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#H)(this.#$.clearTimeoutImpl??clearTimeout)(this.#H);this.#H=void 0;let $=this.#Y;this.#Y=void 0,$?.handle.stop()}#K($,Z){if(this.#J===$)return;this.#J=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#H=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#H=void 0,!this.#X)Z()},$),this.#H.unref?.()}async#D($){let Z;try{Z=await this.#$.enrollmentToken()}catch(J){if(this.#X)return;this.#$.onError?.(J),this.#F("token-unreadable");return}let z=this.#$.client.watchScoped;if(this.#X||this.#Y||!z)return;this.#Z.restart(),this.#N=$;let X,Y;try{Y=z.call(this.#$.client,(J)=>{if(this.#X||!X||this.#Y!==X)return;if(X.notices++,X.notices===1)this.#$.onReachable?.(),X.acceptedAt=(this.#$.now??Date.now)(),this.#K("watching","accepted");if(!this.#Z.continuous(J))this.#N=!0;this.#z=J.view,this.#B.request()},{enrollmentToken:Z})}catch(J){this.#$.onError?.(J),this.#F("watch-failed");return}X={handle:Y,notices:0},this.#Y=X,this.#K("polling",$?"resubscribing":"opening");let G=X;Y.closed.then((J)=>this.#Q(G,J),(J)=>this.#Q(G,{kind:"transport_lost",error:J}))}#Q($,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.#K("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.#G=0;let X=Math.min(1000*2**Math.min(this.#G,16),300000);this.#G++,this.#K("polling","resubscribing"),this.#U(X,()=>void this.#D(!0));return}this.#F(Z.kind)}#F($){this.#K("fallback",$),this.#U(300000,()=>void this.#D(!1))}}function Z4($){let Z=$.identity??e8($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),J=(async()=>{if(z=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await eZ.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([J,G])}finally{X=!0,clearTimeout(Y),z?.close()}},watchUsage(z){let X,Y,G=!1,J=(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 eZ.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:K});if(X=W,G){W.close();return}let D=await W.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){W.close();return}Y=W.subscribe(D,{method:"usage.watch"},z)})();try{await Promise.race([Q,H])}catch(K){throw G=!0,K}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{G=!0,X?.close()});return{stop(){if(G)return;G=!0,Y?.unsubscribe(),X?.close()},closed:J}}}}var x$=60000,$4=4*x$,$9=2*x$,O3=new Map,L$=new Map;function A0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Z9($){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 z9($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class z4{transport;key;#$=[];#Z=!1;#B=new Set;#J=new Map;#Y=new O$(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.#B=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#B)this.#J.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#B.clear()}},()=>{});#H=new c0;#X="polling";#z=0;#N=0;#G=new Map;#K;#U;#D={};#Q=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 L$)if($-X>=x$)L$.delete(z);let Z=L$.get(this.key);if(Z!==void 0&&$-Z<x$)return Promise.resolve();return L$.set(this.key,$),this.#Y.request()}watchMode(){return this.#X}watch($={}){this.#z++;let Z=$.provider;if(Z===void 0)this.#N++;else this.#G.set(Z,(this.#G.get(Z)??0)+1);if(this.#z===1)this.#D=$,this.#x();let z=!1;return()=>{if(z)return;if(z=!0,Z===void 0)this.#N--;else{let X=(this.#G.get(Z)??1)-1;if(X>0)this.#G.set(Z,X);else this.#G.delete(Z)}if(--this.#z===0)this.#F()}}#F(){if(this.#U)(this.#D.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#K;this.#K=void 0,$?.handle?.stop(),this.#X="polling"}#M($){this.#U=(this.#D.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#z>0&&!this.#K)this.#x()},$),this.#U.unref?.()}#x(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#H.restart();let Z={notices:0};this.#K=Z;let z;try{z=$.call(this.transport,(X)=>this.#O(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))}#O($,Z){if(this.#K!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#Q=0;let z=Z9(Z);if(!z)this.#H.restart();if(!(z?this.#H.continuous(z):!1)||z?.provider===void 0||this.#N>0||this.#G.has(z.provider))this.#Y.request()}#P($,Z){if(this.#K!==$)return;this.#K=void 0;let z=z9(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.#Q,16),j$);this.#Q++,this.#X="polling",this.#M(X);return}if(this.#X="fallback",this.#Y.request(),Z===void 0||r(Z)==="unreachable")this.#M(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>=$4)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((J)=>J.provider===$&&typeof J.account==="string"&&J.account.trim()===Z),Y=(X??this.#$.find((J)=>J.provider===$&&J.account===void 0&&J.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 J=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!A0(X.usage)||!Number.isFinite(J))return{miss:"unreachable"};let B={entry:X,context:{fetchedAt:J,...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>=J+$4||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#B.has($))return{miss:"absent"};let G=this.#J.get($)??z;return this.#J.set($,G),{miss:z-G>=$9?"unreachable":"cold"}}}function P3($,Z){let z=JSON.stringify([tZ($.connectionFile),tZ(Z)]),X=O3.get(z);if(!X)X={source:new z4($,z),refs:0},O3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)O3.delete(z)}}}import{ClaustrumCredentialError as Qz}from"@cortexkit/claustrum-client";function q0($){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},G=(B)=>{if(X||Z.signal.aborted)return;Z.abort(B),Y()},J=$.find((B)=>B.aborted);if(J)return Z.abort(J.reason),{signal:Z.signal,dispose:Y};for(let B of $){if(Z.signal.aborted)break;let H=()=>G(B.reason);if(z.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)G(B.reason)}return{signal:Z.signal,dispose:Y}}import{channel as T9}from"node:diagnostics_channel";import{ClaustrumCredentialError as C4}from"@cortexkit/claustrum-client";import{createHash as B9,randomBytes as H9,randomUUID as K9}from"node:crypto";import{constants as X4}from"node:fs";import{chmod as W9,mkdir as Q9,open as Q4,readFile as x3,realpath as U9,rename as V9,stat as U4,unlink as T3}from"node:fs/promises";import{basename as V4,dirname as e,extname as Y4,isAbsolute as J4,join as A3,resolve as D9}from"node:path";import{ClaustrumCredentialError as F9,ClaustrumClient as q9,writeEnrollmentTokenFile as N9}from"@cortexkit/claustrum-client";import{lstat as X9}from"node:fs/promises";import{resolve as Y9}from"node:path";async function J9($){try{let Z=await X9($);return Z.isFile()?Z:void 0}catch(Z){return Z.code==="ENOENT"?"absent":void 0}}function G9($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class L3{#$=new Map;async read($,Z,z){let X=$.map((Q)=>Y9(Q)),Y=JSON.stringify(X),G=await Promise.all(X.map(J9)),J=G.every((Q)=>Q!==void 0)?G:void 0,B=this.#$.get(Y);if(J&&B&&J.every((Q,K)=>{let W=B.identities[K];return W!==void 0&&G9(Q,W)}))return z?.(J),B.value;this.#$.delete(Y);let H=await Z(X);if(J){if(this.#$.size>=64){let Q=this.#$.keys().next().value;if(Q!==void 0)this.#$.delete(Q)}this.#$.set(Y,{identities:J,value:H})}return H}}var M9=1,S$=16384,D4=30000,E3=/^[0-9a-f]{64}$/,F4="unknown_method",q4=new Set([F4,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),N4=new Set(["pending_queue_full"]);function R3($){if(!($ instanceof F9))return;if(q4.has($.code))return{code:$.code,disposition:"terminal"};if(N4.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function _9($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new F("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function j9($){return q9.connect($)}function M4($){let Z=Y4($)||".json",z=V4($,Y4($));return{statePath:A3(e($),`${z}-state${Z}`),tokenPath:$}}function O9($){let Z=$.override?.trim();if(Z&&!J4(Z)&&!$.cwd)throw new F("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=Z?J4(Z)?Z:D9($.cwd,Z):A3($.stateDir,`${$.host}-enrollment.json`);return M4(z)}function _4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function j4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function u0(){return new F("invalid-state","invalid Claustrum enrollment state")}function A$($){if(!_4($)||$.version!==M9||typeof $.proposedName!=="string"||$.proposedName.length===0)throw u0();if($.phase==="pending"){if(!E3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!R$($.createdAt)||!R$($.updatedAt))throw u0();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)||!R$($.updatedAt))throw u0();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"||!R$($.updatedAt))throw u0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw u0()}function C3($){if(!_4($)||!E3.test(String($.token??""))||!j4($.token_generation))throw new F("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function O4($){if(!$.isFile())throw new F("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new F("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new F("unsafe-file","Claustrum enrollment file must be owned by the current user")}function G4($){try{return JSON.parse($)}catch{throw new F("invalid-state","Claustrum enrollment file is not valid JSON")}}async function $0($){if(Z0)try{await S3(e($));let z=await T$($,!0);if(Buffer.byteLength(z)>S$)throw new F("unsafe-file","Claustrum enrollment file is too large");return G4(z)}catch(z){if(z.code==="ENOENT")return;throw z}let Z;try{Z=await Q4($,X4.O_RDONLY|X4.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new F("unsafe-file","Claustrum enrollment file could not be opened safely")}try{O4(await Z.stat());let z=Buffer.alloc(S$+1),{bytesRead:X}=await Z.read(z,0,z.byteLength,0);if(X>S$)throw new F("unsafe-file","Claustrum enrollment file is too large");return G4(z.subarray(0,X).toString("utf8"))}finally{await Z.close()}}function B4($,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 P9($,Z,z){try{let[X,Y]=await Promise.all([x3(z.passwdPath??"/etc/passwd","utf8"),x3(z.groupPath??"/etc/group","utf8")]),G=B4(X,7),J=B4(Y,4);if(!G||!J)return!1;let B=G.filter((W)=>Number(W[2])===$),H=J.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))&&!G.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function P4($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>x3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function L4($,Z={}){if(!Z0){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await U9($)}catch{return}let G;for(;;){let J=await U4(Y).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0){if(G===void 0)G=X!==void 0&&await P9(z,X,Z);if((J.mode&2)!==0||J.uid!==z||J.gid!==X||!G)throw new F("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 K4($,P4(Z))}catch(z){if(!(z instanceof g0))throw z;throw new F("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 S3($,!1,P4(Z));return}await Q9($,{recursive:!0,mode:448});let X=await U4($),Y=process.geteuid?.();if(Y!==void 0&&X.uid!==Y)throw new F("unsafe-file",`Claustrum ${z} must be owned by the current user`);if((X.mode&63)!==0)await W9($,448)}async function N0($,Z,z={}){let X=e($);await E0(X,z),await L4(X,z);let Y=`${JSON.stringify(Z)}
89
- `;if(Buffer.byteLength(Y)>S$)throw new F("invalid-state","Claustrum enrollment state is too large");if(Z0)return W4($,Y);let G=A3(X,`.${V4($)}.${process.pid}.${K9()}.tmp`),J,B=!1;try{J=await Q4(G,"wx",384),B=!0,await J.writeFile(Y,"utf8"),await J.chmod(384),await J.sync(),await J.close(),J=void 0,await V9(G,$),B=!1}finally{if(await J?.close().catch(()=>{}),B)await T3(G).catch(()=>{})}}var L9=new L3;async function I3($,Z){let z=Z0?await H4($,Z):await L9.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,G=$.statePath])=>H4({tokenPath:Y,statePath:G},Z),(Y)=>{for(let G of Y)if(G!=="absent")O4(G)}),X={...z.status};if(z.usesProposedName&&X.state==="approved")X.proposedName=Z;return X}async function H4($,Z){let z=await $0($.tokenPath),X=z===void 0?void 0:C3(z),Y=await $0($.statePath),G=Y===void 0?void 0:A$(Y);if(X)return{usesProposedName:G===void 0,status:{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:X.token_generation}};if(!G)return{status:{state:"idle"},usesProposedName:!1};if(G.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:G.proposedName,code:"missing_token"}};return{status:t(G),usesProposedName:!1}}async function x9($,Z){let z;try{z=await I3($,Z)}catch(X){if(!(X instanceof F)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await $0($.statePath);if(Y===void 0)return"unreadable";let G=A$(Y);return G.phase==="approved"&&G.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 F("not-enrolled","Claustrum enrollment is not configured");return C3(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 x4(){return new F("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class R4{#$;#Z;#B;#J;#Y;#H;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#B=$.proposedName,this.#J=$.now??Date.now,this.#Y=$.mintSecret??(()=>H9(32).toString("hex")),this.#H=$.writeTokenFile??N9}async status(){return I3(this.#Z,this.#B)}async resetTerminal(){return S4(this.#Z,this.#B)}async#z($,Z){let z={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#J()};return await N0(this.#Z.statePath,z,this.#X),t(z)}async reconcile(){await E0(e(this.#Z.statePath),this.#X);let $=await y({name:"ceremony",path:this.#Z.statePath,ttlMs:D4,renew:!0});if(!$)return{state:"busy"};try{let Z=await $0(this.#Z.tokenPath),z=Z===void 0?void 0:C3(Z),X=await $0(this.#Z.statePath),Y=X===void 0?void 0:A$(X);if(Y&&Y.proposedName!==this.#B)throw x4();if(z){if(!Y||Y.phase==="pending"){let J={version:1,phase:"approved",proposedName:Y?.proposedName??this.#B,tokenGeneration:z.token_generation,updatedAt:this.#J()};await N0(this.#Z.statePath,J,this.#X),Y=J}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 J={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#J()};return await N0(this.#Z.statePath,J,this.#X),t(J)}if(Y&&Y.phase!=="pending")return t(Y);if(!Y){let J=this.#J();if(Y={version:1,phase:"pending",proposedName:this.#B,requestSecret:this.#Y(),createdAt:J,updatedAt:J},!E3.test(Y.requestSecret))throw new F("invalid-state","invalid minted Claustrum enrollment secret");await N0(this.#Z.statePath,Y,this.#X)}if(!Y.requestId)try{let J=B9("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B=await this.#$.enrollPropose({name:Y.proposedName,requestSecretHash:J});Y={...Y,requestId:B.requestId,updatedAt:this.#J()},await N0(this.#Z.statePath,Y,this.#X)}catch(J){let B=R3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};if(B.code===F4)return await $.assertOwned(),await T3(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 G=Y.requestId;if(!G)return t(Y);try{let J=await this.#$.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(J.status==="pending")return t(Y);if(J.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#J()};return await N0(this.#Z.statePath,H,this.#X),t(H)}await E0(e(this.#Z.tokenPath),this.#X),await L4(e(this.#Z.tokenPath),this.#X),await this.#H(this.#Z.tokenPath,{token:J.token,token_generation:J.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:J.name,tokenGeneration:J.tokenGeneration,updatedAt:this.#J()};return await N0(this.#Z.statePath,B,this.#X),t(B)}catch(J){let B=R3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:B.code};return this.#z(Y,B.code)}}finally{await $.release()}}}async function S4($,Z){await E0(e($.statePath));let z=await y({name:"ceremony",path:$.statePath,ttlMs:D4,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=A$(X);if(Y.proposedName!==Z)throw x4();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await T3($.statePath),"reset"}finally{await z.release()}}var i0="claustrum-tombstone:v1:";function E$($){return`${i0}${$}`}function k3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function C$($){return typeof $==="string"&&$.startsWith(i0)}function T4($,Z){if(!k3($)||$.type!=="oauth")return!1;return $.refresh===E$(Z)}function A4($,Z){if(T4($,Z))return"placeholder";if(k3($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!C$($.refresh))return"login";if(k3($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function R9($){let Z=A4($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new F("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 F("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((G)=>{z=setTimeout(()=>{X=!0,G()},2000)})]),X&&$.size)Z($.size)}finally{X=!0,clearTimeout(z)}}import{ClaustrumCredentialError as S9}from"@cortexkit/claustrum-client";function E4($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class f3{options;#$=new Map;#Z=new Map;#B=new Set;#J;#Y;#H=!1;#X=!1;#z=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#Y!==void 0,dropped:this.#z}}report($,Z){if(this.#H||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#z++;return}if(!E4(Z)||"credentialId"in Z||"vouched"in Z)throw Error("invalid reading");let z=JSON.stringify(Z);if(Buffer.byteLength(z,"utf8")>15360)throw Error("oversized reading");let X=JSON.parse(z);if(!E4(X)||"credentialId"in X||"vouched"in X||typeof X.observedAtMs!=="number"||!Number.isFinite(X.observedAtMs))throw Error("invalid reading");if(X.observedAtMs<=(this.#Z.get($)??-1/0)){this.#z++;return}if(this.#$.has($))this.#z++;if(this.#Z.set($,X.observedAtMs),this.#$.set($,X),!this.#J&&!this.#Y)this.#J=this.options.setTimeout(()=>{this.#J=void 0,this.#N()},1000),this.#J.unref?.()}catch{this.#z++}}forget($){if(this.#$.delete($))this.#z++;this.#Z.delete($)}#N(){if(this.#Y||!this.#$.size||this.#X)return this.#Y;let $=Promise.resolve().then(async()=>{while(!this.#X&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[z,X]=Z;this.#$.delete(z);try{let Y=await this.options.token();if(this.#X||!this.options.owns(z)){if(!this.#X)this.#z++;continue}await this.options.client.reportUsageScoped?.({credentialId:z,reading:X,enrollmentToken:Y})}catch(Y){if(!this.#X)this.#z++;this.#G(Y)}}});return this.#Y=$,$.finally(()=>{this.#Y=void 0}),$}#G($){let Z="transport_error";try{if($ instanceof S9)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#B.has(Z))return;this.#B.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#H=!0,this.#J)this.options.clearTimeout(this.#J);return this.#J=void 0,this.#N()}drop(){this.#X=!0,this.#z+=this.#$.size+(this.#Y?1:0),this.#Y=void 0,this.#$.clear(),this.#Z.clear()}}function k4($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function A9($,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 y3=A("claustrum");function I4($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new F("invalid-token","Invalid Claustrum enrollment token");return $.token}var X0=T9("common-auth.claustrum.phases");function w3($,Z,z,X=y3){let Y=k4(Z,z);return X.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:A9(Z,z)}),Y}var h3=300000,f4=60000;function b3(){return new F("invalid-material","Claustrum returned invalid credential material")}function E9($){let Z=$.trim();if(Z.startsWith("{")){let z;try{z=JSON.parse(Z)}catch{throw b3()}if(!z||typeof z!=="object")throw b3();let X=z,Y=X.access_token??X.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(i0))throw b3();return Z}function C9($,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=I9($),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 G={credentialId:$.id,credentialType:Y,categories:$.categories,refreshAdapter:$.refreshAdapter,...X};if(G.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let J=Z.classify(G);if(J.kind==="not-mine")return z;if(J.kind==="mine"&&typeof J.member==="string")return{kind:"mine",type:Y,member:J.member};if(J.kind==="refused"&&typeof J.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(J.code)&&!J.code.includes(`
90
- `)&&Z.refusalCodes.includes(J.code))return{kind:"refused",code:J.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 I9($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function k9($){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:G})=>Object.freeze({selectorKind:X,selector:Y,operation:G})))})}class k0{#$;#Z;#B;#J;#Y;#H;#X;#z=new WeakMap;#N=new WeakMap;#G=new Map;#K=new WeakMap;#U;#D=new Map;#Q;#F;#M=!1;#x=new C;#O;#P=!1;#W=-1/0;#q=2000;#R=!1;#V;#j=new Set;#L=new Set;#T;#I;#_;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>z0(Z);else throw new F("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#J=$.family,this.#Y=$.parseIdentity,this.#H=$.requireAssertion??!1,this.#B=$.now??Date.now,this.#X=$.logger??y3,this.#T=C0(this.#X),this.#Q=$.setTimeoutImpl??setTimeout,this.#F=$.clearTimeoutImpl??clearTimeout,this.#U=new f3({client:this.#$,owns:(z)=>this.#D.has(z),token:async()=>I4(await this.#Z()),logger:this.#X,setTimeout:this.#Q,clearTimeout:this.#F})}transportLost($){if(this.#R||this.#M)return;this.#M=!0,this.#x=$ instanceof C4?$:new C,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#A()}reachable(){if(this.#R||!this.#M)return;if(this.#M=!1,this.#O)this.#F(this.#O);this.#O=void 0,this.#q=2000;for(let $ of this.#G.values())$.since=null;(this.#X.info??y3.info)("vault receipt serving resumed",{reason:"reachable"})}#A(){if(this.#R||!this.#M||this.#O||this.#P)return;this.#O=this.#Q(()=>{this.#O=void 0,this.#C(!0)},this.#q),this.#O.unref?.()}#C($=!1){if(this.#R||!this.#M||this.#P)return;if(this.#B()-this.#W<1000){this.#A();return}this.#W=this.#B(),this.#P=!0,this.#f().catch(()=>{if($&&this.#M)this.#q=Math.min(this.#q*2,30000)}).finally(()=>{this.#P=!1,this.#A()})}#S($){if(this.#R)throw new F("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#S($),X0.hasSubscribers)X0.publish({logger:this.#X,phase:"token read begin"});let Z=this.#Z();this.#L.add(Z);let z;try{z=await Z}finally{if(this.#L.delete(Z),X0.hasSubscribers)X0.publish({logger:this.#X,phase:"token read end"})}return this.#S($),I4(z)}async#k($,Z){this.#S(Z);let z,X;try{let Y=$();z=Z?await Promise.race([Y,new Promise((G,J)=>{let B=()=>J(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),X=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await Y}catch(Y){if(this.#S(Z),r(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof C4)throw Y;if(r(Y)==="unreachable")throw new C;throw new F("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#S(Z),this.reachable(),z}async discover($){let Z=await this.#f($);return this.#V=Z.view,Z}async#f($){let Z,z;try{z=await this.#y($)}catch(K){throw this.#G.clear(),this.#h(),K}if(X0.hasSubscribers)X0.publish({logger:this.#X,phase:"list scoped begin"});try{Z=await this.#k(()=>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=[],G=0,J=[],B=new Map;for(let K of Z.rows){let W=C9(K,this.#J);if(W.kind==="not-mine"){G++;continue}if(W.kind==="refused"){Y.push({...K.id.trim()&&{credentialId:K.id},code:W.code});continue}J.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:D}of J){let V;if(!K.id.trim())V="empty credential id";else if((B.get(K.id)??0)>1)V="duplicate credential id";else if(K.accountId!==void 0&&!K.accountId.trim())V="blank account identity";else if(!K.state.trim())V="empty state";if(V){X.push({...K.id.trim()&&{credentialId:K.id},...D!==void 0&&{member:D},reason:V});continue}H.push(Object.freeze({credentialId:K.id,credentialType:W,...D!==void 0&&{member:D},...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=k9(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(X),..."classify"in this.#J&&{refused:Object.freeze(Y),notMine:G},...Q&&{grantReach:Q}}}listFailed($){if(r($)==="unreachable")this.transportLost($);else this.reachable(),this.#G.clear(),this.#h()}forget($){this.#G.delete($),this.#D.delete($),this.#U.forget($)}#h(){for(let $ of this.#D.keys())this.#U.forget($);this.#D.clear()}retain($){let Z=new Map($.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#G){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}for(let[z,X]of this.#D){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.credentialType||Y.accountIdentity!==X.accountIdentity)this.forget(z)}}keptReceiptState(){let $=null;for(let[Z,z]of this.#G){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.#B()>f4}async authorize($,Z,z="vault"){this.#S(Z);let{credentialId:X,credentialType:Y,accountIdentity:G}=$,J=this.#G.get(X);if(J&&(J.attempt.credentialType!==Y||J.attempt.expectedAccountIdentity!==G))this.forget(X),J=void 0;let B;try{B=await this.#y(Z)}catch(H){throw this.#G.clear(),this.#h(),H}if(this.#M&&J)return this.#C(),this.#w(X,J,B,z);try{let H=await this.#E({credentialId:X,credentialType:Y,accountIdentity:G},B,Z);return this.#G.set(X,{attempt:H,routeId:z,since:null}),this.#D.set(X,{...$}),H}catch(H){if(this.#S(Z),r(H)!=="unreachable")throw this.forget(X),H;return this.#w(X,J,B,z,H)}}#w($,Z,z,X,Y=this.#x){if(!Z||this.#G.get($)!==Z||!this.#b(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#B();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#z.set(G,z),this.#K.set(G,X),G}async#E($,Z,z){if(!$.credentialId)throw new F("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:G}=$;if(this.#H&&G===void 0)throw new F("identity-unasserted","Claustrum dispatch requires a known account identity");let J=await this.#k(()=>this.#$.getScoped({credentialId:X,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:h3}}),z);if(J.credentialId!==void 0&&J.credentialId!==X)throw new F("identity-changed","Claustrum served credential identity changed");let B=J.expiresAtMs;if(!Number.isSafeInteger(J.recordVersion)||J.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#B()<h3))throw new F("insufficient-validity","Claustrum served credential has insufficient validity");let H=E9(J.material),Q=J.accountId?.trim()?J.accountId:void 0;if(this.#H&&(J.credentialId===void 0||Q===void 0))throw new F("identity-unasserted","Claustrum served credential did not assert its identity");let K=Q===void 0?this.#Y?.(H):void 0,W=Q??K;if(G!==void 0&&W!==void 0&&W!==G)throw new F("identity-changed","Claustrum served credential identity changed");let D=W??G,U=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...D!==void 0&&{accountIdentity:D},accountIdentitySource:Q!==void 0?"asserted":K!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...J.credentialId!==void 0&&{assertedCredentialId:J.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...J.projectId!==void 0&&{projectId:J.projectId},recordVersion:J.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#z.set(U,Z),U}async reportFailure($,Z,z){if(Z!==401)return;this.#S();let X=this.#z.get($);if(!X)throw new F("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#K.get($);if(Y!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let G=this.#G.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let J=this.#N.get($);if(J)return J;let B=this.#k(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:$.recordVersion,reporterSource:z}));this.#N.set($,B);try{await B,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:z})}catch(H){throw this.#N.delete($),H}}watchRoster($){this.#S();let Z=new P$({client:this.#$,enrollmentToken:()=>this.#y(),view:$.view??(()=>this.#V),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.#B,setTimeoutImpl:this.#Q,clearTimeoutImpl:this.#F});return this.#j.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#j.delete(Z),Z.stop()}}}reportUsage($){if(this.#R)return;try{this.#U.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#U.state()}close(){if(this.#R)return;if(this.#R=!0,this.#O)this.#F(this.#O);this.#O=void 0;for(let Z of this.#j)Z.stop();this.#j.clear(),this.#G.clear();let $=this.#U.close();if($)this.#L.add($),$.then(()=>this.#L.delete($));else this.#$.close();this.#_=I0(this.#L,(Z)=>(this.#I??this.#T)(Z)).finally(()=>{if(this.#U.drop(),this.#D.clear(),$)this.#$.close()})}async dispose($=this.#T){this.#I=$,this.close(),await this.#_}}import{resolve as f$}from"node:path";var b4=30000,y4={now:()=>performance.now(),schedule($,Z){let z=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(z),unref:()=>z.unref?.()}}};function h4($,Z=""){let z=new Map,{observation:X}=$,Y=(B,H,Q)=>z.set(`${Z}:${B}`,{at:H,order:0,publication:{...$,observation:Q}}),G=(B,H)=>JSON.stringify([B??"all",H]),J=new Set;for(let B of X.readings??[]){let H=G(B.scope,B.label);J.add(H),Y(H,X.checkedAt,{checkedAt:X.checkedAt,readings:[{...B}]})}for(let B of X.coverage??[]){let H=G(B.scope,B.label);if(!J.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 f9}from"node:crypto";import{stat as b9}from"node:fs/promises";import{resolve as s0}from"node:path";function w4($,Z,z){if($.accountIdentity!==void 0&&z!==void 0)return $.accountIdentity===z;return $.credentialId===Z}function m3($,Z,z){return $.some((X)=>w4(X,Z,z))}function v3($,Z,z){let X={credentialId:Z,...z!==void 0&&{accountIdentity:z}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==z),X]}function g3($,Z,z){return $.filter((X)=>!Z.some((Y)=>w4(X,Y,z)))}function p3($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>g(Z).map((z)=>({credentialId:z,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function y9($,Z){let z=g(Z),X=Z.accountIdentity===void 0?-1:$.order.findIndex((G)=>G.accountIdentity===Z.accountIdentity),Y=X>=0?X:$.order.findIndex((G)=>z.includes(G.credentialId));return Y>=0?Y:1/0}var k$="vault:";function h9($){return f9("sha256").update($).digest("hex")}function w9($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function m9($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function g($){return[$.credentialId,...$.aliases??[]]}function g4($,Z,z={}){let X=z.now??Date.now(),Y=z.routePrefix??k$,G=z.reservedRouteIds??new Set,J=$?.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])),D=Z.skipped.some((N)=>N.credentialId===void 0),V=(N)=>!K.has(N)&&(W.has(N)||D),U=new Map;for(let N of J){if(N.accountIdentity===void 0)continue;for(let j of g(N))if(!U.has(j))U.set(j,N.accountIdentity)}let _=new Map;for(let N of Z.credentials){let j=N.accountIdentity!==void 0?{credential:N,identity:N.accountIdentity,claimed:!0}:{credential:N,identity:U.get(N.credentialId),claimed:!1},s=m9(j),a=_.get(s)??[];a.push(j),_.set(s,a)}let M=new Set,P=new Set(G),x=[],k=(N,j)=>N.credential.credentialId.localeCompare(j.credential.credentialId),w=[..._.values()].map((N)=>N.toSorted(k)).sort((N,j)=>N[0]&&j[0]?k(N[0],j[0]):0);for(let N of w){let j=N[0]?.identity,s=N.filter((O)=>O.credential.state==="active"),a=s.length?s:N,i$=a.filter((O)=>O.claimed),J$=i$.length?i$:a,s$=new Set(N.map((O)=>O.credential.credentialId)),WZ=J.find((O)=>!M.has(O)&&g(O).some((L0)=>s$.has(L0))&&(O.accountIdentity===void 0||O.accountIdentity===j)),a$=J$.find((O)=>O.credential.credentialId===WZ?.credentialId)??J$[0];if(!a$)continue;let f=a$.credential,m=WZ??(j===void 0?void 0:J.find((O)=>!M.has(O)&&O.accountIdentity===j));if(m)M.add(m);let B0=m?.routeId;if(!B0||G.has(B0)){let O=`${Y}${f.credentialId}${j===void 0?"":`~${h9(j).slice(0,10)}`}`;B0=O;for(let L0=2;P.has(B0);L0++)B0=`${O}~${L0}`}P.add(B0);let a6=m?g(m).filter(V):[],n$=[...new Set([...N.map((O)=>O.credential.credentialId),...a6])].filter((O)=>O!==f.credentialId).sort((O,L0)=>O.localeCompare(L0)),n6=z.mapAccount?.(f)??{};x.push({previousIndex:m?J.indexOf(m):1/0,row:{routeId:B0,credentialId:f.credentialId,credentialType:f.credentialType,...j!==void 0&&{accountIdentity:j},...n$.length&&{aliases:n$},state:f.state,label:n6.label?.trim()||w9(f),...f.email!==void 0&&{email:f.email},...f.orgName!==void 0&&{orgName:f.orgName},enabled:![f.credentialId,...n$].some((O)=>m3(H,O,j)),addedAt:m?.addedAt??X,...m?.quota!==void 0&&{quota:m.quota},...!a$.claimed&&j!==void 0&&{unclaimed:!0}}});let o$=x.at(-1);if(B&&o$)o$.previousIndex=y9(B,o$.row)}return J.forEach((N,j)=>{if(M.has(N)||!g(N).some(V))return;if(P.has(N.routeId))return;let[s,...a]=g(N).filter((s$)=>!K.has(s$));if(s===void 0)return;P.add(N.routeId);let{aliases:i$,...J$}=N;x.push({previousIndex:j,row:{...J$,credentialId:s,...a.length&&{aliases:a},stale:!0}})}),x.sort((N,j)=>N.previousIndex===j.previousIndex?N.row.credentialId.localeCompare(j.row.credentialId):N.previousIndex-j.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:Q,...!Q&&{rejected:Z.skipped.map((N)=>({...N.credentialId!==void 0&&{credentialId:N.credentialId},reason:N.reason}))},rows:x.map((N)=>N.row),declined:H}}function l3($){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 a0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function f0($){return $===void 0||typeof $==="string"}function v9($){let Z=a0($)?K0($.quota):void 0;if(!a0($)||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 g9=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function m4($){if(!Array.isArray($))return;let Z=[];for(let z of $){if(!a0(z)||!f0(z.credentialId)||typeof z.reason!=="string"||!g9.has(z.reason))return;Z.push(z)}return Z}function p4($){if(!a0($)||$.version!==1||!f0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!m4($.rejected))throw new F("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let G=v9(Y);if(!G)throw new F("invalid-state","Claustrum roster file is not valid");Z.push(G)}let z=[];for(let Y of $.declined){if(!a0(Y)||typeof Y.credentialId!=="string"||!f0(Y.accountIdentity))throw new F("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=m4($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...X&&{rejected:X},...$.limits!==void 0&&{limits:$.limits},rows:Z,declined:z}}function d3($){return p4(JSON.parse(JSON.stringify($)))}async function R($){let Z;try{Z=await T$($,Z0)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse(Z)}catch{throw new F("invalid-state","Claustrum roster file is not valid")}return p4(z)}var l4={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},d4={name:"claustrum-roster",ttlMs:30000};async function M0($,Z,z={}){return V3($,{...l4,signal:z.signal},async(X)=>{let Y=await R($),{next:G,result:J}=await Z(Y,{assertOwned:()=>X.assertOwned()});if(G)await X.assertOwned(),await d($,G,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}});return J})}function c3($,Z){return M0($,(z)=>{let X=z?.rows.find((G)=>G.routeId===Z);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");let Y=v3(z.declined,X.credentialId,X.accountIdentity);return{next:{...z,declined:Y,rows:z.rows.map((G)=>G===X?{...G,enabled:!1}:G)},result:void 0}})}function u3($,Z){return M0($,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===Z);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:g3(z.declined,g(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function p9($){return new F("invalid-order",$)}function l9($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let z=new Set($.map((G)=>G.routeId)),X=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(X.has(G))return`route id ${G} appears more than once`;if(!z.has(G))return`route id ${G} is not in the roster`;X.add(G)}let Y=[...z].filter((G)=>!X.has(G)).length;if(Y>0)return`the order leaves out ${Y} roster route id${Y===1?"":"s"}`;return}function i3($,Z,z={}){return M0($,(X)=>{let Y=X?.rows??[],G=l9(Y,Z);if(G)throw p9(G);let J=new Map;for(let Q of Y){let K=J.get(Q.routeId);if(K)K.push(Q);else J.set(Q.routeId,[Q])}let B=[...Z],H=B.flatMap((Q)=>J.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 d9($,Z){if(!g($).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")&&g($).length===1)return"bind";return"refuse"}async function s3($,Z){let{routeId:z,observation:X,...Y}=Z;return c4($,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function c4($,Z){if(!R0(Z.observation))return!1;let z=I($,await R($));if(!Y0(z,Z).kept)return!1;return i4($,Z)}function a3($,Z){return c4($,Z)}function Y0($,Z){let z=$?.rows.find((J)=>J.routeId===Z.routeId),X=!z?"refuse":Z.receipt?d9(z,Z.receipt):z.accountIdentity!==void 0&&z.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!z||X==="refuse")return{roster:$,kept:!1};let Y=m0(z.quota,Z.observation),G=X==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((J)=>J===z?{...J,...G,quota:Y}:J)},kept:!0}}var I$=new Map;function n0($){I$.delete(s0($))}function u4($,Z){let z=s0($);if(Z instanceof F)return Z.kind==="roster-busy";if(Z instanceof V$||Z instanceof U3)return s0(Z.details.target)===z;if(Z instanceof g0){let X=s0(Z.path);return[l4.name,d4.name].some((Y)=>{let G=Q3(z,Y);return X===G||X.startsWith(`${G}.`)})}return!1}var c9=4;async function v4($){try{let{dev:Z,ino:z,size:X,mtimeMs:Y}=await b9($);return{dev:Z,ino:z,size:X,mtimeMs:Y}}catch{return}}function u9($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function i9($,Z,z){for(let X=0;X<c9;X++){let Y=await v4($),G=await R($),J,B,H;try{({target:J,local:B}=Z(G));let Q=JSON.stringify(z(J));H=JSON.stringify(J)!==Q||B!==void 0&&JSON.stringify(B)!==Q}catch{return"commit"}if(!u9(Y,await v4($)))continue;if(H)return"commit";return s4($)?"commit":"unchanged"}return"commit"}async function o0($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){n0($.path);return}let z=await y({...d4,path:$.path,renew:!0});if(!z){let J=await R($.path);if($.signal?.throwIfAborted(),!J?.view)throw new F("roster-busy","Claustrum account discovery is already in progress");return J}let X=s0($.path),Y=$.listedOver,G;try{let J=await R($.path),B=Y?void 0:I$.get(X);G=B&&(B.previousView===J?.view||B.inventory.view===J?.view)?B:{inventory:await $.custody.discover($.signal),previousView:J?.view},I$.delete(X);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let Q=typeof $.projection==="function"?$.projection():$.projection,K=(V)=>g4(V,H,Q),W=async()=>{return $.signal?.throwIfAborted(),await z.assertOwned(),Z()};if(await i9($.path,(V)=>{if(Y)return{target:V};let U=I($.path,V);return{target:V,...U!==V&&{local:U}}},K)==="unchanged"){if(!await W())return;return await R($.path)}return await M0($.path,async(V)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await z.assertOwned(),Y&&V?.view!==Y.view&&V?.view!==H.view)return{result:V};let U=K(V);return{...JSON.stringify(V)!==JSON.stringify(U)&&{next:U},result:U}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await z.assertOwned()}})}catch(J){if(J instanceof V$&&G&&!Y&&!$.signal?.aborted&&await Z())I$.set(X,G);throw J}finally{await z.release($.signal)}}var _0=new Map,s9=A("claustrum"),n4=100;function o4($,Z=y4){let z=f$($),X=_0.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},_0.set(z,X);return X}function r4($,Z,z){let X=o4($,z);X.listeners.add(Z);let Y;return()=>Y??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():n3($)})()}function a9($){return h4($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function i4($,Z){if(!R0(Z.observation))return Promise.resolve(!1);let z=o4($),X=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),Y=z.pending.get(X)??new Map;for(let[G,J]of a9(Z)){let B=Y.get(G);if(!B||J.at>=B.at){if(J.order=++z.order,J.publication.observation.coverage)J.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(G,J)}}if(Y.size)z.pending.set(X,Y);for(let G of z.listeners)G(Z);return e4(z,n4),Promise.resolve(!0)}function t4($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,z)=>Z.order-z.order)}function I($,Z){let z=_0.get(f$($));if(z)for(let X of t4(z.pending)){if(X.priorReading)Z=Y0(Z,X.priorReading).roster;Z=Y0(Z,X.publication).roster}return Z}function s4($){return!!_0.get(f$($))?.pending.size}function e4($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let z=$.draining?0:($.committedAt??-1/0)+b4-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,z),()=>{return $.timer=void 0,$6($)}),!$.draining)$.timer.unref?.()}function a4($){$.timer?.cancel(),$.timer=void 0}function $6($){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 J of t4(Z)){if(J.priorReading)Y=Y0(Y,J.priorReading).roster;Y=Y0(Y,J.publication).roster}let G=JSON.stringify(Y)!==JSON.stringify(X);return{...G&&{next:Y},result:G}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[X,Y]of Z){let G=$.pending.get(X);for(let[J,B]of Y)if(G?.get(J)===B)G.delete(J);if(!G?.size)$.pending.delete(X)}$.failures=0}catch(z){if(!$.abort.signal.aborted&&$.failures++===0)s9.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()):n4;e4($,z)}})(),$.running}async function n3($,Z=1000){let z=f$($),X=_0.get(z);if(!X)return;X.draining=!0,a4(X);let Y,G,J=new Promise((B)=>{G=()=>{if(!X.pending.size||X.abort.signal.aborted)B()},X.wake.add(G),G()});try{if(X.pending.size)$6(X);await Promise.race([J,new Promise((B)=>{Y=setTimeout(B,Math.max(0,Z))})])}finally{if(clearTimeout(Y),G)X.wake.delete(G);if(X.draining=!1,!X.listeners.size){if(X.abort.abort(),a4(X),X.pending.clear(),_0.get(z)===X)_0.delete(z)}}}var b$=1e4;function Z6(){return new C}var o3;function X6($,Z){if(!o3)throw Error("ClaustrumConsumer is not initialized");return o3($,Z)}function z6(){return new F("not-active","Claustrum scoped custody is not active")}class r3{#$;#Z=new AbortController;#B;#J;#Y;#H;#X;#z;#N;#G;#K=!1;#U=new Set;#D;#Q;#F;#M;#x=new Map;#O;#P;#W;#q;#R=new WeakMap;static{o3=($,Z)=>{let z=new r3(Z);return z.#W=$,{consumer:z,hooks:z.#h()}}}constructor($){this.#$=$,this.#B=$.logger??A("claustrum"),this.#J=C0(this.#B,this.#Z.signal),this.#P=r4($.rosterPath,(Z)=>{this.#z=Y0(this.#z,Z).roster})}#V($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#j($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#L(){return await this.#$.isCustodyActive?.()??!0}#T($,Z){let z=q0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((X,Y)=>{let G=()=>{z.signal.removeEventListener("abort",J),z.dispose()},J=()=>{G(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",J,{once:!0}),$.then((B)=>{if(G(),z.signal.aborted)Y(z.signal.reason);else X(B)},(B)=>{G(),Y(B)}),z.signal.aborted)J()})}async#I(){if(this.#V(),this.#Y)return this.#Y;if(!this.#H){let $={timedOut:!1};this.#H=this.#_($),this.#j(this.#H)}return this.#T(this.#H)}#_($){let Z=this.#$.setTimeoutImpl??setTimeout,z=this.#$.clearTimeoutImpl??clearTimeout,X=this.#$.connect().then((J)=>{if(this.#Z.signal.aborted||$.timedOut){if(J.close(),!$.timedOut)this.#V();throw Z6()}if(this.#Y=new k0({client:J,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#B,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&J.insula)this.#Q=P3(J.insula,this.#$.tokenPath);return this.#Y}),Y,G=new Promise((J,B)=>{Y=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#B.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#A()}),B(Z6())},this.#A()),Y.unref?.()});return Promise.race([X,G]).finally(()=>{if(Y)z(Y);this.#H=void 0})}#A(){return this.#$.connectTimeoutMs??b$}snapshot(){return this.#z}grantReach(){if(this.#W)return this.#W.grantReach(this.#z?.view);let $=this.#N;return $&&this.#z?.view===$.view?$.reach:void 0}watchState(){if(this.#W)return Object.freeze({vault:this.#W.watchMode()});return Object.freeze({vault:this.#F?.mode??"polling",...this.#$.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#C(){this.#F?.close(),this.#F=void 0,this.#M?.(),this.#M=void 0}keptReceiptState(){if(this.#W){let $=this.#q;return $&&this.#W.leaseLive($)?$.custody.keptReceiptState():this.#W.keptReceiptState()}return this.#Y?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return l3(this.#z)}refresh(){if(this.#V(),this.#W)return this.#j(this.#b(this.#W));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#L()){if(this.#z=void 0,this.#N=void 0,this.#C(),this.#Y)this.#Y.close(),this.#j(this.#Y.dispose(this.#J));this.#Y=void 0,this.#Q?.release(),this.#Q=void 0;return}let $=await this.#I(),Z,z=await o0({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.#V();let X=z?.view!==this.#z?.view;if(this.#z=I(this.#$.rosterPath,z),$.retain(z?.rows??[]),Z&&z?.view!==void 0)this.#N=Z.grantReach?{view:z.view,reach:Z.grantReach}:void 0;if(z&&X)this.#$.onRoster?.(z);return this.#O=(this.#$.now??Date.now)(),z})().finally(()=>{this.#X=void 0}),this.#j(this.#X),this.#S(this.#X),this.#X}#S($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#K)return;if(this.#V(),this.#K=!0,this.#W){this.#W.start();return}let $=async()=>{try{if(await this.#y())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.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#G=void 0,this.#j($())},Z),this.#G.unref?.()};this.#j($())}async#y(){if(this.#F?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#O===void 0||$-this.#O>=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.#j((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.#Q&&!this.#M)this.#M=this.#Q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{await z0(this.#$.tokenPath),await this.#I(),await this.#Q?.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 R(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 R(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$)?.accountIdentity;if(!X||!this.#Q)return{miss:"unreachable"};let Y=this.#Q.source.lookup(Z.provider,X,(this.#$.now??Date.now)()),G=Y.reading&&Z.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let z=await this.lookupInsulaQuotaForRoute($);if(z.miss==="cold"||z.miss==="upstream-failed"){if(this.#x.get($)!==z.miss)this.#x.set($,z.miss),this.#B.warn("skipped insula provider poll",{reason:z.miss});return}return this.#x.delete($),z.miss?Z():z.reading}#f($){if(!this.#$.insula||!$)return;let Z=this.#Q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#W)return this.#m(this.#W,$,Z);this.#V(Z);let z=this.#z??await this.#T(this.refresh(),Z);if(!z||!await this.#L())throw this.#Y?.close(),this.#Y=void 0,this.#C(),this.#Q?.release(),this.#Q=void 0,new F("not-active","Claustrum scoped custody is not active");let X=I(this.#$.rosterPath,await R(this.#$.rosterPath));this.#V(Z);let Y=z.rows.find((H)=>H.routeId===$),G=X?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(Y)this.#Y?.forget(Y.credentialId);throw new F("route-declined","Claustrum route is disabled")}if(!Y||!G||G.state!=="active"||G.credentialId!==Y.credentialId||G.accountIdentity!==Y.accountIdentity||G.credentialType!==Y.credentialType){if(Y)this.#Y?.forget(Y.credentialId);throw new F("route-unavailable","Claustrum route is disabled, removed or changed")}let J=await this.#T(this.#I(),Z),B=q0([this.#Z.signal,...Z?[Z]:[]]);try{return await J.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},B.signal,$)}finally{B.dispose()}}#h(){return{discovery:($)=>{let Z=this.#W;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let z=this.#j($.then((X)=>this.#w(Z,X)));this.#S(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#b($){let Z=await $.refresh();return this.#w($,Z)}#w($,Z){if(this.#V(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#z}#E($){if($&&this.#q!==$)return;this.#q?.release(),this.#q=void 0}async#p($,Z){let z=this.#q;if(z&&$.leaseLive(z))return z;this.#E();let X=await $.acquire(Z);if(this.#Z.signal.aborted)X.release(),this.#V();let Y=this.#q;if(Y&&$.leaseLive(Y))return X.release(),Y;return this.#q=X,X}async#m($,Z,z){if(this.#V(z),!this.#z)await this.#T($.refresh(),z);let X=this.#z;if(!await $.readAuthority())throw this.#E(),z6();if(this.#V(z),!X)throw new F("route-unavailable","Claustrum has no roster for this provider yet");let Y=I(this.#$.rosterPath,await R(this.#$.rosterPath));this.#V(z);let G=X.rows.find((Q)=>Q.routeId===Z),J=Y?.rows.find((Q)=>Q.routeId===Z);if(J&&!J.enabled){if(G)$.forget(G.credentialId);throw new F("route-declined","Claustrum route is disabled")}if(!G||!J||J.state!=="active"||J.credentialId!==G.credentialId||J.accountIdentity!==G.accountIdentity||J.credentialType!==G.credentialType){if(G)$.forget(G.credentialId);throw new F("route-unavailable","Claustrum route is disabled, removed or changed")}let B={credentialId:J.credentialId,credentialType:J.credentialType,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity}},H=q0([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.#R.set(W,K),W}catch(W){if(Q>0||H.signal.aborted||$.leaseLive(K)||!(W instanceof F)||W.kind!=="closed")throw W;if(this.#E(K),!await $.readAuthority())throw z6()}}}finally{H.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#z?.rows.find((z)=>z.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#W){if(this.#q&&this.#W.leaseLive(this.#q))this.#q.custody.reportUsage($)}else this.#Y?.reportUsage($)}catch{}}usageReportState(){try{return(this.#W?this.#q?.custody:this.#Y)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,z){if(this.#V(),this.#W){let X=this.#R.get($);if(!X)throw new F("no-receipt","Claustrum dispatch receipt has no active owner");await X.custody.reportFailure($,Z,z);return}if(!this.#Y)throw new F("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),G=await Z(Y,X);if(G.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,z.reporterSource??"direct"),G;if(G.status===401&&!X?.aborted){let J;try{J=await this.authorize($,X),X?.throwIfAborted()}catch(B){if(X?.aborted)throw B}if(w3(z.site,Y,J,this.#B))await G.body?.cancel().catch(()=>{}),Y=J,G=await Z(J,X)}if(G.status===401)await this.reportFailure(Y,401,z.reporterSource??"direct").catch((J)=>this.#$.onError?.(J)),Promise.resolve().then(()=>this.refresh()).catch((J)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(J)});return G}async decline($){if(this.#V(),await c3(this.#$.rosterPath,$),this.#z=I(this.#$.rosterPath,await R(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z);if(this.#W)this.#W.retainUnion();else this.#Y?.retain(this.#z?.rows??[])}async accept($){if(this.#V(),await u3(this.#$.rosterPath,$),this.#z=I(this.#$.rosterPath,await R(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z)}async reorder($){this.#V();let Z=await i3(this.#$.rosterPath,$);if(this.#z=I(this.#$.rosterPath,await R(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z);return Z}async recordQuota($,Z,z){return this.#V(),s3(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.#V(),a3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:z})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new F("closed","Claustrum consumer is closed")),this.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);if(this.#G=void 0,this.#C(),this.#Y)this.#Y.close(),this.#j(this.#Y.dispose(this.#J));this.#q?.release(),this.#q=void 0,this.#W?.detach(),this.#Q?.release(),this.#Q=void 0,this.#z=void 0,this.#N=void 0,this.#P(),n0(this.#$.rosterPath)}async dispose(){this.close(),this.#D??=Promise.all([I0(this.#U,this.#J),this.#P()]).then(()=>{}),await this.#D}}import{createHash as n9}from"node:crypto";import{channel as o9}from"node:diagnostics_channel";import{readdir as r9,stat as t9}from"node:fs/promises";import{dirname as e9,join as b0,resolve as Y6}from"node:path";var y$=new Map,$1=/^[a-z0-9][a-z0-9._-]{0,63}$/,Z1=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,z1=/^[0-9a-f]{16}$/,J6=3;function e3($,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 G=0;G<$.length;G++){let J=e3($[G],z);if(J===void 0)return;X.push(J)}return`[${X.join(",")}]`}let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return;for(let G of Object.keys($).sort()){let J=e3($[G],z);if(J===void 0)return;X.push(`${JSON.stringify(G)}:${J}`)}return`{${X.join(",")}}`}function X1($,Z){let z=e3({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??k$,mapAccount:$.mapAccount?String($.mapAccount):null});if(z===void 0)throw new F("invalid-state","Claustrum hub classifierInput must be plain JSON");return n9("sha256").update(z).digest("hex").slice(0,16)}function G6($,Z){if(typeof $!=="string"||!$1.test($)||Z1.test($))throw new F("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function J0($="Claustrum custody lease is closed"){return new F("closed",$)}function t3(){return new F("not-active","Claustrum scoped custody is not active")}function B6(){return new C}function Y1($,Z){return new Promise((z,X)=>{let Y=()=>X(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),$.then((G)=>{Z.removeEventListener("abort",Y),z(G)},(G)=>{Z.removeEventListener("abort",Y),X(G)}),Z.aborted)Y()})}function H6($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class K6{#$;#Z;#B;#J=new AbortController;#Y=new Map;#H=new WeakMap;#X=0;#z;#N;#G;#K;#U;#D;#Q=0;#F;#M;#x;#O=!1;#P=new Set;#W;#q;#R;constructor($){if(!$.family||!("classify"in $.family))throw new F("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=G6($.hostGeneration,"host generation"),z=$.members.map((Y)=>G6(Y,"member"));if(new Set(z).size!==z.length)throw new F("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??A("claustrum"),this.#B=C0(this.#Z,this.#J.signal),this.#q=b0($.stateDir,"rosters",Z),this.#R=X1($,z);let X=b0(this.#q,this.#R);for(let Y of z)this.#Y.set(Y,{provider:Y,path:b0(X,`${Y}.json`),closed:!1})}#V($){return this.#P.add($),$.then(()=>this.#P.delete($),()=>this.#P.delete($)),$}#j(){if(this.#J.signal.aborted)throw J0("Claustrum discovery hub is closed")}#L($){let Z=this.#Y.get($);if(!Z)throw new F("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#L($).path}member($,Z){this.#j();let z=this.#L($);if(z.hooks)throw new F("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 F("wrong-consumer",`Claustrum hub members cannot take ${W}`);let X={provider:z.provider,start:()=>this.start(),refresh:()=>this.#m(),readAuthority:()=>this.#b(),acquire:(W)=>this.acquire(W),leaseLive:(W)=>this.#A(W),grantReach:(W)=>W!==void 0&&this.#F?.view===W?this.#F.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#g(),publishRoster:(W)=>this.#T(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:G,hooks:J}=X6(X,Y);z.hooks=J;let B=Y6(z.path),H=y$.get(B)??new Set,Q=(W)=>{if(z.closed||this.#D!==!0||!this.#z||!this.#_(this.#z)||!J.roster()||this.#l(J,W))return;if(z.seen=JSON.stringify(d3(W)),J.install(W),W.view!==this.#F?.view)z.pending??={failures:0,wait:0};this.#g()};H.add(Q),z.receiveRoster=Q,y$.set(B,H);let K=!0;return z.releaseRoster=()=>{if(!K)return;if(K=!1,H.delete(Q),!H.size)y$.delete(B)},G}#T($,Z){let z=this.#z;if($.closed||!z||!this.#_(z))return;$.seen=JSON.stringify(d3(Z)),$.hooks?.install(Z);for(let X of y$.get(Y6($.path))??[]){if(!this.#_(z))return;if(X!==$.receiveRoster)X(Z)}}#I(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#z=$,$}#_($){return!$.ended&&this.#z===$&&!this.#J.signal.aborted}#A($){let Z=this.#H.get($);return!!Z&&!Z.released&&!Z.generation.ended}#C($,Z=J0()){if($.ended)return;if($.ended=!0,$.count=0,this.#z===$)this.#z=void 0;if(this.#G&&this.#H.get(this.#G)?.generation===$)this.#G=void 0;if(this.#K?.generation===$)this.#K.watch.close(),this.#K=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#V($.custody.dispose(this.#B))}#S($){if($.ended)return;if($.count--,$.count<=0)this.#C($)}#y($){let Z=this.#N;if(Z?.generation===$&&Z.promise)return Z.promise;let z={generation:$,timedOut:!1},X=this.#$.connectTimeoutMs??b$,Y,G=this.#$.connect().then((H)=>{if(z.timedOut)throw H.close(),B6();if(!this.#_($)||$.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}),J=new Promise((H,Q)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(z.timedOut=!0,!this.#_($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:X}),Q(B6())},X),Y.unref?.()});return z.promise=this.#V(Promise.race([G,J]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),z.promise.finally(()=>{if(this.#N===z)this.#N=void 0}).catch(()=>{}),this.#N=z,z.promise}acquire($){try{if(this.#j(),$?.throwIfAborted(),this.#D===!1)throw t3()}catch(z){return Promise.reject(z)}let Z=this.#z??this.#I();return Z.count++,this.#k(Z,$,!0)}async#k($,Z,z){let X=$.custody;if(!X){let Y=q0([$.controller.signal,...Z?[Z]:[]]);try{X=await Y1(this.#y($),Y.signal)}catch(G){if(!$.ended)throw this.#S($),G;return this.#f(Z,z)}finally{Y.dispose()}}if($.ended)return this.#f(Z,z);if(Z?.aborted)throw this.#S($),Z.reason;return this.#h($,X)}#f($,Z){if($?.throwIfAborted(),this.#j(),this.#D===!1)throw t3();if(!Z)throw J0();let z=this.#z??this.#I();return z.count++,this.#k(z,$,!1)}#h($,Z){let z={generation:$,custody:Z,released:!1},X=()=>{if(z.released||$.ended)throw J0()},Y=Object.freeze({authorize:async(J,B,H)=>{X();let Q=q0([$.controller.signal,...B?[B]:[]]);try{return await Z.authorize(J,Q.signal,H)}finally{Q.dispose()}},reportFailure:async(J,B,H)=>{return X(),Z.reportFailure(J,B,H)},reportUsage:(J)=>{if(!z.released&&!$.ended)Z.reportUsage(J)},usageReportState:()=>{return X(),Z.usageReportState()},forget:(J)=>{X(),Z.forget(J)},keptReceiptState:()=>{return X(),Z.keptReceiptState()}}),G=Object.freeze({custody:Y,generation:$.id,release:()=>{if(z.released)return;z.released=!0,this.#S($)}});return this.#H.set(G,z),G}leaseState(){let $=this.#z;return Object.freeze({generation:$?.id,count:$?.count??0})}async#b(){let $=await this.#$.isCustodyActive?.()??!0;if(this.#J.signal.aborted)return!1;let Z=this.#D;if(this.#D=$,!$&&Z!==!1)this.#w();return $}#w(){this.#Q++;let $=this.#z;if($)this.#C($,t3());this.#G=void 0,this.#K?.watch.close(),this.#K=void 0,this.#F=void 0,this.#M=void 0;for(let Z of this.#Y.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),n0(Z.path)}#E(){return[...this.#Y.values()].filter(($)=>$.hooks&&!$.closed)}async#p(){let $=this.#G,Z=$&&this.#H.get($);if($&&Z&&this.#A($))return Z;this.#G=void 0;let z=await this.acquire(this.#J.signal),X=this.#G&&this.#H.get(this.#G);if(this.#G&&X&&this.#A(this.#G))return z.release(),X;this.#G=z;let Y=this.#H.get(z);if(!Y)throw J0();return Y}#m(){try{this.#j()}catch(X){return Promise.reject(X)}let $=this.#U;if($&&!$.generation?.ended)return $.promise;let Z={},z=this.#V(this.#a(Z).finally(()=>{if(this.#U===Z)this.#U=void 0}));Z.promise=z,this.#U=Z;for(let X of this.#E())X.hooks?.discovery(z);return z}async#a($){if(!await this.#b())return;let Z=await this.#p(),z=Z.generation;if($.generation=z,!this.#_(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 R(K.path).then((W)=>W?{file:W}:{},(W)=>W instanceof Error?W:Error(String(W)))])));if(!this.#_(z))return;let G;try{G=await Z.custody.discover(z.controller.signal)}catch(K){if(!this.#_(z))return;for(let W of this.#Y.values())if(W.pending)this.#v(W);throw K}if(!this.#_(z))return;let J=this.#E(),B=await Promise.all(J.map((K)=>K.hooks&&!K.closed?this.#n(K,K.hooks,G,X??Y.get(K),z):void 0));if(!this.#_(z))return;let H=new Map,Q=!0;for(let[K,W]of J.entries()){let D=W.hooks,V=B[K];if(!D||!V)continue;if("error"in V){let{error:_}=V;if(Q=!1,this.#v(W),u4(W.path,_))this.#Z.debug("claustrum hub member commit refused",{member:W.provider});else H.set(W.provider,_);continue}let{roster:U}=V;if(!this.#_(z))return;if(U?.view!==G.view)Q=!1,this.#v(W);else W.pending=void 0;if(!U)continue;if(this.#l(D,U)){Q=!1,this.#v(W);continue}this.#T(W,U)}if(!this.#_(z))return;if(this.#g(),Q)this.#F=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#M=(this.#$.now??Date.now)(),{errors:H}}async#n($,Z,z,X,Y){let G={...z,credentials:z.credentials.filter((J)=>J.member===$.provider),skipped:z.skipped.filter((J)=>J.member===$.provider)};try{if(!X)throw J0("Claustrum hub member has no base view");if(X instanceof Error)throw X;let J;if(!X.file){let H=o9("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{J=await this.#r($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await o0({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#_(Y)&&this.#D===!0,signal:Y.controller.signal,projection:()=>({...Z.projection(),...J&&{seed:J}}),listedOver:{view:X.file?.view}})}}catch(J){return{error:J}}}async#o(){for(let $ of[e9(this.#q),this.#q,b0(this.#q,this.#R)])await E0($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,z=[b0(this.#q,Z)];try{for(let Y of await r9(this.#q))if(Y!==this.#R&&z1.test(Y))z.push(b0(this.#q,Y,Z))}catch{}let X;for(let Y of z)try{let G=(await t9(Y)).mtimeMs,J=await R(Y);if(J&&(!X||G>X.modified))X={modified:G,roster:J}}catch{}return X&&p3(X.roster)}#l($,Z){let z=$.projection().reservedRouteIds;return!!z?.size&&Z.rows.some((X)=>z.has(X.routeId))}#v($){let Z=($.pending?.failures??0)+1,z=Math.max(1,this.#$.pollIntervalMs??5000),X=Math.max(1,Math.ceil(T0/z)),Y=Z<=J6?1:Math.min(2**(Z-J6),X);$.pending={failures:Z,wait:Y-1}}#g(){let $=this.#z?.custody;if(!$)return;$.retain(this.#E().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#Q;for(let Z of this.#E()){let z;try{z=await R(Z.path)}catch(B){Z.hooks?.onError(B);continue}if($!==this.#Q||this.#D!==!0)return;let X=Z.hooks;if(!z||!X||Z.closed)continue;let Y=JSON.stringify(z);if(Y===Z.seen)continue;let G=X.roster();if(!G||G.view!==z.view||this.#l(X,z)){Z.pending??={failures:0,wait:0};continue}let J=H6(G);if(Z.seen=Y,this.#T(Z,z),H6(X.roster())!==J)this.#g()}}#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.#K?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#M===void 0||Z-this.#M>=T0}#$0(){let $=this.#G,Z=$&&this.#H.get($);if(!$||!Z||!this.#A($)||this.#D!==!0)return;let z=Z.generation;if(!this.#_(z)||this.#K?.generation===z)return;let X=Z.custody.watchRoster({view:()=>this.#F?.view,onView:()=>this.#V((async()=>{while(this.#U)await this.#U.promise.catch(()=>{});if(!this.#_(z))return;await this.#i()})()),onRefused:(Y)=>this.#c(Y),onError:(Y)=>this.#d(Y)});this.#K={generation:z,watch:X}}#d($){if(!this.#J.signal.aborted)this.#$.onError?.($)}#c($){if(this.#J.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#E())Z.hooks?.onError($)}#u($){for(let[Z,z]of $?.errors??[])this.#Y.get(Z)?.hooks?.onError(z)}async#i(){let $;try{$=await this.#m()}catch(Z){this.#c(Z);return}this.#u($)}async#s(){try{if(await this.#b()){if(await this.#t(),this.#e())await this.#i();this.#$0()}}catch(Z){this.#d(Z)}if(this.#J.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#x=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#x=void 0,this.#V(this.#s())},$),this.#x.unref?.()}start(){if(this.#O)return;this.#j(),this.#O=!0,this.#V(this.#s())}async refresh(){this.#u(await this.#m())}refusals(){let $=this.#F;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#F?.reach}watchState(){let $=this.#K;return $&&this.#_($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#z?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#J.signal.aborted)return;this.#J.abort(J0("Claustrum discovery hub is closed"));for(let Z of this.#Y.values())Z.releaseRoster?.();if(this.#x)(this.#$.clearTimeoutImpl??clearTimeout)(this.#x);this.#x=void 0;let $=this.#z;if($)this.#C($);this.#G=void 0,this.#K?.watch.close(),this.#K=void 0}async dispose(){this.close(),this.#W??=I0(this.#P,this.#B),await this.#W}}var G1=1e4;async function Hz($){let{connectTimeoutMs:Z,...z}=$,X=Z??G1,Y=J1.connect(z),G=!1,J,B=new Promise((H,Q)=>{J=setTimeout(()=>{G=!0,Q(new C)},X),J.unref?.()});try{let H=await Promise.race([Y,B]);return Object.assign(H,{insula:Z4($)})}catch(H){throw Y.then((Q)=>Q.close(),()=>{}),H}finally{if(!G&&J)clearTimeout(J)}}var W6=E$("openai");function Q6($){return C$($)}function j0($){if(!$||$.corrupt===!0)return!1;return Q6($.refresh)}class r0 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 h$($){if(Q6($))throw new r0}var B1=A("quota"),$Z="primary",ZZ="secondary",H1="app_EMoamEEZ73f0CkXaXp7hrann",K1="https://auth.openai.com";async function Iz($){h$($.refreshToken);let Z=await $.fetchImpl(`${K1}/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:H1}).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 W1="https://chatgpt.com/backend-api/wham/usage";async function kz($){let Z=$.logger??B1,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await $.fetchImpl(W1,{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 J=q3(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:J})}let G=rZ(await Y.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:Y.status,elapsedMs:Date.now()-X}),G}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:U6(Y)}),Y}}import{createHash as Q1}from"node:crypto";var U1=globalThis.setTimeout,V1=5;function t0($){let Z=$?.quota?.checkIntervalMinutes??V1;return Math.max(1,Z)*60000}function D1($){return $?.quota?.enabled!==!1}function w$($,Z){if(!$?.resetsAt)return!1;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z<=Z}function vz($,Z,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=Z===$Z?$?.primary:Z===ZZ?$?.secondary:void 0,J=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(J)&&J>z)return J;return z+X}function F1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function V6($,Z,z){if(!D1(Z))return z+t0(Z);let X=F1(Z),Y=[];for(let G of["primary","secondary"]){let J=$?.[G];if(!J)continue;if(J.remainingPercent>=X[G])continue;let B=J.resetsAt?Date.parse(J.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=z)return z+t0(Z);Y.push(B)}if(!Y.length)return z+t0(Z);return Math.min(...Y)+60000}function q1($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function N1($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function h($){return Q1("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!==h($))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($)!==h(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!D6(Z.quota))return;if(this.mainTokenFp=h($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,zZ(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&&!D6(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(Y&&G&&Y!==G)this.clearRateLimited($);let J=Y??G;if(this.fallbacks.set($,{...Z,accountId:J}),z)this.fallbackTokenFps.set($,h(z));else this.fallbackTokenFps.delete($);if(zZ(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=h($);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 G=this.getFallback($,Z);if(G)return G.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(j0(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=h($);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=N1(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=q1($);if(!z)return;let X=Z?h(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:V6(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=t0(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($)!==h(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([$,h(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 G=U1(Y,G0.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=h($);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 y({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($),G=this.now();if(this.mainTokenFp=h($),this.main={quota:Y,refreshAfter:V6(Y,this.storage,G),checkedAt:G},zZ(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,G,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 y({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+t0(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=p0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(G0.isAuthError(z))return;let X=h(Z),Y=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,p0({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,X)}}function D6($){return Boolean($.primary||$.secondary)}function zZ($){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 M1,randomUUID as _1}from"node:crypto";import{setTimeout as j1}from"node:timers/promises";import{readFile as f1}from"node:fs/promises";var O0=A("refresh"),z$=A("accounts"),O1=1e4,P1=15000,XZ=50;function u($){return $.type==="oauth"&&$.corrupt!==!0}function L1($){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 x1="floors-v1";function $X($){return $.costZeroing?.enabled!==!1}class v$ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var R1=[401,403,429],F6={primary:0,secondary:0},S1=!1,JZ={primary:5,secondary:10};function q($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var T1=new Set(["__proto__","constructor","prototype"]);function A1($){return $.length>0&&!T1.has($)}function E1($){return $ instanceof v$||q($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function m$($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():_1(),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 q6($){if(!q($))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 C1($){if(!q($))return;let Z={};for(let Y of["primary","secondary"]){let G=$[Y];if(!q(G))continue;let J=Number(G.usedPercent),B=Number(G.remainingPercent),H=Number(G.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(B)||!Number.isFinite(H))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[Y]={usedPercent:J,remainingPercent:B,checkedAt:H,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[Y]==="number"?$[Y]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[Y]=G}let z=$.spendControl;if(q(z)){let Y=Number(z.limit),G=Number(z.used),J=Number(z.remaining),B=Number(z.usedPercent),H=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof z.reached==="boolean")Z.spendControl={limit:Y,used:G,remaining:J,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(q(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&(X.overageLimitReached===void 0||typeof X.overageLimitReached==="boolean")){let Y=Number(X.balance),G=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(G)?{checkedAt:G}:{}}}return Object.keys(Z).length?Z:void 0}function I1($){if(!q($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!L1(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...m$($),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{...m$($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...m$($),type:"oauth",corrupt:!0}}return{...m$($),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:q6($.lastRefreshError),lastQuotaRefreshError:q6($.lastQuotaRefreshError),quota:C1($.quota)}}function k1($){if(!q($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!A1(z)||!q(X))continue;let Y={};if(q(X.inFlight))Y.inFlight={...X.inFlight};if(q(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,...q(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 N6=new Set;function R6($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(N6.has(Z))return;N6.add(Z),z$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function S6($){if(!q($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(I1).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let J of Z)if(q(J)&&typeof J.id==="string"&&J.id.trim())X.add(J.id.trim());let Y=new Set(z.map((J)=>J.id)),G=[];for(let J of X)if(!Y.has(J))G.push(J);R6(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:q($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:q($.refresh)?$.refresh:void 0,quota:q($.quota)?$.quota:void 0,reset:k1($.reset),dump:q($.dump)?$.dump:void 0,costZeroing:q($.costZeroing)?$.costZeroing:void 0,killswitch:q($.killswitch)?$.killswitch:void 0,logging:q($.logging)?$.logging:void 0,cachekeep:q($.cachekeep)?$.cachekeep:void 0,cacheKeep:q($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:z}}function T6($){if(!("claustrum"in $))return $;let{claustrum:Z,...z}=$;return z}async function i($){try{return{exists:!0,value:JSON.parse(await f1($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function p($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function b1($){let Z;try{Z=(await i($)).value}catch{return null}return KZ(Z)}function A6($,Z){if(!q($))return $;let z=q(Z)?Z:{},X=q(z.main)?z.main:void 0,Y=q(z.accounts)?z.accounts:{},G=q($.quota)?$.quota:{},J=q($.refresh)?$.refresh:{},B=X??G,H=X??J,K=J.mainRefreshLeaseId!==void 0?{id:J.mainRefreshLeaseId,until:J.mainRefreshLeaseUntil,tokenHash:J.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},D=Array.isArray($.accounts)?$.accounts.map((V)=>{if(!q(V))return V;let U=typeof V.id==="string"&&q(Y[V.id])?Y[V.id]:{};return{...V,...U}}):void 0;return E6({...$,refresh:p({...J,mainLastRefreshError:J.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:K.id,mainRefreshLeaseUntil:K.until,mainRefreshLeaseTokenHash:K.tokenHash}),quota:p({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:D})}async function y1($){let Z=await i($.configPath);if(!Z.exists)return null;let z=await i($.statePath);return S6(A6(Z.value,z.value))}var M6=new Set;async function zX($){try{let{exists:Z,value:z}=await i($.configPath);if(!Z)return null;if(!q(z))throw Error("settings must be an object");let X=q(z.refresh)?z.refresh:{},Y=q(z.quota)?z.quota:{};return{version:1,accounts:[],routing:q(z.routing)?z.routing:void 0,fallbackOn:Array.isArray(z.fallbackOn)?z.fallbackOn.filter((G)=>Number.isInteger(G)):void 0,refresh:p({enabled:X.enabled,refreshBeforeExpiryMinutes:X.refreshBeforeExpiryMinutes}),quota:p({enabled:Y.enabled,checkIntervalMinutes:Y.checkIntervalMinutes,refreshEveryNRequests:Y.refreshEveryNRequests,minimumRemaining:Y.minimumRemaining,failClosedOnUnknownQuota:Y.failClosedOnUnknownQuota}),dump:q(z.dump)?z.dump:void 0,costZeroing:q(z.costZeroing)?z.costZeroing:void 0,killswitch:q(z.killswitch)?z.killswitch:void 0,logging:q(z.logging)?z.logging:void 0,cachekeep:q(z.cachekeep)?z.cachekeep:void 0,cacheKeep:q(z.cacheKeep)?z.cacheKeep:void 0}}catch{if(!M6.has($.configPath))M6.add($.configPath),z$.warn("could not read OpenAI auth settings; using defaults",{path:$.configPath});return null}}function E6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function h1($){return p({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 C6($){if($.type==="api")return p({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return p({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function g$($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function e0($,Z,z){if(z in Z)$[z]=Z[z];else delete $[z]}function w1($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function m1($,Z){if(!w1($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var v1=300000;function _6($,Z){if($===void 0)return 0;return $>Z+v1?0:$}function g1($,Z,z){let X=Date.now(),Y=_6(Z.lastRefreshedAt,X),G=_6(z.lastRefreshedAt,X),J=Z.expires??0,B=z.expires??0,H=G>Y?z:Y>G?Z:B>J?z:J>B?Z:m1(Z,z);e0($,H,"access"),e0($,H,"refresh"),e0($,H,"expires"),e0($,H,"lastRefreshedAt"),e0($,H,"lastRefreshError")}function p1($,Z){if(!q($))return Z;let z=$,X=g$(z.quota),Y=g$(Z.quota),G=X>Y,J=G?{...z,...Z,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete J.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete J.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||z.lastUsed>Z.lastUsed))J.lastUsed=z.lastUsed;return g1(J,z,Z),J}function I6($){let Z=$.refresh?p({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?p({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return E6({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(h1)})}async function X$($,Z=!1){let z=Date.now(),X=z+P1,Y=0;while(Date.now()<=X){Y++;let B=await y({name:"save",ttlMs:O1,path:$,renew:Z});if(B)return B;let H=X-Date.now();if(H<=0)break;await j1(Math.min(XZ+h6(XZ),H))}let G=Date.now()-z,J=Math.round(G/Math.max(1,Y));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${Y} attempts, ~${J}ms apart; retry interval is ${XZ}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 k6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,C6(z)]));return{version:1,main:p({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 KZ($){if(!q($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!q(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function l1($,Z,z,X){if(!q($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],G=[];for(let J of Z){if(z.has(J))continue;if(X.has(J))continue;let B=$.accounts.find((H)=>q(H)&&typeof H.id==="string"&&H.id.trim()===J);if(!B)continue;Y.push(B),G.push(J)}return{preservedRawEntries:Y,preservedIds:G}}function d1($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!q(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function c1($,Z,z){let X=KZ($);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=l1($,X,Z,z);return R6(G),Y}async function XX($,Z,z={}){let{configPath:X,statePath:Y}=Z,G=await X$(X);try{let J=await X$(Y);try{let B=await i(X),H=await i(Y),Q=(B.exists?S6(A6(B.value,H.value)):null)??u1(),K=new Set(Q.accounts.map((w)=>w.id)),W=KZ(B.value)??new Set,D=$(Q,{rawRosterIds:[...W],loadedRosterIds:[...K]})??Q,V=new Set(z.allowDrop??[]),U=c1(B.value,K,V),_=I6(D),M=new Set((Array.isArray(_.accounts)?_.accounts:[]).map((w)=>q(w)&&typeof w.id==="string"?w.id.trim():"").filter(Boolean)),P=U.filter((w)=>{if(!q(w))return!1;if(typeof w.id!=="string")return!1;return!M.has(w.id.trim())}),x=q(B.value)?B.value:{},k={...T6(x),..._,accounts:[...Array.isArray(_.accounts)?_.accounts:[],...P]};if(z.canWrite&&!z.canWrite())return Q;if(await d(X,k),z.canWrite&&!z.canWrite())return Q;return await d(Y,k6(D)),z$.debug("account config written",{accountCount:k.accounts.length,accountIds:d1(k.accounts)}),D}finally{await J.release()}}finally{await G.release()}}function u1(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function i1($,Z){$.main=$.main??{};let z=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:g$($.main.quota),X=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:g$(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 s1($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function GZ($){if(Array.isArray($))return $.map(GZ);if(!q($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,z])=>[Z,GZ(z)]))}async function a1($,Z,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=Z.statePath,G=await X$(Y);try{let J=(await i(Y)).value,B=q(J)?{...J,version:1}:{version:1};if(z.mainQuota)i1(B,$);if(z.mainRefresh)s1(B,$);if(z.accounts){let H=z.accounts===!0?null:new Set(z.accounts),Q=await b1(Z.configPath);B.accounts={...q(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]=p1(B.accounts[K.id],C6(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,GZ(B))}finally{await G.release()}}function n1($){return $?.fallbackOn?.length?$.fallbackOn:R1}function YX($,Z){return n1(Z).includes($)}function o1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??F6.primary,secondary:Z.secondary??Z["1w"]??F6.secondary}}function BZ($){return $?.quota?.enabled!==!1}function Y$($){return $?.quota?.failClosedOnUnknownQuota??S1}function f6($,Z,z=Date.now()){if(!BZ(Z))return!0;if(!$)return!Y$(Z);let X=o1(Z),Y=Y$(Z);for(let G of["primary","secondary"]){let J=$[G];if(!J)continue;if(w$(J,z)){if(Y)return!1;continue}if(J.remainingPercent<X[G])return!1}return!0}function p$($){return $?.killswitch?.enabled===!0}function j6($){return{primary:$?.primary??$?.["5h"]??JZ.primary,secondary:$?.secondary??$?.["1w"]??JZ.secondary}}function JX($){return $?.cacheKeep??$?.cachekeep}function O6($){return typeof $==="number"&&Number.isFinite($)?$:0}function b6($,Z){if(!$?.killswitch)return JZ;if($.killswitch.schema===x1){let{accounts:z,defaults:X}=$.killswitch,Y=Z??"main",G=q(z)&&Object.hasOwn(z,Y)&&q(z[Y])?z[Y]:q(X)?X:void 0;return{primary:O6(G?.primary),secondary:O6(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return j6($.killswitch.accounts[Z]);return j6($.killswitch.main)}function y6($,Z,z,X=Date.now()){if(!p$(Z))return!0;if(!$)return!Y$(Z);let Y=b6(Z,z),G=Y$(Z);for(let J of["primary","secondary"]){let B=$[J];if(!B)continue;if(w$(B,X)){if(G)return!1;continue}if(B.remainingPercent<Y[J])return!1}return!0}function GX($,Z,z,X){if(!p$(X))return 300;let Y=[],G=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:H}of G){if(!H)continue;let Q=b6(X,B),K=[],W=!1;for(let D of["primary","secondary"]){let V=H[D];if(!V||w$(V,z))continue;if(V.remainingPercent>=Q[D])continue;let U=V.resetsAt?Date.parse(V.resetsAt):NaN;if(!Number.isFinite(U)||U<=z){W=!0;break}K.push(U)}if(W||K.length===0)continue;Y.push(Math.max(...K))}if(Y.length===0)return 300;let J=Math.min(...Y);return Math.max(1,Math.ceil((J-z)/1000))}function P6($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function BX($,Z){let{configPath:z,statePath:X}=Z;if(!$)return;try{let G=await i(z);if(G.exists&&q(G.value)&&P6(G.value))return}catch{}let Y=await X$(z);try{let G=await X$(X);try{let J=await i(z);if(J.exists&&q(J.value)){if(P6(J.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=J.exists&&q(J.value)?J.value:{},Q={...T6(H),...I6(B)};await d(z,Q),await d(X,k6(B))}finally{await G.release()}}finally{await Y.release()}}function r1($){return $?.refresh?.enabled!==!1}function t1($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function h6($){return Math.floor(Math.random()*($+1))}function P0($,Z,z){return!$.access||!$.expires||$.expires-z<=t1(Z)}function e1($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function $$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class w6 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 $2="common-auth-placeholder:v1:openai",m6="main";function HX($){return q($)&&$.type==="oauth"&&($.refresh===$2||$.refresh===W6)}function KX($){return $?.accounts.find((Z)=>Z.id===m6&&Z.enabled!==!1&&u(Z))}function WX($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==m6)}}function E($,Z){let z=$.accounts.findIndex((X)=>X.id===Z.id);if(z!==-1)$.accounts[z]=Z}function Z$($){return $ instanceof Error?$.message:String($)}function HZ($,Z,z){if(Z instanceof r0)return;$.lastRefreshError=yZ({error:Z,now:z,refreshToken:$.refresh,previous:$.lastRefreshError})}function YZ($,Z,z){if(Z instanceof r0)return;if($.lastQuotaRefreshError=p0({error:Z,now:z,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)HZ($,Z,z)}function L6($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return Number.isFinite(z)?z>Z:!0}function Z2($,Z){if(!$)return!1;return L6($.primary,Z)||L6($.secondary,Z)}function z2($,Z,z){if(!$)return!1;let X=Z?.quota?.checkIntervalMinutes??5,Y=Math.max(1,X)*60000,G=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return z-G<Y}function x6($,Z,z){return!z2($.quota,Z,z)}function X2($,Z,z,X){return F3(z)&&f6($.quota,Z,X)&&Z2($.quota,X)}function Y2($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var J2=60000,G2=60000,B2=600000;function H2($){return`fallback-oauth-refresh-${M1("sha256").update($).digest("base64url").slice(0,16)}`}var K2=1e4,W2=100;class Q2{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($)h$($.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+Y2(Z),checkedAt:z},$.access,!1,$.accountId)}async load(){return y1(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await a1($,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(()=>{})},J2+h6(G2)),"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($$(Z,Y))continue;if(j0(Y))continue;let G=!1,J=Y;try{if(P0(J,Z,this.now())){let B=J.lastRefreshError;if(B&&Q0(B,J.refresh,this.now()))throw G=!0,Error(D$(B,this.now()));try{J=await this.refreshAccount(J,Z),X=!0}catch(H){if(E1(H))continue;G=!0;let Q=Z.accounts.find((K)=>K.id===Y.id&&u(K));if(Q&&!Q0(Q.lastRefreshError,Q.refresh,this.now()))HZ(Q,H,this.now()),E(Z,Q),X=!0;throw H}}if(this.seedFallbackQuota(J,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),Z))z.push(J)}catch(B){let H=e1(J,this.now());if(G){if(!H)continue}else if(!H)continue;if(X2(J,Z,B,this.now()))O0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:Z$(B)}),z.push(J);else if(!Y$(Z))z.push(J)}}if(X){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{z$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:Z$(G)})})}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$(Z)})}}accountPassesQuotaPolicy($,Z){return f6($.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(!$||!r1($))return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!u(z))continue;if($$($,z))continue;if(j0(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:Z$(X)}),HZ(z,X,this.now()),E($,z),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!BZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!u(z))continue;if($$($,z))continue;if(j0(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):x6(X,$,this.now())))continue;await this.refreshAccountQuota(X,$),Z=!0}catch(Y){YZ(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||!BZ(Z))return{storage:Z,errors:z};if(!this.options.fetchQuotaFn)return{storage:Z,errors:z};let X=$.force??!1,Y=!1;for(let G of Z.accounts){if(G.enabled===!1||!u(G))continue;if($$(Z,G))continue;if(j0(G))continue;let J=G;try{if(P0(J,Z,this.now())){let B=J.lastRefreshError;if(B&&Q0(B,J.refresh,this.now()))throw Error(D$(B,this.now()));J=await this.refreshAccount(J,Z),Y=!0}if(!X&&!x6(J,Z,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,E(Z,J),Y=!0;continue}await this.refreshAccountQuota(J,Z),Y=!0}catch(B){YZ(G,B,this.now()),E(Z,G),Y=!0,z.push({accountId:G.id,message:Z$(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 J=await X;return E(Z,J),J}let Y=this.refreshAccountNow($,Z,z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let G=await Y;return E(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,z,X){let Y=Date.now()+K2;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,W2));let G=await this.load(),J=G?.accounts.find((Q)=>Q.id===$.id&&u(Q));if(!J)continue;if(this.assertNotTombstoned(J),(J.access!==z.access||J.refresh!==z.refresh||(J.expires??0)>(z.expires??0)+60000)&&(X.force||!P0(J,G,this.now())))return E(Z,J),O0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let H=J.lastRefreshError;if(H&&Q0(H,J.refresh,this.now()))throw E(Z,J),Error(D$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,z){if(z.asPoolMain||!Z)return;if($$($,Z))throw new w6(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 G=Y??$,J=await y({name:H2(G.id),ttlMs:B2,path:this.paths.configPath,renew:!0});if(!J){O0.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,G,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 v$($.id);G=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:G.id,force:z.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let H=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=H.access,G.refresh=H.refresh,G.expires=H.expires,G.lastRefreshedAt=H.expires-H.expiresIn*1000,G.lastRefreshError=void 0,E(Z,G),await this.save(Z),!(await this.load())?.accounts.some((K)=>K.id===$.id))throw new v$($.id);return O0.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await J.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=(G)=>this.quotaManager?this.quotaManager.refreshFallback(z.id,G):X({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!z.access)throw Error(`Fallback account ${$.id} has no access token`);let G=await Y(z.access);z.quota=G,z.lastQuotaRefreshError=void 0,E(Z,z),await this.save(Z)}catch(G){throw YZ($,G,this.now()),E(Z,$),G}}}var v6=["primary","secondary"];function l$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function y0($){return typeof $==="number"&&Number.isFinite($)}function U2($,Z){if(!l$(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 V2($){let Z=$.spendControl;if(l$(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 D2($,Z){if(!l$($)||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 VX($,Z,z){if(!l$($)||!y0(Z))return;let X=[],Y=[];for(let Q of v6){let K=U2(Q,$[Q]);if(K)X.push(K);else if(z)Y.push({label:Q})}let G=V2($),J=$.resetCreditsAvailable,B=typeof J==="number"&&Number.isSafeInteger(J)&&J>=0?{resetCredits:{value:J,checkedAt:Z}}:void 0,H=D2($.credits,Z);if(X.length===0&&Y.length===0&&!G&&!B&&!H)return;return{checkedAt:Z,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function g6($){if(!H0($))return;let Z=b($),z={};for(let X of v6){let Y=Z.limits.find((J)=>J.label===X&&J.kind==="reading");if(!Y||!y0(Y.usedPercent))continue;let G={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]=G}return z.primary||z.secondary?z:void 0}var l6="main";function _X($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function jX($,Z,z){let X=new Map;if(p$(Z))for(let Y of $)X.set(Y.id,y6(g6(Y.quota),Z,Y.id===l6?void 0:Y.id,z));return X}var OX=5,F2=5000;function PX($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function LX($,Z=F2){let z=$.rows.filter((J)=>J.kind==="oauth"&&$.killswitch.get(J.id)!==!1&&b(J.quota).limits.length===0);if(z.length===0)return;if(v({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((J)=>$.killswitch.get(J.id)!==!1))return;let Y=[];if(v({rows:z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(J)=>{let B=$.requestPull(J);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let G;return Promise.race([Promise.all(Y),new Promise((J)=>{G=setTimeout(J,Z)})]).then(()=>{}).finally(()=>clearTimeout(G))}function d$($){return $.reason==="exhausted"||$.reason==="budget-spent"}function q2($,Z){if(!l($))return!1;let z=$;if(!(Z-z.checkedAt<=v0))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function c$($,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)),G=new Map(z.refused.map((B)=>[B.id,B])),J=$.filter((B)=>{if(B.kind!=="oauth"||!X(B.id))return!1;if(G.get(B.id)?.reason!=="exhausted")return!1;let H=b(B.quota);if(W0(H,Z.now))return!1;return q2(H.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:J}}function N2($,Z=$.rows){return v({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class M2{#$=new Set;served($,Z,z){let X=N2($),Y=c$($.rows,$,X),G=new Set(Y.credits);if(Y.free.has(Z)){this.#$.clear();return}for(let J of[...this.#$])if(!G.has(J))this.#$.delete(J);if(!G.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 d6($,Z,z){if($===void 0)return{reason:"no-credential"};if(z.get($)===!1)return{reason:"killswitch"};let X=Z.excluded.find((G)=>G.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((G)=>G.id===$);if(Y&&"resetAtMs"in Y)return{reason:"quota-exhausted",resetAtMs:Y.resetAtMs};if(Y)return{reason:"quota-unknown"};return{reason:"no-credential"}}function p6($,Z,z){if(Z.refused.find((Y)=>!d$(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return d6($[0],Z,z)}function xX($){let Z=$.replayable!==!1,z=$.mainId===void 0?l6:$.mainId??"",X=Z?$.placement:"main-first",Y=J3({rows:$.rows,placement:X,formerMainId:z,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),G=Q$($.rows.map((W)=>W.id),X,z),J=new Set(Y.admission.refused.filter((W)=>d$(W)&&$.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=G.filter((W)=>J.has(W)),H=c$($.rows,$,Y.admission),Q=Y.order.filter((W)=>H.free.has(W)),K=G.filter((W)=>H.credits.includes(W));if(!Z){let W=G.includes(z),D=W?z:Q[0]??K[0]??Y.order[0]??B[0];if(D!==void 0&&Y.order.includes(D))return{kind:"send",order:[D],lastPath:!1};if(D!==void 0&&K.includes(D))return{kind:"send",order:[D],lastPath:!1};if(D!==void 0&&J.has(D))return{kind:"send",order:[D],lastPath:!0};return{kind:"block",block:W?d6(z,Y.admission,$.killswitch):p6(G,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((D)=>!K.includes(D))],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:p6(G,Y.admission,$.killswitch)}}function RX($){let Z=v({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=new Map;for(let X of $.rows)z.set(X.id,b(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 c6($,Z,z){let X=z.exclude,Y=X?$.rows.filter((J)=>!X.has(J.id)):$.rows,G=new Map;for(let J of Y){let B=Z.resetCredits(J.id);if(B!==void 0)G.set(J.id,B)}return W3({rows:Y,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...z.pendingBytes?{pendingBytes:z.pendingBytes}:{},rowReservePercent:(J)=>Z.reservePercent(J.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function SX($,Z,z,X){let Y=c6($,Z,{exclude:z,pendingBytes:X}),G=$.rows.filter((K)=>!z.has(K.id)),J=c$(G,$,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&&J.free.has(B.accountId))return B;let H=J.credits[0];if(H===void 0)return B;let Q=b(G.find((K)=>K.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function TX($,Z,z){let X=$.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},G=c6($,Z,{pin:z}),J=c$($.rows,$,G.admission),B=J.credits.includes(z),H=J.credits.some((W)=>W!==z);if(G.outcome==="dispatch"){let W=!J.free.has(G.accountId);if(G.pin.action==="assign"){if(W&&B)return{kind:"serve"};return Y}if(G.accountId!==z)return{kind:"detour"};if(W&&H)return Y;return{kind:"serve"}}let Q=G.admission.refused.find((W)=>W.id===z),K=X||Q!==void 0&&d$(Q);if(B)return{kind:"serve"};if(H)return K?Y:{kind:"detour"};if(!X&&Q&&d$(Q))return{kind:"last-path"};return{kind:"none"}}function AX($,Z,z,X){let Y=$.killswitch.get(z);return K3({quota:Z.projections.get(z),now:$.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as u6}from"node:os";import{join as i6}from"node:path";var _2=["error","warn","info","debug","trace"];function j2(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?i6(u6(),"opencode-openai-auth","opencode-openai-auth.log"):i6(u6(),"opencode-openai-auth.log"))}function O2(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&_2.includes($)?$:void 0}s6({file:j2,level:O2});if(process.once("beforeExit",async()=>{try{await u$()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>u$());
91
- export{H0 as Nc,m0 as Oc,_8 as Pc,Z3 as Qc,z8 as Rc,xZ as Sc,B8 as Tc,H8 as Uc,b as Vc,AZ as Wc,O8 as Xc,Q$ as Yc,P8 as Zc,G3 as _c,L8 as $c,b4 as ad,y4 as bd,L3 as cd,S8 as dd,k8 as ed,bZ as fd,yZ as gd,Q0 as hd,D$ as id,gZ as jd,lZ as kd,w8 as ld,wZ as md,mZ as nd,q$ as od,v8 as pd,F0 as qd,d8 as rd,c8 as sd,u8 as td,i8 as ud,V7 as vd,F7 as wd,q7 as xd,N7 as yd,F as zd,q0 as Ad,F4 as Bd,_9 as Cd,j9 as Dd,O9 as Ed,I3 as Fd,x9 as Gd,R4 as Hd,R9 as Id,R as Jd,r3 as Kd,Hz as Ld,j0 as Md,r0 as Nd,Iz as Od,kz as Pd,vz as Qd,h as Rd,G0 as Sd,u as Td,x1 as Ud,$X as Vd,JZ as Wd,A1 as Xd,b1 as Yd,y1 as Zd,zX as _d,XX as $d,a1 as ae,n1 as be,YX as ce,f6 as de,p$ as ee,JX as fe,b6 as ge,y6 as he,GX as ie,BX as je,t1 as ke,$$ as le,m6 as me,HX as ne,KX as oe,WX as pe,B2 as qe,H2 as re,Q2 as se,VX as te,g6 as ue,l6 as ve,_X as we,jX as xe,OX as ye,PX as ze,LX as Ae,q2 as Be,M2 as Ce,xX as De,RX as Ee,SX as Fe,TX as Ge,AX as He};
@@ -1,8 +0,0 @@
1
- import{Af as S0,Cf as y,rf as Y,sf as C,tf as O,uf as C0,wf as A,xf as a,yf as f,zf as i}from"./index-mcy24ej8.js";import{randomUUID as E}from"node:crypto";import{lstat as T,mkdir as V0,open as A0,readFile as D0,rename as x0,rm as L,stat as M}from"node:fs/promises";import{dirname as d,join as F0}from"node:path";import{join as M0,resolve as L0}from"node:path";function l(z,H){return`${z}.${H}.lock`}class U0 extends Error{details;constructor(z){super(`Timed out acquiring ${z.name} lock for ${z.target}`);this.name="LockContentionError",this.details=z}}class R extends Error{details;constructor(z){super(`Lost ${z.name} lock for ${z.target}`);this.name="LockOwnershipError",this.details=z}}function b0(z,H,$){if(!O(z)||z.stage!=="read"&&z.stage!=="verify")return!1;let Z=L0(l(H,$));return z.path===Z||z.path===M0(Z,"owner.json")}async function c0(z,H,$){let Z=performance.now();for(;;){H.signal?.throwIfAborted();let W,_;try{W=await X0({path:z,name:H.name,ttlMs:H.ttlMs,renew:H.renew??!1,...H.onStep?{onStep:H.onStep}:{},...H.onRenewalTimer?{onRenewalTimer:H.onRenewalTimer}:{}})}catch(V){if(!b0(V,z,H.name))throw V;W=null,_=V}if(W)try{return H.signal?.throwIfAborted(),await $(W)}finally{await W.release(H.signal)}let X=H.timeoutMs-(performance.now()-Z);if(X<=0){if(_)throw _;throw new U0({target:z,name:H.name,timeoutMs:H.timeoutMs})}await new Promise((V)=>setTimeout(V,Math.min(25,Math.ceil(X))))}}async function j0(z,H){let $=await A0(z,"wx",384),Z;try{Z=await $.stat()}catch{Z=void 0}try{await $.writeFile(H,"utf8")}catch(W){try{let _=await T(z).catch(()=>{return});if(Z&&_&&_.dev===Z.dev&&_.ino===Z.ino)await L(z,{force:!0}).catch(()=>{})}catch{}throw W}finally{await $.close()}}var g0=globalThis.setTimeout.bind(globalThis),O0=globalThis.clearTimeout.bind(globalThis);function E0(z){let H=z?.code;return H==="ENOENT"||!Y&&(H==="EINVAL"||H==="ENOTDIR")}var q0;function s(z,H){if(z.dev!==H.dev||z.ino!==H.ino)return!1;if(z.ino===0&&z.birthtimeMs!==H.birthtimeMs)return!1;return!0}var y0=1000;function X0(z){return k0({...z,now:Date.now})}async function k0(z){let H=l(z.path,z.name),$=F0(H,"owner.json"),Z=E(),W=z.now??Date.now,_=null,X=!1,V=!1,D,o,f0=new Promise((N)=>{o=N});function r(N){try{let B=z.onRenewalTimer?.(N);if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}}function e(){if(!_)return;O0(_),_=null,r("cancelled")}function j(N,B){if(D||X)return;D=Object.freeze({reason:N,expectedOwnerId:Z,...typeof B?.ownerId==="string"?{observedOwnerId:B.ownerId}:{},...typeof B?.expiresAt==="number"?{observedExpiresAt:B.expiresAt}:{}}),e(),o(D)}let P,b=null,U=`${H}.evicting`,q=F0(U,"owner.json"),z0=E(),u=5000,N0=8;async function F(){if(Y)try{return JSON.parse(await f(H,!0))}catch(N){if(N.code!=="EISDIR"&&N.reason!=="wrong-kind")throw N;return await A(H,"directory",!0),JSON.parse(await f($,!0))}try{return JSON.parse(await D0(H,"utf8"))}catch(N){if(N.code!=="EISDIR")throw N;return JSON.parse(await D0($,"utf8"))}}async function T0(){if(Y){let K=await F(),Q=Number(K?.expiresAt)-W();await y(H,`${JSON.stringify({ownerId:Z,expiresAt:W()+z.ttlMs})}
2
- `,{deadline:performance.now()+Math.max(0,Q),beforeRename:async()=>{let J=await F();if(J?.ownerId!==Z||!(Number(J?.expiresAt)>W())||!await x())throw new R({target:z.path,name:z.name})}});return}let N=`${H}.${E()}.tmp`,B,G=!1;try{B=await A0(N,"wx",384),G=!0,await B.writeFile(`${JSON.stringify({ownerId:Z,expiresAt:W()+z.ttlMs})}
3
- `,"utf8"),await B.chmod(384),await B.close(),B=void 0;let K=await F();if(K?.ownerId!==Z||!(Number(K?.expiresAt)>W())||!await x())throw new R({target:z.path,name:z.name});await x0(N,H),G=!1}finally{if(await B?.close().catch(()=>{}),G)await L(N,{force:!0}).catch(()=>{})}}async function B0(){let N=`${JSON.stringify({ownerId:Z,expiresAt:W()+z.ttlMs})}
4
- `;if(Y)await i(H,N);else await j0(H,N)}async function G0(N){let B=N.code;if(B!=="EEXIST"&&B!=="EISDIR")return!1;if(Y){if(z.onStep)await z.onStep("lease-contention-read-ready");try{if(B==="EISDIR")await A(H,"directory",!0),await f($,!0);else await F()}catch(G){if(G.code!=="ENOENT")throw G}}return!0}async function m(){if(Y)await a(d(H));try{return await B0(),!0}catch(N){let B=N.code;if(await G0(N))return!1;if(B==="ENOENT"){if(Y)await a(d(H));else await V0(d(H),{recursive:!0});try{return await B0(),!0}catch(G){if(await G0(G))return!1;throw G}}throw N}}async function w(){await new Promise((N)=>setTimeout(N,Math.floor(Math.random()*4)))}async function v(N=!0){if(N&&z.onStep)await z.onStep("lock-read-ready");let B;try{B=await F()}catch(K){if(Y&&K.code!=="ENOENT")throw K}let G=Number(B?.expiresAt);if(Number.isFinite(G)&&G>W())return{status:"live"};if(typeof B?.ownerId==="string"&&Number.isFinite(G))return{status:"stale",identity:{kind:"owner",ownerId:B.ownerId,expiresAt:G}};try{let K=await M(H),Q=Number.isFinite(G)?G:K.mtimeMs+z.ttlMs;if(Q>W())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:K.dev,ino:K.ino,mtimeMs:K.mtimeMs,expiresAt:Q}}}catch(K){if(K.code==="ENOENT"){if(z.onStep)await z.onStep("lock-missing");return{status:"missing"}}throw K}}function H0(N,B){if(B.status!=="stale")return!1;let G=B.identity;if(N.kind==="owner"&&G.kind==="owner")return N.ownerId===G.ownerId&&N.expiresAt===G.expiresAt;return N.kind==="stat"&&G.kind==="stat"&&N.dev===G.dev&&N.ino===G.ino&&N.mtimeMs===G.mtimeMs&&N.expiresAt===G.expiresAt}async function x(){try{return JSON.parse(await f(q,Y))?.ownerId===z0}catch(N){if(Y&&N.code!=="ENOENT")throw N;return!1}}async function h(N){if(Y)await C0(N,"remove",()=>L(N,{recursive:!0,force:!0}));else await L(N,{recursive:!0,force:!0}).catch(()=>{})}function g(N,B){if(!Y||!(N instanceof C)||N.stage!=="remove"||N.path!==B)return!1;return O(N)||N.win32Code===void 0&&N.reason===void 0&&(N.code==="EBUSY"||N.code==="EPERM")}async function p(N,B,G=performance.now()+u+1000){let K,Q=5;while(await B()){try{await h(N);return}catch(I){if(!g(I,N))throw I;K??=I}let J=G-performance.now();if(J<=0)throw K;if(await new Promise((I)=>setTimeout(I,Math.min(Q,J))),performance.now()>=G)throw K;Q=Math.min(Q*2,50)}}async function c(N){let B;await p(U,async()=>{if(!Y)return x();let G=await T(U).catch((K)=>{if(K.code!=="ENOENT")throw K;return});if(!G||B&&!s(B,G))return!1;if(await x())return B=G,!0;if(!B)return!1;try{return await M(q),!1}catch(K){if(K.code!=="ENOENT")throw K;return!0}},N)}async function R0(N,B){if(!N)return!1;let G=!1;try{await p(U,async()=>{G=!1;let K=await T(U).catch(()=>{return});if(!K||!s(N,K))return!1;G=!0;try{return await M(q),!1}catch(Q){return Q.code==="ENOENT"}},B)}catch{}return G}async function K0(N){if(Y)await S0(U);else await V0(U);let B;try{let G=await T(U);B={dev:G.dev,ino:G.ino,birthtimeMs:G.birthtimeMs}}catch{B=void 0}try{await q0?.beforeOwnerWrite?.(U,q);let G=await q0?.failOwnerWrite?.(U,q);if(G!==void 0)throw G;let K=`${JSON.stringify({ownerId:z0,createdAt:W()})}
5
- `;if(Y)await i(q,K);else await j0(q,K)}catch(G){let K=await R0(B,N);if(E0(G)&&!K)return!1;try{await c(N)}catch{}throw G}if(z.onStep)await z.onStep("eviction-marker-acquired");return!0}async function Q0(N){let B;try{B=await M(U)}catch(Q){if(Q.code==="ENOENT")return"missing";throw Q}if(Y)try{await A(U,"directory",!0)}catch(Q){if(Q.code==="ENOENT")return"missing";throw Q}if(B.mtimeMs+u>W()){let Q=!0;try{await M(q)}catch(J){if(J.code==="ENOENT")Q=!1;else return"fresh"}if(Q)return"fresh";if(B.mtimeMs+y0>W())return"fresh"}if(z.onStep)await z.onStep("stale-marker-stat");let G=`${U}.${E()}`;try{await x0(U,G)}catch(Q){if(Q.code==="ENOENT")return"missing";throw Q}if(z.onStep)await z.onStep("stale-marker-claimed");let K=Y?await T(G):void 0;return await p(G,async()=>{if(!K)return!0;let Q=await T(G).catch((J)=>{if(J.code!=="ENOENT")throw J;return});return!!Q&&s(K,Q)},N),"recovered"}async function Y0(N,B){try{if(!await K0(B))return!1}catch(Q){if(Q.code==="EEXIST"){if(Y)try{await A(U,"directory",!0),await f(q,!0)}catch(J){if(J.code!=="ENOENT")throw J}return!1}throw Q}let G=!1,K;try{await N()}catch(Q){G=!0,K=Q}try{await c(B)}catch(Q){if(g(K,H)&&g(Q,U))throw K;throw Q}if(G)throw K;return!0}async function Z0(){for(let N=0;N<N0;N++){if(z.onStep)await z.onStep("relinquish-read");let B;try{B=await F()}catch(G){if(Y)throw G;return}if(B?.ownerId!==Z)return;try{await L(H,{recursive:!0,force:!0});return}catch(G){if(Y)throw G;await w()}}}function $0(){if(!z.renew||X||D)return;let N=z.renewIntervalMs??Math.max(1000,Math.floor(z.ttlMs/3));if(_=g0(()=>{_=null;let B=(async()=>{let G=!X;try{if(!await Y0(async()=>{let Q=await F(),J=W();if(X||D){G=!1;return}if(Q?.ownerId!==Z){j("taken-over",Q),G=!1;return}if(!(Number(Q?.expiresAt)>J)){j("expired",Q),G=!1;return}if(z.onStep)await z.onStep("renewal-owner-confirmed");if(X||D){G=!1;return}if(!await x())return;if(z.onStep)await z.onStep("renewal-write-fenced");if(X||D){G=!1;return}if(!await x())return;if(z.onStep)await z.onStep("renewal-write-ready");if(X||D){G=!1;return}if(await T0(),z.onStep)await z.onStep("renewal-write-finished");if(!await x()){j("marker-lost"),G=!1,await Z0();return}})&&z.onStep)await z.onStep("renewal-marker-unavailable")}catch(K){if(Y&&K instanceof C)P=K,j("renewal-failed"),G=!1;try{let Q=await F();if(Q?.ownerId!==Z)j("taken-over",Q);else if(!(Number(Q?.expiresAt)>W()))j("expired",Q)}catch{j("renewal-failed")}}finally{if(z.onStep)try{await z.onStep("renewal-finished")}catch{}if(G&&!X&&!D)$0()}})();b=B,B.finally(()=>{if(b===B)b=null})},N),"unref"in _)_.unref();r("scheduled")}function J0(){try{let N=z.onContended?.();if(N&&(typeof N==="object"||typeof N==="function")&&"then"in N&&typeof N.then==="function")Promise.resolve(N).catch(()=>{})}catch{}return null}let S=await m();if(!S)for(let N=0;N<N0;N++){if(S=await m(),S)break;let B=await v();if(B.status==="live")return J0();if(B.status==="missing")continue;if(z.onStep)await z.onStep("stale-lock-observed");try{if(!await K0()){await w();continue}}catch(G){if(G.code!=="EEXIST")throw G;if(await Q0()==="fresh")return null;await w();continue}try{let G=await v();if(G.status==="live")return J0();if(!H0(B.identity,G))continue;if(!await x())return null;if(z.onStep)await z.onStep("stale-lock-confirmed");if(!await x())return null;let K=await v(!1);if(!H0(B.identity,K))continue;if(await h(H),!await x())return null;if(z.onStep)await z.onStep("stale-lock-removed");if(S=await m(),!S)return null;if(z.onStep)await z.onStep("stale-lock-recreated");if(!await x())return await Z0(),S=!1,null;break}finally{await c()}}if(!S)return null;return $0(),{ownerId:Z,whenLost:()=>f0,hasLost:()=>D!==void 0,assertOwned:async()=>{if(P)throw P;let N;try{let B=await F();if(N=B,!X&&!D&&B?.ownerId===Z&&Number(B?.expiresAt)>W())return;j(B?.ownerId!==Z?"taken-over":"expired",B)}catch(B){if(j("unreadable"),Y&&B instanceof C)throw B}throw new R({target:z.path,name:z.name,expectedOwnerId:Z,...typeof N?.ownerId==="string"?{observedOwnerId:N.ownerId}:{},...typeof N?.expiresAt==="number"?{observedExpiresAt:N.expiresAt}:{}})},release:async(N)=>{if(Y&&V)return;X=!0,e(),await b;let B=performance.now()+u+1000,G=5,K;for(;;){try{let J=!1;if(await Y0(async()=>{let W0;try{W0=await F()}catch(_0){if(Y&&_0.code==="ENOENT"){J=!0;return}throw _0}if(W0?.ownerId!==Z){J=!0;return}if(z.onStep)await z.onStep("release-owner-confirmed");if(!await x())return;await h(H),J=!0},B)){if(Y&&!J)throw new C(H,"release-not-confirmed",{code:"EIO"});V=J;return}if(N?.aborted)return;await Q0(B)}catch(J){if(!g(J,H)){if(Y)throw J;return}K??=J}let Q=B-performance.now();if(Q<=0)break;if(await new Promise((J)=>setTimeout(J,Math.min(G,Q))),Y&&performance.now()>=B)break;G=Math.min(G*2,50)}if(Y)throw K??new C(H,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{randomUUID as I0}from"node:crypto";import{mkdir as P0,open as k,rename as u0,rm as m0}from"node:fs/promises";import{dirname as n}from"node:path";class t extends Error{constructor(z){super("file or directory sync failed",{cause:z});this.name="AtomicSyncError"}}async function Nz(z,H,$={}){await w0(z,H,$)}async function w0(z,H,$,Z){if(Y)return y(z,$.serialize?$.serialize(H):`${JSON.stringify(H,null,2)}
6
- `,{beforeRename:$.beforeRename,stagePath:`${z}.${($.stageName??I0)()}.tmp`,onRenamed:Z,durable:$.durable,durability:$.durability,onOutcome:$.onOutcome});await P0(n(z),{recursive:!0});let W=`${z}.${($.stageName??I0)()}.tmp`,_,X=!1;try{if(_=await k(W,"wx",384),X=!0,await _.writeFile($.serialize?$.serialize(H):`${JSON.stringify(H,null,2)}
7
- `,"utf8"),await _.chmod(384),$.durable)try{await _.sync()}catch(V){throw new t(V)}if(await _.close(),_=void 0,await $.beforeRename?.(),await u0(W,z),X=!1,Z?.(),$.durable){let V=await k(n(z),"r");try{await V.sync()}catch(D){throw new t(D)}finally{await V.close()}}}finally{if(await _?.close().catch(()=>{}),X)await m0(W,{force:!0}).catch(()=>{})}}async function Bz(z){if(Y){await A(z,"file");let Z=new C(z,"directory-sync-unsupported",{code:"ENOTSUP"});throw Z.published=!0,Z}let H=await k(z,"r");try{await H.sync()}finally{await H.close()}let $=await k(n(z),"r");try{await $.sync()}finally{await $.close()}}var Hz=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});
8
- export{t as Ie,Nz as Je,w0 as Ke,Bz as Le,X0 as Me,l as Ne,U0 as Oe,R as Pe,c0 as Qe,Hz as Re};