@cortexkit/opencode-openai-auth 1.13.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +9 -9
- package/dist/{codex-request-Bu2sjxQn.d.ts → codex-request-Cl6zEfsR.d.ts} +20 -3
- package/dist/{index-p8v28mh9.js → index-2f330s35.js} +2 -2
- package/dist/index-3mbw88h7.js +91 -0
- package/dist/{index-r8y79mzp.js → index-94b345dw.js} +1 -1
- package/dist/{index-khqwa7g2.js → index-999nwa9p.js} +20 -20
- package/dist/{index-tzrf3ax2.js → index-cxnrd85v.js} +1 -1
- package/dist/{index-cs0tey1r.js → index-gkye2xh1.js} +2 -2
- package/dist/{index-zmerz2yv.js → index-k5av4j8p.js} +2 -2
- package/dist/{index-rhe4jm5t.js → index-pc4vrrex.js} +2 -2
- package/dist/{index-4s50rsec.js → index-snq7bwr6.js} +2 -2
- package/dist/{index-th0bzvpn.js → index-wma2ggn9.js} +2 -2
- package/dist/{index-2g95z7kb.js → index-xk7f1aef.js} +21 -21
- package/dist/{index-2ccfywax.js → index-yygzbxjk.js} +1 -1
- package/dist/{index-0bh5fs56.js → index-z9cj13z7.js} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-2qht8n50.js → token-sgwxn4xg.js} +1 -1
- package/dist/token-util-8mrnmkge.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +7 -7
- package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +21 -15
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +81 -4
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +21 -15
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +81 -4
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/dist/index-7s8g79dd.js +0 -91
- package/dist/token-util-20g3fwxd.js +0 -1
package/dist/index-7s8g79dd.js
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import{Af as M3,tf as u,wf as w,xf as q3,yf as M$,zf as N3}from"./index-4s50rsec.js";import{Tf as o$,Uf as C,Wf as Y8,_f as P6}from"./index-rhe4jm5t.js";import{bg as s,cg as d0,fg as N4,hg as k3,ig as k$,mg as M4}from"./index-p8v28mh9.js";var P="all",X3=Object.freeze(["primary"]);function _Z($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function T0($,Z){return JSON.stringify([$,Z])}function t($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function A($){return typeof $==="number"&&Number.isFinite($)}function MZ($){return typeof $==="string"&&$.length>0}function E($,Z,z){return $[Z]===void 0||z($[Z])}function B8($){return A($)&&$>0}function z3($){return typeof $==="string"}function K8($){if(!t($)||!MZ($.scope)||!MZ($.label))return!1;switch($.kind){case"reading":return A($.checkedAt)&&A($.usedPercent)&&E($,"resetsAt",z3)&&E($,"windowMinutes",B8);case"retired":return A($.retiredAt);case"absent":return A($.checkedAt);default:return!1}}function H8($){if(!t($)||!A($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&E($,"remainingPercent",A)&&E($,"usedPercent",A)&&E($,"resetsAt",z3)&&E($,"limit",A)&&E($,"used",A)&&E($,"remaining",A)&&E($,"unit",z3)}function jZ($){return t($)&&A($.value)&&Number.isInteger($.value)&&$.value>=0&&A($.checkedAt)}function Y3($){return t($)&&Object.values($).every(jZ)}function W8($){return typeof $==="boolean"}function c($){return t($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&E($,"balance",A)&&E($,"overageLimitReached",W8)&&A($.checkedAt)}function J3($){if(!t($))return;let Z=Object.entries($).filter(([,z])=>jZ(z));return Z.length===0?void 0:Object.fromEntries(Z)}function W0($){if(H0($))return $;if(!t($))return;let{counters:Z,credits:z,...X}=$;if(!H0(X))return;let Y=J3(Z),G=c(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...G===void 0?{}:{credits:G}}}function H0($){if(!t($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let z of $.limits){if(!K8(z))return!1;let X=T0(z.scope,z.label);if(Z.has(X))return!1;Z.add(X)}return E($,"budget",H8)&&E($,"counters",Y3)&&E($,"credits",c)}var RZ=900000,SZ="no quota reading yet",TZ="no limits reported";function AZ($){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 EZ($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function G3($){if($.scope!==P||$.windowMinutes===void 0)return $.label;return EZ($.windowMinutes)}function B3($){return Math.min(100,Math.max(0,$))}function Q$($){return Math.round(B3($))}function OZ($){return`${Q$($)}% left`}function LZ($,Z,z){let X=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(X)&&X>z?{resetIn:AZ(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>Z&&X<=z}}function Q8($,Z){let z=$.windowMinutes,X=Z.windowMinutes;if(z!==void 0&&X!==void 0&&z!==X)return z-X;if(z===void 0!==(X===void 0))return z===void 0?1:-1;if($.scope!==Z.scope){if($.scope===P)return-1;if(Z.scope===P)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function U8($){let Z=CZ($.filter(({part:z,scope:X})=>z.kind==="window"&&X!==P).map(({scope:z})=>z));for(let z of $)z.part.short=z.part.kind==="budget"?"cr":z.scope===P?z.part.name:Z.get(z.scope)??z.scope;return $}function PZ($){return Number.isFinite($.remainingPercent)&&Number.isFinite($.checkedAt)}function K3($,Z,z=!1){if(!$)return{windows:[]};let{now:X}=Z,G=$.limits.filter((K)=>K.kind==="reading"&&(z||PZ(K))).sort(Q8).map((K)=>{let Q=PZ(K)?{kind:"window",reading:"known",name:G3(K),short:"",figure:OZ(K.remainingPercent),remainingPercent:B3(K.remainingPercent),checkedAt:K.checkedAt,...LZ(K.resetsAt,K.checkedAt,X)}:{kind:"window",reading:"unknown",name:G3(K),short:"",figure:"no reading",resetSinceReading:!1};return{scope:K.scope,...K.windowMinutes===void 0?{}:{windowMinutes:K.windowMinutes},part:Q}}),J=$.budget;if(J){let K=J.remainingPercent,Q=J.reached?"credits spent":K!==void 0?`credits ${OZ(K)}`:"credits available";G.push({scope:P,spent:J.reached,part:{kind:"budget",reading:"known",name:"credits",short:"",figure:Q,...K===void 0?{}:{remainingPercent:B3(K)},checkedAt:J.checkedAt,...LZ(J.resetsAt,J.checkedAt,X)}})}U8(G);let B=G.flatMap(({part:K})=>K.reading==="known"&&K.checkedAt!==void 0?[K.checkedAt]:[]);if(B.length>0){let K=X-Math.min(...B);if(K>(Z.staleAfterMs??RZ))return{windows:G,age:`checked ${AZ(K)} ago`}}return{windows:G}}function D8($,Z){return K3($,Z).age!==void 0}function xZ($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function CZ($){let Z=[...new Set($.map(xZ))],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 K=z.get(B)??2;if(K<B.length)z.set(B,K+1),G=!0}}if(!G)break}return new Map($.map((Y)=>[Y,X(xZ(Y))]))}var V8=2;function F8($){let Z=$.map((X)=>X.label.trim()||X.scope),z=CZ(Z);return Z.map((X)=>z.get(X)??X)}function q8($,Z){if(!$||$.length===0)return;let z=Z.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===P))return;let X=$.flatMap((B,K)=>{let H=z.filter(({scope:W})=>W===B.scope).reduce((W,F)=>W===void 0||(F.part.remainingPercent??0)<(W.part.remainingPercent??0)?F:W,void 0);return H?[{group:B,listed:K,window:H}]:[]});if(X.length===0)return;let Y=F8($),G=(B)=>B.window.part.remainingPercent??0,J=[...X].sort((B,K)=>G(B)-G(K)||B.listed-K.listed).slice(0,V8).sort((B,K)=>B.listed-K.listed);return J.map((B,K)=>{let{windowMinutes:Q}=B.window,H=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[EZ(Q)],`${Q$(G(B))}%`].join(" ");return K===J.length-1?`${H} left`:H})}function N8($,Z){let{windows:z}=K3($,Z),X=q8($?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:F})=>W.kind==="window"&&F===P),G=z.filter(({part:W,scope:F})=>W.kind==="window"&&F!==P),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,F)=>W===void 0||F.remaining<W.remaining?F:W,void 0),H=Y.map(({part:W})=>`${W.name} ${Q$(W.remainingPercent??0)}%`);if(Q)H.push(`${Q.label} ${Q$(Q.remaining)}%`);if(H.length===0)return z.map(({part:W})=>W.figure);return H.map((W,F)=>F===H.length-1?`${W} left`:W)}function IZ($,Z){if(Z.form==="narrow")return N8($,Z);let{windows:z,age:X}=K3($,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 M8($,Z){let z=IZ($,Z);if(z.length>0)return z.join(" · ");return $&&$.limits.length>0?TZ:SZ}function _8($){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 j8($){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 O8($,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 L8($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function y($,Z=P){let z=new Map;for(let H of $?.limits??[]){if(H.scope!==Z&&H.scope!==P)continue;let W=z.get(H.label);if(W===void 0){z.set(H.label,H);continue}let F=H.scope===P?W:H,D=H.scope===P?H:W;z.set(H.label,F.kind==="reading"?F:D)}let X=[...z.values()].map(j8).sort(O8),Y=X.filter((H)=>H.kind==="reading"),G=Y.length>0?Y:X,J=G.length>0?Math.min(...G.map((H)=>H.checkedAt)):void 0,B=$?.budget?.kind==="reading"?L8($.budget):void 0,K=J3($?.counters),Q=c($?.credits)?$.credits:void 0;return{scope:Z,limits:X,...J===void 0?{}:{checkedAt:J},...B===void 0?{}:{budget:B},...K===void 0?{}:{counters:K},...Q===void 0?{}:{credits:Q}}}function Q0($,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 U$($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function v0($,Z){if(typeof $.resetsAt!=="string")return;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z>Z?z:void 0}class D$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function F$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V$($){return typeof $==="number"&&Number.isFinite($)}function kZ($){return $===void 0||typeof $==="string"&&$!==""}function fZ($){return typeof $==="string"&&$!==""}function g0($,Z){return $[Z]===void 0||V$($[Z])}function H3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function P8($){return F$($)&&kZ($.scope)&&fZ($.label)&&V$($.usedPercent)&&H3($,"resetsAt")&&($.windowMinutes===void 0||V$($.windowMinutes)&&$.windowMinutes>0)}function x8($){return F$($)&&kZ($.scope)&&fZ($.label)}function R8($){if(!F$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&g0($,"remainingPercent")&&g0($,"usedPercent")&&H3($,"resetsAt")&&g0($,"limit")&&g0($,"used")&&g0($,"remaining")&&H3($,"unit")}function A0($){if(!F$($)||!V$($.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(!P8(Y))return!1;let G=T0(Y.scope??P,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(x8))return!1;return($.budget===void 0||R8($.budget))&&($.counters===void 0||Y3($.counters))&&($.credits===void 0||c($.credits))}function S8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function T8($,Z,z){if(Z===void 0)return $;if($!==void 0&&z<$.checkedAt)return $;return{...Z,checkedAt:z}}function A8($,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 E8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function p0($,Z){let z=$===void 0?void 0:W0($);if($!==void 0&&z===void 0)throw new D$("stored quota map is malformed");if(!A0(Z))throw new D$("quota observation is malformed");let X=z??{limits:[]},Y=Z.checkedAt,G=new Map;for(let M of X.limits)G.set(T0(M.scope,M.label),M);let J=(M)=>{let L=G.get(M);return L===void 0||Y>=_Z(L)},B=new Set;for(let M of Z.readings??[]){let L=M.scope??P,R=T0(L,M.label);if(B.add(R),!J(R))continue;G.set(R,{scope:L,label:M.label,kind:"reading",checkedAt:Y,usedPercent:M.usedPercent,...M.resetsAt===void 0?{}:{resetsAt:M.resetsAt},...M.windowMinutes===void 0?{}:{windowMinutes:M.windowMinutes}})}for(let M of Z.coverage??[]){let L=M.scope??P,R=T0(L,M.label);if(B.has(R)||!J(R))continue;let f=G.get(R);G.set(R,f===void 0||f.kind==="absent"?{scope:L,label:M.label,kind:"absent",checkedAt:Y}:{scope:L,label:M.label,kind:"retired",retiredAt:Y})}let{limits:K,budget:Q,counters:H,credits:W,...F}=X,D=T8(X.budget,Z.budget,Y),U=A8(X.counters,Z.counters),_=E8(X.credits,Z.credits);return{...F,limits:[...G.values()].sort(S8),...D===void 0?{}:{budget:D},...U===void 0?{}:{counters:U},..._===void 0?{}:{credits:_}}}var C8=Object.freeze({validate:H0,decode:W0,merge:p0});function bZ($,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 I8($,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(U$);for(let J of G)if(v0(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=v0(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 g($){let Z=$.scope??P,z=$.requiredLabels??X3,X=[],Y=[],G=[],J=new Set;for(let D of $.rows){let U=bZ(D.id,$,$.now);if(U){X.push(U);continue}if(D.kind==="api-key"){G.push({id:D.id,kind:D.kind});continue}let _=y(D.quota,Z),M=$.liftedWindows?.get(D.id)??[];if(_.limits.some((R)=>U$(R)&&v0(R,$.now)===void 0&&M.some((f)=>f.scope===R.scope&&f.label===R.label)))J.add(D.id);let L=I8(D.id,_,z,$.now,M);if(L){Y.push(L);continue}G.push({id:D.id,kind:D.kind,projection:_})}let B=new Map(G.flatMap((D)=>{let U=Q0(D.projection,$.now);return U?[[D.id,U]]:[]})),K=B.size>0&&B.size===G.length,Q=[];for(let D of G){let U=B.get(D.id);if(U===void 0)Q.push(D);else if(K)Q.push({...D,lastPath:!0});else Y.push({id:D.id,stage:2,reason:"budget-spent",...U})}let H=new Map($.rows.map((D,U)=>[D.id,U])),W=(D,U)=>(H.get(D.id)??0)-(H.get(U.id)??0);Y.sort(W);for(let D of Y)if("pullRequested"in D)J.add(D.id);let F=$.rows.filter((D)=>J.has(D.id)).map((D)=>D.id);for(let D of F)$.requestPull?.(D);return{admitted:Q,refused:Y,excluded:X,pulls:F}}var yZ="main";function k8($){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=yZ){if(Z==="roster"||!$.includes(z))return[...$];let X=$.filter((Y)=>Y!==z);return Z==="main-first"?[z,...X]:[...X,z]}function W3($){let Z=g($),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 f8($,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 Q3($,Z,z){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof z==="string"&&$.wireIdentity!==z)}function b8($,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 l0=900000,hZ=0.016666666666666666,U3=0.000001;function N$($,Z){for(let z of[$?.checkedAt,Z])if(typeof z==="number"&&Number.isFinite(z))return z;return}function mZ($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function vZ($){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 V3($){let Z=($.classifyStatus??mZ)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let z=N$($.quota,$.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||$.now-z>l0)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of vZ($.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=Q0($.quota,$.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:Z}}function D3($,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,hZ);return X/G}function wZ($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function y8($,Z){if(!$.quota)return;let z=N$($.quota,$.quotaCheckedAt);if(z===void 0||Z-z>l0)return;let X=vZ($.quota).map((J)=>D3({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(D3({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 gZ($){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)=>y8(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,U3),K=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,U3);return B-K||G.candidate.configuredOrder-J.candidate.configuredOrder||wZ(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||wZ(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:N$(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function F3($){let Z=g($),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&&Q3($.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,K=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??{}},H=$.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),L=$.resetCreditsApplicable?.get(U.id);return{accountId:U.id,quota:U.kind==="api-key"?void 0:z.get(U.id)?.projection??y(U.quota,H),reservePercent:Q(U),configuredOrder:_,...L===void 0?{}:{resetCreditsApplicable:L},...M===void 0?{}:{killswitchPasses:M}}}),F=[],D=J?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let U=gZ({candidates:W,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!U)break;let _=X.get(U.accountId);if(_){F.push(_),W=W.filter((L)=>L.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&&!K?{action:"retain"}:{action:"assign",pin:{accountId:U.accountId,inputBytes:$.requestBytes,...M===void 0?{}:{wireIdentity:M},...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt}}},refusedSelections:F,admission:Z}}return{outcome:"no-admissible-account",pin:D,refusedSelections:F,admission:Z}}import{createHash as w8}from"node:crypto";var h8=86400000,m8=300000,v8=3600000,g8=60000,p8=900000,l8=300000;function _3($){return $ instanceof Error?$.message:String($)}function d8($){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 j3($){let Z=_3($),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 pZ($){return w8("sha256").update($).digest("hex")}function lZ($){let Z=pZ($.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(d8($.error))Y=Math.min(v8,m8*2**Math.min(X-1,6));else Y=h8;return{message:_3($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:X,tokenHash:Z}}function U0($,Z,z){if(!$?.nextRetryAt||$.nextRetryAt<=z)return!1;if(!Z)return!0;return $.tokenHash===pZ(Z)}function _$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function c0($){let z=($.previous?.retryCount??0)+1,X,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(j3($.error))X=Math.min(p8,g8*2**Math.min(z-1,6));else X=l8;return{message:_3($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function E0($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function O3($){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 dZ}from"node:http";import{setTimeout as c8}from"node:timers/promises";var P$="app_EMoamEEZ73f0CkXaXp7hrann",F0="https://auth.openai.com",i0=1455,u8=3000,i8="cortexkit-opencode-openai-auth";function sZ($){return`${i8}/${$}`}var aZ="main",s8=`"${aZ}" is a reserved account id; choose a different label.`;function nZ($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function a8(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=nZ(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function cZ($){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 uZ($){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 O$($){if($.id_token){let Z=cZ($.id_token),z=Z&&uZ(Z);if(z)return z}if($.access_token){let Z=cZ($.access_token);return Z?uZ(Z):void 0}return}function n8($){return typeof $==="string"&&$.toLowerCase()===aZ}function L3($){if(n8($))throw Error(s8);return $}function o8($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:P$,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`${F0}/oauth/authorize?${X.toString()}`}async function r8($,Z,z){let X=await fetch(`${F0}/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:P$,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function t8($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var e8=`<!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>`,j$=($)=>`<!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">${t8($)}</div>
|
|
85
|
-
</div>
|
|
86
|
-
</body>
|
|
87
|
-
</html>`,L$=[],u0,i=new Map;function iZ($,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(i0,Z)})}function oZ($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function D0(){return i.size}function q0($){if(i.delete($),D0()===0)V0()}async function $9(){let $=`http://localhost:${i0}/auth/callback`;if(L$.length>0)return{port:i0,redirectUri:$};if(u0)return u0;u0=(async()=>{let Z=(G,J)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${i0}`);if(B.pathname==="/auth/callback"){let K=B.searchParams.get("code"),Q=B.searchParams.get("state"),H=B.searchParams.get("error"),W=B.searchParams.get("error_description");if(H){let D=W||H;if(Q){let U=i.get(Q);if(U)U.reject(Error(D)),q0(Q);else if(D0()===0)V0()}else if(D0()===0)V0();J.writeHead(200,{"Content-Type":"text/html"}),J.end(j$(D));return}if(!Q){if(D0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(j$("Missing state parameter"));return}if(!K){if(D0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(j$("Missing authorization code"));return}let F=i.get(Q);if(!F){if(D0()===0)V0();J.writeHead(400,{"Content-Type":"text/html"}),J.end(j$("Unknown state — authorization may have expired"));return}q0(Q),r8(K,$,F.pkce).then((D)=>F.resolve(D)).catch((D)=>F.reject(D)),J.writeHead(200,{"Content-Type":"text/html"}),J.end(e8);return}if(B.pathname==="/cancel"){let K=B.searchParams.get("state"),Q=K?[K]:[...i.keys()];J.writeHead(200),J.end("Login cancelled");for(let H of Q){let W=i.get(H);if(!W)continue;W.reject(Error("Login cancelled")),q0(H)}if(D0()===0)V0();return}J.writeHead(404),J.end("Not found")},z=dZ(Z);await iZ(z,"127.0.0.1");let X=[z],Y=dZ(Z);try{await iZ(Y,"::1"),X.push(Y)}catch(G){let J=G.code;if(J!=="EADDRNOTAVAIL"&&J!=="EAFNOSUPPORT")throw oZ(z),G}return L$=X,{port:i0,redirectUri:$}})();try{return await u0}finally{u0=void 0}}function V0(){let $=L$;L$=[];for(let Z of $)oZ(Z)}function Z9($,Z,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){q0(Z),G(Error("Login cancelled"));return}let J=setTimeout(()=>{if(i.get(Z))q0(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(J),i.get(Z))q0(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);i.set(Z,{pkce:$,state:Z,resolve:(K)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);Y(K)},reject:(K)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);G(K)}})})}async function z9($){let Z=await fetch(`${F0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":sZ($)},body:JSON.stringify({client_id:P$})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${F0}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function X9($,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(`${F0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":sZ(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let H=await B.json(),W=await fetch(`${F0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:H.authorization_code,redirect_uri:`${F0}/deviceauth/callback`,client_id:P$,code_verifier:H.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 K=G-(Date.now()-J);if(K<=0)throw Error("Device authorization expired");let Q=Math.min(X+u8,K);try{await c8(Q,void 0,{signal:z})}catch(H){if(H instanceof Error&&H.name==="AbortError")throw Error("Device authorization cancelled");throw H}}}async function C7($){let{label:Z,headless:z=!1,signal:X,version:Y}=$;if(L3(Z),z){let{deviceData:H,url:W,instructions:F}=await z9(Y),D=(async()=>{let U=await X9(H,Y,X),_=Date.now(),M=O$(U);return{id:L3(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:F,completion:D}}let{redirectUri:G}=await $9(),J=await a8(),B=nZ(crypto.getRandomValues(new Uint8Array(32)).buffer),K=o8(G,J,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let H=await Z9(J,B,void 0,X),W=Date.now(),F=O$(H);return{id:L3(Z||F||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:H.access_token,refresh:H.refresh_token,expires:W+(H.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:F}}finally{q0(B)}})();return{url:K,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function x$($){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 P3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function rZ($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function tZ($,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=P3($.get(`${Y}-window-minutes`)),J=x$($.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 z4=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function X4($,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 k7($){if(z4.some((G)=>X4($,G)==="invalid"))return{};let Z={},z=tZ($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=tZ($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;let Y=Y9($);if(Y)Z.credits=Y;return Z}function eZ($,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 Y9($){let Z=eZ($,"x-codex-credits-has-credits"),z=eZ($,"x-codex-credits-unlimited");if(Z===void 0||z===void 0)return;let X=e($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:z,...X!==void 0?{balance:X}:{},checkedAt:Date.now()}}function f7($){let Z=z4.map((z)=>X4($,z));return Z.includes("valid")&&!Z.includes("invalid")}function $4($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=P3($.window_minutes),z=x$($.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 b7($){let Z={},z=$4($.rate_limits?.primary);if(z)Z.primary=z;let X=$4($.rate_limits?.secondary);if(X)Z.secondary=X;let Y=J9($.credits);if(Y)Z.credits=Y;return Z}function J9($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let z=e(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 e($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function Z4($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=P3($.limit_window_seconds),z=x$($.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 Y4($){let Z={},z=Z4($.rate_limit?.primary_window);if(z)Z.primary=z;let X=Z4($.rate_limit?.secondary_window);if(X)Z.secondary=X;let Y=rZ($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let G=rZ($.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 K=e(J.limit),Q=e(J.used),H=e(J.remaining),W=e(J.used_percent),F=e(J.remaining_percent);if(K!==void 0&&Q!==void 0&&H!==void 0&&W!==void 0&&F!==void 0)Z.spendControl={limit:K,used:Q,remaining:H,usedPercent:W,remainingPercent:F,resetsAt:x$(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 K=e(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...K!==void 0?{balance:K}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as L1}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as G9}from"@cortexkit/claustrum-client";import{SocketClosedError as B9,SocketTimeoutError as K9,SubcCallError as H9}from"@cortexkit/subc-client";class V extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var x3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",route_busy:"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 x extends V{reason;constructor($){super("unavailable","Claustrum scoped operation unavailable");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function p($){if($ instanceof x||$ instanceof B9||$ instanceof K9)return"unreachable";let Z=$ instanceof G9||$ instanceof H9?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(x3,Z))return"answered";return x3[Z]}import{resolve as J4}from"node:path";import{storeIdentity as W9}from"@cortexkit/claustrum-client";import{SubcClient as G4}from"@cortexkit/subc-client";var C0=300000,R$=300000,R3=1000;class s0{#$;#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 S${#$;#Z;#B;#G=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#B}request(){if(this.#B)return this.#G=!0,this.#B;return this.#B=(async()=>{do{this.#G=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#G)})().finally(()=>{this.#B=void 0}),this.#B}}class T${#$;#Z=new s0;#B;#G="polling";#X;#K;#Y=!1;#z;#D=!1;#J=0;constructor($){this.#$=$,this.#B=new S$(async()=>{let Z=this.#D;if(this.#D=!1,Z||this.#z!==this.#$.view())await this.#$.discover(this.#z??"")},(Z)=>{if(!this.#Y)this.#$.onError?.(Z)})}get mode(){return this.#G}start(){if(this.#Y||this.#X||this.#K)return;if(typeof this.#$.client.watchScoped!=="function"){this.#H("fallback","client-without-watch");return}this.#F(!1)}stop(){if(this.#Y)return;if(this.#Y=!0,this.#K)(this.#$.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#X;this.#X=void 0,$?.handle.stop()}#H($,Z){if(this.#G===$)return;this.#G=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#K=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,!this.#Y)Z()},$),this.#K.unref?.()}async#F($){let Z;try{Z=await this.#$.enrollmentToken()}catch(J){if(this.#Y)return;this.#$.onError?.(J),this.#q("token-unreadable");return}let z=this.#$.client.watchScoped;if(this.#Y||this.#X||!z)return;this.#Z.restart(),this.#D=$;let X,Y;try{Y=z.call(this.#$.client,(J)=>{if(this.#Y||!X||this.#X!==X)return;if(X.notices++,X.notices===1)this.#$.onReachable?.(),X.acceptedAt=(this.#$.now??Date.now)(),this.#H("watching","accepted");if(!this.#Z.continuous(J))this.#D=!0;this.#z=J.view,this.#B.request()},{enrollmentToken:Z})}catch(J){this.#$.onError?.(J),this.#q("watch-failed");return}X={handle:Y,notices:0},this.#X=X,this.#H("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.#Y||this.#X!==$)return;if(this.#X=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#H("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#q("refused");try{this.#$.onRefused(Z.error)}catch(z){this.#$.onError?.(z)}return}if($.notices>0){let z=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&z-$.acceptedAt>=300000)this.#J=0;let X=Math.min(1000*2**Math.min(this.#J,16),300000);this.#J++,this.#H("polling","resubscribing"),this.#U(X,()=>void this.#F(!0));return}this.#q(Z.kind)}#q($){this.#H("fallback",$),this.#U(300000,()=>void this.#F(!1))}}function K4($){let Z=$.identity??W9($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((B,K)=>{Y=setTimeout(()=>K(Error("insula usage timeout")),3000),Y.unref?.()}),J=(async()=>{if(z=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await G4.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,K=new Promise((H,W)=>{B=setTimeout(()=>W(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),Q=(async()=>{let H=Math.min($.handshakeTimeoutMs??3000,3000),W=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:H}):await G4.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:H});if(X=W,G){W.close();return}let F=await W.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){W.close();return}Y=W.subscribe(F,{method:"usage.watch"},z)})();try{await Promise.race([Q,K])}catch(H){throw G=!0,H}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 E$=60000,B4=4*E$,Q9=2*E$,S3=new Map,A$=new Map;function I0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U9($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!I0(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 D9($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class H4{transport;key;#$=[];#Z=!1;#B=new Set;#G=new Map;#X=new S$(async()=>{try{let $=await this.transport.getUsage();if(!I0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>I0(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.#G.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#B.clear()}},()=>{});#K=new s0;#Y="polling";#z=0;#D=0;#J=new Map;#H;#U;#F={};#Q=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#X.running)return this.#X.running;if(this.#Y==="watching")return Promise.resolve();for(let[z,X]of A$)if($-X>=E$)A$.delete(z);let Z=A$.get(this.key);if(Z!==void 0&&$-Z<E$)return Promise.resolve();return A$.set(this.key,$),this.#X.request()}watchMode(){return this.#Y}watch($={}){this.#z++;let Z=$.provider;if(Z===void 0)this.#D++;else this.#J.set(Z,(this.#J.get(Z)??0)+1);if(this.#z===1)this.#F=$,this.#R();let z=!1;return()=>{if(z)return;if(z=!0,Z===void 0)this.#D--;else{let X=(this.#J.get(Z)??1)-1;if(X>0)this.#J.set(Z,X);else this.#J.delete(Z)}if(--this.#z===0)this.#q()}}#q(){if(this.#U)(this.#F.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#H;this.#H=void 0,$?.handle?.stop(),this.#Y="polling"}#M($){this.#U=(this.#F.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#z>0&&!this.#H)this.#R()},$),this.#U.unref?.()}#R(){let $=this.transport.watchUsage;if(!$){this.#Y="fallback";return}this.#Y="polling",this.#K.restart();let Z={notices:0};this.#H=Z;let z;try{z=$.call(this.transport,(X)=>this.#O(Z,X))}catch(X){this.#L(Z,X);return}Z.handle=z,z.closed.then(()=>this.#L(Z,void 0),(X)=>this.#L(Z,X))}#O($,Z){if(this.#H!==$)return;if($.notices++,$.notices===1)this.#Y="watching";if($.notices===2)this.#Q=0;let z=U9(Z);if(!z)this.#K.restart();if(!(z?this.#K.continuous(z):!1)||z?.provider===void 0||this.#D>0||this.#J.has(z.provider))this.#X.request()}#L($,Z){if(this.#H!==$)return;this.#H=void 0;let z=D9(Z);if(z==="unknown_method"||z==="usage_watch_limit"){this.#Y="fallback";return}if($.notices>0){let X=Math.min(R3*2**Math.min(this.#Q,16),R$);this.#Q++,this.#Y="polling",this.#M(X);return}if(this.#Y="fallback",this.#X.request(),Z===void 0||p(Z)==="unreachable")this.#M(R$)}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||!I0(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=B4)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(!I0(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&&(!I0(X.stale)||X.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:B};return z>=J+B4||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#B.has($))return{miss:"absent"};let G=this.#G.get($)??z;return this.#G.set($,G),{miss:z-G>=Q9?"unreachable":"cold"}}}function T3($,Z){let z=JSON.stringify([J4($.connectionFile),J4(Z)]),X=S3.get(z);if(!X)X={source:new H4($,z),refs:0},S3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)S3.delete(z)}}}import{ClaustrumCredentialError as wz}from"@cortexkit/claustrum-client";function N0($){let Z=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:B,listener:K}of z)B.removeEventListener("abort",K);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 K=()=>G(B.reason);if(z.push({source:B,listener:K}),B.addEventListener("abort",K,{once:!0}),B.aborted)G(B.reason)}return{signal:Z.signal,dispose:Y}}import{channel as d9}from"node:diagnostics_channel";import{ClaustrumCredentialError as p4}from"@cortexkit/claustrum-client";import{createHash as x9,randomBytes as R9,randomUUID as S9}from"node:crypto";import{constants as Q4}from"node:fs";import{chmod as T9,mkdir as A9,open as _4,readFile as C3,realpath as E9,rename as C9,stat as j4,unlink as f3}from"node:fs/promises";import{basename as O4,dirname as Z0,extname as U4,isAbsolute as D4,join as b3,resolve as I9}from"node:path";import{ClaustrumCredentialError as L4,ClaustrumClient as k9,writeEnrollmentTokenFile as f9}from"@cortexkit/claustrum-client";import{lstat as V9,stat as F9}from"node:fs/promises";import{resolve as q9}from"node:path";async function N9($,Z){try{let z=await(Z?F9($):V9($));return z.isFile()?z:void 0}catch(z){return z.code==="ENOENT"?"absent":void 0}}function M9($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class a0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks??!1}async read($,Z,z){let X=$.map((Q)=>q9(Q)),Y=JSON.stringify(X),G=await Promise.all(X.map((Q)=>N9(Q,this.#$))),J=G.every((Q)=>Q!==void 0)?G:void 0,B=this.#Z.get(Y);if(J&&B&&J.every((Q,H)=>{let W=B.identities[H];return W!==void 0&&M9(Q,W)}))return z?.(J),B.value;this.#Z.delete(Y);let K=await Z(X);if(J){if(this.#Z.size>=64){let Q=this.#Z.keys().next().value;if(Q!==void 0)this.#Z.delete(Q)}this.#Z.set(Y,{identities:J,value:K})}return K}}import{ClaustrumCredentialError as _9}from"@cortexkit/claustrum-client";var j9="Served by Thalamus",O9="This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.",W4=new WeakSet;function A3($){return W4.has($)}function S(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function E3($){if(typeof $!=="object"||$===null)return $;let Z=$;if(typeof Z.code==="string"&&(Z.class==="transient"||Z.class==="permanent"||Z.class==="auth_required"||Z.class==="context_overflow")&&(Z.action==="gone"||Z.action==="reauth"||Z.action==="retry"||Z.action==="reduce_and_retry"))return new _9(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&p(Object.assign(Error(),{code:Z.code}))==="unreachable")return new x(Z.reason==="host-accessor-missing"||Z.reason==="host-accessor-failed"?Z.reason:void 0);return $}function n0($){try{return $()}catch(Z){throw E3(Z)}}async function M0($){try{return await $()}catch(Z){throw E3(Z)}}function L9($){let Z=$.watchScoped?.bind($),z=$.reportUsageScoped?.bind($);return{listScoped:(...X)=>M0(()=>$.listScoped(...X)),getScoped:(...X)=>M0(()=>$.getScoped(...X)),reportAuthFailureScoped:(...X)=>M0(()=>$.reportAuthFailureScoped(...X)),close:()=>n0(()=>$.close()),...Z&&{watchScoped:(...X)=>{let Y=n0(()=>Z(...X));return{stop:()=>n0(()=>Y.stop()),closed:M0(async()=>{let G=await Y.closed;return G.kind==="refused"||G.kind==="transport_lost"?{...G,error:E3(G.error)}:G})}}},...z&&{reportUsageScoped:(...X)=>M0(()=>z(...X))},...$.insula&&{insula:P9($.insula)}}}function P9($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>M0(()=>$.getUsage()),...Z&&{watchUsage:(...z)=>{let X=n0(()=>Z(...z));return{stop:()=>n0(()=>X.stop()),closed:M0(()=>X.closed)}}}}}function _0($){if(!S()||!$)throw new x;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z==="function"){let z=L9(Z($));return W4.add(z),z}}catch{throw new x("host-accessor-failed")}throw new x("host-accessor-missing")}var b9=1,I$=16384,P4=30000,y3=/^[0-9a-f]{64}$/,x4="unknown_method",R4=new Set([x4,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),S4=new Set(["pending_queue_full"]);function I3($){if(!($ instanceof L4))return;if(R4.has($.code))return{code:$.code,disposition:"terminal"};if(S4.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function y9($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new V("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function T4($){let Z=Array.from($).length;return Z>=1&&Z<=40&&!/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test($)}function w9($){return k9.connect($)}function A4($){let Z=U4($)||".json",z=O4($,U4($));return{statePath:b3(Z0($),`${z}-state${Z}`),tokenPath:$}}function h9($){let Z=$.override?.trim();if(Z&&!D4(Z)&&!$.cwd)throw new V("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=Z?D4(Z)?Z:I9($.cwd,Z):b3($.stateDir,`${$.host}-enrollment.json`);return A4(z)}function E4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function C$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function C4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function o0(){return new V("invalid-state","invalid Claustrum enrollment state")}function f$($){if(!E4($)||$.version!==b9||typeof $.proposedName!=="string"||$.proposedName.length===0)throw o0();if($.phase==="pending"){if(!y3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!C$($.createdAt)||!C$($.updatedAt))throw o0();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)||!C4($.tokenGeneration)||!C$($.updatedAt))throw o0();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"||!C$($.updatedAt))throw o0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw o0()}function w3($){if(!E4($)||!y3.test(String($.token??""))||!C4($.token_generation))throw new V("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function I4($){if(!$.isFile())throw new V("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new V("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new V("unsafe-file","Claustrum enrollment file must be owned by the current user")}function V4($){try{return JSON.parse($)}catch{throw new V("invalid-state","Claustrum enrollment file is not valid JSON")}}async function z0($){if(s)try{await k3(Z0($));let z=await k$($,!0);if(Buffer.byteLength(z)>I$)throw new V("unsafe-file","Claustrum enrollment file is too large");return V4(z)}catch(z){if(z.code==="ENOENT")return;throw z}let Z;try{Z=await _4($,Q4.O_RDONLY|Q4.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new V("unsafe-file","Claustrum enrollment file could not be opened safely")}try{I4(await Z.stat());let z=Buffer.alloc(I$+1),{bytesRead:X}=await Z.read(z,0,z.byteLength,0);if(X>I$)throw new V("unsafe-file","Claustrum enrollment file is too large");return V4(z.subarray(0,X).toString("utf8"))}finally{await Z.close()}}function F4($,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 m9($,Z,z){try{let[X,Y]=await Promise.all([C3(z.passwdPath??"/etc/passwd","utf8"),C3(z.groupPath??"/etc/group","utf8")]),G=F4(X,7),J=F4(Y,4);if(!G||!J)return!1;let B=G.filter((W)=>Number(W[2])===$),K=J.filter((W)=>Number(W[2])===Z);if(B.length!==1||K.length!==1)return!1;let Q=B[0]?.[0],H=K[0]?.[3]??"";return(H===""||H.split(",").every((W)=>W===Q))&&!G.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function k4($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>C3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function f4($,Z={}){if(!s){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await E9($)}catch{return}let G;for(;;){let J=await j4(Y).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0){if(G===void 0)G=X!==void 0&&await m9(z,X,Z);if((J.mode&2)!==0||J.uid!==z||J.gid!==X||!G)throw new V("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=Z0(Y);if(B===Y)return;Y=B}}try{await N4($,k4(Z))}catch(z){if(!(z instanceof d0))throw z;throw new V("unsafe-file",`Claustrum enrollment parent refused: ${z.path} (${z.reason??z.code}). Use a folder that other users cannot write or replace.`)}}async function k0($,Z={},z="enrollment directory"){if(s){await k3($,!1,k4(Z));return}await A9($,{recursive:!0,mode:448});let X=await j4($),Y=process.geteuid?.();if(Y!==void 0&&X.uid!==Y)throw new V("unsafe-file",`Claustrum ${z} must be owned by the current user`);if((X.mode&63)!==0)await T9($,448)}async function j0($,Z,z={}){let X=Z0($);await k0(X,z),await f4(X,z);let Y=`${JSON.stringify(Z)}
|
|
89
|
-
`;if(Buffer.byteLength(Y)>I$)throw new V("invalid-state","Claustrum enrollment state is too large");if(s)return M4($,Y);let G=b3(X,`.${O4($)}.${process.pid}.${S9()}.tmp`),J,B=!1;try{J=await _4(G,"wx",384),B=!0,await J.writeFile(Y,"utf8"),await J.chmod(384),await J.sync(),await J.close(),J=void 0,await C9(G,$),B=!1}finally{if(await J?.close().catch(()=>{}),B)await f3(G).catch(()=>{})}}var v9=new a0;async function h3($,Z){let z=s?await q4($,Z):await v9.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,G=$.statePath])=>q4({tokenPath:Y,statePath:G},Z),(Y)=>{for(let G of Y)if(G!=="absent")I4(G)}),X={...z.status};if(z.usesProposedName&&X.state==="approved")X.proposedName=Z;return X}async function q4($,Z){let z=await z0($.tokenPath),X=z===void 0?void 0:w3(z),Y=await z0($.statePath),G=Y===void 0?void 0:f$(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:$0(G),usesProposedName:!1}}async function b4($,Z){let z;try{z=await h3($,Z)}catch(X){if(!(X instanceof V)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await z0($.statePath);if(Y===void 0)return"unreadable";let G=f$(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 g9($,Z){if(S())return"host";return b4($,Z)}async function X0($){let Z=await z0($);if(Z===void 0)throw new V("not-enrolled","Claustrum enrollment is not configured");return w3(Z)}function $0($){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 y4(){return new V("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class w4{#$;#Z;#B;#G;#X;#K;#Y;#z;constructor($){if($.displayName!==void 0&&!T4($.displayName))throw new V("invalid-state","invalid Claustrum enrollment display name");this.#z=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#B=$.proposedName,this.#G=$.displayName,this.#X=$.now??Date.now,this.#K=$.mintSecret??(()=>R9(32).toString("hex")),this.#Y=$.writeTokenFile??f9}async status(){return h3(this.#Z,this.#B)}async resetTerminal(){return h4(this.#Z,this.#B)}async#D($,Z){let z={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#X()};return await j0(this.#Z.statePath,z,this.#z),$0(z)}async reconcile(){await k0(Z0(this.#Z.statePath),this.#z);let $=await w({name:"ceremony",path:this.#Z.statePath,ttlMs:P4,renew:!0});if(!$)return{state:"busy"};try{let Z=await z0(this.#Z.tokenPath),z=Z===void 0?void 0:w3(Z),X=await z0(this.#Z.statePath),Y=X===void 0?void 0:f$(X);if(Y&&Y.proposedName!==this.#B)throw y4();if(z){if(!Y||Y.phase==="pending"){let J={version:1,phase:"approved",proposedName:Y?.proposedName??this.#B,tokenGeneration:z.token_generation,updatedAt:this.#X()};await j0(this.#Z.statePath,J,this.#z),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.#X()};return await j0(this.#Z.statePath,J,this.#z),$0(J)}if(Y&&Y.phase!=="pending")return $0(Y);if(!Y){let J=this.#X();if(Y={version:1,phase:"pending",proposedName:this.#B,requestSecret:this.#K(),createdAt:J,updatedAt:J},!y3.test(Y.requestSecret))throw new V("invalid-state","invalid minted Claustrum enrollment secret");await j0(this.#Z.statePath,Y,this.#z)}if(!Y.requestId)try{let J=x9("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B={name:Y.proposedName,requestSecretHash:J},K;try{K=await this.#$.enrollPropose({...B,...this.#G!==void 0&&{displayName:this.#G}})}catch(Q){if(this.#G===void 0||!(Q instanceof L4)||Q.code!=="invalid_params")throw Q;K=await this.#$.enrollPropose(B)}Y={...Y,requestId:K.requestId,updatedAt:this.#X()},await j0(this.#Z.statePath,Y,this.#z)}catch(J){let B=I3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};if(B.code===x4)return await $.assertOwned(),await f3(this.#Z.statePath).catch((K)=>{if(K.code!=="ENOENT")throw K}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#D(Y,B.code)}let G=Y.requestId;if(!G)return $0(Y);try{let J=await this.#$.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(J.status==="pending")return $0(Y);if(J.status==="denied"){let K={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#X()};return await j0(this.#Z.statePath,K,this.#z),$0(K)}await k0(Z0(this.#Z.tokenPath),this.#z),await f4(Z0(this.#Z.tokenPath),this.#z),await this.#Y(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.#X()};return await j0(this.#Z.statePath,B,this.#z),$0(B)}catch(J){let B=I3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:B.code};return this.#D(Y,B.code)}}finally{await $.release()}}}async function h4($,Z){await k0(Z0($.statePath));let z=await w({name:"ceremony",path:$.statePath,ttlMs:P4,renew:!0});if(!z)return"busy";try{if(await z0($.tokenPath)!==void 0)return"refused-approved";let X=await z0($.statePath);if(X===void 0)return"idle";let Y=f$(X);if(Y.proposedName!==Z)throw y4();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await f3($.statePath),"reset"}finally{await z.release()}}var r0="claustrum-tombstone:v1:";function b$($){return`${r0}${$}`}function m3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function y$($){return typeof $==="string"&&$.startsWith(r0)}function m4($,Z){if(!m3($)||$.type!=="oauth")return!1;return $.refresh===b$(Z)}function v4($,Z){if(m4($,Z))return"placeholder";if(m3($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!y$($.refresh))return"login";if(m3($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function p9($){let Z=v4($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new V("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 V("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function f0($,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 b0($,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 l9}from"@cortexkit/claustrum-client";function g4($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class v3{options;#$=new Map;#Z=new Map;#B=new Set;#G;#X;#K=!1;#Y=!1;#z=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#X!==void 0,dropped:this.#z}}report($,Z){if(this.#K||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#z++;return}if(!g4(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(!g4(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.#G&&!this.#X)this.#G=this.options.setTimeout(()=>{this.#G=void 0,this.#D()},1000),this.#G.unref?.()}catch{this.#z++}}forget($){if(this.#$.delete($))this.#z++;this.#Z.delete($)}#D(){if(this.#X||!this.#$.size||this.#Y)return this.#X;let $=Promise.resolve().then(async()=>{while(!this.#Y&&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.#Y||!this.options.owns(z)){if(!this.#Y)this.#z++;continue}await this.options.client.reportUsageScoped?.({credentialId:z,reading:X,enrollmentToken:Y})}catch(Y){if(!this.#Y)this.#z++;this.#J(Y)}}});return this.#X=$,$.finally(()=>{this.#X=void 0}),$}#J($){let Z="transport_error";try{if($ instanceof l9)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.#K=!0,this.#G)this.options.clearTimeout(this.#G);return this.#G=void 0,this.#D()}drop(){this.#Y=!0,this.#z+=this.#$.size+(this.#X?1:0),this.#X=void 0,this.#$.clear(),this.#Z.clear()}}function d4($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function c9($,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 p3=C("claustrum");function l4($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new V("invalid-token","Invalid Claustrum enrollment token");return $.token}var Y0=d9("common-auth.claustrum.phases");function d3($,Z,z,X=p3){let Y=d4(Z,z);return X.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:c9(Z,z)}),Y}var l3=300000,c4=60000;function g3(){return new V("invalid-material","Claustrum returned invalid credential material")}function u9($){let Z=$.trim();if(Z.startsWith("{")){let z;try{z=JSON.parse(Z)}catch{throw g3()}if(!z||typeof z!=="object")throw g3();let X=z,Y=X.access_token??X.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(r0))throw g3();return Z}function i9($,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=s9($),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 s9($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function a9($){let{grants:Z,grantTuples:z}=$;if(Z===void 0||z===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(z.map(({selectorKind:X,selector:Y,operation:G})=>Object.freeze({selectorKind:X,selector:Y,operation:G})))})}class y0{#$;#Z;#B;#G;#X;#K;#Y;#z=new WeakMap;#D=new WeakMap;#J=new Map;#H=new WeakMap;#U;#F=new Map;#Q;#q;#M=!1;#R=new x;#O;#L=!1;#W=-1/0;#N=2000;#S=!1;#V;#_=new Set;#P=new Set;#T;#I;#j;constructor($){if(S()&&$.client&&!A3($.client))throw new x;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>X0(Z);else if(S())this.#Z=async()=>{throw new V("not-enrolled","Claustrum enrollment token path is required")};else throw new V("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client??_0($.pluginId),this.#G=$.family,this.#X=$.parseIdentity,this.#K=$.requireAssertion??!1,this.#B=$.now??Date.now,this.#Y=$.logger??p3,this.#T=f0(this.#Y),this.#Q=$.setTimeoutImpl??setTimeout,this.#q=$.clearTimeoutImpl??clearTimeout;let z=()=>this.#$;this.#U=new v3({client:{get reportUsageScoped(){let X=z();return X.reportUsageScoped?.bind(X)}},owns:(X)=>this.#F.has(X),token:async()=>S()?"":l4(await this.#Z()),logger:this.#Y,setTimeout:this.#Q,clearTimeout:this.#q})}replaceClient($){if(this.#x(),$===this.#$)return;if(S()&&!A3($))throw new x;this.#$=$;for(let Z of this.#_)Z.restart()}transportLost($){if(this.#S||this.#M)return;this.#M=!0,this.#R=$ instanceof p4?$:new x($ instanceof x?$.reason:void 0),this.#Y.warn("serving kept vault receipt",{reason:"unreachable"}),this.#A()}reachable(){if(this.#S||!this.#M)return;if(this.#M=!1,this.#O)this.#q(this.#O);this.#O=void 0,this.#N=2000;for(let $ of this.#J.values())$.since=null;(this.#Y.info??p3.info)("vault receipt serving resumed",{reason:"reachable"})}#A(){if(this.#S||!this.#M||this.#O||this.#L)return;this.#O=this.#Q(()=>{this.#O=void 0,this.#C(!0)},this.#N),this.#O.unref?.()}#C($=!1){if(this.#S||!this.#M||this.#L)return;if(this.#B()-this.#W<1000){this.#A();return}this.#W=this.#B(),this.#L=!0,this.#f().catch(()=>{if($&&this.#M)this.#N=Math.min(this.#N*2,30000)}).finally(()=>{this.#L=!1,this.#A()})}#x($){if(this.#S)throw new V("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#x($),S())return"";if(Y0.hasSubscribers)Y0.publish({logger:this.#Y,phase:"token read begin"});let Z=this.#Z();this.#P.add(Z);let z;try{z=await Z}finally{if(this.#P.delete(Z),Y0.hasSubscribers)Y0.publish({logger:this.#Y,phase:"token read end"})}return this.#x($),l4(z)}async#k($,Z){this.#x(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.#x(Z),p(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof p4)throw Y;if(p(Y)==="unreachable")throw new x(Y instanceof x?Y.reason:void 0);throw new V("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#x(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(H){throw this.#J.clear(),this.#w(),H}if(Y0.hasSubscribers)Y0.publish({logger:this.#Y,phase:"list scoped begin"});try{Z=await this.#k(()=>this.#$.listScoped(z),$)}catch(H){throw this.listFailed(H),H}finally{if(Y0.hasSubscribers)Y0.publish({logger:this.#Y,phase:"list scoped end"})}let X=[],Y=[],G=0,J=[],B=new Map;for(let H of Z.rows){let W=i9(H,this.#G);if(W.kind==="not-mine"){G++;continue}if(W.kind==="refused"){Y.push({...H.id.trim()&&{credentialId:H.id},code:W.code});continue}J.push({row:H,type:W.type,...W.member!==void 0&&{member:W.member}}),B.set(H.id,(B.get(H.id)??0)+1)}let K=[];for(let{row:H,type:W,member:F}of J){let D;if(!H.id.trim())D="empty credential id";else if((B.get(H.id)??0)>1)D="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())D="blank account identity";else if(!H.state.trim())D="empty state";if(D){X.push({...H.id.trim()&&{credentialId:H.id},...F!==void 0&&{member:F},reason:D});continue}K.push(Object.freeze({credentialId:H.id,credentialType:W,...F!==void 0&&{member:F},...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of X)this.#Y.warn("skipped malformed vault record",H);let Q=a9(Z);return{view:Z.view,credentials:Object.freeze(K),skipped:Object.freeze(X),..."classify"in this.#G&&{refused:Object.freeze(Y),notMine:G},...Q&&{grantReach:Q}}}listFailed($){if(p($)==="unreachable")this.transportLost($);else this.reachable(),this.#J.clear(),this.#w()}forget($){this.#J.delete($),this.#F.delete($),this.#U.forget($)}#w(){for(let $ of this.#F.keys())this.#U.forget($);this.#F.clear()}retain($){let Z=new Map($.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#J){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}for(let[z,X]of this.#F){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.#J){if(!this.#b(z.attempt)){this.forget(Z);continue}if(z.since!==null)$=Math.min($??z.since,z.since)}return Object.freeze({active:$!==null,since:$})}#b($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#B()>c4}async authorize($,Z,z="vault"){this.#x(Z);let{credentialId:X,credentialType:Y,accountIdentity:G}=$,J=this.#J.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(K){throw this.#J.clear(),this.#w(),K}if(this.#M&&J)return this.#C(),this.#h(X,J,B,z);try{let K=await this.#E({credentialId:X,credentialType:Y,accountIdentity:G},B,Z);return this.#J.set(X,{attempt:K,routeId:z,since:null}),this.#F.set(X,{...$}),K}catch(K){if(this.#x(Z),p(K)!=="unreachable")throw this.forget(X),K;return this.#h(X,J,B,z,K)}}#h($,Z,z,X,Y=this.#R){if(!Z||this.#J.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,this.#z.get(Z.attempt)??{token:z}),this.#H.set(G,X),G}async#E($,Z,z){if(!$.credentialId)throw new V("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:G}=$;if(this.#K&&G===void 0)throw new V("identity-unasserted","Claustrum dispatch requires a known account identity");let J=await this.#k(()=>this.#$.getScoped({credentialId:X,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:l3}}),z);if(J.credentialId!==void 0&&J.credentialId!==X)throw new V("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()<l3))throw new V("insufficient-validity","Claustrum served credential has insufficient validity");let K=u9(J.material),Q=J.accountId?.trim()?J.accountId:void 0;if(this.#K&&(J.credentialId===void 0||Q===void 0))throw new V("identity-unasserted","Claustrum served credential did not assert its identity");let H=Q===void 0?this.#X?.(K):void 0,W=Q??H;if(G!==void 0&&W!==void 0&&W!==G)throw new V("identity-changed","Claustrum served credential identity changed");let F=W??G,U=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...F!==void 0&&{accountIdentity:F},accountIdentitySource:Q!==void 0?"asserted":H!==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:K,enumerable:!1}));return this.#z.set(U,{token:Z}),U}async reportFailure($,Z,z){if(Z!==401)return;this.#x();let X=this.#z.get($);if(!X)throw new V("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#H.get($);if(Y!==void 0){this.forget($.credentialId),this.#Y.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let G=this.#J.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let J=this.#D.get($);if(J)return J;let B=this.#k(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:X.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:z}));this.#D.set($,B);try{await B,this.#Y.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:z})}catch(K){throw this.#D.delete($),K}}watchRoster($){this.#x();let Z=$.view??(()=>this.#V),z,X,Y=(J=!1)=>{let B=new T$({client:this.#$,enrollmentToken:()=>this.#y(),view:()=>J?void 0:Z(),discover:async(K)=>{while(z)await z.catch(()=>{});if(X!==B)return;J=!1,z=Promise.resolve().then(()=>$.onView(K));try{await z}finally{z=void 0}},onRefused:(K)=>{this.listFailed(K),$.onRefused?.(K)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#Y,now:this.#B,setTimeoutImpl:this.#Q,clearTimeoutImpl:this.#q});return B};X=Y();let G={restart:()=>{let J=X.mode;if(X.stop(),X=Y(!0),J!==X.mode)$.onMode?.(X.mode);X.start()},stop:()=>X.stop()};return this.#_.add(G),X.start(),{get mode(){return X.mode},close:()=>{this.#_.delete(G),X.stop()}}}reportUsage($){if(this.#S)return;try{this.#U.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#U.state()}close(){if(this.#S)return;if(this.#S=!0,this.#O)this.#q(this.#O);this.#O=void 0;for(let Z of this.#_)Z.stop();this.#_.clear(),this.#J.clear();let $=this.#U.close();if($)this.#P.add($),$.then(()=>this.#P.delete($));else this.#$.close();this.#j=b0(this.#P,(Z)=>(this.#I??this.#T)(Z)).finally(()=>{if(this.#U.drop(),this.#F.clear(),$)this.#$.close()})}async dispose($=this.#T){this.#I=$,this.close(),await this.#j}}import{resolve as m$}from"node:path";var u4=30000,i4={now:()=>performance.now(),schedule($,Z){let z=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(z),unref:()=>z.unref?.()}}};function s4($,Z=""){let z=new Map,{observation:X}=$,Y=(B,K,Q)=>z.set(`${Z}:${B}`,{at:K,order:0,publication:{...$,observation:Q}}),G=(B,K)=>JSON.stringify([B??"all",K]),J=new Set;for(let B of X.readings??[]){let K=G(B.scope,B.label);J.add(K),Y(K,X.checkedAt,{checkedAt:X.checkedAt,readings:[{...B}]})}for(let B of X.coverage??[]){let K=G(B.scope,B.label);if(!J.has(K))Y(K,X.checkedAt,{checkedAt:X.checkedAt,coverage:[{...B}]})}if(X.budget)Y("budget",X.checkedAt,{checkedAt:X.checkedAt,budget:{...X.budget}});for(let[B,K]of Object.entries(X.counters??{}))Y(`counter:${B}`,K.checkedAt,{checkedAt:X.checkedAt,counters:{[B]:{...K}}});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 n9}from"node:crypto";import{stat as o9}from"node:fs/promises";import{resolve as t0}from"node:path";function a4($,Z,z){if($.accountIdentity!==void 0&&z!==void 0)return $.accountIdentity===z;return $.credentialId===Z}function c3($,Z,z){return $.some((X)=>a4(X,Z,z))}function u3($,Z,z){let X={credentialId:Z,...z!==void 0&&{accountIdentity:z}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==z),X]}function i3($,Z,z){return $.filter((X)=>!Z.some((Y)=>a4(X,Y,z)))}function a3($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>l(Z).map((z)=>({credentialId:z,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function r9($,Z){let z=l(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 h$="vault:";function t9($){return n9("sha256").update($).digest("hex")}function e9($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function $1($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function l($){return[$.credentialId,...$.aliases??[]]}function r4($,Z,z={}){let X=z.now??Date.now(),Y=z.routePrefix??h$,G=z.reservedRouteIds??new Set,J=$?.rows??[],B=$?void 0:z.seed,K=[...$?.declined??B?.declined??[]],Q=Z.skipped.length===0,H=new Set(Z.credentials.map((N)=>N.credentialId)),W=new Set(Z.skipped.flatMap((N)=>N.credentialId===void 0?[]:[N.credentialId])),F=Z.skipped.some((N)=>N.credentialId===void 0),D=(N)=>!H.has(N)&&(W.has(N)||F),U=new Map;for(let N of J){if(N.accountIdentity===void 0)continue;for(let j of l(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},o=$1(j),r=_.get(o)??[];r.push(j),_.set(o,r)}let M=new Set,L=new Set(G),R=[],f=(N,j)=>N.credential.credentialId.localeCompare(j.credential.credentialId),m=[..._.values()].map((N)=>N.toSorted(f)).sort((N,j)=>N[0]&&j[0]?f(N[0],j[0]):0);for(let N of m){let j=N[0]?.identity,o=N.filter((O)=>O.credential.state==="active"),r=o.length?o:N,r$=r.filter((O)=>O.claimed),W$=r$.length?r$:r,t$=new Set(N.map((O)=>O.credential.credentialId)),NZ=J.find((O)=>!M.has(O)&&l(O).some((S0)=>t$.has(S0))&&(O.accountIdentity===void 0||O.accountIdentity===j)),e$=W$.find((O)=>O.credential.credentialId===NZ?.credentialId)??W$[0];if(!e$)continue;let b=e$.credential,v=NZ??(j===void 0?void 0:J.find((O)=>!M.has(O)&&O.accountIdentity===j));if(v)M.add(v);let K0=v?.routeId;if(!K0||G.has(K0)){let O=`${Y}${b.credentialId}${j===void 0?"":`~${t9(j).slice(0,10)}`}`;K0=O;for(let S0=2;L.has(K0);S0++)K0=`${O}~${S0}`}L.add(K0);let J8=v?l(v).filter(D):[],$3=[...new Set([...N.map((O)=>O.credential.credentialId),...J8])].filter((O)=>O!==b.credentialId).sort((O,S0)=>O.localeCompare(S0)),G8=z.mapAccount?.(b)??{};R.push({previousIndex:v?J.indexOf(v):1/0,row:{routeId:K0,credentialId:b.credentialId,credentialType:b.credentialType,...j!==void 0&&{accountIdentity:j},...$3.length&&{aliases:$3},state:b.state,label:G8.label?.trim()||e9(b),...b.email!==void 0&&{email:b.email},...b.orgName!==void 0&&{orgName:b.orgName},enabled:![b.credentialId,...$3].some((O)=>c3(K,O,j)),addedAt:v?.addedAt??X,...v?.quota!==void 0&&{quota:v.quota},...!e$.claimed&&j!==void 0&&{unclaimed:!0}}});let Z3=R.at(-1);if(B&&Z3)Z3.previousIndex=r9(B,Z3.row)}return J.forEach((N,j)=>{if(M.has(N)||!l(N).some(D))return;if(L.has(N.routeId))return;let[o,...r]=l(N).filter((t$)=>!H.has(t$));if(o===void 0)return;L.add(N.routeId);let{aliases:r$,...W$}=N;R.push({previousIndex:j,row:{...W$,credentialId:o,...r.length&&{aliases:r},stale:!0}})}),R.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:R.map((N)=>N.row),declined:K}}function n3($){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 e0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function w0($){return $===void 0||typeof $==="string"}function Z1($){let Z=e0($)?W0($.quota):void 0;if(!e0($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!w0($.accountIdentity)||!w0($.email)||!w0($.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 z1=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function n4($){if(!Array.isArray($))return;let Z=[];for(let z of $){if(!e0(z)||!w0(z.credentialId)||typeof z.reason!=="string"||!z1.has(z.reason))return;Z.push(z)}return Z}function t4($){if(!e0($)||$.version!==1||!w0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!n4($.rejected))throw new V("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let G=Z1(Y);if(!G)throw new V("invalid-state","Claustrum roster file is not valid");Z.push(G)}let z=[];for(let Y of $.declined){if(!e0(Y)||typeof Y.credentialId!=="string"||!w0(Y.accountIdentity))throw new V("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=n4($.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 o3($){return t4(JSON.parse(JSON.stringify($)))}var X1=new a0({followSymlinks:!0});async function T($){if(s)return s3($);let Z=await X1.read([$],([z=$])=>s3(z));return structuredClone(Z)}async function s3($){let Z;try{Z=await k$($,s)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse(Z)}catch{throw new V("invalid-state","Claustrum roster file is not valid")}return t4(z)}var e4={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},$6={name:"claustrum-roster",ttlMs:30000};async function O0($,Z,z={}){return M3($,{...e4,signal:z.signal},async(X)=>{let Y=await s3($),{next:G,result:J}=await Z(Y,{assertOwned:()=>X.assertOwned()});if(G){await X.assertOwned();try{await u($,G,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}})}catch(B){if(B&&typeof B==="object"&&"published"in B&&B.published===!0)z.onPublished?.();throw B}z.onPublished?.()}return J})}function r3($,Z){return O0($,(z)=>{let X=z?.rows.find((G)=>G.routeId===Z);if(!z||!X)throw new V("route-unavailable","Claustrum route is not in the roster");let Y=u3(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 t3($,Z){return O0($,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===Z);if(!z||!X)throw new V("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:i3(z.declined,l(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function Y1($){return new V("invalid-order",$)}function J1($,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 e3($,Z,z={}){return O0($,(X)=>{let Y=X?.rows??[],G=J1(Y,Z);if(G)throw Y1(G);let J=new Map;for(let Q of Y){let H=J.get(Q.routeId);if(H)H.push(Q);else J.set(Q.routeId,[Q])}let B=[...Z],K=B.flatMap((Q)=>J.get(Q)??[]);if(!X||K.every((Q,H)=>Q===Y[H]))return{result:{ids:B,outcome:"unchanged"}};return{next:{...X,rows:K},result:{ids:B,outcome:"reordered"}}},{...z.signal&&{signal:z.signal}})}function G1($,Z){if(!l($).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")&&l($).length===1)return"bind";return"refuse"}async function $Z($,Z){let{routeId:z,observation:X,...Y}=Z;return Z6($,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function Z6($,Z){if(!A0(Z.observation))return!1;let z=k($,await T($));if(!J0(z,Z).kept)return!1;return X6($,Z)}function ZZ($,Z){return Z6($,Z)}function J0($,Z){let z=$?.rows.find((J)=>J.routeId===Z.routeId),X=!z?"refuse":Z.receipt?G1(z,Z.receipt):z.accountIdentity!==void 0&&z.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!z||X==="refuse")return{roster:$,kept:!1};let Y=p0(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 w$=new Map;function $$($){w$.delete(t0($))}function z6($,Z){let z=t0($);if(Z instanceof V)return Z.kind==="roster-busy";if(Z instanceof M$||Z instanceof N3)return t0(Z.details.target)===z;if(Z instanceof d0){let X=t0(Z.path);return[e4.name,$6.name].some((Y)=>{let G=q3(z,Y);return X===G||X.startsWith(`${G}.`)})}return!1}var B1=4;async function o4($){try{let{dev:Z,ino:z,size:X,mtimeMs:Y}=await o9($);return{dev:Z,ino:z,size:X,mtimeMs:Y}}catch{return}}function K1($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function H1($,Z,z){for(let X=0;X<B1;X++){let Y=await o4($),G=await T($),J,B,K;try{({target:J,local:B}=Z(G));let Q=JSON.stringify(z(J));K=JSON.stringify(J)!==Q||B!==void 0&&JSON.stringify(B)!==Q}catch{return"commit"}if(!K1(Y,await o4($)))continue;if(K)return"commit";return Y6($)?"commit":"unchanged"}return"commit"}async function Z$($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){$$($.path);return}let z=await w({...$6,path:$.path,renew:!0});if(!z){let J=await T($.path);if($.signal?.throwIfAborted(),!J?.view)throw new V("roster-busy","Claustrum account discovery is already in progress");return J}let X=t0($.path),Y=$.listedOver,G;try{let J=await T($.path),B=Y?void 0:w$.get(X);G=B&&(B.previousView===J?.view||B.inventory.view===J?.view)?B:{inventory:await $.custody.discover($.signal),previousView:J?.view},w$.delete(X);let{inventory:K}=G;$.onInventory?.(K),$.signal?.throwIfAborted();let Q=typeof $.projection==="function"?$.projection():$.projection,H=(D)=>r4(D,K,Q),W=async()=>{return $.signal?.throwIfAborted(),await z.assertOwned(),Z()};if(await H1($.path,(D)=>{if(Y)return{target:D};let U=k($.path,D);return{target:D,...U!==D&&{local:U}}},H)==="unchanged"){if(!await W())return;return await T($.path)}return await O0($.path,async(D)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await z.assertOwned(),Y&&D?.view!==Y.view&&D?.view!==K.view)return{result:D};let U=H(D);return{...JSON.stringify(D)!==JSON.stringify(U)&&{next:U},result:U}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await z.assertOwned()}})}catch(J){if(J instanceof M$&&G&&!Y&&!$.signal?.aborted&&await Z())w$.set(X,G);throw J}finally{await z.release($.signal)}}var L0=new Map,W1=C("claustrum"),G6=100;function B6($,Z=i4){let z=m$($),X=L0.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},L0.set(z,X);return X}function K6($,Z,z){let X=B6($,z);X.listeners.add(Z);let Y;return()=>Y??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():zZ($)})()}function Q1($){return s4($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function X6($,Z){if(!A0(Z.observation))return Promise.resolve(!1);let z=B6($),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 Q1(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 W6(z,G6),Promise.resolve(!0)}function H6($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,z)=>Z.order-z.order)}function k($,Z){let z=L0.get(m$($));if(z)for(let X of H6(z.pending)){if(X.priorReading)Z=J0(Z,X.priorReading).roster;Z=J0(Z,X.publication).roster}return Z}function Y6($){return!!L0.get(m$($))?.pending.size}function W6($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let z=$.draining?0:($.committedAt??-1/0)+u4-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,z),()=>{return $.timer=void 0,Q6($)}),!$.draining)$.timer.unref?.()}function J6($){$.timer?.cancel(),$.timer=void 0}function Q6($){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 O0($.path,(X)=>{let Y=X;for(let J of H6(Z)){if(J.priorReading)Y=J0(Y,J.priorReading).roster;Y=J0(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)W1.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()):G6;W6($,z)}})(),$.running}async function zZ($,Z=1000){let z=m$($),X=L0.get(z);if(!X)return;X.draining=!0,J6(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)Q6(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(),J6(X),X.pending.clear(),L0.get(z)===X)L0.delete(z)}}}var v$=1e4;function U6(){return new x}var XZ;function V6($,Z){if(!XZ)throw Error("ClaustrumConsumer is not initialized");return XZ($,Z)}function D6(){return new V("not-active","Claustrum scoped custody is not active")}class YZ{#$;#Z=new AbortController;#B;#G;#X;#K;#Y;#z;#D;#J;#H=!1;#U=new Set;#F;#Q;#q;#M;#R=new Map;#O;#L;#W;#N;#S=new WeakMap;static{XZ=($,Z)=>{let z=new YZ(Z);return z.#W=$,{consumer:z,hooks:z.#w()}}}constructor($){this.#$=$,this.#B=$.logger??C("claustrum"),this.#G=f0(this.#B,this.#Z.signal),this.#L=K6($.rosterPath,(Z)=>{this.#z=J0(this.#z,Z).roster})}#V($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#_($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#P(){if(S())return!0;return await this.#$.isCustodyActive?.()??!0}#T($,Z){let z=N0([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.#X)return this.#X;if(!this.#K){let $={timedOut:!1};this.#K=this.#j($),this.#_(this.#K)}return this.#T(this.#K)}#j($){let Z=this.#$.setTimeoutImpl??setTimeout,z=this.#$.clearTimeoutImpl??clearTimeout,X=(!S()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>_0(this.#$.pluginId))).then((J)=>{if(this.#Z.signal.aborted||$.timedOut){if(J.close(),!$.timedOut)this.#V();throw U6()}if(this.#X=new y0({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=T3(J.insula,this.#$.tokenPath);return this.#X}),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(U6())},this.#A()),Y.unref?.()});return Promise.race([X,G]).finally(()=>{if(Y)z(Y);this.#K=void 0})}#A(){return this.#$.connectTimeoutMs??v$}snapshot(){return this.#z}grantReach(){if(this.#W)return this.#W.grantReach(this.#z?.view);let $=this.#D;return $&&this.#z?.view===$.view?$.reach:void 0}watchState(){if(this.#W)return Object.freeze({vault:this.#W.watchMode()});return Object.freeze({vault:this.#q?.mode??"polling",...this.#$.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#C(){this.#q?.close(),this.#q=void 0,this.#M?.(),this.#M=void 0}keptReceiptState(){if(this.#W){let $=this.#N;return $&&this.#W.leaseLive($)?$.custody.keptReceiptState():this.#W.keptReceiptState()}return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return n3(this.#z)}refresh(){if(this.#V(),this.#W)return this.#_(this.#b(this.#W));if(this.#Y)return this.#Y;return this.#Y=(async()=>{if(!await this.#P()){if(this.#z=void 0,this.#D=void 0,this.#C(),this.#X)this.#X.close(),this.#_(this.#X.dispose(this.#G));this.#X=void 0,this.#Q?.release(),this.#Q=void 0;return}let $=await this.#I(),Z,z=await Z$({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#P(),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=k(this.#$.rosterPath,z),$.retain(z?.rows??[]),Z&&z?.view!==void 0)this.#D=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.#Y=void 0}),this.#_(this.#Y),this.#x(this.#Y),this.#Y}#x($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#H)return;if(this.#V(),this.#H=!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.#J=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#J=void 0,this.#_($())},Z),this.#J.unref?.()};this.#_($())}async#y(){if(this.#q?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#O===void 0||$-this.#O>=C0)return!0;return!await this.#P()}#k(){let $=this.#X;if(this.#Z.signal.aborted||!$)return;if(this.#q??=$.watchRoster({view:()=>this.#z?.view,onView:()=>this.#_((async()=>{while(this.#Y)await this.#Y.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.#P())return;try{if(!S())await X0(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.#P())return;try{if(!S())await X0(this.#$.tokenPath);return this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#P())return;try{if(!S())await X0(this.#$.tokenPath);let z=k(this.#$.rosterPath,await T(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.#P())return{miss:"unreachable"};try{if(!S())await X0(this.#$.tokenPath);let X=k(this.#$.rosterPath,await T(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.#R.get($)!==z.miss)this.#R.set($,z.miss),this.#B.warn("skipped insula provider poll",{reason:z.miss});return}return this.#R.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.#P())throw this.#X?.close(),this.#X=void 0,this.#C(),this.#Q?.release(),this.#Q=void 0,new V("not-active","Claustrum scoped custody is not active");let X=k(this.#$.rosterPath,await T(this.#$.rosterPath));this.#V(Z);let Y=z.rows.find((K)=>K.routeId===$),G=X?.rows.find((K)=>K.routeId===$);if(G&&!G.enabled){if(Y)this.#X?.forget(Y.credentialId);throw new V("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.#X?.forget(Y.credentialId);throw new V("route-unavailable","Claustrum route is disabled, removed or changed")}let J=await this.#T(this.#I(),Z),B=N0([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()}}#w(){return{discovery:($)=>{let Z=this.#W;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let z=this.#_($.then((X)=>this.#h(Z,X)));this.#x(z)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#z?.view;if(this.#z=k(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.#h($,Z)}#h($,Z){if(this.#V(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#z}#E($){if($&&this.#N!==$)return;this.#N?.release(),this.#N=void 0}async#p($,Z){let z=this.#N;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.#N;if(Y&&$.leaseLive(Y))return X.release(),Y;return this.#N=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(),D6();if(this.#V(z),!X)throw new V("route-unavailable","Claustrum has no roster for this provider yet");let Y=k(this.#$.rosterPath,await T(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 V("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 V("route-unavailable","Claustrum route is disabled, removed or changed")}let B={credentialId:J.credentialId,credentialType:J.credentialType,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity}},K=N0([this.#Z.signal,...z?[z]:[]]);try{for(let Q=0;;Q++){let H=await this.#p($,K.signal);try{let W=await H.custody.authorize(B,K.signal,Z);return this.#S.set(W,H),W}catch(W){if(Q>0||K.signal.aborted||$.leaseLive(H)||!(W instanceof V)||W.kind!=="closed")throw W;if(this.#E(H),!await $.readAuthority())throw D6()}}}finally{K.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.#N&&this.#W.leaseLive(this.#N))this.#N.custody.reportUsage($)}else this.#X?.reportUsage($)}catch{}}usageReportState(){try{return(this.#W?this.#N?.custody:this.#X)?.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.#S.get($);if(!X)throw new V("no-receipt","Claustrum dispatch receipt has no active owner");await X.custody.reportFailure($,Z,z);return}if(!this.#X)throw new V("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.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(d3(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 r3(this.#$.rosterPath,$),this.#z=k(this.#$.rosterPath,await T(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z);if(this.#W)this.#W.retainUnion();else this.#X?.retain(this.#z?.rows??[])}async accept($){if(this.#V(),await t3(this.#$.rosterPath,$),this.#z=k(this.#$.rosterPath,await T(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z)}async reorder($){this.#V();let Z=await e3(this.#$.rosterPath,$);if(this.#z=k(this.#$.rosterPath,await T(this.#$.rosterPath)),this.#z)this.#W?.publishRoster(this.#z);return Z}async recordQuota($,Z,z){return this.#V(),$Z(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(),ZZ(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:z})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new V("closed","Claustrum consumer is closed")),this.#J)(this.#$.clearTimeoutImpl??clearTimeout)(this.#J);if(this.#J=void 0,this.#C(),this.#X)this.#X.close(),this.#_(this.#X.dispose(this.#G));this.#N?.release(),this.#N=void 0,this.#W?.detach(),this.#Q?.release(),this.#Q=void 0,this.#z=void 0,this.#D=void 0,this.#L(),$$(this.#$.rosterPath)}async dispose(){this.close(),this.#F??=Promise.all([b0(this.#U,this.#G),this.#L()]).then(()=>{}),await this.#F}}import{createHash as U1}from"node:crypto";import{channel as D1}from"node:diagnostics_channel";import{readdir as V1,stat as F1}from"node:fs/promises";import{dirname as q1,join as h0,resolve as F6}from"node:path";var g$=new Map,N1=/^[a-z0-9][a-z0-9._-]{0,63}$/,M1=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,_1=/^[0-9a-f]{16}$/,q6=3;function GZ($,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=GZ($[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=GZ($[G],z);if(J===void 0)return;X.push(`${JSON.stringify(G)}:${J}`)}return`{${X.join(",")}}`}function j1($,Z){let z=GZ({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??h$,mapAccount:$.mapAccount?String($.mapAccount):null});if(z===void 0)throw new V("invalid-state","Claustrum hub classifierInput must be plain JSON");return U1("sha256").update(z).digest("hex").slice(0,16)}function N6($,Z){if(typeof $!=="string"||!N1.test($)||M1.test($))throw new V("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function G0($="Claustrum custody lease is closed"){return new V("closed",$)}function JZ(){return new V("not-active","Claustrum scoped custody is not active")}function M6(){return new x}function O1($,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 _6($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class j6{#$;#Z;#B;#G=new AbortController;#X=new Map;#K=new WeakMap;#Y=0;#z;#D;#J;#H;#U;#F;#Q=0;#q;#M;#R;#O=!1;#L=new Set;#W;#N;#S;constructor($){if(!$.family||!("classify"in $.family))throw new V("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=N6($.hostGeneration,"host generation"),z=$.members.map((Y)=>N6(Y,"member"));if(new Set(z).size!==z.length)throw new V("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??C("claustrum"),this.#B=f0(this.#Z,this.#G.signal),this.#N=h0($.stateDir,"rosters",Z),this.#S=j1($,z);let X=h0(this.#N,this.#S);for(let Y of z)this.#X.set(Y,{provider:Y,path:h0(X,`${Y}.json`),closed:!1})}#V($){return this.#L.add($),$.then(()=>this.#L.delete($),()=>this.#L.delete($)),$}#_(){if(this.#G.signal.aborted)throw G0("Claustrum discovery hub is closed")}#P($){let Z=this.#X.get($);if(!Z)throw new V("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#P($).path}member($,Z){this.#_();let z=this.#P($);if(z.hooks)throw new V("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 V("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.#q?.view===W?this.#q.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}=V6(X,Y);z.hooks=J;let B=F6(z.path),K=g$.get(B)??new Set,Q=(W)=>{if(z.closed||this.#F!==!0||!this.#z||!this.#j(this.#z)||!J.roster()||this.#l(J,W))return;if(z.seen=JSON.stringify(o3(W)),J.install(W),W.view!==this.#q?.view)z.pending??={failures:0,wait:0};this.#g()};K.add(Q),z.receiveRoster=Q,g$.set(B,K);let H=!0;return z.releaseRoster=()=>{if(!H)return;if(H=!1,K.delete(Q),!K.size)g$.delete(B)},G}#T($,Z){let z=this.#z;if($.closed||!z||!this.#j(z))return;$.seen=JSON.stringify(o3(Z)),$.hooks?.install(Z);for(let X of g$.get(F6($.path))??[]){if(!this.#j(z))return;if(X!==$.receiveRoster)X(Z)}}#I(){let $={id:++this.#Y,count:0,ended:!1,controller:new AbortController};return this.#z=$,$}#j($){return!$.ended&&this.#z===$&&!this.#G.signal.aborted}#A($){let Z=this.#K.get($);return!!Z&&!Z.released&&!Z.generation.ended}#C($,Z=G0()){if($.ended)return;if($.ended=!0,$.count=0,this.#z===$)this.#z=void 0;if(this.#J&&this.#K.get(this.#J)?.generation===$)this.#J=void 0;if(this.#H?.generation===$)this.#H.watch.close(),this.#H=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#V($.custody.dispose(this.#B))}#x($){if($.ended)return;if($.count--,$.count<=0)this.#C($)}#y($){let Z=this.#D;if(Z?.generation===$&&Z.promise)return Z.promise;let z={generation:$,timedOut:!1},X=this.#$.connectTimeoutMs??v$,Y,G=(!S()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>_0(this.#$.pluginId))).then((K)=>{if(z.timedOut)throw K.close(),M6();if(!this.#j($)||$.count<=0)throw K.close(),G0("Claustrum connection is no longer wanted");return $.custody=new y0({client:K,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((K,Q)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(z.timedOut=!0,!this.#j($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:X}),Q(M6())},X),Y.unref?.()});return z.promise=this.#V(Promise.race([G,J]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),z.promise.finally(()=>{if(this.#D===z)this.#D=void 0}).catch(()=>{}),this.#D=z,z.promise}acquire($){try{if(this.#_(),$?.throwIfAborted(),this.#F===!1)throw JZ()}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=N0([$.controller.signal,...Z?[Z]:[]]);try{X=await O1(this.#y($),Y.signal)}catch(G){if(!$.ended)throw this.#x($),G;return this.#f(Z,z)}finally{Y.dispose()}}if($.ended)return this.#f(Z,z);if(Z?.aborted)throw this.#x($),Z.reason;return this.#w($,X)}#f($,Z){if($?.throwIfAborted(),this.#_(),this.#F===!1)throw JZ();if(!Z)throw G0();let z=this.#z??this.#I();return z.count++,this.#k(z,$,!1)}#w($,Z){let z={generation:$,custody:Z,released:!1},X=()=>{if(z.released||$.ended)throw G0()},Y=Object.freeze({authorize:async(J,B,K)=>{X();let Q=N0([$.controller.signal,...B?[B]:[]]);try{return await Z.authorize(J,Q.signal,K)}finally{Q.dispose()}},reportFailure:async(J,B,K)=>{return X(),Z.reportFailure(J,B,K)},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.#x($)}});return this.#K.set(G,z),G}leaseState(){let $=this.#z;return Object.freeze({generation:$?.id,count:$?.count??0})}async#b(){let $=S()||(await this.#$.isCustodyActive?.()??!0);if(this.#G.signal.aborted)return!1;let Z=this.#F;if(this.#F=$,!$&&Z!==!1)this.#h();return $}#h(){this.#Q++;let $=this.#z;if($)this.#C($,JZ());this.#J=void 0,this.#H?.watch.close(),this.#H=void 0,this.#q=void 0,this.#M=void 0;for(let Z of this.#X.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),$$(Z.path)}#E(){return[...this.#X.values()].filter(($)=>$.hooks&&!$.closed)}async#p(){let $=this.#J,Z=$&&this.#K.get($);if($&&Z&&this.#A($))return Z;this.#J=void 0;let z=await this.acquire(this.#G.signal),X=this.#J&&this.#K.get(this.#J);if(this.#J&&X&&this.#A(this.#J))return z.release(),X;this.#J=z;let Y=this.#K.get(z);if(!Y)throw G0();return Y}#m(){try{this.#_()}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.#j(z))return;let X=await this.#o().then(()=>{return},(H)=>H instanceof Error?H:Error(String(H))),Y=new Map(await Promise.all([...this.#X.values()].map(async(H)=>[H,await T(H.path).then((W)=>W?{file:W}:{},(W)=>W instanceof Error?W:Error(String(W)))])));if(!this.#j(z))return;let G;try{G=await Z.custody.discover(z.controller.signal)}catch(H){if(!this.#j(z))return;for(let W of this.#X.values())if(W.pending)this.#v(W);throw H}if(!this.#j(z))return;let J=this.#E(),B=await Promise.all(J.map((H)=>H.hooks&&!H.closed?this.#n(H,H.hooks,G,X??Y.get(H),z):void 0));if(!this.#j(z))return;let K=new Map,Q=!0;for(let[H,W]of J.entries()){let F=W.hooks,D=B[H];if(!F||!D)continue;if("error"in D){let{error:_}=D;if(Q=!1,this.#v(W),z6(W.path,_))this.#Z.debug("claustrum hub member commit refused",{member:W.provider});else K.set(W.provider,_);continue}let{roster:U}=D;if(!this.#j(z))return;if(U?.view!==G.view)Q=!1,this.#v(W);else W.pending=void 0;if(!U)continue;if(this.#l(F,U)){Q=!1,this.#v(W);continue}this.#T(W,U)}if(!this.#j(z))return;if(this.#g(),Q)this.#q=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:K}}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 G0("Claustrum hub member has no base view");if(X instanceof Error)throw X;let J;if(!X.file){let K=D1("common-auth.claustrum.phases");if(K.hasSubscribers)K.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{J=await this.#r($)}finally{if(K.hasSubscribers)K.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await Z$({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#j(Y)&&this.#F===!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[q1(this.#N),this.#N,h0(this.#N,this.#S)])await k0($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,z=[h0(this.#N,Z)];try{for(let Y of await V1(this.#N))if(Y!==this.#S&&_1.test(Y))z.push(h0(this.#N,Y,Z))}catch{}let X;for(let Y of z)try{let G=(await F1(Y)).mtimeMs,J=await T(Y);if(J&&(!X||G>X.modified))X={modified:G,roster:J}}catch{}return X&&a3(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(C0/z)),Y=Z<=q6?1:Math.min(2**(Z-q6),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 T(Z.path)}catch(B){Z.hooks?.onError(B);continue}if($!==this.#Q||this.#F!==!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=_6(G);if(Z.seen=Y,this.#T(Z,z),_6(X.roster())!==J)this.#g()}}#e(){let $=!1;for(let z of this.#X.values()){if(!z.pending)continue;if(z.pending.wait<=0)$=!0;else z.pending.wait--}if(this.#H?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#M===void 0||Z-this.#M>=C0}#$0(){let $=this.#J,Z=$&&this.#K.get($);if(!$||!Z||!this.#A($)||this.#F!==!0)return;let z=Z.generation;if(!this.#j(z)||this.#H?.generation===z)return;let X=Z.custody.watchRoster({view:()=>this.#q?.view,onView:()=>this.#V((async()=>{while(this.#U)await this.#U.promise.catch(()=>{});if(!this.#j(z))return;await this.#i()})()),onRefused:(Y)=>this.#c(Y),onError:(Y)=>this.#d(Y)});this.#H={generation:z,watch:X}}#d($){if(!this.#G.signal.aborted)this.#$.onError?.($)}#c($){if(this.#G.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#E())Z.hooks?.onError($)}#u($){for(let[Z,z]of $?.errors??[])this.#X.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.#G.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#R=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#R=void 0,this.#V(this.#s())},$),this.#R.unref?.()}start(){if(this.#O)return;this.#_(),this.#O=!0,this.#V(this.#s())}async refresh(){this.#u(await this.#m())}refusals(){let $=this.#q;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#q?.reach}watchState(){let $=this.#H;return $&&this.#j($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#z?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#G.signal.aborted)return;this.#G.abort(G0("Claustrum discovery hub is closed"));for(let Z of this.#X.values())Z.releaseRoster?.();if(this.#R)(this.#$.clearTimeoutImpl??clearTimeout)(this.#R);this.#R=void 0;let $=this.#z;if($)this.#C($);this.#J=void 0,this.#H?.watch.close(),this.#H=void 0}async dispose(){this.close(),this.#W??=b0(this.#L,this.#B),await this.#W}}var P1=1e4;async function fz($){let{connectTimeoutMs:Z,...z}=$,X=Z??P1,Y=L1.connect(z),G=!1,J,B=new Promise((K,Q)=>{J=setTimeout(()=>{G=!0,Q(new x)},X),J.unref?.()});try{let K=await Promise.race([Y,B]);return Object.assign(K,{insula:K4($)})}catch(K){throw Y.then((Q)=>Q.close(),()=>{}),K}finally{if(!G&&J)clearTimeout(J)}}var O6=b$("openai");function L6($){return y$($)}function P0($){if(!$||$.corrupt===!0)return!1;return L6($.refresh)}class z$ 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 p$($){if(L6($))throw new z$}var x1=C("quota"),BZ="primary",KZ="secondary",R1="app_EMoamEEZ73f0CkXaXp7hrann",S1="https://auth.openai.com";async function XX($){p$($.refreshToken);let Z=await $.fetchImpl(`${S1}/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:R1}).toString()});if(!Z.ok){let Y=O3(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 T1="https://chatgpt.com/backend-api/wham/usage";async function YX($){let Z=$.logger??x1,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await $.fetchImpl(T1,{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=O3(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:J})}let G=Y4(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:P6(Y)}),Y}}import{createHash as A1}from"node:crypto";var E1=globalThis.setTimeout,C1=5;function X$($){let Z=$?.quota?.checkIntervalMinutes??C1;return Math.max(1,Z)*60000}function I1($){return $?.quota?.enabled!==!1}function l$($,Z){if(!$?.resetsAt)return!1;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z<=Z}function QX($,Z,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=Z===BZ?$?.primary:Z===KZ?$?.secondary:void 0,J=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(J)&&J>z)return J;return z+X}function k1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function x6($,Z,z){if(!I1(Z))return z+X$(Z);let X=k1(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+X$(Z);Y.push(B)}if(!Y.length)return z+X$(Z);return Math.min(...Y)+60000}function f1($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function b1($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function h($){return A1("sha256").update($).digest("hex").slice(0,16)}class B0{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&&!R6(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,HZ(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&&!R6(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(HZ(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=B0.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(P0(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=b1(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=f1($);if(!z)return;let X=Z?h(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:x6(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&&E0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=X$(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 E0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==h(Z))return!1}return E0(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<B0.API_CALL_GAP_MS)await new Promise((Y)=>{let G=E1(Y,B0.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 w({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:x6(Y,this.storage,G),checkedAt:G},HZ(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 w({name:B0.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+X$(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(B0.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(B0.isAuthError($))return;this.mainLastApiError=c0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(B0.isAuthError(z))return;let X=h(Z),Y=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,c0({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,X)}}function R6($){return Boolean($.primary||$.secondary)}function HZ($){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 y1,randomUUID as w1}from"node:crypto";import{setTimeout as h1}from"node:timers/promises";import{readFile as o1}from"node:fs/promises";var x0=C("refresh"),B$=C("accounts"),m1=1e4,v1=15000,WZ=50;function a($){return $.type==="oauth"&&$.corrupt!==!0}function g1($){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 p1="floors-v1";function SX($){return $.costZeroing?.enabled!==!1}class c$ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var l1=[401,403,429],S6={primary:0,secondary:0},d1=!1,UZ={primary:5,secondary:10};function q($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var c1=new Set(["__proto__","constructor","prototype"]);function u1($){return $.length>0&&!c1.has($)}function i1($){return $ instanceof c$||q($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function d$($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():w1(),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 T6($){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 s1($){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),K=Number(G.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(B)||!Number.isFinite(K))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[Y]={usedPercent:J,remainingPercent:B,checkedAt:K,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),K=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(K)&&typeof z.reached==="boolean")Z.spendControl={limit:Y,used:G,remaining:J,usedPercent:B,remainingPercent:K,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 a1($){if(!q($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!g1(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...d$($),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{...d$($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...d$($),type:"oauth",corrupt:!0}}return{...d$($),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:T6($.lastRefreshError),lastQuotaRefreshError:T6($.lastQuotaRefreshError),quota:s1($.quota)}}function n1($){if(!q($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!u1(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 A6=new Set;function w6($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(A6.has(Z))return;A6.add(Z),B$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function h6($){if(!q($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(a1).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);w6(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:n1($.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 m6($){if(!("claustrum"in $))return $;let{claustrum:Z,...z}=$;return z}async function n($){try{return{exists:!0,value:JSON.parse(await o1($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function d($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function r1($){let Z;try{Z=(await n($)).value}catch{return null}return qZ(Z)}function v6($,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,K=X??J,H=J.mainRefreshLeaseId!==void 0?{id:J.mainRefreshLeaseId,until:J.mainRefreshLeaseUntil,tokenHash:J.mainRefreshLeaseTokenHash}:{id:K.refreshLeaseId,until:K.refreshLeaseUntil,tokenHash:K.refreshLeaseTokenHash},F=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!q(D))return D;let U=typeof D.id==="string"&&q(Y[D.id])?Y[D.id]:{};return{...D,...U}}):void 0;return g6({...$,refresh:d({...J,mainLastRefreshError:J.mainLastRefreshError??K.lastRefreshError,mainRefreshLeaseId:H.id,mainRefreshLeaseUntil:H.until,mainRefreshLeaseTokenHash:H.tokenHash}),quota:d({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:F})}async function t1($){let Z=await n($.configPath);if(!Z.exists)return null;let z=await n($.statePath);return h6(v6(Z.value,z.value))}var E6=new Set;async function AX($){try{let{exists:Z,value:z}=await n($.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:d({enabled:X.enabled,refreshBeforeExpiryMinutes:X.refreshBeforeExpiryMinutes}),quota:d({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(!E6.has($.configPath))E6.add($.configPath),B$.warn("could not read OpenAI auth settings; using defaults",{path:$.configPath});return null}}function g6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function e1($){return d({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 p6($){if($.type==="api")return d({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return d({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function u$($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function Y$($,Z,z){if(z in Z)$[z]=Z[z];else delete $[z]}function $2($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function Z2($,Z){if(!$2($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var z2=300000;function C6($,Z){if($===void 0)return 0;return $>Z+z2?0:$}function X2($,Z,z){let X=Date.now(),Y=C6(Z.lastRefreshedAt,X),G=C6(z.lastRefreshedAt,X),J=Z.expires??0,B=z.expires??0,K=G>Y?z:Y>G?Z:B>J?z:J>B?Z:Z2(Z,z);Y$($,K,"access"),Y$($,K,"refresh"),Y$($,K,"expires"),Y$($,K,"lastRefreshedAt"),Y$($,K,"lastRefreshError")}function Y2($,Z){if(!q($))return Z;let z=$,X=u$(z.quota),Y=u$(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 X2(J,z,Z),J}function l6($){let Z=$.refresh?d({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?d({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return g6({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(e1)})}async function K$($,Z=!1){let z=Date.now(),X=z+v1,Y=0;while(Date.now()<=X){Y++;let B=await w({name:"save",ttlMs:m1,path:$,renew:Z});if(B)return B;let K=X-Date.now();if(K<=0)break;await h1(Math.min(WZ+s6(WZ),K))}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 ${WZ}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 d6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,p6(z)]));return{version:1,main:d({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 qZ($){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 J2($,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((K)=>q(K)&&typeof K.id==="string"&&K.id.trim()===J);if(!B)continue;Y.push(B),G.push(J)}return{preservedRawEntries:Y,preservedIds:G}}function G2($){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 B2($,Z,z){let X=qZ($);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=J2($,X,Z,z);return w6(G),Y}async function EX($,Z,z={}){let{configPath:X,statePath:Y}=Z,G=await K$(X);try{let J=await K$(Y);try{let B=await n(X),K=await n(Y),Q=(B.exists?h6(v6(B.value,K.value)):null)??K2(),H=new Set(Q.accounts.map((m)=>m.id)),W=qZ(B.value)??new Set,F=$(Q,{rawRosterIds:[...W],loadedRosterIds:[...H]})??Q,D=new Set(z.allowDrop??[]),U=B2(B.value,H,D),_=l6(F),M=new Set((Array.isArray(_.accounts)?_.accounts:[]).map((m)=>q(m)&&typeof m.id==="string"?m.id.trim():"").filter(Boolean)),L=U.filter((m)=>{if(!q(m))return!1;if(typeof m.id!=="string")return!1;return!M.has(m.id.trim())}),R=q(B.value)?B.value:{},f={...m6(R),..._,accounts:[...Array.isArray(_.accounts)?_.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return Q;if(await u(X,f),z.canWrite&&!z.canWrite())return Q;return await u(Y,d6(F)),B$.debug("account config written",{accountCount:f.accounts.length,accountIds:G2(f.accounts)}),F}finally{await J.release()}}finally{await G.release()}}function K2(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function H2($,Z){$.main=$.main??{};let z=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:u$($.main.quota),X=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:u$(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 W2($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function DZ($){if(Array.isArray($))return $.map(DZ);if(!q($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,z])=>[Z,DZ(z)]))}async function Q2($,Z,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=Z.statePath,G=await K$(Y);try{let J=(await n(Y)).value,B=q(J)?{...J,version:1}:{version:1};if(z.mainQuota)H2(B,$);if(z.mainRefresh)W2(B,$);if(z.accounts){let K=z.accounts===!0?null:new Set(z.accounts),Q=await r1(Z.configPath);B.accounts={...q(B.accounts)?B.accounts:{}};for(let H of $.accounts){if(K&&!K.has(H.id))continue;if(Q&&!Q.has(H.id))continue;B.accounts[H.id]=Y2(B.accounts[H.id],p6(H))}if(K){for(let H of K)if(!$.accounts.some((W)=>W.id===H))delete B.accounts[H]}if(Q){for(let H of Object.keys(B.accounts))if(!Q.has(H))delete B.accounts[H]}}if(X&&!X())return;await u(Y,DZ(B))}finally{await G.release()}}function U2($){return $?.fallbackOn?.length?$.fallbackOn:l1}function CX($,Z){return U2(Z).includes($)}function D2($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??S6.primary,secondary:Z.secondary??Z["1w"]??S6.secondary}}function VZ($){return $?.quota?.enabled!==!1}function H$($){return $?.quota?.failClosedOnUnknownQuota??d1}function c6($,Z,z=Date.now()){if(!VZ(Z))return!0;if(!$)return!H$(Z);let X=D2(Z),Y=H$(Z);for(let G of["primary","secondary"]){let J=$[G];if(!J)continue;if(l$(J,z)){if(Y)return!1;continue}if(J.remainingPercent<X[G])return!1}return!0}function i$($){return $?.killswitch?.enabled===!0}function I6($){return{primary:$?.primary??$?.["5h"]??UZ.primary,secondary:$?.secondary??$?.["1w"]??UZ.secondary}}function IX($){return $?.cacheKeep??$?.cachekeep}function k6($){return typeof $==="number"&&Number.isFinite($)?$:0}function u6($,Z){if(!$?.killswitch)return UZ;if($.killswitch.schema===p1){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:k6(G?.primary),secondary:k6(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return I6($.killswitch.accounts[Z]);return I6($.killswitch.main)}function i6($,Z,z,X=Date.now()){if(!i$(Z))return!0;if(!$)return!H$(Z);let Y=u6(Z,z),G=H$(Z);for(let J of["primary","secondary"]){let B=$[J];if(!B)continue;if(l$(B,X)){if(G)return!1;continue}if(B.remainingPercent<Y[J])return!1}return!0}function kX($,Z,z,X){if(!i$(X))return 300;let Y=[],G=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:K}of G){if(!K)continue;let Q=u6(X,B),H=[],W=!1;for(let F of["primary","secondary"]){let D=K[F];if(!D||l$(D,z))continue;if(D.remainingPercent>=Q[F])continue;let U=D.resetsAt?Date.parse(D.resetsAt):NaN;if(!Number.isFinite(U)||U<=z){W=!0;break}H.push(U)}if(W||H.length===0)continue;Y.push(Math.max(...H))}if(Y.length===0)return 300;let J=Math.min(...Y);return Math.max(1,Math.ceil((J-z)/1000))}function f6($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function fX($,Z){let{configPath:z,statePath:X}=Z;if(!$)return;try{let G=await n(z);if(G.exists&&q(G.value)&&f6(G.value))return}catch{}let Y=await K$(z);try{let G=await K$(X);try{let J=await n(z);if(J.exists&&q(J.value)){if(f6(J.value))return}if(!$)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let H=O$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(H)B.mainAccountId=H}let K=J.exists&&q(J.value)?J.value:{},Q={...m6(K),...l6(B)};await u(z,Q),await u(X,d6(B))}finally{await G.release()}}finally{await Y.release()}}function V2($){return $?.refresh?.enabled!==!1}function F2($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function s6($){return Math.floor(Math.random()*($+1))}function R0($,Z,z){return!$.access||!$.expires||$.expires-z<=F2(Z)}function q2($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function J$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class a6 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 N2="common-auth-placeholder:v1:openai",n6="main";function bX($){return q($)&&$.type==="oauth"&&($.refresh===N2||$.refresh===O6)}function yX($){return $?.accounts.find((Z)=>Z.id===n6&&Z.enabled!==!1&&a(Z))}function wX($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==n6)}}function I($,Z){let z=$.accounts.findIndex((X)=>X.id===Z.id);if(z!==-1)$.accounts[z]=Z}function G$($){return $ instanceof Error?$.message:String($)}function FZ($,Z,z){if(Z instanceof z$)return;$.lastRefreshError=lZ({error:Z,now:z,refreshToken:$.refresh,previous:$.lastRefreshError})}function QZ($,Z,z){if(Z instanceof z$)return;if($.lastQuotaRefreshError=c0({error:Z,now:z,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)FZ($,Z,z)}function b6($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return Number.isFinite(z)?z>Z:!0}function M2($,Z){if(!$)return!1;return b6($.primary,Z)||b6($.secondary,Z)}function _2($,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 y6($,Z,z){return!_2($.quota,Z,z)}function j2($,Z,z,X){return j3(z)&&c6($.quota,Z,X)&&M2($.quota,X)}function O2($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var L2=60000,P2=60000,x2=600000;function R2($){return`fallback-oauth-refresh-${y1("sha256").update($).digest("base64url").slice(0,16)}`}var S2=1e4,T2=100;class A2{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($)p$($.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+O2(Z),checkedAt:z},$.access,!1,$.accountId)}async load(){return t1(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await Q2($,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(()=>{})},L2+s6(P2)),"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||!a(Y))continue;if(J$(Z,Y))continue;if(P0(Y))continue;let G=!1,J=Y;try{if(R0(J,Z,this.now())){let B=J.lastRefreshError;if(B&&U0(B,J.refresh,this.now()))throw G=!0,Error(_$(B,this.now()));try{J=await this.refreshAccount(J,Z),X=!0}catch(K){if(i1(K))continue;G=!0;let Q=Z.accounts.find((H)=>H.id===Y.id&&a(H));if(Q&&!U0(Q.lastRefreshError,Q.refresh,this.now()))FZ(Q,K,this.now()),I(Z,Q),X=!0;throw K}}if(this.seedFallbackQuota(J,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),Z))z.push(J)}catch(B){let K=q2(J,this.now());if(G){if(!K)continue}else if(!K)continue;if(j2(J,Z,B,this.now()))x0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:G$(B)}),z.push(J);else if(!H$(Z))z.push(J)}}if(X){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{B$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:G$(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){B$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:G$(Z)})}}accountPassesQuotaPolicy($,Z){return c6($.quota,Z,this.now())}quotaPolicyAccount($){if(!this.quotaManager)return $;let Z=this.quotaManager.getFallback($.id,$.access)?.quota;return Z?{...$,quota:Z}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!V2($))return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!a(z))continue;if(J$($,z))continue;if(P0(z))continue;if(!R0(z,$,this.now()))continue;if(U0(z.lastRefreshError,z.refresh,this.now()))continue;try{x0.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){x0.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:G$(X)}),FZ(z,X,this.now()),I($,z),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!VZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!a(z))continue;if(J$($,z))continue;if(P0(z))continue;let X=z;try{if(R0(X,$,this.now())){if(U0(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,$),Z=!0}if(E0(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,$),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):y6(X,$,this.now())))continue;await this.refreshAccountQuota(X,$),Z=!0}catch(Y){QZ(z,Y,this.now()),I($,z),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),z=[];if(!Z||!VZ(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||!a(G))continue;if(J$(Z,G))continue;if(P0(G))continue;let J=G;try{if(R0(J,Z,this.now())){let B=J.lastRefreshError;if(B&&U0(B,J.refresh,this.now()))throw Error(_$(B,this.now()));J=await this.refreshAccount(J,Z),Y=!0}if(!X&&!y6(J,Z,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,I(Z,J),Y=!0;continue}await this.refreshAccountQuota(J,Z),Y=!0}catch(B){QZ(G,B,this.now()),I(Z,G),Y=!0,z.push({accountId:G.id,message:G$(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 I(Z,J),J}let Y=this.refreshAccountNow($,Z,z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let G=await Y;return I(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,z,X){let Y=Date.now()+S2;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,T2));let G=await this.load(),J=G?.accounts.find((Q)=>Q.id===$.id&&a(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||!R0(J,G,this.now())))return I(Z,J),x0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let K=J.lastRefreshError;if(K&&U0(K,J.refresh,this.now()))throw I(Z,J),Error(_$(K,this.now()))}return null}assertNotShieldedMainRow($,Z,z){if(z.asPoolMain||!Z)return;if(J$($,Z))throw new a6(Z.id)}async refreshAccountNow($,Z,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===$.id&&a(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!R0(Y,X,this.now()))return I(Z,Y),Y;let G=Y??$,J=await w({name:R2(G.id),ttlMs:x2,path:this.paths.configPath,renew:!0});if(!J){x0.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((H)=>H.id===$.id&&a(H)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!R0(Y,X,this.now()))return I(Z,Y),Y;if(!Y)throw new c$($.id);G=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});x0.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 K=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=K.access,G.refresh=K.refresh,G.expires=K.expires,G.lastRefreshedAt=K.expires-K.expiresIn*1000,G.lastRefreshError=void 0,I(Z,G),await this.save(Z),!(await this.load())?.accounts.some((H)=>H.id===$.id))throw new c$($.id);return x0.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,I(Z,z),await this.save(Z)}catch(G){throw QZ($,G,this.now()),I(Z,$),G}}}var o6=["primary","secondary"];function s$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function m0($){return typeof $==="number"&&Number.isFinite($)}function E2($,Z){if(!s$(Z))return;let z=Z.usedPercent;if(!m0(z)||z<0||z>100)return;return{label:$,usedPercent:z,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...m0(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function C2($){let Z=$.spendControl;if(s$(Z)&&typeof Z.reached==="boolean"){let z=(X)=>m0(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 I2($,Z){if(!s$($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...m0($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function vX($,Z,z){if(!s$($)||!m0(Z))return;let X=[],Y=[];for(let Q of o6){let H=E2(Q,$[Q]);if(H)X.push(H);else if(z)Y.push({label:Q})}let G=C2($),J=$.resetCreditsAvailable,B=typeof J==="number"&&Number.isSafeInteger(J)&&J>=0?{resetCredits:{value:J,checkedAt:Z}}:void 0,K=I2($.credits,Z);if(X.length===0&&Y.length===0&&!G&&!B&&!K)return;return{checkedAt:Z,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...B?{counters:B}:{},...K?{credits:K}:{}}}function r6($){if(!H0($))return;let Z=y($),z={};for(let X of o6){let Y=Z.limits.find((J)=>J.label===X&&J.kind==="reading");if(!Y||!m0(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 e6="main";function uX($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function iX($,Z,z){let X=new Map;if(i$(Z))for(let Y of $)X.set(Y.id,i6(r6(Y.quota),Z,Y.id===e6?void 0:Y.id,z));return X}var sX=5,k2=5000;function aX($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function nX($,Z=k2){let z=$.rows.filter((J)=>J.kind==="oauth"&&$.killswitch.get(J.id)!==!1&&y(J.quota).limits.length===0);if(z.length===0)return;if(g({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((J)=>$.killswitch.get(J.id)!==!1))return;let Y=[];if(g({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 a$($){return $.reason==="exhausted"||$.reason==="budget-spent"}function f2($,Z){if(!c($))return!1;let z=$;if(!(Z-z.checkedAt<=l0))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function n$($,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 K=y(B.quota);if(Q0(K,Z.now))return!1;return f2(K.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:J}}function b2($,Z=$.rows){return g({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class y2{#$=new Set;served($,Z,z){let X=b2($),Y=n$($.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 $8($,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 t6($,Z,z){if(Z.refused.find((Y)=>!a$(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return $8($[0],Z,z)}function oX($){let Z=$.replayable!==!1,z=$.mainId===void 0?e6:$.mainId??"",X=Z?$.placement:"main-first",Y=W3({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)=>a$(W)&&$.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=G.filter((W)=>J.has(W)),K=n$($.rows,$,Y.admission),Q=Y.order.filter((W)=>K.free.has(W)),H=G.filter((W)=>K.credits.includes(W));if(!Z){let W=G.includes(z),F=W?z:Q[0]??H[0]??Y.order[0]??B[0];if(F!==void 0&&Y.order.includes(F))return{kind:"send",order:[F],lastPath:!1};if(F!==void 0&&H.includes(F))return{kind:"send",order:[F],lastPath:!1};if(F!==void 0&&J.has(F))return{kind:"send",order:[F],lastPath:!0};return{kind:"block",block:W?$8(z,Y.admission,$.killswitch):t6(G,Y.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(H.length>0){let W=Y.order.length>0?Y.order:B;return{kind:"send",order:[...H,...W.filter((F)=>!H.includes(F))],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:t6(G,Y.admission,$.killswitch)}}function rX($){let Z=g({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=new Map;for(let X of $.rows)z.set(X.id,y(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 Z8($,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 F3({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 tX($,Z,z,X){let Y=Z8($,Z,{exclude:z,pendingBytes:X}),G=$.rows.filter((H)=>!z.has(H.id)),J=n$(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 K=J.credits[0];if(K===void 0)return B;let Q=y(G.find((H)=>H.id===K)?.quota).checkedAt;return{accountId:K,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function eX($,Z,z){let X=$.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},G=Z8($,Z,{pin:z}),J=n$($.rows,$,G.admission),B=J.credits.includes(z),K=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&&K)return Y;return{kind:"serve"}}let Q=G.admission.refused.find((W)=>W.id===z),H=X||Q!==void 0&&a$(Q);if(B)return{kind:"serve"};if(K)return H?Y:{kind:"detour"};if(!X&&Q&&a$(Q))return{kind:"last-path"};return{kind:"none"}}function $Y($,Z,z,X){let Y=$.killswitch.get(z);return V3({quota:Z.projections.get(z),now:$.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as z8}from"node:os";import{join as X8}from"node:path";var w2=["error","warn","info","debug","trace"];function h2(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?X8(z8(),"opencode-openai-auth","opencode-openai-auth.log"):X8(z8(),"opencode-openai-auth.log"))}function m2(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&w2.includes($)?$:void 0}Y8({file:h2,level:m2});if(process.once("beforeExit",async()=>{try{await o$()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>o$());
|
|
91
|
-
export{H0 as qd,p0 as rd,C8 as sd,G3 as td,D8 as ud,IZ as vd,M8 as wd,_8 as xd,y as yd,Q0 as zd,yZ as Ad,k8 as Bd,q$ as Cd,f8 as Dd,Q3 as Ed,b8 as Fd,u4 as Gd,i4 as Hd,a0 as Id,V as Jd,x as Kd,N0 as Ld,j9 as Md,O9 as Nd,S as Od,_0 as Pd,x4 as Qd,y9 as Rd,w9 as Sd,h9 as Td,h3 as Ud,g9 as Vd,w4 as Wd,p9 as Xd,T as Yd,O0 as Zd,YZ as _d,fz as $d,h8 as ae,d8 as be,pZ as ce,lZ as de,U0 as ee,_$ as fe,sZ as ge,nZ as he,a8 as ie,cZ as je,uZ as ke,O$ as le,o8 as me,q0 as ne,$9 as oe,Z9 as pe,z9 as qe,X9 as re,C7 as se,k7 as te,f7 as ue,b7 as ve,P0 as we,z$ as xe,XX as ye,YX as ze,QX as Ae,h as Be,B0 as Ce,a as De,p1 as Ee,SX as Fe,UZ as Ge,u1 as He,r1 as Ie,t1 as Je,AX as Ke,EX as Le,Q2 as Me,U2 as Ne,CX as Oe,c6 as Pe,i$ as Qe,IX as Re,u6 as Se,i6 as Te,kX as Ue,fX as Ve,F2 as We,J$ as Xe,n6 as Ye,bX as Ze,yX as _e,wX as $e,x2 as af,R2 as bf,A2 as cf,vX as df,r6 as ef,e6 as ff,uX as gf,iX as hf,sX as if,aX as jf,nX as kf,f2 as lf,y2 as mf,oX as nf,rX as of,tX as pf,eX as qf,$Y as rf};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a}from"./index-0bh5fs56.js";import"./index-tzrf3ax2.js";export default a();
|