@cortexkit/opencode-openai-auth 1.19.1 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +8 -8
- package/dist/{codex-request-Bj3F3fFg.d.ts → codex-request-Dvj28zFK.d.ts} +9 -2
- package/dist/{index-1ttg64ny.js → index-09rjj0qc.js} +2 -2
- package/dist/{index-3wr1ebxp.js → index-3yf405db.js} +2 -2
- package/dist/index-62e0dx41.js +101 -0
- package/dist/{index-62xhtkv8.js → index-h7veb7th.js} +1 -1
- package/dist/index-hybc4q33.js +2 -0
- package/dist/{index-663p60em.js → index-j5fk9tyk.js} +1 -1
- package/dist/index-mfvnmkrh.js +64 -0
- package/dist/{index-hsrx1pkq.js → index-q3j22pg7.js} +2 -2
- package/dist/{index-mbxq1g4n.js → index-qfer1qeq.js} +1 -1
- package/dist/{index-kgzevj7y.js → index-rrmycmen.js} +1 -1
- package/dist/index-tv6zrkss.js +75 -0
- package/dist/{index-977gx5br.js → index-vyc1q51y.js} +2 -2
- package/dist/{index-nrkvrvpw.js → index-x9h58tf9.js} +2 -2
- package/dist/{index-r6k6hh93.js → index-y9k6nshb.js} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-y3kre94n.js → token-t7hstws6.js} +1 -1
- package/dist/token-util-33bcnrmj.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 +2 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +31 -14
- package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +8 -3
- package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +34 -13
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +31 -14
- package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +8 -3
- package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +34 -13
- package/dist/index-34r6y4jf.js +0 -64
- package/dist/index-8km6f9bq.js +0 -2
- package/dist/index-ckkhe4r4.js +0 -76
- package/dist/index-jk0zyyny.js +0 -101
- package/dist/token-util-kwahm03g.js +0 -1
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import{_f as G0,bg as g,cg as N$,dg as e,eg as M$,fg as E3,gg as C0,hg as rZ,kg as k3}from"./index-x9h58tf9.js";import{Bg as j1,Cg as TZ,Dg as xZ,Fg as q3}from"./index-rrmycmen.js";import{Lg as yZ,Mg as wZ,Ng as p}from"./index-09rjj0qc.js";import{Og as Q0,Pg as B0,Sg as B9,Ug as g0,Vg as QZ,Zg as G9}from"./index-hybc4q33.js";var E="all",mZ=Object.freeze(["primary"]);function G8($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function r0($,Z){return JSON.stringify([$,Z])}function q0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function m($){return typeof $==="number"&&Number.isFinite($)}function B8($){return typeof $==="string"&&$.length>0}function v($,Z,X){return $[Z]===void 0||X($[Z])}function R1($){return m($)&&$>0}function hZ($){return typeof $==="string"}function T1($){if(!q0($)||!B8($.scope)||!B8($.label))return!1;switch($.kind){case"reading":return m($.checkedAt)&&m($.usedPercent)&&v($,"resetsAt",hZ)&&v($,"windowMinutes",R1);case"retired":return m($.retiredAt);case"absent":return m($.checkedAt);default:return!1}}function x1($){if(!q0($)||!m($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&v($,"remainingPercent",m)&&v($,"usedPercent",m)&&v($,"resetsAt",hZ)&&v($,"limit",m)&&v($,"used",m)&&v($,"remaining",m)&&v($,"unit",hZ)}function H8($){return q0($)&&m($.value)&&Number.isInteger($.value)&&$.value>=0&&m($.checkedAt)}function vZ($){return q0($)&&Object.values($).every(H8)}function A1($){return typeof $==="boolean"}function J0($){return q0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&v($,"balance",m)&&v($,"overageLimitReached",A1)&&m($.checkedAt)}function gZ($){if(!q0($))return;let Z=Object.entries($).filter(([,X])=>H8(X));return Z.length===0?void 0:Object.fromEntries(Z)}function E0($){if(A0($))return $;if(!q0($))return;let{counters:Z,credits:X,...z}=$;if(!A0(z))return;let Y=gZ(Z),J=J0(X)?X:void 0;return{...z,...Y===void 0?{}:{counters:Y},...J===void 0?{}:{credits:J}}}function A0($){if(!q0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!T1(X))return!1;let z=r0(X.scope,X.label);if(Z.has(z))return!1;Z.add(z)}return v($,"budget",x1)&&v($,"counters",vZ)&&v($,"credits",J0)}var D8=900000,V8="no quota reading yet",q8="no limits reported";function N8($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let Y=Math.floor(Z/60),J=Z%60;return J===0?`${Y}h`:`${Y}h${J}m`}let X=Math.floor(Z/1440),z=Math.floor(Z%1440/60);return z===0?`${X}d`:`${X}d${z}h`}function M8($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function pZ($){if($.scope!==E||$.windowMinutes===void 0)return $.label;return M8($.windowMinutes)}function dZ($){return Math.min(100,Math.max(0,$))}function l$($){return Math.round(dZ($))}function K8($){return`${l$($)}% left`}function Q8($,Z,X){let z=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(z)&&z>X?{resetIn:N8(z-X)}:{},resetSinceReading:Number.isFinite(z)&&z>Z&&z<=X}}function E1($,Z){let X=$.windowMinutes,z=Z.windowMinutes;if(X!==void 0&&z!==void 0&&X!==z)return X-z;if(X===void 0!==(z===void 0))return X===void 0?1:-1;if($.scope!==Z.scope){if($.scope===E)return-1;if(Z.scope===E)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function S1($){let Z=_8($.filter(({part:X,scope:z})=>X.kind==="window"&&z!==E).map(({scope:X})=>X));for(let X of $)X.part.short=X.part.kind==="budget"?"cr":X.scope===E?X.part.name:Z.get(X.scope)??X.scope;return $}function W8($){return Number.isFinite($.remainingPercent)&&Number.isFinite($.checkedAt)}function lZ($,Z,X=!1){if(!$)return{windows:[]};let{now:z}=Z,J=$.limits.filter((H)=>H.kind==="reading"&&(X||W8(H))).sort(E1).map((H)=>{let K=W8(H)?{kind:"window",reading:"known",name:pZ(H),short:"",figure:K8(H.remainingPercent),remainingPercent:dZ(H.remainingPercent),checkedAt:H.checkedAt,...Q8(H.resetsAt,H.checkedAt,z)}:{kind:"window",reading:"unknown",name:pZ(H),short:"",figure:"no reading",resetSinceReading:!1};return{scope:H.scope,...H.windowMinutes===void 0?{}:{windowMinutes:H.windowMinutes},part:K}}),B=$.budget;if(B){let H=B.remainingPercent,K=B.reached?"credits spent":H!==void 0?`credits ${K8(H)}`:"credits available";J.push({scope:E,spent:B.reached,part:{kind:"budget",reading:"known",name:"credits",short:"",figure:K,...H===void 0?{}:{remainingPercent:dZ(H)},checkedAt:B.checkedAt,...Q8(B.resetsAt,B.checkedAt,z)}})}S1(J);let G=J.flatMap(({part:H})=>H.reading==="known"&&H.checkedAt!==void 0?[H.checkedAt]:[]);if(G.length>0){let H=z-Math.min(...G);if(H>(Z.staleAfterMs??D8))return{windows:J,age:`checked ${N8(H)} ago`}}return{windows:J}}function C1($,Z){return lZ($,Z).age!==void 0}function U8($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function _8($){let Z=[...new Set($.map(U8))],X=new Map(Z.map((Y)=>[Y,2])),z=(Y)=>Y.slice(0,X.get(Y));for(;;){let Y=new Map;for(let B of Z)Y.set(z(B),[...Y.get(z(B))??[],B]);let J=!1;for(let B of Y.values()){if(B.length<2)continue;for(let G of B){let H=X.get(G)??2;if(H<G.length)X.set(G,H+1),J=!0}}if(!J)break}return new Map($.map((Y)=>[Y,z(U8(Y))]))}var I1=2;function b1($){let Z=$.map((z)=>z.label.trim()||z.scope),X=_8(Z);return Z.map((z)=>X.get(z)??z)}function k1($,Z){if(!$||$.length===0)return;let X=Z.filter(({part:G})=>G.kind==="window");if(X.some(({scope:G})=>G===E))return;let z=$.flatMap((G,H)=>{let W=X.filter(({scope:Q})=>Q===G.scope).reduce((Q,U)=>Q===void 0||(U.part.remainingPercent??0)<(Q.part.remainingPercent??0)?U:Q,void 0);return W?[{group:G,listed:H,window:W}]:[]});if(z.length===0)return;let Y=b1($),J=(G)=>G.window.part.remainingPercent??0,B=[...z].sort((G,H)=>J(G)-J(H)||G.listed-H.listed).slice(0,I1).sort((G,H)=>G.listed-H.listed);return B.map((G,H)=>{let{windowMinutes:K}=G.window,W=[Y[G.listed]??G.group.scope,...K===void 0?[]:[M8(K)],`${l$(J(G))}%`].join(" ");return H===B.length-1?`${W} left`:W})}function f1($,Z){let{windows:X}=lZ($,Z),z=k1($?.groups,X);if(z)return z;let Y=X.filter(({part:Q,scope:U})=>Q.kind==="window"&&U===E),J=X.filter(({part:Q,scope:U})=>Q.kind==="window"&&U!==E),B=X.find(({part:Q})=>Q.kind==="budget"),G=B?.spent?0:B?.part.remainingPercent,K=[...J.map(({part:Q})=>({label:Q.short,remaining:Q.remainingPercent??0})),...G===void 0||B===void 0?[]:[{label:B.part.short,remaining:G}]].reduce((Q,U)=>Q===void 0||U.remaining<Q.remaining?U:Q,void 0),W=Y.map(({part:Q})=>`${Q.name} ${l$(Q.remainingPercent??0)}%`);if(K)W.push(`${K.label} ${l$(K.remaining)}%`);if(W.length===0)return X.map(({part:Q})=>Q.figure);return W.map((Q,U)=>U===W.length-1?`${Q} left`:Q)}function F8($,Z){if(Z.form==="narrow")return f1($,Z);let{windows:X,age:z}=lZ($,Z),Y=(Z.form??"full")==="full",J=X.map(({part:B})=>{let G=Y&&B.resetIn?`, resets ${B.resetIn}`:"";return`${B.kind==="budget"?"":`${B.name} `}${B.figure}${G}`});return z===void 0?J:[...J,z]}function y1($,Z){let X=F8($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?q8:V8}function w1($){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 h1($){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 m1($,Z){let X=$.windowMinutes!==void 0,z=Z.windowMinutes!==void 0;if(X!==z)return X?-1:1;if(X&&z&&$.windowMinutes!==Z.windowMinutes)return(Z.windowMinutes??0)-($.windowMinutes??0);if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function v1($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function s($,Z=E){let X=new Map;for(let W of $?.limits??[]){if(W.scope!==Z&&W.scope!==E)continue;let Q=X.get(W.label);if(Q===void 0){X.set(W.label,W);continue}let U=W.scope===E?Q:W,D=W.scope===E?W:Q;X.set(W.label,U.kind==="reading"?U:D)}let z=[...X.values()].map(h1).sort(m1),Y=z.filter((W)=>W.kind==="reading"),J=Y.length>0?Y:z,B=J.length>0?Math.min(...J.map((W)=>W.checkedAt)):void 0,G=$?.budget?.kind==="reading"?v1($.budget):void 0,H=gZ($?.counters),K=J0($?.credits)?$.credits:void 0;return{scope:Z,limits:z,...B===void 0?{}:{checkedAt:B},...G===void 0?{}:{budget:G},...H===void 0?{}:{counters:H},...K===void 0?{}:{credits:K}}}function S0($,Z){let X=$?.budget;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let z=Date.parse(X.resetsAt);if(!Number.isFinite(z)||z<=Z)return;return{resetsAt:X.resetsAt,resetAtMs:z}}function c$($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function U$($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}class u$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function s$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function i$($){return typeof $==="number"&&Number.isFinite($)}function L8($){return $===void 0||typeof $==="string"&&$!==""}function O8($){return typeof $==="string"&&$!==""}function D$($,Z){return $[Z]===void 0||i$($[Z])}function cZ($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function g1($){return s$($)&&L8($.scope)&&O8($.label)&&i$($.usedPercent)&&cZ($,"resetsAt")&&($.windowMinutes===void 0||i$($.windowMinutes)&&$.windowMinutes>0)}function p1($){return s$($)&&L8($.scope)&&O8($.label)}function d1($){if(!s$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&D$($,"remainingPercent")&&D$($,"usedPercent")&&cZ($,"resetsAt")&&D$($,"limit")&&D$($,"used")&&D$($,"remaining")&&cZ($,"unit")}function t0($){if(!s$($)||!i$($.checkedAt))return!1;let Z=$.readings??[],X=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(X))return!1;let z=new Set;for(let Y of Z){if(!g1(Y))return!1;let J=r0(Y.scope??E,Y.label);if(z.has(J))return!1;z.add(J)}if(!X.every(p1))return!1;return($.budget===void 0||d1($.budget))&&($.counters===void 0||vZ($.counters))&&($.credits===void 0||J0($.credits))}function l1($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function c1($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function u1($,Z){let X=new Map(Object.entries($??{}));for(let[z,Y]of Object.entries(Z??{})){let J=X.get(z);if(J===void 0||Y.checkedAt>=J.checkedAt)X.set(z,Y)}return X.size===0?void 0:Object.fromEntries(X)}function i1($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function V$($,Z){let X=$===void 0?void 0:E0($);if($!==void 0&&X===void 0)throw new u$("stored quota map is malformed");if(!t0(Z))throw new u$("quota observation is malformed");let z=X??{limits:[]},Y=Z.checkedAt,J=new Map;for(let N of z.limits)J.set(r0(N.scope,N.label),N);let B=(N)=>{let R=J.get(N);return R===void 0||Y>=G8(R)},G=new Set;for(let N of Z.readings??[]){let R=N.scope??E,x=r0(R,N.label);if(G.add(x),!B(x))continue;J.set(x,{scope:R,label:N.label,kind:"reading",checkedAt:Y,usedPercent:N.usedPercent,...N.resetsAt===void 0?{}:{resetsAt:N.resetsAt},...N.windowMinutes===void 0?{}:{windowMinutes:N.windowMinutes}})}for(let N of Z.coverage??[]){let R=N.scope??E,x=r0(R,N.label);if(G.has(x)||!B(x))continue;let L=J.get(x);J.set(x,L===void 0||L.kind==="absent"?{scope:R,label:N.label,kind:"absent",checkedAt:Y}:{scope:R,label:N.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:K,counters:W,credits:Q,...U}=z,D=c1(z.budget,Z.budget,Y),V=u1(z.counters,Z.counters),_=i1(z.credits,Z.credits);return{...U,limits:[...J.values()].sort(l1),...D===void 0?{}:{budget:D},...V===void 0?{}:{counters:V},..._===void 0?{}:{credits:_}}}var s1=Object.freeze({validate:A0,decode:E0,merge:V$});function P8($,Z,X){let z=Z.rateLimitMarks?.get($);if(z!==void 0&&X<z)return{id:$,reason:"rate-limited",until:z};let Y=Z.refreshBackoff?.get($);if(Y!==void 0&&X<Y)return{id:$,reason:"refresh-backoff",until:Y};return}function a1($,Z,X,z,Y){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let B of X)if(!Z.limits.some((G)=>G.label===B))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:B},pullRequested:!0};let J=Z.limits.filter(c$);for(let B of J)if(U$(B,z)===void 0&&!Y.some((G)=>G.scope===B.scope&&G.label===B.label))return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:B.scope,label:B.label},pullRequested:!0};for(let B of J){let G=U$(B,z);if(G!==void 0&&typeof B.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:B.scope,label:B.label},resetsAt:B.resetsAt,resetAtMs:G}}return}function t($){let Z=$.scope??E,X=$.requiredLabels??mZ,z=[],Y=[],J=[],B=new Set;for(let D of $.rows){let V=P8(D.id,$,$.now);if(V){z.push(V);continue}if(D.kind==="api-key"){J.push({id:D.id,kind:D.kind});continue}let _=s(D.quota,Z),N=$.liftedWindows?.get(D.id)??[];if(_.limits.some((x)=>c$(x)&&U$(x,$.now)===void 0&&N.some((L)=>L.scope===x.scope&&L.label===x.label)))B.add(D.id);let R=a1(D.id,_,X,$.now,N);if(R){Y.push(R);continue}J.push({id:D.id,kind:D.kind,projection:_})}let G=new Map(J.flatMap((D)=>{let V=S0(D.projection,$.now);return V?[[D.id,V]]:[]})),H=G.size>0&&G.size===J.length,K=[];for(let D of J){let V=G.get(D.id);if(V===void 0)K.push(D);else if(H)K.push({...D,lastPath:!0});else Y.push({id:D.id,stage:2,reason:"budget-spent",...V})}let W=new Map($.rows.map((D,V)=>[D.id,V])),Q=(D,V)=>(W.get(D.id)??0)-(W.get(V.id)??0);Y.sort(Q);for(let D of Y)if("pullRequested"in D)B.add(D.id);let U=$.rows.filter((D)=>B.has(D.id)).map((D)=>D.id);for(let D of U)$.requestPull?.(D);return{admitted:K,refused:Y,excluded:z,pulls:U}}var j8="main";function n1($){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 a$($,Z,X=j8){if(Z==="roster"||!$.includes(X))return[...$];let z=$.filter((Y)=>Y!==X);return Z==="main-first"?[X,...z]:[...z,X]}function uZ($){let Z=t($),X=new Set(Z.admitted.map((Y)=>Y.id));return{order:a$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>X.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function o1($,Z,X){let z=Z.at(-1);if(z!==void 0){if(z.status===void 0||!X.includes(z.status))return}let Y=new Set(Z.map((J)=>J.id));return $.find((J)=>!Y.has(J))}function iZ($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function r1($,Z,X){let z=new Map;for(let[Y,J]of $){if(Y===X)continue;if(J.quotaCheckedAt!==Z.get(J.accountId))continue;z.set(J.accountId,(z.get(J.accountId)??0)+(J.inputBytes??0))}return z}var q$=900000,T8=0.016666666666666666,sZ=0.000001;function n$($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function x8($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function A8($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,X)=>{let z=Z.windowMinutes!==void 0,Y=X.windowMinutes!==void 0;if(z!==Y)return z?-1:1;if(z&&Y)return(X.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function nZ($){let Z=($.classifyStatus??x8)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=n$($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>q$)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of A8($.quota)){let J=Y.remainingPercent;if(typeof J==="number"&&Number.isFinite(J)&&J<=0)return{action:"migrate",reason:"exhausted",window:{scope:Y.scope,label:Y.label},...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{}}}let z=S0($.quota,$.now);if(z)return{action:"migrate",reason:"exhausted",resetsAt:z.resetsAt};return{action:"retain",reason:Z}}function aZ($,Z,X){let z=Math.max(0,$.remainingPercent-Z);if(z<=0)return 0;if(!$.resetsAt)return z;let Y=Date.parse($.resetsAt);if(!Number.isFinite(Y)||Y<=X)return z;let J=Math.max((Y-X)/3600000,T8);return z/J}function R8($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function t1($,Z){if(!$.quota)return;let X=n$($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>q$)return;let z=A8($.quota).map((B)=>aZ({remainingPercent:B.remainingPercent??Number.NaN,...B.resetsAt===void 0?{}:{resetsAt:B.resetsAt}},$.reservePercent[B.label]??0,Z)),Y=$.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))z.push(aZ({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,Z));let J=z.length>0?Math.min(...z):0;return J>0?{candidate:$,quotaCheckedAt:X,weight:J}:void 0}function E8($){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 X=Z.map((Y)=>t1(Y,$.now)).filter((Y)=>Y!==void 0);if(X.length>0){X.sort((J,B)=>{let G=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,sZ),H=(($.pendingBytes.get(B.candidate.accountId)??0)+$.requestBytes)/Math.max(B.weight,sZ);return G-H||J.candidate.configuredOrder-B.candidate.configuredOrder||R8(J.candidate.accountId,B.candidate.accountId)});let Y=X[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let z=[...Z].sort((Y,J)=>{let B=(Y.resetCreditsApplicable??0)>0?1:0;return((J.resetCreditsApplicable??0)>0?1:0)-B||Y.configuredOrder-J.configuredOrder||R8(Y.accountId,J.accountId)})[0];if(!z)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:z.accountId,quotaCheckedAt:n$(z.quota,z.quotaCheckedAt),source:"mode-fallback"}}function oZ($){let Z=t($),X=new Map(Z.admitted.map((V)=>[V.id,V])),z=new Map(Z.refused.map((V)=>[V.id,V])),Y=new Set(Z.excluded.map((V)=>V.id)),J=new Set($.rows.map((V)=>V.id)),B=$.pin!==void 0&&iZ($.pin,J,$.identities?.get($.pin.accountId));if(B&&$.pin){let V=X.get($.pin.accountId);if(V&&$.killswitch?.get(V.id)!==!1)return{outcome:"dispatch",accountId:V.id,source:"pin",...V.projection?.checkedAt===void 0?{}:{quotaCheckedAt:V.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let G=$.pin?z.get($.pin.accountId):void 0,H=B&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||G?.reason==="exhausted"||G?.reason==="budget-spent"),K=(V)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(V):$.rowReservePercent?.get(V.id))??$.reservePercent??{}},W=$.scope,Q=$.rows.map((V,_)=>({row:V,configuredOrder:_})).filter(({row:V})=>!Y.has(V.id)).map(({row:V,configuredOrder:_})=>{let N=$.killswitch?.get(V.id),R=$.resetCreditsApplicable?.get(V.id);return{accountId:V.id,quota:V.kind==="api-key"?void 0:X.get(V.id)?.projection??s(V.quota,W),reservePercent:K(V),configuredOrder:_,...R===void 0?{}:{resetCreditsApplicable:R},...N===void 0?{}:{killswitchPasses:N}}}),U=[],D=B?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(Q.length>0){let V=E8({candidates:Q,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!V)break;let _=z.get(V.accountId);if(_){U.push(_),Q=Q.filter((R)=>R.accountId!==V.accountId);continue}let N=$.identities?.get(V.accountId);return{outcome:"dispatch",accountId:V.accountId,source:V.source,...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt},pin:B&&!H?{action:"retain"}:{action:"assign",pin:{accountId:V.accountId,inputBytes:$.requestBytes,...N===void 0?{}:{wireIdentity:N},...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt}}},refusedSelections:U,admission:Z}}return{outcome:"no-admissible-account",pin:D,refusedSelections:U,admission:Z}}import{createHash as e1}from"node:crypto";var $2=86400000,Z2=300000,X2=3600000,z2=60000,Y2=900000,J2=300000;function tZ($){return $ instanceof Error?$.message:String($)}function B2($){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 eZ($){let Z=tZ($),X=$?.status;if(typeof X==="number")return X===429||X>=500;if(!($ instanceof Error))return!1;let z=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||z==="ECONNRESET"||z==="ECONNREFUSED"||z==="ETIMEDOUT"||z==="UND_ERR_CONNECT_TIMEOUT"}function S8($){return e1("sha256").update($).digest("hex")}function C8($){let Z=S8($.refreshToken),z=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,Y,J=$.error?.retryAfter;if(typeof J==="number"&&J>0)Y=J*1000;else if(B2($.error))Y=Math.min(X2,Z2*2**Math.min(z-1,6));else Y=$2;return{message:tZ($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:z,tokenHash:Z}}function I0($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===S8(Z)}function o$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function _$($){let X=($.previous?.retryCount??0)+1,z,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)z=Y*1000;else if(eZ($.error))z=Math.min(Y2,z2*2**Math.min(X-1,6));else z=J2;return{message:tZ($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:X}}function e0($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function $6($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let X=Date.parse($);if(Number.isFinite(X)){let z=Math.ceil((X-Date.now())/1000);return z>0?z:void 0}return}import{createServer as I8}from"node:http";import{setTimeout as G2}from"node:timers/promises";var $Z="app_EMoamEEZ73f0CkXaXp7hrann",f0="https://auth.openai.com",L$=1455,H2=3000,K2="cortexkit-opencode-openai-auth";function y8($){return`${K2}/${$}`}var w8="main",Q2=`"${w8}" is a reserved account id; choose a different label.`;function h8($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function W2(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),X=h8(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function b8($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let X=Z[1];if(!X||X.length>8192)return;try{return JSON.parse(Buffer.from(X,"base64url").toString())}catch{return}}function k8($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let X=$["https://api.openai.com/auth"];if(X&&typeof X==="object"&&!Array.isArray(X)&&typeof X.chatgpt_account_id==="string"&&X.chatgpt_account_id.length>0)return X.chatgpt_account_id;let z=$.organizations;if(Array.isArray(z)){let Y=z[0];if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string"&&Y.id.length>0)return Y.id}return}function t$($){if($.id_token){let Z=b8($.id_token),X=Z&&k8(Z);if(X)return X}if($.access_token){let Z=b8($.access_token);return Z?k8(Z):void 0}return}function U2($){return typeof $==="string"&&$.toLowerCase()===w8}function Z6($){if(U2($))throw Error(Q2);return $}function D2($,Z,X){let z=new URLSearchParams({response_type:"code",client_id:$Z,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:X,originator:"opencode"});return`${f0}/oauth/authorize?${z.toString()}`}async function V2($,Z,X){let z=await fetch(`${f0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:$Z,code_verifier:X.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function q2($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var N2=`<!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>`,r$=($)=>`<!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">${q2($)}</div>
|
|
85
|
+
</div>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`,e$=[],F$,H0=new Map;function f8($,Z){return new Promise((X,z)=>{let Y=(B)=>{$.off("listening",J),z(B)},J=()=>{$.off("error",Y),X()};$.once("error",Y),$.once("listening",J),$.listen(L$,Z)})}function m8($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function b0(){return H0.size}function y0($){if(H0.delete($),b0()===0)k0()}async function M2(){let $=`http://localhost:${L$}/auth/callback`;if(e$.length>0)return{port:L$,redirectUri:$};if(F$)return F$;F$=(async()=>{let Z=(J,B)=>{let G=new URL(J.url||"/",`http://127.0.0.1:${L$}`);if(G.pathname==="/auth/callback"){let H=G.searchParams.get("code"),K=G.searchParams.get("state"),W=G.searchParams.get("error"),Q=G.searchParams.get("error_description");if(W){let D=Q||W;if(K){let V=H0.get(K);if(V)V.reject(Error(D)),y0(K);else if(b0()===0)k0()}else if(b0()===0)k0();B.writeHead(200,{"Content-Type":"text/html"}),B.end(r$(D));return}if(!K){if(b0()===0)k0();B.writeHead(400,{"Content-Type":"text/html"}),B.end(r$("Missing state parameter"));return}if(!H){if(b0()===0)k0();B.writeHead(400,{"Content-Type":"text/html"}),B.end(r$("Missing authorization code"));return}let U=H0.get(K);if(!U){if(b0()===0)k0();B.writeHead(400,{"Content-Type":"text/html"}),B.end(r$("Unknown state — authorization may have expired"));return}y0(K),V2(H,$,U.pkce).then((D)=>U.resolve(D)).catch((D)=>U.reject(D)),B.writeHead(200,{"Content-Type":"text/html"}),B.end(N2);return}if(G.pathname==="/cancel"){let H=G.searchParams.get("state"),K=H?[H]:[...H0.keys()];B.writeHead(200),B.end("Login cancelled");for(let W of K){let Q=H0.get(W);if(!Q)continue;Q.reject(Error("Login cancelled")),y0(W)}if(b0()===0)k0();return}B.writeHead(404),B.end("Not found")},X=I8(Z);await f8(X,"127.0.0.1");let z=[X],Y=I8(Z);try{await f8(Y,"::1"),z.push(Y)}catch(J){let B=J.code;if(B!=="EADDRNOTAVAIL"&&B!=="EAFNOSUPPORT")throw m8(X),J}return e$=z,{port:L$,redirectUri:$}})();try{return await F$}finally{F$=void 0}}function k0(){let $=e$;e$=[];for(let Z of $)m8(Z)}function _2($,Z,X=300000,z){return new Promise((Y,J)=>{if(z?.aborted){y0(Z),J(Error("Login cancelled"));return}let B=setTimeout(()=>{if(H0.get(Z))y0(Z),J(Error("OAuth callback timeout — authorization took too long"))},X),G=()=>{if(clearTimeout(B),H0.get(Z))y0(Z),J(Error("Login cancelled"))};if(z)z.addEventListener("abort",G);H0.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(B),z)z.removeEventListener("abort",G);Y(H)},reject:(H)=>{if(clearTimeout(B),z)z.removeEventListener("abort",G);J(H)}})})}async function F2($){let Z=await fetch(`${f0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y8($)},body:JSON.stringify({client_id:$Z})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${f0}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function L2($,Z,X){let z=Math.max(parseInt($.interval,10)||5,1)*1000,Y=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),J=!Number.isNaN(Y)&&Y>0?Y*1000:900000,B=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-B>J)throw Error("Device authorization expired");let G=await fetch(`${f0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y8(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(G.ok){let W=await G.json(),Q=await fetch(`${f0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:W.authorization_code,redirect_uri:`${f0}/deviceauth/callback`,client_id:$Z,code_verifier:W.code_verifier}).toString()});if(!Q.ok)throw Error(`Token exchange failed: ${Q.status}`);return await Q.json()}if(G.status!==403&&G.status!==404)throw Error(`Device authorization failed: ${G.status}`);let H=J-(Date.now()-B);if(H<=0)throw Error("Device authorization expired");let K=Math.min(z+H2,H);try{await G2(K,void 0,{signal:X})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function hX($){let{label:Z,headless:X=!1,signal:z,version:Y}=$;if(Z6(Z),X){let{deviceData:W,url:Q,instructions:U}=await F2(Y),D=(async()=>{let V=await L2(W,Y,z),_=Date.now(),N=t$(V);return{id:Z6(Z||N||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:_+(V.expires_in??3600)*1000,enabled:!0,addedAt:_,lastUsed:_,lastRefreshedAt:_,accountId:N}})();return{url:Q,instructions:U,completion:D}}let{redirectUri:J}=await M2(),B=await W2(),G=h8(crypto.getRandomValues(new Uint8Array(32)).buffer),H=D2(J,B,G),K=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let W=await _2(B,G,void 0,z),Q=Date.now(),U=t$(W);return{id:Z6(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:W.access_token,refresh:W.refresh_token,expires:Q+(W.expires_in??3600)*1000,enabled:!0,addedAt:Q,lastUsed:Q,lastRefreshedAt:Q,accountId:U}}finally{y0(G)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:K}}function ZZ($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let z=Z<100000000000?Z*1000:Z,Y=new Date(z);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let X=new Date($);return Number.isNaN(X.getTime())?void 0:X.toISOString()}function X6($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function v8($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function g8($,Z){let X=$.get(Z);if(X===null||X.trim()==="")return;let z=Number(X);if(!Number.isFinite(z)||z<0||z>100)return;let Y=Z.slice(0,-13),J=X6($.get(`${Y}-window-minutes`)),B=ZZ($.get(`${Y}-reset-at`)??void 0);if(z===0&&$.get(`${Y}-window-minutes`)==="0"&&!B)return;return{usedPercent:z,remainingPercent:100-z,resetsAt:B,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}var c8=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function u8($,Z){let X=$.get(Z);if(X===null)return"absent";if(X.trim()==="")return"invalid";let z=Number(X);return Number.isFinite(z)&&z>=0&&z<=100?"valid":"invalid"}function vX($){if(c8.some((J)=>u8($,J)==="invalid"))return{};let Z={},X=g8($,"x-codex-primary-used-percent");if(X)Z.primary=X;let z=g8($,"x-codex-secondary-used-percent");if(z)Z.secondary=z;let Y=O2($);if(Y)Z.credits=Y;return Z}function p8($,Z){let X=$.get(Z)?.trim();if(X===void 0)return;if(X.toLowerCase()==="true"||X==="1")return!0;if(X.toLowerCase()==="false"||X==="0")return!1;return}function O2($){let Z=p8($,"x-codex-credits-has-credits"),X=p8($,"x-codex-credits-unlimited");if(Z===void 0||X===void 0)return;let z=N0($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:X,...z!==void 0?{balance:z}:{},checkedAt:Date.now()}}function gX($){let Z=c8.map((X)=>u8($,X));return Z.includes("valid")&&!Z.includes("invalid")}function d8($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=X6($.window_minutes),X=ZZ($.reset_at);if($.used_percent===0&&Z===void 0&&!X)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:X,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function pX($){let Z={},X=d8($.rate_limits?.primary);if(X)Z.primary=X;let z=d8($.rate_limits?.secondary);if(z)Z.secondary=z;let Y=P2($.credits);if(Y)Z.credits=Y;return Z}function P2($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let X=N0(typeof Z.balance==="string"?Z.balance.trim():Z.balance);return{hasCredits:Z.has_credits,unlimited:Z.unlimited,...X!==void 0?{balance:X}:{},...typeof Z.overage_limit_reached==="boolean"?{overageLimitReached:Z.overage_limit_reached}:{},checkedAt:Date.now()}}function N0($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function l8($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=X6($.limit_window_seconds),X=ZZ($.reset_at);if($.used_percent===0&&Z===void 0&&!X)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:X,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function i8($){let Z={},X=l8($.rate_limit?.primary_window);if(X)Z.primary=X;let z=l8($.rate_limit?.secondary_window);if(z)Z.secondary=z;let Y=v8($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let J=v8($.rate_limit_reset_credits?.applicable_available_count);if(J!==void 0)Z.resetCreditsApplicable=J;let B=$.spend_control?.individual_limit;if($.spend_control===null||B===null)Z.spendControlCleared=!0;if(B&&typeof $.spend_control?.reached==="boolean"){let H=N0(B.limit),K=N0(B.used),W=N0(B.remaining),Q=N0(B.used_percent),U=N0(B.remaining_percent);if(H!==void 0&&K!==void 0&&W!==void 0&&Q!==void 0&&U!==void 0)Z.spendControl={limit:H,used:K,remaining:W,usedPercent:Q,remainingPercent:U,resetsAt:ZZ(B.reset_at),unit:B.unit,source:B.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 H=N0(G.balance);Z.credits={hasCredits:G.has_credits,unlimited:G.unlimited,overageLimitReached:G.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as h4}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as j2}from"@cortexkit/claustrum-client";import{SocketClosedError as R2,SocketTimeoutError as T2,SubcCallError as x2}from"@cortexkit/subc-client";class q extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var z6=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 S extends q{reason;constructor($){super("unavailable","Claustrum vault could not be reached");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function a($){if($ instanceof S||$ instanceof R2||$ instanceof T2)return"unreachable";let Z=$ instanceof j2||$ instanceof x2?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(z6,Z))return"answered";return z6[Z]}import{resolve as s8}from"node:path";import{storeIdentity as A2}from"@cortexkit/claustrum-client";import{SubcClient as a8}from"@cortexkit/subc-client";var $$=300000,XZ=300000,Y6=1000;class O${#$;#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 zZ{#$;#Z;#B;#G=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#B}request(){if(this.#B)return this.#G=!0,this.#B;return this.#B=(async()=>{do{this.#G=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#G)})().finally(()=>{this.#B=void 0}),this.#B}}class YZ{#$;#Z=new O$;#B;#G="polling";#z;#H;#Y=!1;#X;#Q=!1;#J=0;constructor($){this.#$=$,this.#B=new zZ(async()=>{let Z=this.#Q;if(this.#Q=!1,Z||this.#X!==this.#$.view())await this.#$.discover(this.#X??"")},(Z)=>{if(!this.#Y)this.#$.onError?.(Z)})}get mode(){return this.#G}start(){if(this.#Y||this.#z||this.#H)return;if(typeof this.#$.client.watchScoped!=="function"){this.#U("fallback","client-without-watch");return}this.#M(!1)}stop(){if(this.#Y)return;if(this.#Y=!0,this.#H)(this.#$.clearTimeoutImpl??clearTimeout)(this.#H);this.#H=void 0;let $=this.#z;this.#z=void 0,$?.handle.stop()}#U($,Z){if(this.#G===$)return;this.#G=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#D($,Z){this.#H=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#H=void 0,!this.#Y)Z()},$),this.#H.unref?.()}async#M($){let Z;try{Z=await this.#$.enrollmentToken()}catch(B){if(this.#Y)return;this.#$.onError?.(B),this.#_("token-unreadable");return}let X=this.#$.client.watchScoped;if(this.#Y||this.#z||!X)return;this.#Z.restart(),this.#Q=$;let z,Y;try{Y=X.call(this.#$.client,(B)=>{if(this.#Y||!z||this.#z!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#U("watching","accepted");if(!this.#Z.continuous(B))this.#Q=!0;this.#X=B.view,this.#B.request()},{enrollmentToken:Z})}catch(B){this.#$.onError?.(B),this.#_("watch-failed");return}z={handle:Y,notices:0},this.#z=z,this.#U("polling",$?"resubscribing":"opening");let J=z;Y.closed.then((B)=>this.#W(J,B),(B)=>this.#W(J,{kind:"transport_lost",error:B}))}#W($,Z){if(this.#Y||this.#z!==$)return;if(this.#z=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#U("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#_("refused");try{this.#$.onRefused(Z.error)}catch(X){this.#$.onError?.(X)}return}if($.notices>0){let X=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&X-$.acceptedAt>=300000)this.#J=0;let z=Math.min(1000*2**Math.min(this.#J,16),300000);this.#J++,this.#U("polling","resubscribing"),this.#D(z,()=>void this.#M(!0));return}this.#_(Z.kind)}#_($){this.#U("fallback",$),this.#D(300000,()=>void this.#M(!1))}}function o8($){let Z=$.identity??A2($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let X,z=!1,Y,J=new Promise((G,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),B=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await a8.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),z)throw X.close(),Error("insula usage timeout");let G=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(G,{method:"usage.get",params:{}})})();try{return await Promise.race([B,J])}finally{z=!0,clearTimeout(Y),X?.close()}},watchUsage(X){let z,Y,J=!1,B=(async()=>{let G,H=new Promise((W,Q)=>{G=setTimeout(()=>Q(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),G.unref?.()}),K=(async()=>{let W=Math.min($.handshakeTimeoutMs??3000,3000),Q=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:W}):await a8.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:W});if(z=Q,J){Q.close();return}let U=await Q.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(J){Q.close();return}Y=Q.subscribe(U,{method:"usage.watch"},X)})();try{await Promise.race([K,H])}catch(W){throw J=!0,W}finally{clearTimeout(G)}if(Y)await Y.closed})().finally(()=>{J=!0,z?.close()});return{stop(){if(J)return;J=!0,Y?.unsubscribe(),z?.close()},closed:B}}}}var BZ=60000,n8=4*BZ,E2=2*BZ,J6=new Map,JZ=new Map;function Z$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function S2($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!Z$(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 C2($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class r8{transport;key;#$=[];#Z=!1;#B=new Set;#G=new Map;#z=new zZ(async()=>{try{let $=await this.transport.getUsage();if(!Z$($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>Z$(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#B=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#B)this.#G.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#B.clear()}},()=>{});#H=new O$;#Y="polling";#X=0;#Q=0;#J=new Map;#U;#D;#M={};#W=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#z.running)return this.#z.running;if(this.#Y==="watching")return Promise.resolve();for(let[X,z]of JZ)if($-z>=BZ)JZ.delete(X);let Z=JZ.get(this.key);if(Z!==void 0&&$-Z<BZ)return Promise.resolve();return JZ.set(this.key,$),this.#z.request()}watchMode(){return this.#Y}watch($={}){this.#X++;let Z=$.provider;if(Z===void 0)this.#Q++;else this.#J.set(Z,(this.#J.get(Z)??0)+1);if(this.#X===1)this.#M=$,this.#T();let X=!1;return()=>{if(X)return;if(X=!0,Z===void 0)this.#Q--;else{let z=(this.#J.get(Z)??1)-1;if(z>0)this.#J.set(Z,z);else this.#J.delete(Z)}if(--this.#X===0)this.#_()}}#_(){if(this.#D)(this.#M.clearTimeoutImpl??clearTimeout)(this.#D);this.#D=void 0;let $=this.#U;this.#U=void 0,$?.handle?.stop(),this.#Y="polling"}#V($){this.#D=(this.#M.setTimeoutImpl??setTimeout)(()=>{if(this.#D=void 0,this.#X>0&&!this.#U)this.#T()},$),this.#D.unref?.()}#T(){let $=this.transport.watchUsage;if(!$){this.#Y="fallback";return}this.#Y="polling",this.#H.restart();let Z={notices:0};this.#U=Z;let X;try{X=$.call(this.transport,(z)=>this.#j(Z,z))}catch(z){this.#x(Z,z);return}Z.handle=X,X.closed.then(()=>this.#x(Z,void 0),(z)=>this.#x(Z,z))}#j($,Z){if(this.#U!==$)return;if($.notices++,$.notices===1)this.#Y="watching";if($.notices===2)this.#W=0;let X=S2(Z);if(!X)this.#H.restart();if(!(X?this.#H.continuous(X):!1)||X?.provider===void 0||this.#Q>0||this.#J.has(X.provider))this.#z.request()}#x($,Z){if(this.#U!==$)return;this.#U=void 0;let X=C2(Z);if(X==="unknown_method"||X==="usage_watch_limit"){this.#Y="fallback";return}if($.notices>0){let z=Math.min(Y6*2**Math.min(this.#W,16),XZ);this.#W++,this.#Y="polling",this.#V(z);return}if(this.#Y="fallback",this.#z.request(),Z===void 0||a(Z)==="unreachable")this.#V(XZ)}current($,Z,X){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!Z$(z.usage))continue;let Y=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||X-Y>=n8)continue;return{entry:z,context:{fetchedAt:Y,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,X){if(!this.#Z)return{miss:"unreachable"};let z=this.#$.find((B)=>B.provider===$&&typeof B.account==="string"&&B.account.trim()===Z),Y=(z??this.#$.find((B)=>B.provider===$&&B.account===void 0&&B.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(z){let B=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Z$(z.usage)||!Number.isFinite(B))return{miss:"unreachable"};let G={entry:z,context:{fetchedAt:B,...typeof z.source==="string"&&{source:z.source}}};if(z.stale!==void 0&&(!Z$(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:G};return X>=B+n8||z.stale!==void 0?{miss:"stale",reading:G}:{reading:G}}if(this.#B.has($))return{miss:"absent"};let J=this.#G.get($)??X;return this.#G.set($,J),{miss:X-J>=E2?"unreachable":"cold"}}}function B6($,Z){let X=JSON.stringify([s8($.connectionFile),s8(Z)]),z=J6.get(X);if(!z)z={source:new r8($,X),refs:0},J6.set(X,z);z.refs++;let Y=!1;return{source:z.source,release(){if(Y)return;if(Y=!0,--z.refs===0)J6.delete(X)}}}import{ClaustrumCredentialError as lY}from"@cortexkit/claustrum-client";function w0($){let Z=new AbortController,X=[],z=!1,Y=()=>{if(z)return;z=!0;for(let{source:G,listener:H}of X)G.removeEventListener("abort",H);X.length=0},J=(G)=>{if(z||Z.signal.aborted)return;Z.abort(G),Y()},B=$.find((G)=>G.aborted);if(B)return Z.abort(B.reason),{signal:Z.signal,dispose:Y};for(let G of $){if(Z.signal.aborted)break;let H=()=>J(G.reason);if(X.push({source:G,listener:H}),G.addEventListener("abort",H,{once:!0}),G.aborted)J(G.reason)}return{signal:Z.signal,dispose:Y}}import{channel as B4}from"node:diagnostics_channel";import{ClaustrumCredentialError as S9}from"@cortexkit/claustrum-client";import{createHash as p2,randomBytes as d2,randomUUID as l2}from"node:crypto";import{constants as e8}from"node:fs";import{chmod as c2,mkdir as u2,open as H9,readFile as K6,realpath as i2,rename as s2,stat as K9,unlink as W6}from"node:fs/promises";import{basename as Q9,dirname as F0,extname as $9,isAbsolute as Z9,join as U6,resolve as a2}from"node:path";import{ClaustrumCredentialError as W9,ClaustrumClient as n2,writeEnrollmentTokenFile as o2}from"@cortexkit/claustrum-client";import{lstat as I2,stat as b2}from"node:fs/promises";import{resolve as k2}from"node:path";async function f2($,Z){try{let X=await Z($);return X.isFile()?X:void 0}catch(X){return X.code==="ENOENT"?"absent":void 0}}function y2($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class M0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks?(Z)=>($.stat??b2)(Z):(Z)=>($.lstat??I2)(Z)}async read($,Z,X){let z=$.map((K)=>k2(K)),Y=JSON.stringify(z),J=await Promise.all(z.map((K)=>f2(K,this.#$))),B=J.every((K)=>K!==void 0)?J:void 0,G=this.#Z.get(Y);if(B&&G&&B.every((K,W)=>{let Q=G.identities[W];return Q!==void 0&&y2(K,Q)}))return X?.(B),G.value;this.#Z.delete(Y);let H=await Z(z);if(B){if(this.#Z.size>=64){let K=this.#Z.keys().next().value;if(K!==void 0)this.#Z.delete(K)}this.#Z.set(Y,{identities:B,value:H})}return H}}import{ClaustrumCredentialError as w2}from"@cortexkit/claustrum-client";var h2="Served by Thalamus",m2="This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.",t8=new WeakSet;function G6($){return t8.has($)}function b(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function H6($){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 w2(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&a(Object.assign(Error(),{code:Z.code}))==="unreachable")return new S(Z.reason==="host-accessor-missing"||Z.reason==="host-accessor-failed"?Z.reason:void 0);return $}function P$($){try{return $()}catch(Z){throw H6(Z)}}async function h0($){try{return await $()}catch(Z){throw H6(Z)}}function v2($){let Z=$.watchScoped?.bind($),X=$.reportUsageScoped?.bind($);return{listScoped:(...z)=>h0(()=>$.listScoped(...z)),getScoped:(...z)=>h0(()=>$.getScoped(...z)),reportAuthFailureScoped:(...z)=>h0(()=>$.reportAuthFailureScoped(...z)),close:()=>P$(()=>$.close()),...Z&&{watchScoped:(...z)=>{let Y=P$(()=>Z(...z));return{stop:()=>P$(()=>Y.stop()),closed:h0(async()=>{let J=await Y.closed;return J.kind==="refused"||J.kind==="transport_lost"?{...J,error:H6(J.error)}:J})}}},...X&&{reportUsageScoped:(...z)=>h0(()=>X(...z))},...$.insula&&{insula:g2($.insula)}}}function g2($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>h0(()=>$.getUsage()),...Z&&{watchUsage:(...X)=>{let z=P$(()=>Z(...X));return{stop:()=>P$(()=>z.stop()),closed:h0(()=>z.closed)}}}}}function m0($){if(!b()||!$)throw new S;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z==="function"){let X=v2(Z($));return t8.add(X),X}}catch{throw new S("host-accessor-failed")}throw new S("host-accessor-missing")}var r2=1,HZ=16384,U9=30000,D6=/^[0-9a-f]{64}$/,D9="unknown_method",V9=new Set([D9,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),q9=new Set(["pending_queue_full"]);function Q6($){if(!($ instanceof W9))return;if(V9.has($.code))return{code:$.code,disposition:"terminal"};if(q9.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function t2($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new q("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function N9($){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 V6($){return Array.isArray($)&&$.length>=1&&$.length<=4&&Array.from($).every((Z)=>{if(!KZ(Z)||Object.keys(Z).length!==2||Z.operation!=="read"&&Z.operation!=="list"||!KZ(Z.selector))return!1;let X=Object.keys(Z.selector),z=X[0];return X.length===1&&(z==="category"||z==="exact")&&typeof Z.selector[z]==="string"&&Z.selector[z].trim().length>0})}function K0($){return{...$.requestedGrants!==void 0&&{requestedGrants:$.requestedGrants},...$.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:$.requestedGrantsStatus}}}function e2($){return n2.connect($)}function M9($){let Z=$9($)||".json",X=Q9($,$9($));return{statePath:U6(F0($),`${X}-state${Z}`),tokenPath:$}}function $4($){let Z=$.override?.trim();if(Z&&!Z9(Z)&&!$.cwd)throw new q("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?Z9(Z)?Z:a2($.cwd,Z):U6($.stateDir,`${$.host}-enrollment.json`);return M9(X)}function KZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function GZ($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function _9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function j$(){return new q("invalid-state","invalid Claustrum enrollment state")}function WZ($){if(!KZ($)||$.version!==r2||typeof $.proposedName!=="string"||$.proposedName.length===0)throw j$();if($.phase==="pending"){let Z=X9($);if(!D6.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!GZ($.createdAt)||!GZ($.updatedAt))throw j$();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt,...Z}}if($.phase==="approved"){let Z=X9($);if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!_9($.tokenGeneration)||!GZ($.updatedAt))throw j$();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"||!GZ($.updatedAt))throw j$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw j$()}function X9($){if($.requestedGrants!==void 0&&!V6($.requestedGrants)||$.requestedGrantsStatus!==void 0&&($.requestedGrants===void 0||$.requestedGrantsStatus!=="sent"&&$.requestedGrantsStatus!=="dropped"))return{};return K0($)}function q6($){if(!KZ($)||!D6.test(String($.token??""))||!_9($.token_generation))throw new q("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function F9($){if(!$.isFile())throw new q("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new q("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new q("unsafe-file","Claustrum enrollment file must be owned by the current user")}function z9($){try{return JSON.parse($)}catch{throw new q("invalid-state","Claustrum enrollment file is not valid JSON")}}async function L0($){if(Q0)try{await g0(F0($));let X=await QZ($,!0);if(Buffer.byteLength(X)>HZ)throw new q("unsafe-file","Claustrum enrollment file is too large");return z9(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await H9($,e8.O_RDONLY|e8.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new q("unsafe-file","Claustrum enrollment file could not be opened safely")}try{F9(await Z.stat());let X=Buffer.alloc(HZ+1),{bytesRead:z}=await Z.read(X,0,X.byteLength,0);if(z>HZ)throw new q("unsafe-file","Claustrum enrollment file is too large");return z9(X.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function Y9($,Z){let X=[];for(let z of $.split(`
|
|
88
|
+
`)){if(z.trim()===""||z.startsWith("#"))continue;let Y=z.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;X.push(Y)}return X}async function Z4($,Z,X){try{let[z,Y]=await Promise.all([K6(X.passwdPath??"/etc/passwd","utf8"),K6(X.groupPath??"/etc/group","utf8")]),J=Y9(z,7),B=Y9(Y,4);if(!J||!B)return!1;let G=J.filter((Q)=>Number(Q[2])===$),H=B.filter((Q)=>Number(Q[2])===Z);if(G.length!==1||H.length!==1)return!1;let K=G[0]?.[0],W=H[0]?.[3]??"";return(W===""||W.split(",").every((Q)=>Q===K))&&!J.some((Q)=>Number(Q[2])!==$&&Number(Q[3])===Z)}catch{return!1}}function L9($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>K6(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function O9($,Z={}){if(!Q0){let X=process.geteuid?.();if(X===void 0)return;let z=process.getegid?.(),Y;try{Y=await i2($)}catch{return}let J;for(;;){let B=await K9(Y).catch(()=>{return});if(B&&(B.mode&18)!==0&&(B.mode&512)===0){if(J===void 0)J=z!==void 0&&await Z4(X,z,Z);if((B.mode&2)!==0||B.uid!==X||B.gid!==z||!J)throw new q("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let G=F0(Y);if(G===Y)return;Y=G}}try{await B9($,L9(Z))}catch(X){if(!(X instanceof B0))throw X;throw new q("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function X$($,Z={},X="enrollment directory"){if(Q0){await g0($,!1,L9(Z));return}await u2($,{recursive:!0,mode:448});let z=await K9($),Y=process.geteuid?.();if(Y!==void 0&&z.uid!==Y)throw new q("unsafe-file",`Claustrum ${X} must be owned by the current user`);if((z.mode&63)!==0)await c2($,448)}async function v0($,Z,X={}){let z=F0($);await X$(z,X),await O9(z,X);let Y=`${JSON.stringify(Z)}
|
|
89
|
+
`;if(Buffer.byteLength(Y)>HZ)throw new q("invalid-state","Claustrum enrollment state is too large");if(Q0)return G9($,Y);let J=U6(z,`.${Q9($)}.${process.pid}.${l2()}.tmp`),B,G=!1;try{B=await H9(J,"wx",384),G=!0,await B.writeFile(Y,"utf8"),await B.chmod(384),await B.sync(),await B.close(),B=void 0,await s2(J,$),G=!1}finally{if(await B?.close().catch(()=>{}),G)await W6(J).catch(()=>{})}}var X4=new M0;async function N6($,Z){let X=Q0?await J9($,Z):await X4.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,J=$.statePath])=>J9({tokenPath:Y,statePath:J},Z),(Y)=>{for(let J of Y)if(J!=="absent")F9(J)}),z={...X.status};if(X.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function J9($,Z){let X=await L0($.tokenPath),z=X===void 0?void 0:q6(X),Y=await L0($.statePath),J=Y===void 0?void 0:WZ(Y);if(z)return{usesProposedName:J===void 0,status:{state:"approved",proposedName:J?.proposedName??Z,...J?.phase==="approved"&&J.approvedName!==void 0&&{approvedName:J.approvedName},tokenGeneration:z.token_generation,...J&&(J.phase==="approved"||J.phase==="pending")&&K0(J)}};if(!J)return{status:{state:"idle"},usesProposedName:!1};if(J.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:J.proposedName,code:"missing_token"}};return{status:_0(J),usesProposedName:!1}}async function P9($,Z){let X;try{X=await N6($,Z)}catch(z){if(!(z instanceof q)||z.kind!=="invalid-state"&&z.kind!=="invalid-token")return"unreadable";try{let Y=await L0($.statePath);if(Y===void 0)return"unreadable";let J=WZ(Y);return J.phase==="approved"&&J.proposedName===Z?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in X&&X.proposedName!==Z)return"unreadable";if(X.state==="approved"||X.state==="blocked"&&X.code==="missing_token")return"vault";return"local"}async function z4($,Z){if(b())return"host";return P9($,Z)}async function O0($){let Z=await L0($);if(Z===void 0)throw new q("not-enrolled","Claustrum enrollment is not configured");return q6(Z)}function _0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId},...K0($)};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,...K0($)};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function j9(){return new q("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class R9{#$;#Z;#B;#G;#z;#H;#Y;#X;#Q;constructor($){if($.displayName!==void 0&&!N9($.displayName))throw new q("invalid-state","invalid Claustrum enrollment display name");if($.requestedGrants!==void 0&&!V6($.requestedGrants))throw new q("invalid-state","invalid Claustrum enrollment requested grants");this.#z=$.requestedGrants?.map((Z)=>({selector:{...Z.selector},operation:Z.operation})),this.#Q=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#B=$.proposedName,this.#G=$.displayName,this.#H=$.now??Date.now,this.#Y=$.mintSecret??(()=>d2(32).toString("hex")),this.#X=$.writeTokenFile??o2}async status(){return N6(this.#Z,this.#B)}async resetTerminal(){return T9(this.#Z,this.#B)}async#J($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#H()};return await v0(this.#Z.statePath,X,this.#Q),_0(X)}async reconcile(){await X$(F0(this.#Z.statePath),this.#Q);let $=await g({name:"ceremony",path:this.#Z.statePath,ttlMs:U9,renew:!0});if(!$)return{state:"busy"};try{let Z=await L0(this.#Z.tokenPath),X=Z===void 0?void 0:q6(Z),z=await L0(this.#Z.statePath),Y=z===void 0?void 0:WZ(z);if(Y&&Y.proposedName!==this.#B)throw j9();if(X){if(!Y||Y.phase==="pending"){let B={version:1,phase:"approved",proposedName:Y?.proposedName??this.#B,tokenGeneration:X.token_generation,...Y&&K0(Y),updatedAt:this.#H()};await v0(this.#Z.statePath,B,this.#Q),Y=B}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:X.token_generation,...Y.phase==="approved"&&K0(Y)}}if(Y?.phase==="approved"){let B={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#H()};return await v0(this.#Z.statePath,B,this.#Q),_0(B)}if(Y&&Y.phase!=="pending")return _0(Y);if(!Y){let B=this.#H();if(Y={version:1,phase:"pending",proposedName:this.#B,requestSecret:this.#Y(),createdAt:B,updatedAt:B,...this.#z!==void 0&&{requestedGrants:this.#z}},!D6.test(Y.requestSecret))throw new q("invalid-state","invalid minted Claustrum enrollment secret");await v0(this.#Z.statePath,Y,this.#Q)}if(!Y.requestId)try{let B=p2("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),G={name:Y.proposedName,requestSecretHash:B},H,K=Y.requestedGrantsStatus;try{if(H=await this.#$.enrollPropose({...G,...this.#G!==void 0&&{displayName:this.#G},...Y.requestedGrants!==void 0&&{requestedGrants:Y.requestedGrants}}),Y.requestedGrants!==void 0)K="sent"}catch(W){if(this.#G===void 0&&Y.requestedGrants===void 0||!(W instanceof W9)||W.code!=="invalid_params")throw W;if(H=await this.#$.enrollPropose(G),Y.requestedGrants!==void 0)K="dropped"}Y={...Y,requestId:H.requestId,updatedAt:this.#H(),...K!==void 0&&{requestedGrantsStatus:K}},await v0(this.#Z.statePath,Y,this.#Q)}catch(B){let G=Q6(B);if(!G)throw B;if(G.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:G.code,...K0(Y)};if(G.code===D9)return await $.assertOwned(),await W6(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:Y.proposedName,code:G.code};return this.#J(Y,G.code)}let J=Y.requestId;if(!J)return _0(Y);try{let B=await this.#$.enrollPoll({requestId:J,requestSecret:Y.requestSecret});if(B.status==="pending")return _0(Y);if(B.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#H()};return await v0(this.#Z.statePath,H,this.#Q),_0(H)}await X$(F0(this.#Z.tokenPath),this.#Q),await O9(F0(this.#Z.tokenPath),this.#Q),await this.#X(this.#Z.tokenPath,{token:B.token,token_generation:B.tokenGeneration});let G={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:B.name,tokenGeneration:B.tokenGeneration,...K0(Y),updatedAt:this.#H()};return await v0(this.#Z.statePath,G,this.#Q),_0(G)}catch(B){let G=Q6(B);if(!G)throw B;if(G.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:J,retryCode:G.code,...K0(Y)};return this.#J(Y,G.code)}}finally{await $.release()}}}async function T9($,Z){await X$(F0($.statePath));let X=await g({name:"ceremony",path:$.statePath,ttlMs:U9,renew:!0});if(!X)return"busy";try{if(await L0($.tokenPath)!==void 0)return"refused-approved";let z=await L0($.statePath);if(z===void 0)return"idle";let Y=WZ(z);if(Y.proposedName!==Z)throw j9();if(Y.phase==="pending")return"refused-pending";return await X.assertOwned(),await W6($.statePath),"reset"}finally{await X.release()}}var R$="claustrum-tombstone:v1:";function UZ($){return`${R$}${$}`}function M6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function DZ($){return typeof $==="string"&&$.startsWith(R$)}function x9($,Z){if(!M6($)||$.type!=="oauth")return!1;return $.refresh===UZ(Z)}function A9($,Z){if(x9($,Z))return"placeholder";if(M6($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!DZ($.refresh))return"login";if(M6($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function Y4($){let Z=A9($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new q("host-slot-login",`${$.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if($.mode==="local"&&Z==="placeholder")throw new q("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function z$($,Z){let X=!1;return(z)=>{if(X)return;if(!Z||Z.aborted)X=!0;$.warn("claustrum shutdown drain timed out",{pendingOperations:z})}}async function Y$($,Z){if(!$.size)return;let X,z=!1,Y=(async()=>{while(!z&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([Y,new Promise((J)=>{X=setTimeout(()=>{z=!0,J()},2000)})]),z&&$.size)Z($.size)}finally{z=!0,clearTimeout(X)}}import{ClaustrumCredentialError as J4}from"@cortexkit/claustrum-client";function E9($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class _6{options;#$=new Map;#Z=new Map;#B=new Set;#G;#z;#H=!1;#Y=!1;#X=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#z!==void 0,dropped:this.#X}}report($,Z){if(this.#H||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#X++;return}if(!E9(Z)||"credentialId"in Z||"vouched"in Z)throw Error("invalid reading");let X=JSON.stringify(Z);if(Buffer.byteLength(X,"utf8")>15360)throw Error("oversized reading");let z=JSON.parse(X);if(!E9(z)||"credentialId"in z||"vouched"in z||typeof z.observedAtMs!=="number"||!Number.isFinite(z.observedAtMs))throw Error("invalid reading");if(z.observedAtMs<=(this.#Z.get($)??-1/0)){this.#X++;return}if(this.#$.has($))this.#X++;if(this.#Z.set($,z.observedAtMs),this.#$.set($,z),!this.#G&&!this.#z)this.#G=this.options.setTimeout(()=>{this.#G=void 0,this.#Q()},1000),this.#G.unref?.()}catch{this.#X++}}forget($){if(this.#$.delete($))this.#X++;this.#Z.delete($)}#Q(){if(this.#z||!this.#$.size||this.#Y)return this.#z;let $=Promise.resolve().then(async()=>{while(!this.#Y&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[X,z]=Z;this.#$.delete(X);try{let Y=await this.options.token();if(this.#Y||!this.options.owns(X)){if(!this.#Y)this.#X++;continue}await this.options.client.reportUsageScoped?.({credentialId:X,reading:z,enrollmentToken:Y})}catch(Y){if(!this.#Y)this.#X++;this.#J(Y)}}});return this.#z=$,$.finally(()=>{this.#z=void 0}),$}#J($){let Z="transport_error";try{if($ instanceof J4)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#B.has(Z))return;this.#B.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#H=!0,this.#G)this.options.clearTimeout(this.#G);return this.#G=void 0,this.#Q()}drop(){this.#Y=!0,this.#X+=this.#$.size+(this.#z?1:0),this.#z=void 0,this.#$.clear(),this.#Z.clear()}}function b9($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function G4($,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 L6=p("claustrum");function C9($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new q("invalid-token","Invalid Claustrum enrollment token");return $.token}var P0=B4("common-auth.claustrum.phases");function P6($,Z,X,z=L6){let Y=b9(Z,X);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:Y,reason:G4(Z,X)}),Y}var O6=300000,k9=60000,f9=1e4,y9=60000;function F6(){return new q("invalid-material","Claustrum returned invalid credential material")}function H4($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw F6()}if(!X||typeof X!=="object")throw F6();let z=X,Y=z.access_token??z.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(R$))throw F6();return Z}function K4($,Z){let X={kind:"not-mine"};if(!$.operations.includes("read"))return X;if(!$.categories.includes(Z.category))return X;if("classify"in Z){let J=I9($),B;switch(J.authMethod){case"apikey":B="api_key";break;case"chatgpt":case"antigravity":case"oauth":B="oauth";break;default:return{kind:"refused",code:"unknown-auth-method"}}let G={credentialId:$.id,credentialType:B,categories:$.categories,refreshAdapter:$.refreshAdapter,...J};if(G.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let H=Z.classify(G);if(H.kind==="not-mine")return X;if(H.kind==="mine"&&typeof H.member==="string")return{kind:"mine",type:B,member:H.member};if(H.kind==="refused"&&typeof H.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(H.code)&&!H.code.includes(`
|
|
90
|
+
`)&&Z.refusalCodes.includes(H.code))return{kind:"refused",code:H.code}}catch{}return{kind:"refused",code:"unclassified"}}let z=$.credentialType;if(z==="oauth"){if($.refreshAdapter!==Z.refreshAdapter)return X}else if(z==="api_key"){if(!Z.apiKeys||$.refreshAdapter!==void 0)return X}else return X;let{authMethod:Y}=I9($,{includeProviderIds:!1});if(Y!==void 0){if(!(z==="oauth"?Y==="chatgpt"||Y==="antigravity"||Y==="oauth":Y==="apikey"))return{kind:"refused",code:"unknown-auth-method"}}return{kind:"mine",type:z}}function I9($,{includeProviderIds:Z=!0}={}){let X=$;return{providerIds:Z?X.providerIds:void 0,authMethod:X.authMethod}}function Q4($){let{grants:Z,grantTuples:X}=$;if(Z===void 0||X===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(X.map(({selectorKind:z,selector:Y,operation:J})=>Object.freeze({selectorKind:z,selector:Y,operation:J})))})}class J${#$;#Z;#B;#G;#z;#H;#Y;#X=new WeakMap;#Q=new WeakMap;#J=new Map;#U=new WeakMap;#D;#M=new Map;#W;#_;#V=!1;#T=0;#j=!1;#x=new S;#K=new Map;#q;#R=!1;#N=-1/0;#O=2000;#L=!1;#C;#A=new Set;#I=new Set;#F;#E;#b;constructor($){if(b()&&$.client&&!G6($.client))throw new S;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>O0(Z);else if(b())this.#Z=async()=>{throw new q("not-enrolled","Claustrum enrollment token path is required")};else throw new q("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client??m0($.pluginId),this.#G=$.family,this.#z=$.parseIdentity,this.#H=$.requireAssertion??!1,this.#B=$.now??Date.now,this.#Y=$.logger??L6,this.#F=z$(this.#Y),this.#W=$.setTimeoutImpl??setTimeout,this.#_=$.clearTimeoutImpl??clearTimeout;let X=()=>this.#$;this.#D=new _6({client:{get reportUsageScoped(){let z=X();return z.reportUsageScoped?.bind(z)}},owns:(z)=>this.#M.has(z),token:async()=>b()?"":C9(await this.#Z()),logger:this.#Y,setTimeout:this.#W,clearTimeout:this.#_})}replaceClient($){if(this.#P(),$===this.#$)return;if(b()&&!G6($))throw new S;this.#$=$;for(let Z of this.#A)Z.restart()}transportLost($){if(this.#L||this.#V)return;this.#V=!0,this.#T=this.#B(),this.#j=!1,this.#x=$ instanceof S9?$:new S($ instanceof S?$.reason:void 0),this.#Y.warn("serving kept vault receipt",{reason:"unreachable"}),this.#k()}reachable(){if(this.#L||!this.#V)return;if(this.#V=!1,this.#q)this.#_(this.#q);this.#q=void 0,this.#O=2000;for(let $ of this.#J.values())$.since=null;(this.#Y.info??L6.info)("vault receipt serving resumed",{reason:"reachable"})}#k(){if(this.#L||!this.#V||this.#q||this.#R)return;this.#q=this.#W(()=>{this.#q=void 0,this.#m(!0)},this.#O),this.#q.unref?.()}#m($=!1){if(this.#L||!this.#V||this.#R)return;if(this.#B()-this.#N<1000){this.#k();return}this.#N=this.#B(),this.#R=!0,this.#f().catch(()=>{if($&&this.#V)this.#O=Math.min(this.#O*2,30000)}).finally(()=>{this.#R=!1,this.#k()})}#P($){if(this.#L)throw new q("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#w($){if(this.#P($),b())return"";if(P0.hasSubscribers)P0.publish({logger:this.#Y,phase:"token read begin"});let Z=this.#Z();this.#I.add(Z);let X;try{X=await Z}finally{if(this.#I.delete(Z),P0.hasSubscribers)P0.publish({logger:this.#Y,phase:"token read end"})}return this.#P($),C9(X)}async#h($,Z){this.#P(Z);let X,z;try{let Y=$();X=Z?await Promise.race([Y,new Promise((J,B)=>{let G=()=>B(Z.reason);if(Z.addEventListener("abort",G,{once:!0}),z=()=>Z.removeEventListener("abort",G),Z.aborted)G()})]):await Y}catch(Y){if(this.#P(Z),a(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof S9)throw Y;if(a(Y)==="unreachable")throw new S(Y instanceof S?Y.reason:void 0);throw new q("unavailable","Claustrum scoped operation failed")}finally{z?.()}return this.#P(Z),this.reachable(),X}async discover($){let Z=await this.#f($);return this.#C=Z.view,Z}async#f($){let Z,X;try{X=await this.#w($)}catch(Q){throw this.#J.clear(),this.#y(),Q}if(P0.hasSubscribers)P0.publish({logger:this.#Y,phase:"list scoped begin"});try{Z=await this.#h(()=>this.#$.listScoped(X),$)}catch(Q){throw this.listFailed(Q),Q}finally{if(P0.hasSubscribers)P0.publish({logger:this.#Y,phase:"list scoped end"})}let z=[],Y=[],J=0,B=[],G=new Map;for(let Q of Z.rows){let U=K4(Q,this.#G);if(U.kind==="not-mine"){J++;continue}if(U.kind==="refused"){Y.push({...Q.id.trim()&&{credentialId:Q.id},code:U.code});continue}B.push({row:Q,type:U.type,...U.member!==void 0&&{member:U.member}}),G.set(Q.id,(G.get(Q.id)??0)+1)}let H=[];for(let{row:Q,type:U,member:D}of B){let V;if(!Q.id.trim())V="empty credential id";else if((G.get(Q.id)??0)>1)V="duplicate credential id";else if(Q.accountId!==void 0&&!Q.accountId.trim())V="blank account identity";else if(!Q.state.trim())V="empty state";if(V){z.push({...Q.id.trim()&&{credentialId:Q.id},...D!==void 0&&{member:D},reason:V});continue}H.push(Object.freeze({credentialId:Q.id,credentialType:U,...D!==void 0&&{member:D},...Q.accountId!==void 0&&{accountIdentity:Q.accountId},state:Q.state,...Q.email!==void 0&&{email:Q.email},...Q.orgName!==void 0&&{orgName:Q.orgName}}))}for(let Q of z)this.#Y.warn("skipped malformed vault record",Q);let K=Q4(Z),W="classify"in this.#G;return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),...(W||Y.length>0)&&{refused:Object.freeze(Y)},...W&&{notMine:J},...K&&{grantReach:K}}}listFailed($){if(a($)==="unreachable")this.transportLost($);else this.reachable(),this.#J.clear(),this.#y()}forget($){this.#J.delete($),this.#M.delete($),this.#D.forget($)}#y(){for(let $ of this.#M.keys())this.#D.forget($);this.#M.clear()}retain($){let Z=new Map($.map((X)=>[X.credentialId,X]));for(let[X,z]of this.#J){let Y=Z.get(X);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==z.attempt.credentialType||Y.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(X)}for(let[X,z]of this.#M){let Y=Z.get(X);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==z.credentialType||Y.accountIdentity!==z.accountIdentity)this.forget(X)}}keptReceiptState(){let $=null;for(let[Z,X]of this.#J){if(!this.#S(X.attempt)){this.forget(Z);continue}if(X.since!==null)$=Math.min($??X.since,X.since)}return Object.freeze({active:$!==null,since:$})}#S($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#B()>k9}async authorize($,Z,X="vault"){this.#P(Z);let z=this.#B(),{credentialId:Y,credentialType:J,accountIdentity:B}=$,G=this.#J.get(Y);if(G&&(G.attempt.credentialType!==J||G.attempt.expectedAccountIdentity!==B||!this.#S(G.attempt)))this.forget(Y),G=void 0;let H;try{H=await this.#w(Z)}catch(K){throw this.#J.clear(),this.#y(),K}if(this.#V&&G)return this.#m(),this.#p(Y,G,H,X);try{let K;try{if(this.#V&&this.#K.has(this.#v({credentialId:Y,credentialType:J,accountIdentity:B},H)))throw this.#x;K=await this.#d({credentialId:Y,credentialType:J,accountIdentity:B},H,Z)}catch(W){if(this.#P(Z),a(W)!=="unreachable"||G)throw W;K=await this.#g({credentialId:Y,credentialType:J,accountIdentity:B},H,z,W,Z)}return this.#J.set(Y,{attempt:K,routeId:X,since:null}),this.#M.set(Y,{...$}),K}catch(K){if(this.#P(Z),a(K)!=="unreachable")throw this.forget(Y),K;return this.#p(Y,G,H,X,K)}}#v($,Z){return JSON.stringify([$.credentialId,$.credentialType,$.accountIdentity,Z])}async#g($,Z,X,z,Y){let J=f9-(this.#B()-X);if(J<=0||this.#j||this.#B()-this.#T>=y9)throw z;let B=this.#v($,Z),G=this.#K.get(B);if(!G){let Q=new AbortController,U={controller:Q,users:0,error:z,pending:Promise.resolve().then(async()=>{let V=250;for(;;){await this.#u(V,Q.signal);try{return await this.#d($,Z,Q.signal)}catch(_){if(this.#P(Q.signal),a(_)!=="unreachable")throw _;U.error=_,V=Math.min(V*2,1000)}}})};G=U,this.#K.set(B,G);let D=()=>{if(this.#K.get(B)===U)this.#K.delete(B)};G.pending.then(D,D)}let H=G;H.users++;let K,W;try{let Q=await Promise.race([H.pending,new Promise((D,V)=>{if(K=this.#W(()=>{if(this.#V)this.#j=!0;V(H.error)},J),K.unref?.(),Y){if(W=()=>V(Y.reason),Y.addEventListener("abort",W,{once:!0}),Y.aborted)W()}})]);this.#P(Y);let U=Object.freeze(Object.defineProperty({...Q},"accessToken",{value:Q.accessToken,enumerable:!1}));return this.#X.set(U,{token:Z}),U}finally{if(K)this.#_(K);if(W)Y?.removeEventListener("abort",W);if(--H.users===0){if(H.controller.abort(),this.#K.get(B)===H)this.#K.delete(B)}}}#u($,Z){return this.#P(Z),new Promise((X,z)=>{let Y=()=>{this.#_(J),Z.removeEventListener("abort",Y),z(Z.reason)},J=this.#W(()=>{Z.removeEventListener("abort",Y),X()},$);if(J.unref?.(),Z.addEventListener("abort",Y,{once:!0}),Z.aborted)Y()})}#p($,Z,X,z,Y=this.#x){if(!Z||this.#J.get($)!==Z||!this.#S(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#B();let J=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#X.set(J,this.#X.get(Z.attempt)??{token:X}),this.#U.set(J,z),J}async#d($,Z,X){if(!$.credentialId)throw new q("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:Y,accountIdentity:J}=$;if(this.#H&&J===void 0)throw new q("identity-unasserted","Claustrum dispatch requires a known account identity");let B=await this.#h(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:O6}}),X);if(B.credentialId!==void 0&&B.credentialId!==z)throw new q("identity-changed","Claustrum served credential identity changed");let G=B.expiresAtMs;if(!Number.isSafeInteger(B.recordVersion)||B.recordVersion<0||G===null&&Y==="oauth"||G!==null&&(!Number.isFinite(G)||G-this.#B()<O6))throw new q("insufficient-validity","Claustrum served credential has insufficient validity");let H=H4(B.material),K=B.accountId?.trim()?B.accountId:void 0;if(this.#H&&(B.credentialId===void 0||K===void 0))throw new q("identity-unasserted","Claustrum served credential did not assert its identity");let W=K===void 0?this.#z?.(H):void 0,Q=K??W;if(J!==void 0&&Q!==void 0&&Q!==J)throw new q("identity-changed","Claustrum served credential identity changed");let U=Q??J,V=Object.freeze(Object.defineProperty({credentialId:z,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:K!==void 0?"asserted":W!==void 0?"parsed":J!==void 0?"expected":"none",...J!==void 0&&{expectedAccountIdentity:J},...B.credentialId!==void 0&&{assertedCredentialId:B.credentialId},...K!==void 0&&{assertedAccountIdentity:K},...B.projectId!==void 0&&{projectId:B.projectId},recordVersion:B.recordVersion,expiresAtMs:G},"accessToken",{value:H,enumerable:!1}));return this.#X.set(V,{token:Z}),V}async reportFailure($,Z,X){if(Z!==401)return;this.#P();let z=this.#X.get($);if(!z)throw new q("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#U.get($);if(Y!==void 0){this.forget($.credentialId),this.#Y.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let J=this.#J.get($.credentialId);if(J&&J.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let B=this.#Q.get($);if(B)return B;let G=this.#h(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#Q.set($,G);try{await G,this.#Y.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(H){throw this.#Q.delete($),H}}watchRoster($){this.#P();let Z=$.view??(()=>this.#C),X,z,Y=(B=!1)=>{let G=new YZ({client:this.#$,enrollmentToken:()=>this.#w(),view:()=>B?void 0:Z(),discover:async(H)=>{while(X)await X.catch(()=>{});if(z!==G)return;B=!1,X=Promise.resolve().then(()=>$.onView(H));try{await X}finally{X=void 0}},onRefused:(H)=>{this.listFailed(H),$.onRefused?.(H)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#Y,now:this.#B,setTimeoutImpl:this.#W,clearTimeoutImpl:this.#_});return G};z=Y();let J={restart:()=>{let B=z.mode;if(z.stop(),z=Y(!0),B!==z.mode)$.onMode?.(z.mode);z.start()},stop:()=>z.stop()};return this.#A.add(J),z.start(),{get mode(){return z.mode},close:()=>{this.#A.delete(J),z.stop()}}}reportUsage($){if(this.#L)return;try{this.#D.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#D.state()}close(){if(this.#L)return;this.#L=!0;for(let Z of this.#K.values())Z.controller.abort();if(this.#K.clear(),this.#q)this.#_(this.#q);this.#q=void 0;for(let Z of this.#A)Z.stop();this.#A.clear(),this.#J.clear();let $=this.#D.close();if($)this.#I.add($),$.then(()=>this.#I.delete($));else this.#$.close();this.#b=Y$(this.#I,(Z)=>(this.#E??this.#F)(Z)).finally(()=>{if(this.#D.drop(),this.#M.clear(),$)this.#$.close()})}async dispose($=this.#F){this.#E=$,this.close(),await this.#b}}import{resolve as NZ}from"node:path";var w9=30000,h9={now:()=>performance.now(),schedule($,Z){let X=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(X),unref:()=>X.unref?.()}}};function m9($,Z=""){let X=new Map,{observation:z}=$,Y=(G,H,K)=>X.set(`${Z}:${G}`,{at:H,order:0,publication:{...$,observation:K}}),J=(G,H)=>JSON.stringify([G??"all",H]),B=new Set;for(let G of z.readings??[]){let H=J(G.scope,G.label);B.add(H),Y(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...G}]})}for(let G of z.coverage??[]){let H=J(G.scope,G.label);if(!B.has(H))Y(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...G}]})}if(z.budget)Y("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[G,H]of Object.entries(z.counters??{}))Y(`counter:${G}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[G]:{...H}}});if(z.credits)Y("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!X.size)Y("empty",z.checkedAt,{checkedAt:z.checkedAt});return X}import{createHash as W4}from"node:crypto";import{stat as U4}from"node:fs/promises";import{resolve as T$}from"node:path";function v9($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function j6($,Z,X){return $.some((z)=>v9(z,Z,X))}function R6($,Z,X){let z={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==X),z]}function T6($,Z,X){return $.filter((z)=>!Z.some((Y)=>v9(z,Y,X)))}function A6($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>$0(Z).map((X)=>({credentialId:X,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function D4($,Z){let X=$0(Z),z=Z.accountIdentity===void 0?-1:$.order.findIndex((J)=>J.accountIdentity===Z.accountIdentity),Y=z>=0?z:$.order.findIndex((J)=>X.includes(J.credentialId));return Y>=0?Y:1/0}var qZ="vault:";function V4($){return W4("sha256").update($).digest("hex")}function q4($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function N4($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function $0($){return[$.credentialId,...$.aliases??[]]}function d9($,Z,X={}){let z=X.now??Date.now(),Y=X.routePrefix??qZ,J=X.reservedRouteIds??new Set,B=$?.rows??[],G=$?void 0:X.seed,H=[...$?.declined??G?.declined??[]],K=Z.skipped.length===0,W=new Set(Z.credentials.map((F)=>F.credentialId)),Q=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),U=Z.skipped.some((F)=>F.credentialId===void 0),D=(F)=>!W.has(F)&&(Q.has(F)||U),V=new Map;for(let F of B){if(F.accountIdentity===void 0)continue;for(let P of $0(F))if(!V.has(P))V.set(P,F.accountIdentity)}let _=new Map;for(let F of Z.credentials){let P=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:V.get(F.credentialId),claimed:!1},w=N4(P),l=_.get(w)??[];l.push(P),_.set(w,l)}let N=new Set,R=new Set(J),x=[],L=(F,P)=>F.credential.credentialId.localeCompare(P.credential.credentialId),O=[..._.values()].map((F)=>F.toSorted(L)).sort((F,P)=>F[0]&&P[0]?L(F[0],P[0]):0);for(let F of O){let P=F[0]?.identity,w=F.filter((T)=>T.credential.state==="active"),l=w.length?w:F,s0=l.filter((T)=>T.claimed),i=s0.length?s0:l,a0=new Set(F.map((T)=>T.credential.credentialId)),d$=B.find((T)=>!N.has(T)&&$0(T).some((o0)=>a0.has(o0))&&(T.accountIdentity===void 0||T.accountIdentity===P)),n0=i.find((T)=>T.credential.credentialId===d$?.credentialId)??i[0];if(!n0)continue;let h=n0.credential,c=d$??(P===void 0?void 0:B.find((T)=>!N.has(T)&&T.accountIdentity===P));if(c)N.add(c);let r=c?.routeId;if(!r||J.has(r)){let T=`${Y}${h.credentialId}${P===void 0?"":`~${V4(P).slice(0,10)}`}`;r=T;for(let o0=2;R.has(r);o0++)r=`${T}~${o0}`}R.add(r);let I=c?$0(c).filter(D):[],y=[...new Set([...F.map((T)=>T.credential.credentialId),...I])].filter((T)=>T!==h.credentialId).sort((T,o0)=>T.localeCompare(o0)),V0=X.mapAccount?.(h)??{};x.push({previousIndex:c?B.indexOf(c):1/0,row:{routeId:r,credentialId:h.credentialId,credentialType:h.credentialType,...P!==void 0&&{accountIdentity:P},...y.length&&{aliases:y},state:h.state,label:V0.label?.trim()||q4(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...y].some((T)=>j6(H,T,P)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!n0.claimed&&P!==void 0&&{unclaimed:!0}}});let Y0=x.at(-1);if(G&&Y0)Y0.previousIndex=D4(G,Y0.row)}return B.forEach((F,P)=>{if(N.has(F)||!$0(F).some(D))return;if(R.has(F.routeId))return;let[w,...l]=$0(F).filter((a0)=>!W.has(a0));if(w===void 0)return;R.add(F.routeId);let{aliases:s0,...i}=F;x.push({previousIndex:P,row:{...i,credentialId:w,...l.length&&{aliases:l},stale:!0}})}),x.sort((F,P)=>F.previousIndex===P.previousIndex?F.row.credentialId.localeCompare(P.row.credentialId):F.previousIndex-P.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:K,...!K&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:x.map((F)=>F.row),declined:H}}function E6($){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 x$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function B$($){return $===void 0||typeof $==="string"}function M4($){let Z=x$($)?E0($.quota):void 0;if(!x$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!B$($.accountIdentity)||!B$($.email)||!B$($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((X)=>typeof X==="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 _4=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function g9($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!x$(X)||!B$(X.credentialId)||typeof X.reason!=="string"||!_4.has(X.reason))return;Z.push(X)}return Z}function l9($){if(!x$($)||$.version!==1||!B$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!g9($.rejected))throw new q("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let J=M4(Y);if(!J)throw new q("invalid-state","Claustrum roster file is not valid");Z.push(J)}let X=[];for(let Y of $.declined){if(!x$(Y)||typeof Y.credentialId!=="string"||!B$(Y.accountIdentity))throw new q("invalid-state","Claustrum roster file is not valid");X.push(Y)}let z=g9($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},...$.limits!==void 0&&{limits:$.limits},rows:Z,declined:X}}function S6($){return l9(JSON.parse(JSON.stringify($)))}var F4=new M0({followSymlinks:!0});async function f($){if(Q0)return x6($);let Z=await F4.read([$],([X=$])=>x6(X));return structuredClone(Z)}async function x6($){let Z;try{Z=await QZ($,Q0)}catch(z){if(z.code==="ENOENT")return;throw z}let X;try{X=JSON.parse(Z)}catch{throw new q("invalid-state","Claustrum roster file is not valid")}return l9(X)}var c9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},u9={name:"claustrum-roster",ttlMs:30000};async function p0($,Z,X={}){return C0($,{...c9,signal:X.signal},async(z)=>{let Y=await x6($),{next:J,result:B}=await Z(Y,{assertOwned:()=>z.assertOwned()});if(J){await z.assertOwned();try{await G0($,J,{beforeRename:async()=>{await X.beforePublish?.(),X.signal?.throwIfAborted(),await z.assertOwned()}})}catch(G){if(G&&typeof G==="object"&&"published"in G&&G.published===!0)X.onPublished?.();throw G}X.onPublished?.()}return B})}function C6($,Z){return p0($,(X)=>{let z=X?.rows.find((J)=>J.routeId===Z);if(!X||!z)throw new q("route-unavailable","Claustrum route is not in the roster");let Y=R6(X.declined,z.credentialId,z.accountIdentity);return{next:{...X,declined:Y,rows:X.rows.map((J)=>J===z?{...J,enabled:!1}:J)},result:void 0}})}function I6($,Z){return p0($,(X)=>{let z=X?.rows.find((Y)=>Y.routeId===Z);if(!X||!z)throw new q("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:T6(X.declined,$0(z),z.accountIdentity),rows:X.rows.map((Y)=>Y===z?{...Y,enabled:!0}:Y)},result:void 0}})}function L4($){return new q("invalid-order",$)}function O4($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let X=new Set($.map((J)=>J.routeId)),z=new Set;for(let J of Z){if(typeof J!=="string")return"route ids must be an array of route ids";if(z.has(J))return`route id ${J} appears more than once`;if(!X.has(J))return`route id ${J} is not in the roster`;z.add(J)}let Y=[...X].filter((J)=>!z.has(J)).length;if(Y>0)return`the order leaves out ${Y} roster route id${Y===1?"":"s"}`;return}function b6($,Z,X={}){return p0($,(z)=>{let Y=z?.rows??[],J=O4(Y,Z);if(J)throw L4(J);let B=new Map;for(let K of Y){let W=B.get(K.routeId);if(W)W.push(K);else B.set(K.routeId,[K])}let G=[...Z],H=G.flatMap((K)=>B.get(K)??[]);if(!z||H.every((K,W)=>K===Y[W]))return{result:{ids:G,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:G,outcome:"reordered"}}},{...X.signal&&{signal:X.signal}})}function P4($,Z){if(!$0($).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")&&$0($).length===1)return"bind";return"refuse"}async function k6($,Z){let{routeId:X,observation:z,...Y}=Z;return i9($,{routeId:X,observation:z,accountIdentity:Y.accountIdentity,receipt:Y})}async function i9($,Z){if(!t0(Z.observation))return!1;let X=u($,await f($));if(!j0(X,Z).kept)return!1;return a9($,Z)}function f6($,Z){return i9($,Z)}function j0($,Z){let X=$?.rows.find((B)=>B.routeId===Z.routeId),z=!X?"refuse":Z.receipt?P4(X,Z.receipt):X.accountIdentity!==void 0&&X.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!X||z==="refuse")return{roster:$,kept:!1};let Y=V$(X.quota,Z.observation),J=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((B)=>B===X?{...B,...J,quota:Y}:B)},kept:!0}}var VZ=new Map;function A$($){VZ.delete(T$($))}function s9($,Z){let X=T$($);if(Z instanceof q)return Z.kind==="roster-busy";if(Z instanceof e||Z instanceof M$)return T$(Z.details.target)===X;if(Z instanceof B0){let z=T$(Z.path);return[c9.name,u9.name].some((Y)=>{let J=N$(X,Y);return z===J||z.startsWith(`${J}.`)})}return!1}var j4=4;async function p9($){try{let{dev:Z,ino:X,size:z,mtimeMs:Y}=await U4($);return{dev:Z,ino:X,size:z,mtimeMs:Y}}catch{return}}function R4($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function T4($,Z,X){for(let z=0;z<j4;z++){let Y=await p9($),J=await f($),B,G,H;try{({target:B,local:G}=Z(J));let K=JSON.stringify(X(B));H=JSON.stringify(B)!==K||G!==void 0&&JSON.stringify(G)!==K}catch{return"commit"}if(!R4(Y,await p9($)))continue;if(H)return"commit";return n9($)?"commit":"unchanged"}return"commit"}async function E$($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){A$($.path);return}let X=await g({...u9,path:$.path,renew:!0});if(!X){let B=await f($.path);if($.signal?.throwIfAborted(),!B?.view)throw new q("roster-busy","Claustrum account discovery is already in progress");return B}let z=T$($.path),Y=$.listedOver,J;try{let B=await f($.path),G=Y?void 0:VZ.get(z);J=G&&(G.previousView===B?.view||G.inventory.view===B?.view)?G:{inventory:await $.custody.discover($.signal),previousView:B?.view},VZ.delete(z);let{inventory:H}=J;$.onInventory?.(H),$.signal?.throwIfAborted();let K=typeof $.projection==="function"?$.projection():$.projection,W=(D)=>d9(D,H,K),Q=async()=>{return $.signal?.throwIfAborted(),await X.assertOwned(),Z()};if(await T4($.path,(D)=>{if(Y)return{target:D};let V=u($.path,D);return{target:D,...V!==D&&{local:V}}},W)==="unchanged"){if(!await Q())return;return await f($.path)}return await p0($.path,async(D)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await X.assertOwned(),Y&&D?.view!==Y.view&&D?.view!==H.view)return{result:D};let V=W(D);return{...JSON.stringify(D)!==JSON.stringify(V)&&{next:V},result:V}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await X.assertOwned()}})}catch(B){if(B instanceof e&&J&&!Y&&!$.signal?.aborted&&await Z())VZ.set(z,J);throw B}finally{await X.release($.signal)}}var d0=new Map,x4=p("claustrum"),r9=100;function t9($,Z=h9){let X=NZ($),z=d0.get(X);if(!z)z={path:X,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},d0.set(X,z);return z}function e9($,Z,X){let z=t9($,X);z.listeners.add(Z);let Y;return()=>Y??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():y6($)})()}function A4($){return m9($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function a9($,Z){if(!t0(Z.observation))return Promise.resolve(!1);let X=t9($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),Y=X.pending.get(z)??new Map;for(let[J,B]of A4(Z)){let G=Y.get(J);if(!G||B.at>=G.at){if(B.order=++X.order,B.publication.observation.coverage)B.priorReading=G?.publication.observation.readings?G.publication:G?.priorReading;Y.set(J,B)}}if(Y.size)X.pending.set(z,Y);for(let J of X.listeners)J(Z);return Z3(X,r9),Promise.resolve(!0)}function $3($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,X)=>Z.order-X.order)}function u($,Z){let X=d0.get(NZ($));if(X)for(let z of $3(X.pending)){if(z.priorReading)Z=j0(Z,z.priorReading).roster;Z=j0(Z,z.publication).roster}return Z}function n9($){return!!d0.get(NZ($))?.pending.size}function Z3($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let X=$.draining?0:($.committedAt??-1/0)+w9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,X),()=>{return $.timer=void 0,X3($)}),!$.draining)$.timer.unref?.()}function o9($){$.timer?.cancel(),$.timer=void 0}function X3($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([X,z])=>[X,new Map(z)]));return $.running=(async()=>{try{if(await p0($.path,(z)=>{let Y=z;for(let B of $3(Z)){if(B.priorReading)Y=j0(Y,B.priorReading).roster;Y=j0(Y,B.publication).roster}let J=JSON.stringify(Y)!==JSON.stringify(z);return{...J&&{next:Y},result:J}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[z,Y]of Z){let J=$.pending.get(z);for(let[B,G]of Y)if(J?.get(B)===G)J.delete(B);if(!J?.size)$.pending.delete(z)}$.failures=0}catch(X){if(!$.abort.signal.aborted&&$.failures++===0)x4.warn("vault quota publication delayed; retrying",{error:X instanceof Error?X.message:String(X)})}finally{$.running=void 0;for(let z of $.wake)z();let X=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):r9;Z3($,X)}})(),$.running}async function y6($,Z=1000){let X=NZ($),z=d0.get(X);if(!z)return;z.draining=!0,o9(z);let Y,J,B=new Promise((G)=>{J=()=>{if(!z.pending.size||z.abort.signal.aborted)G()},z.wake.add(J),J()});try{if(z.pending.size)X3(z);await Promise.race([B,new Promise((G)=>{Y=setTimeout(G,Math.max(0,Z))})])}finally{if(clearTimeout(Y),J)z.wake.delete(J);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),o9(z),z.pending.clear(),d0.get(X)===z)d0.delete(X)}}}var MZ=1e4;function z3(){return new S}var w6;function J3($,Z){if(!w6)throw Error("ClaustrumConsumer is not initialized");return w6($,Z)}function Y3(){return new q("not-active","Claustrum scoped custody is not active")}class h6{#$;#Z=new AbortController;#B;#G;#z;#H;#Y;#X;#Q;#J;#U=!1;#D=new Set;#M;#W;#_;#V;#T=new Map;#j;#x;#K;#q;#R=new WeakMap;static{w6=($,Z)=>{let X=new h6(Z);return X.#K=$,{consumer:X,hooks:X.#w()}}}constructor($){this.#$=$,this.#B=$.logger??p("claustrum"),this.#G=z$(this.#B,this.#Z.signal),this.#x=e9($.rosterPath,(Z)=>{this.#X=j0(this.#X,Z).roster})}#N($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#O($){return this.#D.add($),$.then(()=>this.#D.delete($),()=>this.#D.delete($)),$}async#L(){if(b())return!0;return await this.#$.isCustodyActive?.()??!0}#C($,Z){let X=w0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,Y)=>{let J=()=>{X.signal.removeEventListener("abort",B),X.dispose()},B=()=>{J(),Y(X.signal.reason)};if(X.signal.addEventListener("abort",B,{once:!0}),$.then((G)=>{if(J(),X.signal.aborted)Y(X.signal.reason);else z(G)},(G)=>{J(),Y(G)}),X.signal.aborted)B()})}async#A(){if(this.#N(),this.#z)return this.#z;if(!this.#H){let $={timedOut:!1};this.#H=this.#I($),this.#O(this.#H)}return this.#C(this.#H)}#I($){let Z=this.#$.setTimeoutImpl??setTimeout,X=this.#$.clearTimeoutImpl??clearTimeout,z=(!b()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>m0(this.#$.pluginId))).then((B)=>{if(this.#Z.signal.aborted||$.timedOut){if(B.close(),!$.timedOut)this.#N();throw z3()}if(this.#z=new J$({client:B,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#B,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&B.insula)this.#W=B6(B.insula,this.#$.tokenPath);return this.#z}),Y,J=new Promise((B,G)=>{Y=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#B.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#F()}),G(z3())},this.#F()),Y.unref?.()});return Promise.race([z,J]).finally(()=>{if(Y)X(Y);this.#H=void 0})}#F(){return this.#$.connectTimeoutMs??MZ}snapshot(){return this.#X}grantReach(){if(this.#K)return this.#K.grantReach(this.#X?.view);let $=this.#Q;return $&&this.#X?.view===$.view?$.reach:void 0}watchState(){if(this.#K)return Object.freeze({vault:this.#K.watchMode()});return Object.freeze({vault:this.#_?.mode??"polling",...this.#$.insula&&{insula:this.#W?.source.watchMode()??"polling"}})}#E(){this.#_?.close(),this.#_=void 0,this.#V?.(),this.#V=void 0}keptReceiptState(){if(this.#K){let $=this.#q;return $&&this.#K.leaseLive($)?$.custody.keptReceiptState():this.#K.keptReceiptState()}return this.#z?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return E6(this.#X)}refresh(){if(this.#N(),this.#K)return this.#O(this.#h(this.#K));if(this.#Y)return this.#Y;return this.#Y=(async()=>{if(!await this.#L()){if(this.#X=void 0,this.#Q=void 0,this.#E(),this.#z)this.#z.close(),this.#O(this.#z.dispose(this.#G));this.#z=void 0,this.#W?.release(),this.#W=void 0;return}let $=await this.#A(),Z,X=await E$({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#L(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#N();let z=X?.view!==this.#X?.view;if(this.#X=u(this.#$.rosterPath,X),$.retain(X?.rows??[]),Z&&X?.view!==void 0)this.#Q=Z.grantReach?{view:X.view,reach:Z.grantReach}:void 0;if(X&&z)this.#$.onRoster?.(X);return this.#j=(this.#$.now??Date.now)(),X})().finally(()=>{this.#Y=void 0}),this.#O(this.#Y),this.#b(this.#Y),this.#Y}#b($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#U)return;if(this.#N(),this.#U=!0,this.#K){this.#K.start();return}let $=async()=>{try{if(await this.#k())await this.refresh();await this.refreshInsulaQuota(),this.#m()}catch(X){if(!this.#Z.signal.aborted)this.#$.onError?.(X)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#J=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#J=void 0,this.#O($())},Z),this.#J.unref?.()};this.#O($())}async#k(){if(this.#_?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#j===void 0||$-this.#j>=$$)return!0;return!await this.#L()}#m(){let $=this.#z;if(this.#Z.signal.aborted||!$)return;if(this.#_??=$.watchRoster({view:()=>this.#X?.view,onView:()=>this.#O((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.#W&&!this.#V)this.#V=this.#W.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{if(!b())await O0(this.#$.tokenPath);await this.#A(),await this.#W?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{if(!b())await O0(this.#$.tokenPath);return this.#P($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{if(!b())await O0(this.#$.tokenPath);let X=u(this.#$.rosterPath,await f(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#P(X?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#L())return{miss:"unreachable"};try{if(!b())await O0(this.#$.tokenPath);let z=u(this.#$.rosterPath,await f(this.#$.rosterPath))?.rows.find((B)=>B.routeId===$)?.accountIdentity;if(!z||!this.#W)return{miss:"unreachable"};let Y=this.#W.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),J=Y.reading&&Z.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...J!==void 0&&{reading:J}};return J===void 0?{miss:"unreachable"}:{reading:J}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let X=await this.lookupInsulaQuotaForRoute($);if(X.miss==="cold"||X.miss==="upstream-failed"){if(this.#T.get($)!==X.miss)this.#T.set($,X.miss),this.#B.warn("skipped insula provider poll",{reason:X.miss});return}return this.#T.delete($),X.miss?Z():X.reading}#P($){if(!this.#$.insula||!$)return;let Z=this.#W?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#K)return this.#v(this.#K,$,Z);this.#N(Z);let X=this.#X??await this.#C(this.refresh(),Z);if(!X||!await this.#L())throw this.#z?.close(),this.#z=void 0,this.#E(),this.#W?.release(),this.#W=void 0,new q("not-active","Claustrum scoped custody is not active");let z=u(this.#$.rosterPath,await f(this.#$.rosterPath));this.#N(Z);let Y=X.rows.find((H)=>H.routeId===$),J=z?.rows.find((H)=>H.routeId===$);if(J&&!J.enabled){if(Y)this.#z?.forget(Y.credentialId);throw new q("route-declined","Claustrum route is disabled")}if(!Y||!J||J.state!=="active"||J.credentialId!==Y.credentialId||J.accountIdentity!==Y.accountIdentity||J.credentialType!==Y.credentialType){if(Y)this.#z?.forget(Y.credentialId);throw new q("route-unavailable","Claustrum route is disabled, removed or changed")}let B=await this.#C(this.#A(),Z),G=w0([this.#Z.signal,...Z?[Z]:[]]);try{return await B.authorize({credentialId:J.credentialId,credentialType:J.credentialType,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity}},G.signal,$)}finally{G.dispose()}}#w(){return{discovery:($)=>{let Z=this.#K;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let X=this.#O($.then((z)=>this.#f(Z,z)));this.#b(X)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#X?.view;if(this.#X=u(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(X){this.#$.onError?.(X)}},reset:()=>{this.#X=void 0},roster:()=>this.#X,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#h($){let Z=await $.refresh();return this.#f($,Z)}#f($,Z){if(this.#N(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#X}#y($){if($&&this.#q!==$)return;this.#q?.release(),this.#q=void 0}async#S($,Z){let X=this.#q;if(X&&$.leaseLive(X))return X;this.#y();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#N();let Y=this.#q;if(Y&&$.leaseLive(Y))return z.release(),Y;return this.#q=z,z}async#v($,Z,X){if(this.#N(X),!this.#X)await this.#C($.refresh(),X);let z=this.#X;if(!await $.readAuthority())throw this.#y(),Y3();if(this.#N(X),!z)throw new q("route-unavailable","Claustrum has no roster for this provider yet");let Y=u(this.#$.rosterPath,await f(this.#$.rosterPath));this.#N(X);let J=z.rows.find((K)=>K.routeId===Z),B=Y?.rows.find((K)=>K.routeId===Z);if(B&&!B.enabled){if(J)$.forget(J.credentialId);throw new q("route-declined","Claustrum route is disabled")}if(!J||!B||B.state!=="active"||B.credentialId!==J.credentialId||B.accountIdentity!==J.accountIdentity||B.credentialType!==J.credentialType){if(J)$.forget(J.credentialId);throw new q("route-unavailable","Claustrum route is disabled, removed or changed")}let G={credentialId:B.credentialId,credentialType:B.credentialType,...B.accountIdentity!==void 0&&{accountIdentity:B.accountIdentity}},H=w0([this.#Z.signal,...X?[X]:[]]);try{for(let K=0;;K++){let W=await this.#S($,H.signal);try{let Q=await W.custody.authorize(G,H.signal,Z);return this.#R.set(Q,W),Q}catch(Q){if(K>0||H.signal.aborted||$.leaseLive(W)||!(Q instanceof q)||Q.kind!=="closed")throw Q;if(this.#y(W),!await $.readAuthority())throw Y3()}}}finally{H.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#X?.rows.find((X)=>X.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#K){if(this.#q&&this.#K.leaseLive(this.#q))this.#q.custody.reportUsage($)}else this.#z?.reportUsage($)}catch{}}usageReportState(){try{return(this.#K?this.#q?.custody:this.#z)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,X){if(this.#N(),this.#K){let z=this.#R.get($);if(!z)throw new q("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,X);return}if(!this.#z)throw new q("no-receipt","Claustrum dispatch receipt has no active owner");await this.#z.reportFailure($,Z,X)}async send($,Z,X){let z=X.signal,Y=await this.authorize($,z),J=await Z(Y,z);if(J.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,X.reporterSource??"direct"),J;if(J.status===401&&!z?.aborted){let B;try{B=await this.authorize($,z),z?.throwIfAborted()}catch(G){if(z?.aborted)throw G}if(P6(X.site,Y,B,this.#B))await J.body?.cancel().catch(()=>{}),Y=B,J=await Z(B,z)}if(J.status===401)await this.reportFailure(Y,401,X.reporterSource??"direct").catch((B)=>this.#$.onError?.(B)),Promise.resolve().then(()=>this.refresh()).catch((B)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(B)});return J}async decline($){if(this.#N(),await C6(this.#$.rosterPath,$),this.#X=u(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#K?.publishRoster(this.#X);if(this.#K)this.#K.retainUnion();else this.#z?.retain(this.#X?.rows??[])}async accept($){if(this.#N(),await I6(this.#$.rosterPath,$),this.#X=u(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#K?.publishRoster(this.#X)}async reorder($){this.#N();let Z=await b6(this.#$.rosterPath,$);if(this.#X=u(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#K?.publishRoster(this.#X);return Z}async recordQuota($,Z,X){return this.#N(),k6(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:X.credentialId,accountIdentitySource:X.accountIdentitySource,...X.accountIdentity!==void 0&&{accountIdentity:X.accountIdentity},...X.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:X.expectedAccountIdentity}})}async recordAccountQuota($,Z,X){return this.#N(),f6(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new q("closed","Claustrum consumer is closed")),this.#J)(this.#$.clearTimeoutImpl??clearTimeout)(this.#J);if(this.#J=void 0,this.#E(),this.#z)this.#z.close(),this.#O(this.#z.dispose(this.#G));this.#q?.release(),this.#q=void 0,this.#K?.detach(),this.#W?.release(),this.#W=void 0,this.#X=void 0,this.#Q=void 0,this.#x(),A$(this.#$.rosterPath)}async dispose(){this.close(),this.#M??=Promise.all([Y$(this.#D,this.#G),this.#x()]).then(()=>{}),await this.#M}}import{createHash as E4}from"node:crypto";import{channel as B3}from"node:diagnostics_channel";import{readdir as S4,stat as C4}from"node:fs/promises";import{dirname as I4,join as G$,resolve as G3}from"node:path";var _Z=new Map,b4=/^[a-z0-9][a-z0-9._-]{0,63}$/,k4=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,f4=/^[0-9a-f]{16}$/,H3=3;function v6($,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 X=new Set(Z).add($),z=[];if(Array.isArray($)){for(let J=0;J<$.length;J++){let B=v6($[J],X);if(B===void 0)return;z.push(B)}return`[${z.join(",")}]`}let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return;for(let J of Object.keys($).sort()){let B=v6($[J],X);if(B===void 0)return;z.push(`${JSON.stringify(J)}:${B}`)}return`{${z.join(",")}}`}function y4($,Z){let X=v6({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??qZ,mapAccount:$.mapAccount?String($.mapAccount):null});if(X===void 0)throw new q("invalid-state","Claustrum hub classifierInput must be plain JSON");return E4("sha256").update(X).digest("hex").slice(0,16)}function K3($,Z){if(typeof $!=="string"||!b4.test($)||k4.test($))throw new q("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function R0($="Claustrum custody lease is closed"){return new q("closed",$)}function m6(){return new q("not-active","Claustrum scoped custody is not active")}function Q3(){return new S}function w4($,Z){return new Promise((X,z)=>{let Y=()=>z(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),$.then((J)=>{Z.removeEventListener("abort",Y),X(J)},(J)=>{Z.removeEventListener("abort",Y),z(J)}),Z.aborted)Y()})}function W3($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class U3{#$;#Z;#B;#G=new AbortController;#z=new Map;#H=new WeakMap;#Y=0;#X;#Q;#J;#U;#D;#M=new Set;#W;#_=0;#V;#T;#j;#x=!1;#K=new Set;#q;#R;#N;constructor($){if(!$.family||!("classify"in $.family))throw new q("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=K3($.hostGeneration,"host generation"),X=$.members.map((Y)=>K3(Y,"member"));if(new Set(X).size!==X.length)throw new q("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??p("claustrum"),this.#B=z$(this.#Z,this.#G.signal),this.#R=G$($.stateDir,"rosters",Z),this.#N=y4($,X);let z=G$(this.#R,this.#N);for(let Y of X)this.#z.set(Y,{provider:Y,path:G$(z,`${Y}.json`),closed:!1})}#O($){return this.#K.add($),$.then(()=>this.#K.delete($),()=>this.#K.delete($)),$}#L(){if(this.#G.signal.aborted)throw R0("Claustrum discovery hub is closed")}#C($){let Z=this.#z.get($);if(!Z)throw new q("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#C($).path}member($,Z){this.#L();let X=this.#C($);if(X.hooks)throw new q("wrong-consumer","Claustrum hub member was already built");for(let Q of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(Q in Z)throw new q("wrong-consumer",`Claustrum hub members cannot take ${Q}`);let z={provider:X.provider,start:()=>this.start(),refresh:()=>this.#g(),readAuthority:()=>this.#f(),acquire:(Q)=>this.acquire(Q),leaseLive:(Q)=>this.#E(Q),grantReach:(Q)=>Q!==void 0&&this.#V?.view===Q?this.#V.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#c(),publishRoster:(Q)=>this.#A(X,Q),forget:(Q)=>this.#X?.custody?.forget(Q),detach:()=>{X.closed=!0,X.releaseRoster?.()}},Y={rosterPath:X.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:J,hooks:B}=J3(z,Y);X.hooks=B;let G=G3(X.path),H=_Z.get(G)??new Set,K=(Q)=>{if(X.closed||this.#W!==!0||!this.#X||!this.#F(this.#X)||!B.roster()||this.#i(B,Q))return;if(X.seen=JSON.stringify(S6(Q)),B.install(Q),Q.view!==this.#V?.view)X.pending??={failures:0,wait:0};this.#c()};H.add(K),X.receiveRoster=K,_Z.set(G,H);let W=!0;return X.releaseRoster=()=>{if(!W)return;if(W=!1,H.delete(K),!H.size)_Z.delete(G)},J}#A($,Z){let X=this.#X;if($.closed||!X||!this.#F(X))return;$.seen=JSON.stringify(S6(Z)),$.hooks?.install(Z);for(let z of _Z.get(G3($.path))??[]){if(!this.#F(X))return;if(z!==$.receiveRoster)z(Z)}}#I(){let $={id:++this.#Y,count:0,ended:!1,controller:new AbortController};return this.#X=$,$}#F($){return!$.ended&&this.#X===$&&!this.#G.signal.aborted}#E($){let Z=this.#H.get($);return!!Z&&!Z.released&&!Z.generation.ended}#b($,Z=R0()){if($.ended)return;if($.ended=!0,$.count=0,this.#X===$)this.#X=void 0;if(this.#J&&this.#H.get(this.#J)?.generation===$)this.#J=void 0;if(this.#U?.generation===$)this.#U.watch.close(),this.#U=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#O($.custody.dispose(this.#B))}#k($){if($.ended)return;if($.count--,$.count<=0)this.#b($)}#m($){let Z=this.#Q;if(Z?.generation===$&&Z.promise)return Z.promise;let X={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??MZ,Y,J=(!b()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>m0(this.#$.pluginId))).then((H)=>{if(X.timedOut)throw H.close(),Q3();if(!this.#F($)||$.count<=0)throw H.close(),R0("Claustrum connection is no longer wanted");return $.custody=new J$({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),B=new Promise((H,K)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(X.timedOut=!0,!this.#F($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),K(Q3())},z),Y.unref?.()});return X.promise=this.#O(Promise.race([J,B]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),X.promise.finally(()=>{if(this.#Q===X)this.#Q=void 0}).catch(()=>{}),this.#Q=X,X.promise}acquire($){try{if(this.#L(),$?.throwIfAborted(),this.#W===!1)throw m6()}catch(X){return Promise.reject(X)}let Z=this.#X??this.#I();return Z.count++,this.#P(Z,$,!0)}async#P($,Z,X){let z=$.custody;if(!z){let Y=w0([$.controller.signal,...Z?[Z]:[]]);try{z=await w4(this.#m($),Y.signal)}catch(J){if(!$.ended)throw this.#k($),J;return this.#w(Z,X)}finally{Y.dispose()}}if($.ended)return this.#w(Z,X);if(Z?.aborted)throw this.#k($),Z.reason;return this.#h($,z)}#w($,Z){if($?.throwIfAborted(),this.#L(),this.#W===!1)throw m6();if(!Z)throw R0();let X=this.#X??this.#I();return X.count++,this.#P(X,$,!1)}#h($,Z){let X={generation:$,custody:Z,released:!1},z=()=>{if(X.released||$.ended)throw R0()},Y=Object.freeze({authorize:async(B,G,H)=>{z();let K=w0([$.controller.signal,...G?[G]:[]]);try{return await Z.authorize(B,K.signal,H)}finally{K.dispose()}},reportFailure:async(B,G,H)=>{return z(),Z.reportFailure(B,G,H)},reportUsage:(B)=>{if(!X.released&&!$.ended)Z.reportUsage(B)},usageReportState:()=>{return z(),Z.usageReportState()},forget:(B)=>{z(),Z.forget(B)},keptReceiptState:()=>{return z(),Z.keptReceiptState()}}),J=Object.freeze({custody:Y,generation:$.id,release:()=>{if(X.released)return;X.released=!0,this.#k($)}});return this.#H.set(J,X),J}leaseState(){let $=this.#X;return Object.freeze({generation:$?.id,count:$?.count??0})}async#f(){let $=b()||(await this.#$.isCustodyActive?.()??!0);if(this.#G.signal.aborted)return!1;let Z=this.#W;if(this.#W=$,!$&&Z!==!1)this.#y();return $}#y(){this.#_++;let $=this.#X;if($)this.#b($,m6());this.#J=void 0,this.#U?.watch.close(),this.#U=void 0,this.#V=void 0,this.#T=void 0;for(let Z of this.#z.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),A$(Z.path)}#S(){return[...this.#z.values()].filter(($)=>$.hooks&&!$.closed)}async#v(){let $=this.#J,Z=$&&this.#H.get($);if($&&Z&&this.#E($))return Z;this.#J=void 0;let X=await this.acquire(this.#G.signal),z=this.#J&&this.#H.get(this.#J);if(this.#J&&z&&this.#E(this.#J))return X.release(),z;this.#J=X;let Y=this.#H.get(X);if(!Y)throw R0();return Y}#g(){try{this.#L()}catch(z){return Promise.reject(z)}let $=this.#D;if($&&!$.generation?.ended)return $.promise;let Z={},X=this.#O(this.#u(Z).finally(()=>{if(this.#D===Z)this.#D=void 0}));Z.promise=X,this.#D=Z;for(let z of this.#S())z.hooks?.discovery(X);return X}async#u($){if(!await this.#f())return;let Z=await this.#v(),X=Z.generation;if($.generation=X,!this.#F(X))return;let z=await this.#t().then(()=>{return},(Q)=>Q instanceof Error?Q:Error(String(Q)));if(await this.#d(),!this.#F(X))return;let Y=new Map(await Promise.all([...this.#z.values()].map(async(Q)=>[Q,await f(Q.path).then((U)=>U?{file:U}:{},(U)=>U instanceof Error?U:Error(String(U)))])));if(!this.#F(X))return;let J;try{J=await Z.custody.discover(X.controller.signal)}catch(Q){if(!this.#F(X))return;for(let U of this.#z.values())if(U.pending)this.#l(U);throw Q}if(!this.#F(X))return;let B=this.#S(),G=Promise.all(B.map((Q)=>Q.hooks&&!Q.closed?this.#p(Q,Q.hooks,J,z??Y.get(Q),X):void 0));this.#M.add(G);let H;try{H=await G}finally{this.#M.delete(G)}if(!this.#F(X))return;let K=new Map,W=!0;for(let[Q,U]of B.entries()){let D=U.hooks,V=H[Q];if(!D||!V)continue;if("error"in V){let{error:N}=V;if(W=!1,this.#l(U),s9(U.path,N))this.#Z.debug("claustrum hub member commit refused",{member:U.provider});else K.set(U.provider,N);continue}let{roster:_}=V;if(!this.#F(X))return;if(_?.view!==J.view)W=!1,this.#l(U);else U.pending=void 0;if(!_)continue;if(this.#i(D,_)){W=!1,this.#l(U);continue}this.#A(U,_)}if(!this.#F(X))return;if(this.#c(),W)this.#V=Object.freeze({view:J.view,...J.grantReach&&{reach:J.grantReach},refused:Object.freeze([...J.refused??[]]),notMine:J.notMine??0});return this.#T=(this.#$.now??Date.now)(),{errors:K}}async#p($,Z,X,z,Y){let J={...X,credentials:X.credentials.filter((B)=>B.member===$.provider),skipped:X.skipped.filter((B)=>B.member===$.provider)};try{if(!z)throw R0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let B;if(!z.file){let H=B3("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{B=await this.#e($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await E$({path:$.path,custody:{discover:async()=>J},isActive:()=>this.#F(Y)&&this.#W===!0,signal:Y.controller.signal,projection:()=>({...Z.projection(),...B&&{seed:B}}),listedOver:{view:z.file?.view}})}}catch(B){return{error:B}}}async#d(){if(!this.#M.size)return;let $=B3("common-auth.claustrum.phases"),Z=(X)=>{if($.hasSubscribers)$.publish({logger:this.#Z,phase:X})};Z("earlier fan-out drain begin");try{while(this.#M.size)await Promise.allSettled([...this.#M])}finally{Z("earlier fan-out drain end")}}async#t(){for(let $ of[I4(this.#R),this.#R,G$(this.#R,this.#N)])await X$($,{},"roster directory")}async#e($){let Z=`${$.provider}.json`,X=[G$(this.#R,Z)];try{for(let Y of await S4(this.#R))if(Y!==this.#N&&f4.test(Y))X.push(G$(this.#R,Y,Z))}catch{}let z;for(let Y of X)try{let J=(await C4(Y)).mtimeMs,B=await f(Y);if(B&&(!z||J>z.modified))z={modified:J,roster:B}}catch{}return z&&A6(z.roster)}#i($,Z){let X=$.projection().reservedRouteIds;return!!X?.size&&Z.rows.some((z)=>X.has(z.routeId))}#l($){let Z=($.pending?.failures??0)+1,X=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil($$/X)),Y=Z<=H3?1:Math.min(2**(Z-H3),z);$.pending={failures:Z,wait:Y-1}}#c(){let $=this.#X?.custody;if(!$)return;$.retain(this.#S().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#$0(){let $=this.#_;for(let Z of this.#S()){let X;try{X=await f(Z.path)}catch(G){Z.hooks?.onError(G);continue}if($!==this.#_||this.#W!==!0)return;let z=Z.hooks;if(!X||!z||Z.closed)continue;let Y=JSON.stringify(X);if(Y===Z.seen)continue;let J=z.roster();if(!J||J.view!==X.view||this.#i(z,X)){Z.pending??={failures:0,wait:0};continue}let B=W3(J);if(Z.seen=Y,this.#A(Z,X),W3(z.roster())!==B)this.#c()}}#Z0(){let $=!1;for(let X of this.#z.values()){if(!X.pending)continue;if(X.pending.wait<=0)$=!0;else X.pending.wait--}if(this.#U?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#T===void 0||Z-this.#T>=$$}#X0(){let $=this.#J,Z=$&&this.#H.get($);if(!$||!Z||!this.#E($)||this.#W!==!0)return;let X=Z.generation;if(!this.#F(X)||this.#U?.generation===X)return;let z=Z.custody.watchRoster({view:()=>this.#V?.view,onView:()=>this.#O((async()=>{while(this.#D)await this.#D.promise.catch(()=>{});if(!this.#F(X))return;await this.#o()})()),onRefused:(Y)=>this.#a(Y),onError:(Y)=>this.#s(Y)});this.#U={generation:X,watch:z}}#s($){if(!this.#G.signal.aborted)this.#$.onError?.($)}#a($){if(this.#G.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#S())Z.hooks?.onError($)}#n($){for(let[Z,X]of $?.errors??[])this.#z.get(Z)?.hooks?.onError(X)}async#o(){let $;try{$=await this.#g()}catch(Z){this.#a(Z);return}this.#n($)}async#r(){try{if(await this.#f()){if(await this.#$0(),this.#Z0())await this.#o();this.#X0()}}catch(Z){this.#s(Z)}if(this.#G.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#j=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#j=void 0,this.#O(this.#r())},$),this.#j.unref?.()}start(){if(this.#x)return;this.#L(),this.#x=!0,this.#O(this.#r())}async refresh(){this.#n(await this.#g())}refusals(){let $=this.#V;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#V?.reach}watchState(){let $=this.#U;return $&&this.#F($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#X?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#G.signal.aborted)return;this.#G.abort(R0("Claustrum discovery hub is closed"));for(let Z of this.#z.values())Z.releaseRoster?.();if(this.#j)(this.#$.clearTimeoutImpl??clearTimeout)(this.#j);this.#j=void 0;let $=this.#X;if($)this.#b($);this.#J=void 0,this.#U?.watch.close(),this.#U=void 0}async dispose(){this.close(),this.#q??=Y$(this.#K,this.#B),await this.#q}}var m4=1e4;async function gY($){let{connectTimeoutMs:Z,...X}=$,z=Z??m4,Y=h4.connect(X),J=!1,B,G=new Promise((H,K)=>{B=setTimeout(()=>{J=!0,K(new S)},z),B.unref?.()});try{let H=await Promise.race([Y,G]);return Object.assign(H,{insula:o8($)})}catch(H){throw Y.then((K)=>K.close(),()=>{}),H}finally{if(!J&&B)clearTimeout(B)}}var D3=UZ("openai");function V3($){return DZ($)}function l0($){if(!$||$.corrupt===!0)return!1;return V3($.refresh)}class S$ 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 FZ($){if(V3($))throw new S$}var v4=p("quota"),g6="primary",p6="secondary",g4="app_EMoamEEZ73f0CkXaXp7hrann",p4="https://auth.openai.com";async function QJ($){FZ($.refreshToken);let Z=await $.fetchImpl(`${p4}/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:g4}).toString()});if(!Z.ok){let Y=$6(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:Y,isRefreshError:!0})}let X=await Z.json();if(!X||typeof X.access_token!=="string"||!X.access_token||typeof X.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});if(X.refresh_token!==void 0&&typeof X.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});let z=typeof X.refresh_token==="string"&&X.refresh_token?X.refresh_token:$.refreshToken;return{access:X.access_token,refresh:z,expires:$.now()+X.expires_in*1000,expiresIn:X.expires_in}}var d4="https://chatgpt.com/backend-api/wham/usage";async function WJ($){let Z=$.logger??v4,X=$.accountKey??"unknown",z=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let Y=await $.fetchImpl(d4,{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 B=$6(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:B})}let J=i8(await Y.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:X,status:Y.status,elapsedMs:Date.now()-z}),J}catch(Y){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:X,status:typeof Y?.status==="number"?Y.status:"error",elapsedMs:Date.now()-z,error:q3(Y)}),Y}}import{createHash as l4}from"node:crypto";var c4=globalThis.setTimeout,u4=5;function C$($){let Z=$?.quota?.checkIntervalMinutes??u4;return Math.max(1,Z)*60000}function i4($){return $?.quota?.enabled!==!1}function LZ($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function _J($,Z,X,z,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>X)return Y;let J=Z===g6?$?.primary:Z===p6?$?.secondary:void 0,B=J?.resetsAt?Date.parse(J.resetsAt):NaN;if(Number.isFinite(B)&&B>X)return B;return X+z}function s4($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function N3($,Z,X){if(!i4(Z))return X+C$(Z);let z=s4(Z),Y=[];for(let J of["primary","secondary"]){let B=$?.[J];if(!B)continue;if(B.remainingPercent>=z[J])continue;let G=B.resetsAt?Date.parse(B.resetsAt):Number.NaN;if(!Number.isFinite(G)||G<=X)return X+C$(Z);Y.push(G)}if(!Y.length)return X+C$(Z);return Math.min(...Y)+60000}function a4($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function n4($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function n($){return l4("sha256").update($).digest("hex").slice(0,16)}class T0{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!==n($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let X=this.fallbacks.get($)??null;if(!Z||!X)return X;if(this.fallbackTokenFps.get($)!==n(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,z=!1){if(!z&&!M3(Z.quota))return;if(this.mainTokenFp=n($),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=Z,d6(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let X=this.fallbacks.get($)??null;if(Z&&X?.accountId&&X.accountId!==Z)return null;return X}setFallback($,Z,X,z=!1,Y){if(!z&&!M3(Z.quota))return;let J=this.fallbacks.get($)?.accountId;if(Y&&J&&Y!==J)this.clearRateLimited($);let B=Y??J;if(this.fallbacks.set($,{...Z,accountId:B}),X)this.fallbackTokenFps.set($,n(X));else this.fallbackTokenFps.delete($);if(d6(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let X=this.rateLimitedUntilMap.get($);if(X!==void 0&&X>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=n($);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 X=T0.fallbackInflightKey($,Z),z=this.inflightFallbacks.get(X);if(z)return z;if(this.isFallbackBackedOff($,Z)){let J=this.getFallback($,Z);if(J)return J.quota;throw Error("Quota API rate-limited — try again later")}let Y=this._fetchFallback($,Z);return this.inflightFallbacks.set(X,Y),Y}async refreshAllFallbacks($){let Z=this.now();for(let X of $){if(X.enabled===!1)continue;if(l0(X)||!X.access)continue;let z=this.getFallback(X.id,X.access);if(z&&Z<z.refreshAfter)continue;try{await this.refreshFallback(X.id,X.access)}catch{}}}refreshMainInBackground($){let Z=n($);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 X=this.getFallback($,Z);if(!X)return!0;return this.now()>=X.refreshAfter}shouldRefreshOnRequestCount($){let Z=n4(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 X=a4($);if(!X)return;let z=Z?n(Z):null;if(z&&X.tokenFingerprint&&X.tokenFingerprint!==z)return;let Y={quota:X.quota,refreshAfter:N3(X.quota,$,X.checkedAt),checkedAt:X.checkedAt};if(this.main&&this.main.checkedAt>=Y.checkedAt&&(!z||!this.mainTokenFp||this.mainTokenFp===z))return;if(this.main=Y,this.mainTokenFp=X.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&e0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=C$(this.storage);for(let X of $){if(X.enabled===!1)continue;if(!X.quota)continue;let z=Math.max(X.quota.primary?.checkedAt??0,X.quota.secondary?.checkedAt??0);if(z<=0)continue;let Y=this.getFallback(X.id,X.access);if(Y&&Y.checkedAt>=z)continue;this.setFallback(X.id,{quota:X.quota,refreshAfter:z+Z,checkedAt:z},X.access,!1,X.accountId)}}isBackedOff(){return e0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==n(Z))return!1}return e0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,n(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let z=this.now()-this.lastApiCallAt;if(z<T0.API_CALL_GAP_MS)await new Promise((Y)=>{let J=c4(Y,T0.API_CALL_GAP_MS-z);if(typeof J==="object"&&"unref"in J)J.unref()});return this.lastApiCallAt=this.now(),$()},X=this.apiGate.then(Z,Z);return this.apiGate=X.catch(()=>{}),X}async _fetchMain($){let Z=n($);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 X=await g({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!X){let z=this.main;if(z&&this.now()<z.refreshAfter)return z.quota;throw Error("Quota refresh is already in progress")}try{let z=this.now(),Y=await this._fetchQuota($),J=this.now();if(this.mainTokenFp=n($),this.main={quota:Y,refreshAfter:N3(Y,this.storage,J),checkedAt:J},d6(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,J,this.mainTokenFp,z),Y}catch(z){throw this._handleMainFetchError(z),z}finally{await X.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 z=this.getFallback($,Z);if(z)return z.quota;throw Error("Quota API rate-limited — try again later")}let X=await g({name:T0.quotaLockName($),ttlMs:30000,path:this.configPath});if(!X){let z=this.getFallback($,Z);if(z&&this.now()<z.refreshAfter)return z.quota;throw Error("Quota refresh is already in progress")}try{let z=await this._fetchQuota(Z),Y=this.now();return this.setFallback($,{quota:z,refreshAfter:Y+C$(this.storage),checkedAt:Y},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),z}finally{await X.release()}}catch(X){throw this._handleFallbackFetchError($,Z,X),X}finally{this.inflightFallbacks.delete(T0.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(T0.isAuthError($))return;this.mainLastApiError=_$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(T0.isAuthError(X))return;let z=n(Z),Y=this.fallbackErrorTokenFps.get($)===z?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,_$({error:X,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,z)}}function M3($){return Boolean($.primary||$.secondary)}function d6($){let{primary:Z,secondary:X}=$;if(!Z&&!X)return!1;if(Z&&Z.usedPercent>=100)return!1;if(X&&X.usedPercent>=100)return!1;return!0}import{createHash as v7,randomUUID as g7}from"node:crypto";import{setTimeout as p7}from"node:timers/promises";import{createHash as I7}from"node:crypto";import{existsSync as b7,realpathSync as g3}from"node:fs";import{homedir as p3}from"node:os";import{basename as k7,dirname as f7,join as y7,posix as w7,resolve as r6,win32 as h7}from"node:path";function o4(){return Object.freeze({kind:"boolean"})}function r4({min:$,max:Z}={}){return Object.freeze({kind:"integer",min:$,max:Z})}function t4({min:$,max:Z}={}){return Object.freeze({kind:"number",min:$,max:Z})}function e4(){return Object.freeze({kind:"string"})}function $7($){return Object.freeze({kind:"oneOf",values:Object.freeze([...$])})}function Z7($){return c0({kind:"list",item:$})}function X7($){return c0({kind:"object",fields:{...$}})}function k($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let Z=Object.getPrototypeOf($);return Z===Object.prototype||Z===null}function o($,Z,X={}){switch($.kind){case"boolean":return typeof Z==="boolean";case"integer":case"number":return typeof Z==="number"&&Number.isFinite(Z)&&($.kind!=="integer"||Number.isInteger(Z))&&($.min===void 0||Z>=$.min)&&($.max===void 0||Z<=$.max);case"string":return typeof Z==="string";case"oneOf":return typeof Z==="string"&&$.values.includes(Z);case"list":return Array.isArray(Z)&&Array.from(Z).every((z)=>o($.item,z,{...X,completeObjects:!0}));case"object":return k(Z)&&Object.entries(Z).every(([z,Y])=>Object.hasOwn($.fields,z)?o($.fields[z],Y,X):X.allowUnknownFields===!0)&&(!X.completeObjects||Object.keys($.fields).every((z)=>Object.hasOwn(Z,z)));case"record":return k(Z)&&Object.values(Z).every((z)=>o($.value,z,{...X,completeObjects:!0}))}}function c0($){if($&&typeof $==="object"){for(let Z of Object.values($))c0(Z);Object.freeze($)}return $}function z7($){for(let[Z,X]of Object.entries($.settings)){if(Z==="schema_version"||Z==="$schema")throw TypeError(`Reserved setting name: ${Z}`);if(!/^[a-z][a-z0-9_]*$/.test(Z)||/\s/.test(Z))throw TypeError(`Setting name must be snake_case: ${Z}`);if(Z==="sidebar"&&X.value.kind!=="object")throw TypeError("The sidebar setting must use an object descriptor");if(X.overrides!==void 0&&(X.value.kind==="object"||X.value.kind==="record"))throw TypeError(`Object and record settings cannot use overrides: ${Z}`);if(!Object.hasOwn(X,"default")||!o(X.value,X.default,{completeObjects:!0}))throw TypeError(`Invalid default for setting: ${Z}`)}return c0({plugin:$.plugin,settings:Object.fromEntries(Object.entries($.settings).map(([Z,X])=>[Z,structuredClone({...X,project:X.project??"user-only"})]))})}function _3($,Z){if(Z==="default")return!0;if(Z==="opencode"||Z==="pi")return $.host===!0;return $.model===!0}import{join as M7,resolve as i6}from"node:path";import*as C from"node:fs/promises";var Y7={readFile:C.readFile,stat:C.stat,lstat:C.lstat,readlink:C.readlink,realpath:C.realpath,open:C.open,rename:C.rename,link:C.link,unlink:C.unlink,mkdir:C.mkdir,readdir:C.readdir},j={...Y7};import{parseTree as J7}from"jsonc-parser";function W0($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function l6($,Z=()=>{},X=[]){if($.type==="object"){let z={};for(let Y of $.children??[]){let[J,B]=Y.children??[];if(!J||!B)continue;let G=J.value,H=[...X,G];if(Object.hasOwn(z,G))Z(H);W0(z,G,l6(B,Z,H))}return z}if($.type==="array")return($.children??[]).map((z,Y)=>l6(z,Z,[...X,String(Y)]));return $.value}function H$($){let Z=$.startsWith("\uFEFF"),X=Z?$.slice(1):$;if(/^[\x20\t\r\n]*$/.test(X))return{parseable:!0,text:X,hasBom:Z,tree:void 0,value:{},duplicateKeyPaths:[],hasDuplicates:!1};let z=[],Y=J7(X,z,{allowTrailingComma:!0});if(z.length||Y?.type!=="object")return{parseable:!1,text:X,hasBom:Z,tree:Y,errors:z};let J=new Map,B=l6(Y,(G)=>{J.set(JSON.stringify(G),G)});return{parseable:!0,text:X,hasBom:Z,tree:Y,value:B,duplicateKeyPaths:[...J.values()],hasDuplicates:J.size>0}}function F3($,Z,X,z){if(!X||!Object.hasOwn(X.settings,Z))return;let Y=X.settings[Z];if($.overrides===void 0||!k(Y))return Y;let{model:J,host:B}=z;if($.overrides.model&&J!==void 0&&J!=="default"&&J!=="opencode"&&J!=="pi"&&Object.hasOwn(Y,J))return Y[J];if($.overrides.host&&(B==="opencode"||B==="pi")&&Object.hasOwn(Y,B))return Y[B];return Object.hasOwn(Y,"default")?Y.default:void 0}function L3($,Z){if($.kind!=="object")return Z.find((z)=>z!==void 0);let X={};for(let[z,Y]of Object.entries($.fields)){let J=Z.map((B)=>k(B)&&Object.hasOwn(B,z)?B[z]:void 0);W0(X,z,L3(Y,J))}return X}function O3($,Z,X,z={}){if(!Object.hasOwn($.settings,Z))throw TypeError(`Undeclared setting: ${Z}`);let Y=$.settings[Z],J=[];if(Y.project==="allowed"&&X.project!==void 0)J.push(F3(Y,Z,z.project,X));return J.push(F3(Y,Z,z.user,X)),J.push(Y.default),structuredClone(L3(Y.value,J))}function I$($,Z,X,z,Y,J){let B=()=>{return J(X,"invalid-value"),{valid:!1}};if($.kind==="object"){if(!k(Z))return B();let G={},H=!0;for(let[K,W]of Object.entries(Z)){if(!Object.hasOwn($.fields,K)){J([...X,K],Y);continue}let Q=I$($.fields[K],W,[...X,K],z,Y,J);if(Q.valid)W0(G,K,Q.value);else H=!1}if(z){for(let K of Object.keys($.fields))if(!Object.hasOwn(Z,K))J([...X,K],"invalid-value"),H=!1}return H||!z?{valid:!0,value:G}:{valid:!1}}if($.kind==="list"){if(!Array.isArray(Z))return B();let G=[],H=!0;for(let[K,W]of Z.entries()){let Q=I$($.item,W,[...X,String(K)],!0,Y,J);if(Q.valid)G.push(Q.value);else H=!1}return H?{valid:!0,value:G}:{valid:!1}}if($.kind==="record"){if(!k(Z))return B();let G={},H=!0;for(let[K,W]of Object.entries(Z)){let Q=I$($.value,W,[...X,K],!0,Y,J);if(Q.valid)W0(G,K,Q.value);else H=!1}return H?{valid:!0,value:G}:{valid:!1}}return o($,Z)?{valid:!0,value:Z}:B()}function P3($,Z,X){let z=[],Y=new Set,J=(K,W)=>{let Q=JSON.stringify([K,W]);if(Y.has(Q))return;Y.add(Q),z.push({file:{...Z},keyPath:[...K],reason:W})},B={file:{...Z},settings:{},entries:z,schemaVersion:1,newer:!1,hasDuplicates:X.parseable&&X.hasDuplicates,parsed:X};if(!X.parseable)return J([],"unparseable"),B;for(let K of X.duplicateKeyPaths)J(K,"duplicate-key");let G=X.value;if(Object.hasOwn(G,"schema_version")){let K=G.schema_version;if(typeof K==="number"&&Number.isInteger(K)&&K>=1)B.schemaVersion=K,B.newer=K>1;else J(["schema_version"],"invalid-schema-version")}let H=B.newer?"newer-version-key-ignored":"unknown-key";for(let[K,W]of Object.entries(G)){if(K==="schema_version"||K==="$schema")continue;if(!Object.hasOwn($.settings,K)){J([K],H);continue}let Q=$.settings[K];if(!Q)continue;if(Z.kind!=="user"&&Q.project!=="allowed"){J([K],"user-only-in-project");continue}if(k(W)&&Q.overrides!==void 0){let D={};for(let[V,_]of Object.entries(W)){if(!_3(Q.overrides,V)){J([K,V],"override-not-allowed");continue}let N=I$(Q.value,_,[K,V],!1,H,J);if(N.valid)W0(D,V,N.value)}W0(B.settings,K,D);continue}if(k(W)&&Q.value.kind!=="object"&&Q.value.kind!=="record"){J([K],"override-not-allowed");continue}let U=I$(Q.value,W,[K],!1,H,J);if(U.valid)W0(B.settings,K,U.value)}return B}import{dirname as N7}from"node:path";import{isDeepStrictEqual as j3}from"node:util";import{applyEdits as c6,createScanner as G7,findNodeAtLocation as k$,modify as H7}from"jsonc-parser";var B7=Object.freeze(["settings-unparseable","settings-newer-version","settings-invalid-value","settings-busy","settings-unavailable"]);class A extends Error{code;name="SettingsRefusal";constructor($,Z,X){super(Z,X);this.code=$}}var x0={CommaToken:5,LineCommentTrivia:12,BlockCommentTrivia:13,Trivia:15,EOF:17};function Z0(){throw new A("settings-invalid-value","The settings edit does not match its declared value")}function b$($){let Z=H$($);if(!Z.parseable||Z.hasDuplicates)throw new A("settings-unparseable","Settings must be an object without duplicate keys");return Z}function x3($,Z){let X=$;for(let z of Z)if(X.kind==="object"&&Object.hasOwn(X.fields,z))X=X.fields[z];else if(X.kind==="record")X=X.value;else Z0();return X}function K7($,Z,X,{host:z,model:Y},J){if(J!==void 0)return J==="default"&&!k(X)?[Z]:[Z,J];if($.overrides!==void 0&&k(X)){if($.overrides.model&&Y!==void 0&&Y!=="default"&&Y!=="opencode"&&Y!=="pi"&&Object.hasOwn(X,Y))return[Z,Y];if($.overrides.host&&(z==="opencode"||z==="pi")&&Object.hasOwn(X,z))return[Z,z];return[Z,"default"]}return[Z]}function Q7($,Z,X){let z=$,Y=[...Z];for(let J of X){if(z.kind==="record"||z.kind==="list")break;z=x3(z,[J]),Y.push(J)}return{path:Y,descriptor:z}}function W7($,Z){for(let X=1;X<Z.length;X++){let z=$.tree&&k$($.tree,Z.slice(0,X));if(z&&z.type!=="object")Z0()}}function U7($,Z){let X=$.tree&&k$($.tree,[Z]);if(!X)Z0();let z=$.text.slice(X.offset,X.offset+X.length);return b$(c6($.text,[{offset:X.offset,length:X.length,content:`{ "default": ${z} }`}]))}function R3($,Z,X){let z=Z&&k$(Z,X)?.parent,Y=z?.parent;if(z?.type!=="property"||!Y?.children)return $;let J=G7($,!1),B=z.offset+z.length,G=Y.children.indexOf(z),K=Y.children[G+1]?.offset??Y.offset+Y.length-1,W;J.setPosition(B);while(J.getPosition()<K){let N=J.scan();if(N===x0.CommaToken){W={start:J.getTokenOffset(),end:J.getPosition()};break}if(N===x0.EOF)break}if(!W&&G>0){let N=Y.children[G-1];J.setPosition(N.offset+N.length);while(J.getPosition()<z.offset){let R=J.scan();if(R===x0.CommaToken){W={start:J.getTokenOffset(),end:J.getPosition()};break}if(R===x0.EOF)break}}let Q=B;J.setPosition(B);while(J.getPosition()<K){let N=J.scan();if(N===x0.Trivia||N===x0.CommaToken)continue;if(N!==x0.LineCommentTrivia&&N!==x0.BlockCommentTrivia)break;if(Q=J.getPosition(),/[\r\n]/.test(J.getTokenValue()))break}if(W&&W.start>=B&&!/[\r\n]/.test($.slice(B,W.start)))Q=Math.max(Q,W.end);let U=Math.max($.lastIndexOf(`
|
|
91
|
+
`,z.offset-1),$.lastIndexOf("\r",z.offset-1))+1,D=z.offset,V=/^[\t ]*(\r\n|\r|\n)/.exec($.slice(Q));if(/^[\t ]*$/.test($.slice(U,z.offset))&&V)D=U,Q+=V[0].length;let _=[{offset:D,length:Q-D,content:""}];if(W&&(W.start<D||W.start>=Q))_.push({offset:W.start,length:W.end-W.start,content:""});return c6($,_)}function A3($,Z,X,z){for(let G of X){if(!Object.hasOwn($.settings,G.setting))Z0();let H=$.settings[G.setting];if(G.level!==void 0){if(G.path!==void 0)Z0();if(G.level==="default"){if(H.overrides===void 0)Z0()}else if(G.level!=="opencode"&&G.level!=="pi"||!H.overrides?.host)Z0()}if(G.path!==void 0&&H.value.kind!=="object"&&H.value.kind!=="record")Z0();let K=x3(H.value,G.path??[]);if(G.remove!==!0&&!o(K,G.value))Z0()}let Y=b$(Z),J=Y,B=[];for(let G of X){let H=$.settings[G.setting];if(G.level!==void 0&&G.level!=="default"&&!k(J.value[G.setting])){if(G.remove===!0)continue;if(Object.hasOwn(J.value,G.setting))J=U7(J,G.setting);for(let D of B)if(D.path.length===1&&D.path[0]===G.setting)D.path.push("default")}let K=G.path!==void 0?[G.setting]:K7(H,G.setting,J.value[G.setting],z,G.level),W=[...K,...G.path??[]];W7(J,W),B.push(Q7(H.value,K,G.path??[]));let Q=J.tree&&k$(J.tree,W),U;if(G.remove===!0){if(!Q)continue;U=R3(J.text,J.tree,W);let D=b$(U),V=D.value[G.setting];if(K.length===2&&k(V)&&Object.keys(V).length===0)U=R3(U,D.tree,[G.setting]),D=b$(U);J=D}else{if(Q&&j3(T3(J.value,W),G.value))continue;U=c6(J.text,H7(J.text,W,G.value,{formattingOptions:{insertSpaces:!0,tabSize:2}})),J=b$(U)}}for(let G of B)if(J.tree&&k$(J.tree,G.path)&&!o(G.descriptor,T3(J.value,G.path),{allowUnknownFields:!0}))Z0();if(j3(Y.value,J.value))return{outcome:"unchanged",text:Y.text,hasBom:Y.hasBom};return{outcome:"updated",text:J.text,hasBom:Y.hasBom}}function T3($,Z){let X=$;for(let z of Z){if(!k(X)||!Object.hasOwn(X,z))return;X=X[z]}return X}function OZ($,Z,X){if($ instanceof e||E3($,Z,X))throw new A("settings-busy",`Settings lock is busy: ${Z}`,{cause:$});if($ instanceof B0&&($.stage==="safe-parent"||$.stage==="directory"))throw new A("settings-unavailable",`Settings lock folder is unavailable: ${Z}`,{cause:$});throw $}import{randomUUID as D7}from"node:crypto";var V7,q7=new Set(["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS"]);async function S3($){let{target:Z,text:X,hasBom:z,existingMode:Y,lock:J,logger:B}=$,G=$.platform??process.platform,H=`${Z}.${D7()}.tmp`,K=!1,W=!1;try{let Q=await j.open(H,"wx",420);K=!0;try{if(await Q.writeFile(`${z?"\uFEFF":""}${X}`,"utf8"),G!=="win32"&&Y!==void 0)await Q.chmod(Y&511);await Q.sync()}finally{await Q.close()}if(await V7?.("staged",{target:Z,temp:H}),await J.assertOwned(),Y!==void 0){try{await j.rename(H,Z)}catch(U){if(G==="win32"&&["EPERM","EACCES","EBUSY"].includes(U.code??""))throw new A("settings-busy",`Settings file is busy: ${Z}`,{cause:U});throw U}W=!0}else{try{await j.link(H,Z)}catch(U){let D=U.code??"";if(D==="EEXIST")throw new A("settings-busy",`Settings file appeared before publication: ${Z}`,{cause:U});if(q7.has(D))throw new A("settings-unavailable",`Settings file cannot be created on this filesystem: ${Z}`,{cause:U});throw U}W=!0;try{await j.unlink(H)}catch(U){B?.warn("Settings temp cleanup failed after publication",{target:Z,temp:H,error:U})}}return{outcome:"updated"}}finally{if(K&&!W)await j.unlink(H).catch(()=>{})}}var u6=Object.freeze({name:"settings-write",ttlMs:1e4,timeoutMs:2000,renew:!0});function PZ($,Z){throw new A("settings-unavailable",`Settings file is unavailable: ${$}`,{cause:Z})}async function C3($){try{return await rZ($,j)}catch(Z){PZ($,Z)}}async function I3($,Z,X,z){if(Z.separateInstall)throw new A("settings-unavailable","Settings are unavailable for a separate install");let Y=N7(Z.file);try{if(!Z.createMissing)await j.stat(Y);else if(process.platform==="win32")await g0(Y);else await j.mkdir(Y,{recursive:!0,mode:448})}catch(G){PZ(Z.file,G)}let J=await C3(Z.file),B;try{return await C0(J,{...u6,timeoutMs:Z.lockTimeoutMs??u6.timeoutMs},async(G)=>{try{if(await C3(Z.file)!==J)throw new A("settings-busy",`Settings target changed while locking: ${Z.file}`);let H,K,W=!1;try{H=await j.readFile(J,"utf8")}catch(_){if(_.code!=="ENOENT"||!Z.createMissing)PZ(J,_);W=!0,H=""}if(!W)try{K=(await j.stat(J)).mode}catch(_){PZ(J,_)}let Q=H$(H);if(!Q.parseable||Q.hasDuplicates)throw new A("settings-unparseable","Settings must be an object without duplicate keys");let U=Q.value.schema_version;if(Number.isInteger(U)&&U>1)throw new A("settings-newer-version","Settings were written by a newer version");if(typeof X==="function"){let _=X(c0(W?{status:"missing"}:{status:"ready",document:structuredClone(Q.value)}));if(_!==null&&(typeof _==="object"||typeof _==="function")&&"then"in _&&typeof _.then==="function")throw new A("settings-invalid-value","Settings update plans must be synchronous");X=_}if(!Q.tree)H=`${Q.hasBom?"\uFEFF":""}// ${$.plugin} settings
|
|
92
|
+
{
|
|
93
|
+
"schema_version": 1
|
|
94
|
+
}
|
|
95
|
+
`;let D=A3($,H,X,z),V=D.outcome==="unchanged"?{outcome:"unchanged"}:await S3({target:J,text:D.text,hasBom:D.hasBom,existingMode:K,lock:G,logger:Z.log});return B={outcome:"fulfilled",result:V},V}catch(H){throw B={outcome:"rejected",error:H},H}})}catch(G){if(!B)OZ(G,J,u6.name);if(B.outcome==="fulfilled"||G!==B.error)try{Z.log.warn("Settings lock release failed",{target:J,error:G})}catch{}if(B.outcome==="rejected")throw B.error;return B.result}}var b3=Symbol.for("cortexkit.common-auth.settings.reported.v1");function _7(){let $=Reflect.get(globalThis,b3);if(!$)$=new Set,Reflect.set(globalThis,b3,$);return $}function F7($,Z){Z={createMissing:!1,lockTimeoutMs:2000,...Z};let X=i6(Z.file),z={followSymlinks:!0,stat:(L)=>j.stat(L),lstat:(L)=>j.lstat(L)},Y=new M0(z),J=new M0(z),B,G=new Map,H=new Map,K=new Map,W=0,Q=new Map,U=(L)=>i6(M7(L,".cortexkit",`${$.plugin}.jsonc`)),D=process.platform==="win32",V=new Map,_={missing:Symbol("missing"),unreadable:Symbol("unreadable")};async function N(L,O){let F=++W,P=L.kind==="user"?Y:J,w=!1,l=(I,y)=>{if(!D){w=!0;return}w=V.get(I)!==y,V.set(I,y)},s0=async([I])=>{let y;try{y=await j.readFile(I,"utf8")}catch(Y0){let T=Y0.code==="ENOENT"?"missing":"unreadable";return l(I,_[T]),{status:T}}l(I,y);let V0;if(O){let Y0;try{Y0=O(y)}catch{return{status:"unreadable"}}if(!k(Y0))return{status:"unparseable"};V0={parseable:!0,text:y,hasBom:!1,tree:void 0,value:Y0,duplicateKeyPaths:[],hasDuplicates:!1}}else V0=H$(y);return V0.parseable?{status:"snapshot",snapshot:P3($,L,V0)}:{status:"unparseable"}},i=process.platform==="win32"?await s0([L.path]):await P.read([L.path],s0),a0=JSON.stringify([L.kind,L.path]);if(F<=(Q.get(a0)??0))return;Q.set(a0,F);let d$=L.kind==="user"?B:G.get(L.path),n0=i.status==="snapshot"?i.snapshot:i.status==="missing"?void 0:d$?.snapshot,h=[...n0?.entries??[]];if(i.status==="unparseable"||i.status==="unreadable")h.unshift({file:{...L},keyPath:[],reason:i.status});let c={status:i.status,snapshot:n0,entries:h};if(L.kind==="user")B=c;else{if(w)G.delete(L.path);if(!G.has(L.path)&&G.size>=64){let I=G.keys().next().value;if(I!==void 0){G.delete(I),V.delete(I);for(let[y,V0]of H)if(V0===I)H.delete(y)}}G.set(L.path,c)}let r=_7();for(let I of h){let y=JSON.stringify([I.file.path,I.keyPath,I.reason]);if(r.has(y))continue;r.add(y),Z.log.warn(`Settings ${I.reason}: ${I.file.path} (${I.keyPath.join(".")||"<root>"})`,structuredClone(I))}}async function R(L){let O=U(L),F=++W;if(await N({kind:"project",path:O}),F<=(K.get(O)??0))return;let P=O;if(G.get(O)?.status==="missing"){let w=Z.legacyProject?.(L);if(w)P=i6(w.path),await N({kind:"legacy-project",path:P},(l)=>w.read(l))}if(F<=(K.get(O)??0))return;K.set(O,F),H.set(O,P)}let x={async read({project:L}={}){if(Z.separateInstall)return;await Promise.all([N({kind:"user",path:X}),...L===void 0?[]:[R(L)]])},async get(L,O){if(!Object.hasOwn($.settings,L))throw TypeError(`Undeclared setting: ${L}`);return await x.read({project:O.project}),O3($,L,O,{user:B?.snapshot,project:O.project===void 0?void 0:G.get(H.get(U(O.project))??"")?.snapshot})},report(){return structuredClone([...B?.entries??[],...Array.from(new Set(H.values())).flatMap((L)=>G.get(L)?.entries??[])])},update(L,O){return I3($,{...Z,file:X},L,O)},watch(L){if(Z.separateInstall)return()=>{};return k3(X,L,{fs:{stat:(O)=>j.stat(O),readFile:(O)=>j.readFile(O,"utf8")}})}};return x}import{randomUUID as P7}from"node:crypto";import{basename as j7,dirname as f$,join as R7,resolve as T7}from"node:path";import{isDeepStrictEqual as f3}from"node:util";var s6=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function L7($,Z,X){let z=(B)=>{try{let G=X.onLockEvent?.({type:B,name:$.name,path:$.path});if(G&&(typeof G==="object"||typeof G==="function")&&"then"in G&&typeof G.then==="function")Promise.resolve(G).catch(()=>{})}catch{}},Y={...Z,...O7($)},J=performance.now();for(;;){let B=await g({name:$.name,path:$.path,ttlMs:Y.ttlMs,renew:Y.renew,onContended:()=>z("contended"),...X.onRenewalTimer?{onRenewalTimer:(K)=>X.onRenewalTimer?.({name:$.name,path:$.path},K)}:{},...Y.renewIntervalMs!==void 0?{renewIntervalMs:Y.renewIntervalMs}:{},...X.onLockStep?{onStep:(K)=>X.onLockStep?.({name:$.name,path:$.path},K)}:{}});if(B){z("acquired");let K={name:$.name,path:$.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),z("released")}};try{await K.assertOwned()}catch(W){throw await K.release(),W}return K}let G=Y.timeoutMs-(performance.now()-J);if(G<=0)throw new e({target:$.path,name:$.name,timeoutMs:Y.timeoutMs});let H=Math.floor(Math.random()*(Y.retryMs+1));await new Promise((K)=>setTimeout(K,Math.min(Y.retryMs+H,G)))}}function O7($){let Z={};if($.ttlMs!==void 0)Z.ttlMs=$.ttlMs;if($.timeoutMs!==void 0)Z.timeoutMs=$.timeoutMs;if($.retryMs!==void 0)Z.retryMs=$.retryMs;if($.renew!==void 0)Z.renew=$.renew;if($.renewIntervalMs!==void 0)Z.renewIntervalMs=$.renewIntervalMs;return Z}class a6{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await L7($,this.defaults,this.env);return this.held.push(Z),await this.assertAll(),Z}async assertAll(){for(let $ of this.held)await $.assertOwned()}async releaseTo($){while(this.held.length>$)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}var n6;function X0($){return{outcome:$,unmapped:[],differing:[],noteFailures:[],postPublishFailures:[]}}function RZ($,Z){return $!==null&&typeof $==="object"&&"code"in $&&$.code===Z}async function jZ($){try{return await j.lstat($),!0}catch(Z){if(RZ(Z,"ENOENT"))return!1;throw Z}}function y$($,Z,X,z){try{$.log[Z](X,z)}catch{}}function y3($,Z,X){let z=$,Y=new Set;while(z!==null&&typeof z==="object"&&!Y.has(z)){if(Y.add(z),z instanceof e||z instanceof M$||z instanceof B0)break;if(!("cause"in z))break;z=z.cause}try{OZ(z,Z,X)}catch(J){return{...X0(J instanceof A&&J.code==="settings-busy"?"busy":"failed"),cause:$}}}function x7($,Z,X,z){z.unmapped=[...X.unmapped];let Y=new Map;for(let B of X.entries){let G=Z[B.source];if(!Number.isInteger(B.source)||!G?.present)throw TypeError(`Move entry has no present source: ${B.source}`);let H=Object.hasOwn($.definition.settings,B.setting)?$.definition.settings[B.setting]:void 0,K=!H?"unknown-setting":!o(H.value,B.value)?"invalid-value":void 0;if(K){z.unmapped.push({source:B.source,key:B.setting,reason:K});continue}let W=Y.get(B.setting)??[];W.push({...B,host:G.host}),Y.set(B.setting,W)}let J={schema_version:1};for(let[B,G]of Object.entries($.definition.settings)){let H=Y.get(B)?.sort((U,D)=>U.source-D.source),K=H?.[0];if(!H||!K)continue;let W=new Map;if(G.overrides?.host)for(let U of["opencode","pi"]){let D=H.find((V)=>V.host===U);if(D&&!f3(D.value,K.value))W.set(U,D.value)}Object.defineProperty(J,B,{value:W.size?{default:K.value,...Object.fromEntries(W)}:K.value,enumerable:!0});let Q=H.map((U)=>({source:U.source,host:U.host,value:U.value}));if(Q.some(({host:U,value:D})=>!f3(W.has(U)?W.get(U):K.value,D)))z.differing.push({setting:B,values:Q}),y$($,"info",`Differing legacy settings: ${B}`,{values:Q})}return J}async function A7($){let Z=`${j7($)}.move-`,X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/i;for(let z of await j.readdir(f$($)))if(z.startsWith(Z)&&X.test(z.slice(Z.length)))await j.unlink(R7(f$($),z))}async function E7($,Z,X){for(let z of Z){if(!z.present)continue;let Y=`${z.path}.MOVED_READPLEASE`;try{let J;try{J=await j.open(Y,"wx")}catch(B){if(RZ(B,"EEXIST"))continue;throw B}try{await J.writeFile(`Settings moved to ${$.target}.
|
|
96
|
+
A rollback loses changes made after the move.
|
|
97
|
+
`,"utf8")}finally{await J.close()}}catch(J){X.noteFailures.push({path:Y,error:J}),y$($,"warn","Could not write settings move note",{path:Y,error:J})}}}async function S7($,Z,X,z,Y,J){let{target:B}=$,G=`${B}.move-${P7()}.tmp`,H=!1;try{let K=await j.open(G,"wx",420);H=!0;try{let W=[`// Settings moved on ${new Date().toISOString().slice(0,10)} (UTC) from:`,...$.sources.map((Q)=>`// ${JSON.stringify(Q.path)}`)].join(`
|
|
98
|
+
`);await K.writeFile(`${W}
|
|
99
|
+
${JSON.stringify(X,null,2)}
|
|
100
|
+
`,"utf8"),await K.sync()}finally{await K.close()}await n6?.("staged",{target:B,temp:G}),await n6?.("before-publish",{target:B,temp:G}),await z.assertOwned(),await Y.assertAll();try{await j.link(G,B)}catch(W){if(!RZ(W,"EEXIST"))throw W;return J.outcome="aborted-target-appeared",J}J.outcome="moved";try{await j.unlink(G),H=!1}catch(W){J.postPublishFailures.push({step:"temp-unlink",error:W}),y$($,"warn","Settings move temp cleanup failed",{temp:G,error:W})}if(process.platform!=="win32")try{let W=await j.open(f$(B),"r");try{await W.sync()}finally{await W.close()}}catch(W){J.postPublishFailures.push({step:"directory-sync",error:W}),y$($,"warn","Settings move directory sync failed",{target:B,error:W})}return await E7($,Z,J),J}finally{if(H&&J.outcome!=="moved")await j.unlink(G).catch(()=>{})}}async function C7($){try{if($.separateInstall)return X0("separate-install");if(await jZ($.target))return X0("done-already");if(!await $.fence())return X0("fence-closed");let Z=f$($.target);if(process.platform==="win32")await g0(Z);else await j.mkdir(Z,{recursive:!0,mode:448});let X;try{return await C0($.target,{name:"settings-move",...s6},async(z)=>{let Y=new a6(s6,{});try{let J=new Set,B=new Map;for(let G of $.sources)for(let H of G.locks){let K=T7(H.path),W=B.get(K)??new Set;if(W.has(H.name))continue;W.add(H.name),B.set(K,W);let Q=f$(N$(H.path,H.name));if(!await jZ(Q)){J.add(Q);continue}try{await Y.acquire(H)}catch(U){return X=y3(U,H.path,H.name),X}}if(await jZ($.target))X=X0("done-already");else if(!await $.fence())X=X0("fence-closed");else{await A7($.target),await n6?.("locked",{target:$.target});let G=[];for(let Q of $.sources){let U;try{U=await j.readFile(Q.path,"utf8")}catch(D){if(!RZ(D,"ENOENT"))throw D;G.push({host:Q.host,path:Q.path,present:!1});continue}G.push({host:Q.host,path:Q.path,present:!0,value:Q.read(U)})}let H=await $.map(G);for(let Q of J)if(await jZ(Q))return X=X0("busy"),X;let K=X0("failed"),W=x7($,G,H,K);X=await S7($,G,W,z,Y,K)}}catch(J){X={...X0("failed"),cause:J}}finally{await Y.releaseAll()}return X})}catch(z){if(!X)return y3(z,$.target,"settings-move");if(X.outcome==="moved")X.postPublishFailures.push({step:"lock-release",error:z});return y$($,"warn","Settings move lock release failed",{error:z}),X}}catch(Z){return{...X0("failed"),cause:Z}}}import{posix as w3,win32 as h3}from"node:path";function K$($,Z){if(Z!=="win32")return $.startsWith("/");if($.startsWith("\\\\?\\")||$.startsWith("\\\\.\\"))return!0;if(/^[a-zA-Z]:[\\/]/.test($))return!0;return/^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test($)}function m3({env:$,platform:Z,homedir:X}){let z=Z==="win32"?h3:w3,Y=(B)=>B!==void 0&&K$(B,Z),J;if(Y($.XDG_CONFIG_HOME))J=$.XDG_CONFIG_HOME;else if(Z==="win32"&&Y($.APPDATA))J=$.APPDATA;else{let B=Z==="win32"?$.USERPROFILE:$.HOME;if(!Y(B)){if(!Y(X))throw new A("settings-unavailable","No absolute home or config directory is available");B=X}J=Z==="win32"?z.join(z.join(B,"AppData"),"Roaming"):z.join(B,".config")}return z.join(J,"cortexkit")}function o6({plugin:$,override:Z,...X}){if(Z&&K$(Z,X.platform))return Z;return(X.platform==="win32"?h3:w3).join(m3(X),`${$}.jsonc`)}function Q$($){let Z=r6($),X=[];for(;;)try{return y7(g3.native(Z),...X)}catch{let z=f7(Z);if(z===Z)return r6($);X.unshift(k7(Z)),Z=z}}var v3=new Map;function t6($){let Z=v3.get($);if(Z===void 0)Z=Q$($),v3.set($,Z);return Z}function m7($={}){let Z=$.env??process.env,X=$.platform??process.platform,z=($.homedir??p3)(),Y=X==="win32"?h7:w7,J=Z.XDG_CONFIG_HOME,B=Y.join(J&&K$(J,X)?J:Y.join(z,".config"),"opencode"),G=Y.join(z,".config","opencode"),H=(D)=>{try{return g3.native(D)}catch{return r6(D)}},K=H(B),W=Y.join(Z.XDG_STATE_HOME||Y.join(z,".local","state"),"cortexkit","openai-auth",K===H(G)?"opencode":`opencode-${I7("sha256").update(K).digest("hex").slice(0,16)}`),Q=b7(Y.join(W,"layout.json"))?W:B,U=Y.join(z,".pi","agent");return[{host:"opencode",configPath:Y.join(B,TZ),statePath:Y.join(Q,xZ)},{host:"pi",configPath:Y.join(U,TZ),statePath:Y.join(U,xZ)}]}function oB($){let Z=$.env??process.env,X=$.platform??process.platform,z=$.homedir??p3,Y=m7({env:Z,platform:X,homedir:z}),J=Y[$.host==="opencode"?0:1],B=Q$($.paths.configPath),G=B!==Q$(J.configPath),H=$.host==="opencode"?"OPENCODE_OPENAI_AUTH_SETTINGS_FILE":"PI_OPENAI_AUTH_SETTINGS_FILE",K=Z[H],W=K!==void 0&&K$(K,X)?K:void 0;if(W!==void 0){let D=Q$(W);if([$.paths,...Y].some((_)=>Q$(_.configPath)===D||Q$(_.statePath)===D))W=void 0,($.logger??console).warn(`openai-auth ignored ${H}: the settings file must not be an account config or state file.`)}let Q=W!==void 0,U=!Q&&G;return{host:$.host,configIdentity:B,target:W??o6({plugin:"openai-auth",env:Z,platform:X,homedir:z()}),optIn:Q,separate:U,sources:U?[]:Q?G?[{host:$.host,...$.paths}]:[]:Y.map((D)=>D.host===$.host?{host:$.host,...$.paths}:D)}}var d3=Symbol.for("@cortexkit/openai-auth/settings-decisions"),l3=globalThis,AZ=l3[d3]??new Map;l3[d3]=AZ;function c3($){return AZ.get(t6($))}function eB($,Z){let X=t6($),z=AZ.get(X);if(z!==void 0)return z;return AZ.set(X,Z),Z}import{readFile as $5}from"node:fs/promises";var u0=p("refresh"),v$=p("accounts"),d7=1e4,l7=15000,e6=50;function U0($){return $.type==="oauth"&&$.corrupt!==!0}function c7($){let Z=$?.trim();if(!Z)return!1;try{let X=new URL(Z);return(X.protocol==="http:"||X.protocol==="https:")&&!X.username&&!X.password}catch{return!1}}var u7="floors-v1";function DG($){return $.costZeroing?.enabled!==!1}class SZ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var i7=[401,403,429],u3={primary:0,secondary:0},s7=!1,Z8={primary:5,secondary:10};function M($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var a7=new Set(["__proto__","constructor","prototype"]);function n7($){return $.length>0&&!a7.has($)}function o7($){return $ instanceof SZ||M($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function EZ($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():g7(),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 i3($){if(!M($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let X=Number($.nextRetryAt),z=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(X)?X:void 0,retryCount:Number.isFinite(z)?z:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function r7($){if(!M($))return;let Z={};for(let Y of["primary","secondary"]){let J=$[Y];if(!M(J))continue;let B=Number(J.usedPercent),G=Number(J.remainingPercent),H=Number(J.checkedAt);if(!Number.isFinite(B)||!Number.isFinite(G)||!Number.isFinite(H))continue;let K=typeof J.windowMinutes==="number"?J.windowMinutes:Number.NaN;Z[Y]={usedPercent:B,remainingPercent:G,checkedAt:H,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...Number.isFinite(K)&&K>0?{windowMinutes:K}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let J=typeof $[Y]==="number"?$[Y]:Number.NaN;if(Number.isFinite(J)&&J>=0)Z[Y]=J}let X=$.spendControl;if(M(X)){let Y=Number(X.limit),J=Number(X.used),B=Number(X.remaining),G=Number(X.usedPercent),H=Number(X.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(G)&&Number.isFinite(H)&&typeof X.reached==="boolean")Z.spendControl={limit:Y,used:J,remaining:B,usedPercent:G,remainingPercent:H,resetsAt:typeof X.resetsAt==="string"?X.resetsAt:void 0,unit:typeof X.unit==="string"?X.unit:void 0,source:typeof X.source==="string"?X.source:void 0,reached:X.reached}}let z=$.credits;if(M(z)&&typeof z.hasCredits==="boolean"&&typeof z.unlimited==="boolean"&&(z.overageLimitReached===void 0||typeof z.overageLimitReached==="boolean")){let Y=Number(z.balance),J=typeof z.checkedAt==="number"?z.checkedAt:Number.NaN;Z.credits={hasCredits:z.hasCredits,unlimited:z.unlimited,...typeof z.overageLimitReached==="boolean"?{overageLimitReached:z.overageLimitReached}:{},...Number.isFinite(Y)?{balance:Y}:{},...Number.isFinite(J)?{checkedAt:J}:{}}}return Object.keys(Z).length?Z:void 0}function t7($){if(!M($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!c7(Z))return null;let z=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...EZ($),type:"api",apiKey:X||void 0,baseURL:Z,authHeader:z}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...EZ($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...EZ($),type:"oauth",corrupt:!0}}return{...EZ($),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:i3($.lastRefreshError),lastQuotaRefreshError:i3($.lastQuotaRefreshError),quota:r7($.quota)}}function e7($){if(!M($))return;let Z=Object.create(null);for(let[X,z]of Object.entries($)){if(!n7(X)||!M(z))continue;let Y={};if(M(z.inFlight))Y.inFlight={...z.inFlight};if(M(z.lastOutcome)&&typeof z.lastOutcome.code==="string"&&z.lastOutcome.code.length>0&&typeof z.lastOutcome.at==="number"&&Number.isFinite(z.lastOutcome.at))Y.lastOutcome={code:z.lastOutcome.code,at:z.lastOutcome.at,...M(z.lastOutcome.previousOutcome)&&typeof z.lastOutcome.previousOutcome.code==="string"&&z.lastOutcome.previousOutcome.code.length>0&&typeof z.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(z.lastOutcome.previousOutcome.at)?{previousOutcome:{code:z.lastOutcome.previousOutcome.code,at:z.lastOutcome.previousOutcome.at}}:{}};if(typeof z.cooldownUntil==="number"&&Number.isFinite(z.cooldownUntil))Y.cooldownUntil=z.cooldownUntil;if(Object.keys(Y).length>0)Z[X]=Y}return Object.keys(Z).length>0?Z:void 0}var s3=new Set;function Z1($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(s3.has(Z))return;s3.add(Z),v$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function X1($){if(!M($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(t7).filter((z)=>z!=null);if(X.length<Z.length){let z=new Set;for(let B of Z)if(M(B)&&typeof B.id==="string"&&B.id.trim())z.add(B.id.trim());let Y=new Set(X.map((B)=>B.id)),J=[];for(let B of z)if(!Y.has(B))J.push(B);Z1(J)}return{version:1,main:{type:"opencode",provider:"openai"},routing:M($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((z)=>Number.isInteger(z)):void 0,refresh:M($.refresh)?$.refresh:void 0,quota:M($.quota)?$.quota:void 0,reset:e7($.reset),dump:M($.dump)?$.dump:void 0,costZeroing:M($.costZeroing)?$.costZeroing:void 0,killswitch:M($.killswitch)?$.killswitch:void 0,logging:M($.logging)?$.logging:void 0,cachekeep:M($.cachekeep)?$.cachekeep:void 0,cacheKeep:M($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:X}}function z1($){if(!("claustrum"in $))return $;let{claustrum:Z,...X}=$;return X}async function D0($){try{return{exists:!0,value:JSON.parse(await $5($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function z0($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function Z5($){let Z;try{Z=(await D0($)).value}catch{return null}return J8(Z)}function Y1($,Z){if(!M($))return $;let X=M(Z)?Z:{},z=M(X.main)?X.main:void 0,Y=M(X.accounts)?X.accounts:{},J=M($.quota)?$.quota:{},B=M($.refresh)?$.refresh:{},G=z??J,H=z??B,W=B.mainRefreshLeaseId!==void 0?{id:B.mainRefreshLeaseId,until:B.mainRefreshLeaseUntil,tokenHash:B.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!M(D))return D;let V=typeof D.id==="string"&&M(Y[D.id])?Y[D.id]:{};return{...D,...V}}):void 0;return J1({...$,refresh:z0({...B,mainLastRefreshError:B.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:z0({...J,mainQuota:G.quota,mainQuotaCheckedAt:G.quotaCheckedAt,mainQuotaToken:G.quotaToken,mainLastQuotaApiError:G.lastQuotaApiError}),accounts:U})}async function X5($){let Z=await D0($.configPath);if(!Z.exists)return null;let X=await D0($.statePath);return X1(Y1(Z.value,X.value))}var a3=new Set;async function qG($){try{let{exists:Z,value:X}=await D0($.configPath);if(!Z)return null;if(!M(X))throw Error("settings must be an object");let z=M(X.refresh)?X.refresh:{},Y=M(X.quota)?X.quota:{};return{version:1,accounts:[],routing:M(X.routing)?X.routing:void 0,fallbackOn:Array.isArray(X.fallbackOn)?X.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:z0({enabled:z.enabled,refreshBeforeExpiryMinutes:z.refreshBeforeExpiryMinutes}),quota:z0({enabled:Y.enabled,checkIntervalMinutes:Y.checkIntervalMinutes,refreshEveryNRequests:Y.refreshEveryNRequests,minimumRemaining:Y.minimumRemaining,failClosedOnUnknownQuota:Y.failClosedOnUnknownQuota}),dump:M(X.dump)?X.dump:void 0,costZeroing:M(X.costZeroing)?X.costZeroing:void 0,killswitch:M(X.killswitch)?X.killswitch:void 0,logging:M(X.logging)?X.logging:void 0,cachekeep:M(X.cachekeep)?X.cachekeep:void 0,cacheKeep:M(X.cacheKeep)?X.cacheKeep:void 0}}catch{if(!a3.has($.configPath))a3.add($.configPath),v$.warn("could not read OpenAI auth settings; using defaults",{path:$.configPath});return null}}function J1($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function z5($){return z0({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 B1($){if($.type==="api")return z0({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return z0({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function CZ($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function w$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function Y5($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function J5($,Z){if(!Y5($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var B5=300000;function n3($,Z){if($===void 0)return 0;return $>Z+B5?0:$}function G5($,Z,X){let z=Date.now(),Y=n3(Z.lastRefreshedAt,z),J=n3(X.lastRefreshedAt,z),B=Z.expires??0,G=X.expires??0,H=J>Y?X:Y>J?Z:G>B?X:B>G?Z:J5(Z,X);w$($,H,"access"),w$($,H,"refresh"),w$($,H,"expires"),w$($,H,"lastRefreshedAt"),w$($,H,"lastRefreshError")}function H5($,Z){if(!M($))return Z;let X=$,z=CZ(X.quota),Y=CZ(Z.quota),J=z>Y,B=J?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!J&&!("lastQuotaRefreshError"in Z))delete B.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete B.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))B.lastUsed=X.lastUsed;return G5(B,X,Z),B}function G1($){let Z=$.refresh?z0({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,X=$.quota?z0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return J1({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:X,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,cacheKeep:$.cacheKeep,mainAccountId:$.mainAccountId,accounts:$.accounts.map(z5)})}function K5($,Z,X,z){if(c3(z)!=="shared")return $;let Y={...$};for(let B of["routing","fallbackOn","refresh","quota","dump","costZeroing","killswitch","logging","cachekeep","cacheKeep","dumpDir","dumpMaxBytes","webSockets","rawWebSocket","responsesLite","codexApiEndpoint"])if(delete Y[B],Object.hasOwn(Z,B))Y[B]=Z[B];let J=M(Z.refresh)?{...Z.refresh}:{};for(let B of["mainLastRefreshError","mainRefreshLeaseId","mainRefreshLeaseUntil","mainRefreshLeaseTokenHash"]){delete J[B];let G=X.refresh?.[B];if(G!==void 0)J[B]=G}if(M(Z.refresh)||Object.keys(J).length>0)Y.refresh=J;return Y}async function g$($,Z=!1){let X=Date.now(),z=X+l7,Y=0;while(Date.now()<=z){Y++;let G=await g({name:"save",ttlMs:d7,path:$,renew:Z});if(G)return G;let H=z-Date.now();if(H<=0)break;await p7(Math.min(e6+U1(e6),H))}let J=Date.now()-X,B=Math.round(J/Math.max(1,Y));throw Error(`Timed out after ${J}ms waiting for the account store lock on ${$} (${Y} attempts, ~${B}ms apart; retry interval is ${e6}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 H1($){let Z=Object.fromEntries($.accounts.map((X)=>[X.id,B1(X)]));return{version:1,main:z0({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 J8($){if(!M($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let X of $.accounts){if(!M(X))continue;if(typeof X.id!=="string")continue;let z=X.id.trim();if(!z)continue;Z.add(z)}return Z}function Q5($,Z,X,z){if(!M($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],J=[];for(let B of Z){if(X.has(B))continue;if(z.has(B))continue;let G=$.accounts.find((H)=>M(H)&&typeof H.id==="string"&&H.id.trim()===B);if(!G)continue;Y.push(G),J.push(B)}return{preservedRawEntries:Y,preservedIds:J}}function W5($){if(!Array.isArray($))return[];let Z=[];for(let X of $){if(!M(X))continue;if(typeof X.id!=="string")continue;Z.push(X.id)}return Z}function U5($,Z,X){let z=J8($);if(z===null)return[];let{preservedRawEntries:Y,preservedIds:J}=Q5($,z,Z,X);return Z1(J),Y}async function NG($,Z,X={}){let{configPath:z,statePath:Y}=Z,J=await g$(z);try{let B=await g$(Y);try{let G=await D0(z),H=await D0(Y),K=M(G.value)?structuredClone(G.value):{},W=(G.exists?X1(Y1(G.value,H.value)):null)??D5(),Q=new Set(W.accounts.map((O)=>O.id)),U=J8(G.value)??new Set,D=$(W,{rawRosterIds:[...U],loadedRosterIds:[...Q]})??W,V=new Set(X.allowDrop??[]),_=U5(G.value,Q,V),N=G1(D),R=new Set((Array.isArray(N.accounts)?N.accounts:[]).map((O)=>M(O)&&typeof O.id==="string"?O.id.trim():"").filter(Boolean)),x=_.filter((O)=>{if(!M(O))return!1;if(typeof O.id!=="string")return!1;return!R.has(O.id.trim())}),L={...z1(K),...N,accounts:[...Array.isArray(N.accounts)?N.accounts:[],...x]};if(X.canWrite&&!X.canWrite())return W;if(await G0(z,K5(L,K,D,z)),X.canWrite&&!X.canWrite())return W;return await G0(Y,H1(D)),v$.debug("account config written",{accountCount:L.accounts.length,accountIds:W5(L.accounts)}),D}finally{await B.release()}}finally{await J.release()}}function D5(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function V5($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:CZ($.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:CZ(Z.quota?.mainQuota);if(X>z)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function q5($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function X8($){if(Array.isArray($))return $.map(X8);if(!M($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,X8(X)]))}async function N5($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},z){let Y=Z.statePath,J=await g$(Y);try{let B=(await D0(Y)).value,G=M(B)?{...B,version:1}:{version:1};if(X.mainQuota)V5(G,$);if(X.mainRefresh)q5(G,$);if(X.accounts){let H=X.accounts===!0?null:new Set(X.accounts),K=await Z5(Z.configPath);G.accounts={...M(G.accounts)?G.accounts:{}};for(let W of $.accounts){if(H&&!H.has(W.id))continue;if(K&&!K.has(W.id))continue;G.accounts[W.id]=H5(G.accounts[W.id],B1(W))}if(H){for(let W of H)if(!$.accounts.some((Q)=>Q.id===W))delete G.accounts[W]}if(K){for(let W of Object.keys(G.accounts))if(!K.has(W))delete G.accounts[W]}}if(z&&!z())return;await G0(Y,X8(G))}finally{await J.release()}}function M5($){return $?.fallbackOn?.length?$.fallbackOn:i7}function MG($,Z){return M5(Z).includes($)}function _5($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??u3.primary,secondary:Z.secondary??Z["1w"]??u3.secondary}}function z8($){return $?.quota?.enabled!==!1}function p$($){return $?.quota?.failClosedOnUnknownQuota??s7}function K1($,Z,X=Date.now()){if(!z8(Z))return!0;if(!$)return!p$(Z);let z=_5(Z),Y=p$(Z);for(let J of["primary","secondary"]){let B=$[J];if(!B)continue;if(LZ(B,X)){if(Y)return!1;continue}if(B.remainingPercent<z[J])return!1}return!0}function IZ($){return $?.killswitch?.enabled===!0}function o3($){return{primary:$?.primary??$?.["5h"]??Z8.primary,secondary:$?.secondary??$?.["1w"]??Z8.secondary}}function _G($){return $?.cacheKeep??$?.cachekeep}function r3($){return typeof $==="number"&&Number.isFinite($)?$:0}function Q1($,Z){if(!$?.killswitch)return Z8;if($.killswitch.schema===u7){let{accounts:X,defaults:z}=$.killswitch,Y=Z??"main",J=M(X)&&Object.hasOwn(X,Y)&&M(X[Y])?X[Y]:M(z)?z:void 0;return{primary:r3(J?.primary),secondary:r3(J?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return o3($.killswitch.accounts[Z]);return o3($.killswitch.main)}function W1($,Z,X,z=Date.now()){if(!IZ(Z))return!0;if(!$)return!p$(Z);let Y=Q1(Z,X),J=p$(Z);for(let B of["primary","secondary"]){let G=$[B];if(!G)continue;if(LZ(G,z)){if(J)return!1;continue}if(G.remainingPercent<Y[B])return!1}return!0}function FG($,Z,X,z){if(!IZ(z))return 300;let Y=[],J=[{accountId:void 0,quota:$},...Z];for(let{accountId:G,quota:H}of J){if(!H)continue;let K=Q1(z,G),W=[],Q=!1;for(let U of["primary","secondary"]){let D=H[U];if(!D||LZ(D,X))continue;if(D.remainingPercent>=K[U])continue;let V=D.resetsAt?Date.parse(D.resetsAt):NaN;if(!Number.isFinite(V)||V<=X){Q=!0;break}W.push(V)}if(Q||W.length===0)continue;Y.push(Math.max(...W))}if(Y.length===0)return 300;let B=Math.min(...Y);return Math.max(1,Math.ceil((B-X)/1000))}function t3($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function LG($,Z){let{configPath:X,statePath:z}=Z;if(!$)return;try{let J=await D0(X);if(J.exists&&M(J.value)&&t3(J.value))return}catch{}let Y=await g$(X);try{let J=await g$(z);try{let B=await D0(X);if(B.exists&&M(B.value)){if(t3(B.value))return}if(!$)return;let G={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let W=t$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(W)G.mainAccountId=W}let H=B.exists&&M(B.value)?B.value:{},K={...z1(H),...G1(G)};await G0(X,K),await G0(z,H1(G))}finally{await J.release()}}finally{await Y.release()}}function F5($){return $?.refresh?.enabled!==!1}function L5($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function U1($){return Math.floor(Math.random()*($+1))}function i0($,Z,X){return!$.access||!$.expires||$.expires-X<=L5(Z)}function O5($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function h$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class D1 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 P5="common-auth-placeholder:v1:openai",V1="main";function OG($){return M($)&&$.type==="oauth"&&($.refresh===P5||$.refresh===D3)}function PG($){return $?.accounts.find((Z)=>Z.id===V1&&Z.enabled!==!1&&U0(Z))}function jG($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==V1)}}function d($,Z){let X=$.accounts.findIndex((z)=>z.id===Z.id);if(X!==-1)$.accounts[X]=Z}function m$($){return $ instanceof Error?$.message:String($)}function Y8($,Z,X){if(Z instanceof S$)return;$.lastRefreshError=C8({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function $8($,Z,X){if(Z instanceof S$)return;if($.lastQuotaRefreshError=_$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)Y8($,Z,X)}function e3($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function j5($,Z){if(!$)return!1;return e3($.primary,Z)||e3($.secondary,Z)}function R5($,Z,X){if(!$)return!1;let z=Z?.quota?.checkIntervalMinutes??5,Y=Math.max(1,z)*60000,J=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return X-J<Y}function $1($,Z,X){return!R5($.quota,Z,X)}function T5($,Z,X,z){return eZ(X)&&K1($.quota,Z,z)&&j5($.quota,z)}function x5($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var A5=60000,E5=60000,S5=600000;function C5($){return`fallback-oauth-refresh-${v7("sha256").update($).digest("base64url").slice(0,16)}`}var I5=1e4,b5=100;class k5{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($)FZ($.refresh)}seedFallbackQuota($,Z){if(!this.quotaManager)return;if(!$.quota)return;let X=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(X<=0)return;let z=this.quotaManager.getFallback($.id,$.access);if(z&&z.checkedAt>=X)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:X+x5(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return X5(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await N5($,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(()=>{})},A5+U1(E5)),"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 X=[],z=!1;for(let Y of Z.accounts){if(Y.enabled===!1||!U0(Y))continue;if(h$(Z,Y))continue;if(l0(Y))continue;let J=!1,B=Y;try{if(i0(B,Z,this.now())){let G=B.lastRefreshError;if(G&&I0(G,B.refresh,this.now()))throw J=!0,Error(o$(G,this.now()));try{B=await this.refreshAccount(B,Z),z=!0}catch(H){if(o7(H))continue;J=!0;let K=Z.accounts.find((W)=>W.id===Y.id&&U0(W));if(K&&!I0(K.lastRefreshError,K.refresh,this.now()))Y8(K,H,this.now()),d(Z,K),z=!0;throw H}}if(this.seedFallbackQuota(B,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(B),Z))X.push(B)}catch(G){let H=O5(B,this.now());if(J){if(!H)continue}else if(!H)continue;if(T5(B,Z,G,this.now()))u0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:B.id,error:m$(G)}),X.push(B);else if(!p$(Z))X.push(B)}}if(z){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((J)=>{v$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:m$(J)})})}return X}async markUsed($){try{let Z=await this.load();if(!Z)return;let X=Z.accounts.find((z)=>z.id===$.id);if(!X)return;X.lastUsed=this.now(),await this.save(Z,[X.id])}catch(Z){v$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:m$(Z)})}}accountPassesQuotaPolicy($,Z){return K1($.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(!$||!F5($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!U0(X))continue;if(h$($,X))continue;if(l0(X))continue;if(!i0(X,$,this.now()))continue;if(I0(X.lastRefreshError,X.refresh,this.now()))continue;try{u0.debug("fallback oauth background due",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),await this.refreshAccount(X,$),Z=!0}catch(z){u0.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:m$(z)}),Y8(X,z,this.now()),d($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!z8($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!U0(X))continue;if(h$($,X))continue;if(l0(X))continue;let z=X;try{if(i0(z,$,this.now())){if(I0(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,$),Z=!0}if(e0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,$),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):$1(z,$,this.now())))continue;await this.refreshAccountQuota(z,$),Z=!0}catch(Y){$8(X,Y,this.now()),d($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!z8(Z))return{storage:Z,errors:X};if(!this.options.fetchQuotaFn)return{storage:Z,errors:X};let z=$.force??!1,Y=!1;for(let J of Z.accounts){if(J.enabled===!1||!U0(J))continue;if(h$(Z,J))continue;if(l0(J))continue;let B=J;try{if(i0(B,Z,this.now())){let G=B.lastRefreshError;if(G&&I0(G,B.refresh,this.now()))throw Error(o$(G,this.now()));B=await this.refreshAccount(B,Z),Y=!0}if(!z&&!$1(B,Z,this.now())){if(B.lastQuotaRefreshError)B.lastQuotaRefreshError=void 0,d(Z,B),Y=!0;continue}await this.refreshAccountQuota(B,Z),Y=!0}catch(G){$8(J,G,this.now()),d(Z,J),Y=!0,X.push({accountId:J.id,message:m$(G)})}}if(Y)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let z=this.refreshPromises.get($.id);if(z){let B=await z;return d(Z,B),B}let Y=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let J=await Y;return d(Z,J),J}async waitForConcurrentFallbackRefresh($,Z,X,z){let Y=Date.now()+I5;while(Date.now()<Y){await new Promise((K)=>setTimeout(K,b5));let J=await this.load(),B=J?.accounts.find((K)=>K.id===$.id&&U0(K));if(!B)continue;if(this.assertNotTombstoned(B),(B.access!==X.access||B.refresh!==X.refresh||(B.expires??0)>(X.expires??0)+60000)&&(z.force||!i0(B,J,this.now())))return d(Z,B),u0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:B.id,expiresInMs:B.expires?B.expires-this.now():void 0}),B;let H=B.lastRefreshError;if(H&&I0(H,B.refresh,this.now()))throw d(Z,B),Error(o$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(h$($,Z))throw new D1(Z.id)}async refreshAccountNow($,Z,X){let z=await this.load(),Y=z?.accounts.find((G)=>G.id===$.id&&U0(G));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(z,Y,X),Y&&!X.force&&!i0(Y,z,this.now()))return d(Z,Y),Y;let J=Y??$,B=await g({name:C5(J.id),ttlMs:S5,path:this.paths.configPath,renew:!0});if(!B){u0.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:J.id});let G=await this.waitForConcurrentFallbackRefresh($,Z,J,X);if(G)return G;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),Y=z?.accounts.find((W)=>W.id===$.id&&U0(W)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(z,Y,X),Y&&!X.force&&!i0(Y,z,this.now()))return d(Z,Y),Y;if(!Y)throw new SZ($.id);J=Y;let G=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});u0.debug("fallback oauth refresh request start",{pid:process.pid,accountId:J.id,force:X.force===!0,expiresInMs:J.expires?J.expires-this.now():void 0});let H=await G({refreshToken:J.refresh,fetchImpl:this.fetchImpl,now:this.now});if(J.access=H.access,J.refresh=H.refresh,J.expires=H.expires,J.lastRefreshedAt=H.expires-H.expiresIn*1000,J.lastRefreshError=void 0,d(Z,J),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new SZ($.id);return u0.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J}finally{await B.release()}}async refreshAccountQuota($,Z){let X=$;if(this.assertNotTombstoned(X),!X.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 z=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(J)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,J):z({accessToken:J,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${$.id} has no access token`);let J=await Y(X.access);X.quota=J,X.lastQuotaRefreshError=void 0,d(Z,X),await this.save(Z)}catch(J){throw $8($,J,this.now()),d(Z,$),J}}}var q1=["primary","secondary"];function bZ($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function W$($){return typeof $==="number"&&Number.isFinite($)}function f5($,Z){if(!bZ(Z))return;let X=Z.usedPercent;if(!W$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...W$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function y5($){let Z=$.spendControl;if(bZ(Z)&&typeof Z.reached==="boolean"){let X=(z)=>W$(Z[z])?{[z]:Z[z]}:{};return{kind:"reading",reached:Z.reached,...X("remainingPercent"),...X("usedPercent"),...X("limit"),...X("used"),...X("remaining"),...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...typeof Z.unit==="string"?{unit:Z.unit}:{}}}if($.spendControlCleared===!0)return{kind:"cleared"};return}function w5($,Z){if(!bZ($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...W$($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function xG($,Z,X){if(!bZ($)||!W$(Z))return;let z=[],Y=[];for(let K of q1){let W=f5(K,$[K]);if(W)z.push(W);else if(X)Y.push({label:K})}let J=y5($),B=$.resetCreditsAvailable,G=typeof B==="number"&&Number.isSafeInteger(B)&&B>=0?{resetCredits:{value:B,checkedAt:Z}}:void 0,H=w5($.credits,Z);if(z.length===0&&Y.length===0&&!J&&!G&&!H)return;return{checkedAt:Z,...z.length>0?{readings:z}:{},...Y.length>0?{coverage:Y}:{},...J?{budget:J}:{},...G?{counters:G}:{},...H?{credits:H}:{}}}function N1($){if(!A0($))return;let Z=s($),X={};for(let z of q1){let Y=Z.limits.find((B)=>B.label===z&&B.kind==="reading");if(!Y||!W$(Y.usedPercent))continue;let J={usedPercent:Y.usedPercent,remainingPercent:100-Y.usedPercent,checkedAt:Y.checkedAt,...Y.resetsAt!==void 0?{resetsAt:Y.resetsAt}:{},...Y.windowMinutes!==void 0?{windowMinutes:Y.windowMinutes}:{}};X[z]=J}return X.primary||X.secondary?X:void 0}var _1="main";function bG($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function kG($,Z,X){let z=new Map;if(IZ(Z))for(let Y of $)z.set(Y.id,W1(N1(Y.quota),Z,Y.id===_1?void 0:Y.id,X));return z}var fG=5,h5=5000;function yG($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function wG($,Z=h5){let X=$.rows.filter((B)=>B.kind==="oauth"&&$.killswitch.get(B.id)!==!1&&s(B.quota).limits.length===0);if(X.length===0)return;if(t({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((B)=>$.killswitch.get(B.id)!==!1))return;let Y=[];if(t({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(B)=>{let G=$.requestPull(B);if(G)Y.push(G.catch(()=>{}))}}),Y.length===0)return;let J;return Promise.race([Promise.all(Y),new Promise((B)=>{J=setTimeout(B,Z)})]).then(()=>{}).finally(()=>clearTimeout(J))}function kZ($){return $.reason==="exhausted"||$.reason==="budget-spent"}function m5($,Z){if(!J0($))return!1;let X=$;if(!(Z-X.checkedAt<=q$))return!1;if(X.overageLimitReached===!0)return!1;if(X.unlimited)return!0;return X.hasCredits&&(X.balance===void 0||X.balance>0)}function fZ($,Z,X){let z=(G)=>Z.killswitch.get(G)!==!1,Y=new Set(X.admitted.filter((G)=>G.lastPath!==!0&&z(G.id)).map((G)=>G.id)),J=new Map(X.refused.map((G)=>[G.id,G])),B=$.filter((G)=>{if(G.kind!=="oauth"||!z(G.id))return!1;if(J.get(G.id)?.reason!=="exhausted")return!1;let H=s(G.quota);if(S0(H,Z.now))return!1;return m5(H.credits,Z.now)}).map((G)=>G.id);return{free:Y,credits:B}}function v5($,Z=$.rows){return t({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class g5{#$=new Set;served($,Z,X){let z=v5($),Y=fZ($.rows,$,z),J=new Set(Y.credits);if(Y.free.has(Z)){this.#$.clear();return}for(let B of[...this.#$])if(!J.has(B))this.#$.delete(B);if(!J.has(Z)||this.#$.has(Z))return;this.#$.add(Z),X?.info("serving requests on prepaid credits",{accountId:Z,reason:"free quota used up"})}has($){return this.#$.has($)}ids(){return new Set(this.#$)}}function F1($,Z,X){if($===void 0)return{reason:"no-credential"};if(X.get($)===!1)return{reason:"killswitch"};let z=Z.excluded.find((J)=>J.id===$);if(z?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:z.until};if(z)return{reason:"no-credential"};let Y=Z.refused.find((J)=>J.id===$);if(Y&&"resetAtMs"in Y)return{reason:"quota-exhausted",resetAtMs:Y.resetAtMs};if(Y)return{reason:"quota-unknown"};return{reason:"no-credential"}}function M1($,Z,X){if(Z.refused.find((Y)=>!kZ(Y)&&X.get(Y.id)!==!1))return{reason:"quota-unknown"};return F1($[0],Z,X)}function hG($){let Z=$.replayable!==!1,X=$.mainId===void 0?_1:$.mainId??"",z=Z?$.placement:"main-first",Y=uZ({rows:$.rows,placement:z,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),J=a$($.rows.map((U)=>U.id),z,X),B=new Set(Y.admission.refused.filter((U)=>kZ(U)&&$.killswitch.get(U.id)!==!1).map((U)=>U.id)),G=J.filter((U)=>B.has(U)),H=fZ($.rows,$,Y.admission),K=Y.order.filter((U)=>H.free.has(U)),W=J.filter((U)=>H.credits.includes(U)),Q=(U,D)=>({kind:"send",order:U,lastPath:D,tiers:Object.fromEntries(U.map((V)=>[V,H.free.has(V)?"free":H.credits.includes(V)?"credits":"last-path"]))});if(!Z){let U=J.includes(X),D=U?X:K[0]??W[0]??Y.order[0]??G[0];if(D!==void 0&&Y.order.includes(D))return Q([D],!1);if(D!==void 0&&W.includes(D))return Q([D],!1);if(D!==void 0&&B.has(D))return Q([D],!0);return{kind:"block",block:U?F1(X,Y.admission,$.killswitch):M1(J,Y.admission,$.killswitch)}}if(K.length>0)return Q(K,!1);if(W.length>0){let U=Y.order.length>0?Y.order:G;return Q([...W,...U.filter((D)=>!W.includes(D))],!1)}if(Y.order.length>0)return Q(Y.order,!1);if(G.length>0)return Q(G,!0);return{kind:"block",block:M1(J,Y.admission,$.killswitch)}}function mG($){let Z=t({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),X=new Map;for(let z of $.rows)X.set(z.id,s(z.quota));for(let z of Z.admitted)if(z.projection)X.set(z.id,z.projection);return{projections:X,excluded:new Set(Z.excluded.map((z)=>z.id))}}function L1($,Z,X){let z=X.exclude,Y=z?$.rows.filter((B)=>!z.has(B.id)):$.rows,J=new Map;for(let B of Y){let G=Z.resetCredits(B.id);if(G!==void 0)J.set(B.id,G)}return oZ({rows:Y,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(B)=>Z.reservePercent(B.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:J,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function vG($,Z,X,z){let Y=L1($,Z,{exclude:X,pendingBytes:z}),J=$.rows.filter((W)=>!X.has(W.id)),B=fZ(J,$,Y.admission),G=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,tier:B.free.has(Y.accountId)?"free":"last-path",...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(G&&B.free.has(G.accountId))return G;let H=B.credits[0];if(H===void 0)return G;let K=s(J.find((W)=>W.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",tier:"credits",...K===void 0?{}:{quotaCheckedAt:K}}}function gG($,Z,X){let z=$.killswitch.get(X)===!1,Y={kind:"move",reason:z?"killswitch":"exhausted"},J=L1($,Z,{pin:X}),B=fZ($.rows,$,J.admission),G=B.credits.includes(X),H=B.credits.some((Q)=>Q!==X);if(J.outcome==="dispatch"){let Q=!B.free.has(J.accountId);if(J.pin.action==="assign"){if(Q&&G)return{kind:"serve",tier:"credits"};return Y}if(J.accountId!==X)return{kind:"detour"};if(Q&&H)return Y;return{kind:"serve",tier:Q?"last-path":"free"}}let K=J.admission.refused.find((Q)=>Q.id===X),W=z||K!==void 0&&kZ(K);if(G)return{kind:"serve",tier:"credits"};if(H)return W?Y:{kind:"detour"};if(!z&&K&&kZ(K))return{kind:"last-path"};return{kind:"none"}}function pG($,Z,X,z){let Y=$.killswitch.get(X);return nZ({quota:Z.projections.get(X),now:$.now,...z===void 0?{}:{status:z},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as O1}from"node:os";import{join as P1}from"node:path";var p5=["error","warn","info","debug","trace"];function d5(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?P1(O1(),"opencode-openai-auth","opencode-openai-auth.log"):P1(O1(),"opencode-openai-auth.log"))}function l5(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&p5.includes($)?$:void 0}function nG($,Z){if($!=="default")yZ($);else if(Z==="refresh")yZ(void 0)}j1({file:d5,level:l5});if(process.once("beforeExit",async()=>{try{await wZ()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>wZ());
|
|
101
|
+
export{A0 as Bd,V$ as Cd,s1 as Dd,pZ as Ed,C1 as Fd,F8 as Gd,y1 as Hd,w1 as Id,s as Jd,S0 as Kd,j8 as Ld,n1 as Md,a$ as Nd,o1 as Od,iZ as Pd,r1 as Qd,s6 as Rd,a6 as Sd,w9 as Td,h9 as Ud,M0 as Vd,q as Wd,S as Xd,w0 as Yd,h2 as Zd,m2 as _d,b as $d,m0 as ae,D9 as be,t2 as ce,V6 as de,e2 as ee,$4 as fe,N6 as ge,z4 as he,O0 as ie,R9 as je,Y4 as ke,f as le,p0 as me,h6 as ne,gY as oe,$2 as pe,B2 as qe,S8 as re,C8 as se,I0 as te,o$ as ue,y8 as ve,h8 as we,W2 as xe,b8 as ye,k8 as ze,t$ as Ae,D2 as Be,y0 as Ce,M2 as De,_2 as Ee,F2 as Fe,L2 as Ge,hX as He,vX as Ie,gX as Je,pX as Ke,l0 as Le,S$ as Me,QJ as Ne,WJ as Oe,_J as Pe,n as Qe,T0 as Re,o4 as Se,r4 as Te,t4 as Ue,e4 as Ve,$7 as We,Z7 as Xe,X7 as Ye,z7 as Ze,A as _e,F7 as $e,C7 as af,Q$ as bf,t6 as cf,oB as df,c3 as ef,eB as ff,U0 as gf,u7 as hf,DG as if,Z8 as jf,n7 as kf,Z5 as lf,X5 as mf,qG as nf,NG as of,N5 as pf,M5 as qf,MG as rf,K1 as sf,IZ as tf,_G as uf,Q1 as vf,W1 as wf,FG as xf,LG as yf,L5 as zf,h$ as Af,V1 as Bf,OG as Cf,PG as Df,jG as Ef,S5 as Ff,C5 as Gf,k5 as Hf,xG as If,N1 as Jf,_1 as Kf,bG as Lf,kG as Mf,fG as Nf,h5 as Of,yG as Pf,wG as Qf,m5 as Rf,g5 as Sf,hG as Tf,mG as Uf,vG as Vf,gG as Wf,pG as Xf,nG as Yf};
|