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