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