@cortexkit/opencode-openai-auth 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +9 -9
- package/dist/{codex-request-CN4rD2kf.d.ts → codex-request-DohnbsFR.d.ts} +69 -21
- package/dist/index-3v868rnp.js +63 -0
- package/dist/{index-7zy4vdd3.js → index-5d4y47h8.js} +2 -2
- package/dist/{index-yayz83vv.js → index-5dxpsa3t.js} +2 -2
- package/dist/{index-dr93b3g6.js → index-8pk9savd.js} +6 -6
- package/dist/{index-g08eptzm.js → index-cbcka7sa.js} +1 -1
- package/dist/{index-p9vnmnzr.js → index-cxstwq02.js} +1 -1
- package/dist/{index-r4avvxf0.js → index-dtwgf694.js} +1 -1
- package/dist/index-dzaqj248.js +2 -0
- package/dist/index-g3d50jz0.js +74 -0
- package/dist/{index-2e2kqmsy.js → index-n7fxqgfb.js} +2 -2
- package/dist/{index-b5459de4.js → index-th47aqez.js} +2 -2
- package/dist/index-tvban5vp.js +91 -0
- package/dist/{index-jaqm1xda.js → index-x7jzcvqy.js} +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.js +1 -1
- package/dist/{port-file-8ElfwDcq.d.ts → port-file-DQ7-ItDK.d.ts} +1 -1
- package/dist/{protocol-BeeDdtpa.d.ts → protocol-CVQK-d3j.d.ts} +1 -1
- package/dist/rpc/port-file.d.ts +4 -2
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{rpc-client-DlR9a0_7.d.ts → rpc-client-BQfIKrXI.d.ts} +3 -3
- package/dist/{sidebar-state-DHsZ9axt.d.ts → sidebar-state-B1cq68UB.d.ts} +4 -4
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-511npvw8.js → token-gy442bba.js} +1 -1
- package/dist/token-util-rxy0p234.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +3 -3
- package/dist/v2/server.d.ts +15 -7
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +95 -11
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +320 -35
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +187 -12
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +988 -0
- package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +4 -0
- package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +34 -12
- package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +16 -6
- package/src/tui-compiled/raw/shared/88b7fc40900fb003-commit-interval.js +18 -0
- package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +57 -0
- package/src/tui-compiled/raw/shared/a670cb7f5987bc1b-shutdown.js +42 -0
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +37 -12
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
- package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +37 -4
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +95 -11
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +320 -35
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +187 -12
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +988 -0
- package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +4 -0
- package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +34 -12
- package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +16 -6
- package/src/tui-compiled/runtime/shared/88b7fc40900fb003-commit-interval.js +18 -0
- package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +57 -0
- package/src/tui-compiled/runtime/shared/a670cb7f5987bc1b-shutdown.js +42 -0
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +37 -12
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
- package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +37 -4
- package/dist/index-0p3cbtwq.js +0 -2
- package/dist/index-apkavdvq.js +0 -90
- package/dist/index-qg2syg0r.js +0 -65
- package/dist/index-se9ykks8.js +0 -69
- package/dist/token-util-jsw1zdc6.js +0 -1
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import{Ce as f,De as H3,Ee as K$,Fe as K3,Ge as W3,ze as l}from"./index-8pk9savd.js";import{Ze as l$,_e as A,af as g6,ef as G6}from"./index-5d4y47h8.js";import{hf as e,if as y0,kf as J4,mf as L3,nf as R$,rf as G4}from"./index-5dxpsa3t.js";var P="all",n$=Object.freeze(["primary"]);function BZ($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function L0($,Z){return JSON.stringify([$,Z])}function s($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function S($){return typeof $==="number"&&Number.isFinite($)}function GZ($){return typeof $==="string"&&$.length>0}function T($,Z,z){return $[Z]===void 0||z($[Z])}function d6($){return S($)&&$>0}function a$($){return typeof $==="string"}function c6($){if(!s($)||!GZ($.scope)||!GZ($.label))return!1;switch($.kind){case"reading":return S($.checkedAt)&&S($.usedPercent)&&T($,"resetsAt",a$)&&T($,"windowMinutes",d6);case"retired":return S($.retiredAt);case"absent":return S($.checkedAt);default:return!1}}function u6($){if(!s($)||!S($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&T($,"remainingPercent",S)&&T($,"usedPercent",S)&&T($,"resetsAt",a$)&&T($,"limit",S)&&T($,"used",S)&&T($,"remaining",S)&&T($,"unit",a$)}function HZ($){return s($)&&S($.value)&&Number.isInteger($.value)&&$.value>=0&&S($.checkedAt)}function o$($){return s($)&&Object.values($).every(HZ)}function i6($){return typeof $==="boolean"}function p($){return s($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&T($,"balance",S)&&T($,"overageLimitReached",i6)&&S($.checkedAt)}function r$($){if(!s($))return;let Z=Object.entries($).filter(([,z])=>HZ(z));return Z.length===0?void 0:Object.fromEntries(Z)}function H0($){if(B0($))return $;if(!s($))return;let{counters:Z,credits:z,...X}=$;if(!B0(X))return;let Y=r$(Z),J=p(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...J===void 0?{}:{credits:J}}}function B0($){if(!s($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let z of $.limits){if(!c6(z))return!1;let X=L0(z.scope,z.label);if(Z.has(X))return!1;Z.add(X)}return T($,"budget",u6)&&T($,"counters",o$)&&T($,"credits",p)}var UZ=900000,DZ="no quota reading yet",VZ="no limits reported";function qZ($){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 z=Math.floor(Z/1440),X=Math.floor(Z%1440/60);return X===0?`${z}d`:`${z}d${X}h`}function FZ($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function NZ($){if($.scope!==P||$.windowMinutes===void 0)return $.label;return FZ($.windowMinutes)}function t$($){return Math.min(100,Math.max(0,$))}function z$($){return Math.round(t$($))}function KZ($){return`${z$($)}% left`}function WZ($,Z,z){let X=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(X)&&X>z?{resetIn:qZ(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>Z&&X<=z}}function s6($,Z){let z=$.windowMinutes,X=Z.windowMinutes;if(z!==void 0&&X!==void 0&&z!==X)return z-X;if(z===void 0!==(X===void 0))return z===void 0?1:-1;if($.scope!==Z.scope){if($.scope===P)return-1;if(Z.scope===P)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function MZ($,Z){let{windows:z,age:X}=e$($,Z),Y=z.map(({part:J})=>J);return X===void 0?{windows:Y}:{windows:Y,age:X}}function a6($){let Z=jZ($.filter(({part:z,scope:X})=>z.kind==="window"&&X!==P).map(({scope:z})=>z));for(let z of $)z.part.short=z.part.kind==="budget"?"cr":z.scope===P?z.part.name:Z.get(z.scope)??z.scope;return $}function e$($,Z){if(!$)return{windows:[]};let{now:z}=Z,Y=$.limits.filter((G)=>G.kind==="reading"&&G.remainingPercent!==void 0).sort(s6).map((G)=>{let B=t$(G.remainingPercent??0);return{scope:G.scope,...G.windowMinutes===void 0?{}:{windowMinutes:G.windowMinutes},part:{kind:"window",name:NZ(G),short:"",figure:KZ(G.remainingPercent??0),remainingPercent:B,checkedAt:G.checkedAt,...WZ(G.resetsAt,G.checkedAt,z)}}}),J=$.budget;if(J){let G=J.remainingPercent,B=J.reached?"credits spent":G!==void 0?`credits ${KZ(G)}`:"credits available";Y.push({scope:P,spent:J.reached,part:{kind:"budget",name:"credits",short:"",figure:B,...G===void 0?{}:{remainingPercent:t$(G)},checkedAt:J.checkedAt,...WZ(J.resetsAt,J.checkedAt,z)}})}if(a6(Y),Y.length>0){let G=z-Math.min(...Y.map(({part:B})=>B.checkedAt));if(G>(Z.staleAfterMs??UZ))return{windows:Y,age:`checked ${qZ(G)} ago`}}return{windows:Y}}function n6($,Z){return e$($,Z).age!==void 0}function QZ($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function jZ($){let Z=[...new Set($.map(QZ))],z=new Map(Z.map((Y)=>[Y,2])),X=(Y)=>Y.slice(0,z.get(Y));for(;;){let Y=new Map;for(let G of Z)Y.set(X(G),[...Y.get(X(G))??[],G]);let J=!1;for(let G of Y.values()){if(G.length<2)continue;for(let B of G){let H=z.get(B)??2;if(H<B.length)z.set(B,H+1),J=!0}}if(!J)break}return new Map($.map((Y)=>[Y,X(QZ(Y))]))}var o6=2;function r6($){let Z=$.map((X)=>X.label.trim()||X.scope),z=jZ(Z);return Z.map((X)=>z.get(X)??X)}function t6($,Z){if(!$||$.length===0)return;let z=Z.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===P))return;let X=$.flatMap((B,H)=>{let K=z.filter(({scope:W})=>W===B.scope).reduce((W,U)=>W===void 0||(U.part.remainingPercent??0)<(W.part.remainingPercent??0)?U:W,void 0);return K?[{group:B,listed:H,window:K}]:[]});if(X.length===0)return;let Y=r6($),J=(B)=>B.window.part.remainingPercent??0,G=[...X].sort((B,H)=>J(B)-J(H)||B.listed-H.listed).slice(0,o6).sort((B,H)=>B.listed-H.listed);return G.map((B,H)=>{let{windowMinutes:Q}=B.window,K=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[FZ(Q)],`${z$(J(B))}%`].join(" ");return H===G.length-1?`${K} left`:K})}function e6($,Z){let{windows:z}=e$($,Z),X=t6($?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:U})=>W.kind==="window"&&U===P),J=z.filter(({part:W,scope:U})=>W.kind==="window"&&U!==P),G=z.find(({part:W})=>W.kind==="budget"),B=G?.spent?0:G?.part.remainingPercent,Q=[...J.map(({part:W})=>({label:W.short,remaining:W.remainingPercent??0})),...B===void 0||G===void 0?[]:[{label:G.part.short,remaining:B}]].reduce((W,U)=>W===void 0||U.remaining<W.remaining?U:W,void 0),K=Y.map(({part:W})=>`${W.name} ${z$(W.remainingPercent??0)}%`);if(Q)K.push(`${Q.label} ${z$(Q.remaining)}%`);if(K.length===0)return z.map(({part:W})=>W.figure);return K.map((W,U)=>U===K.length-1?`${W} left`:W)}function _Z($,Z){if(Z.form==="narrow")return e6($,Z);let z=MZ($,Z),X=(Z.form??"full")==="full",Y=z.windows.map((J)=>{let G=X&&J.resetIn?`, resets ${J.resetIn}`:"";return`${J.kind==="budget"?"":`${J.name} `}${J.figure}${G}`});return z.age===void 0?Y:[...Y,z.age]}function $8($,Z){let z=_Z($,Z);if(z.length>0)return z.join(" · ");return $&&$.limits.length>0?VZ:DZ}function Z8($){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 z8($){if($.kind==="retired")return{scope:$.scope,label:$.label,kind:"retired",checkedAt:$.retiredAt};if($.kind==="absent")return{scope:$.scope,label:$.label,kind:"absent",checkedAt:$.checkedAt};return{scope:$.scope,label:$.label,kind:"reading",checkedAt:$.checkedAt,usedPercent:$.usedPercent,remainingPercent:100-$.usedPercent,...$.windowMinutes===void 0?{}:{windowMinutes:$.windowMinutes},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function X8($,Z){let z=$.windowMinutes!==void 0,X=Z.windowMinutes!==void 0;if(z!==X)return z?-1:1;if(z&&X&&$.windowMinutes!==Z.windowMinutes)return(Z.windowMinutes??0)-($.windowMinutes??0);if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function Y8($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function k($,Z=P){let z=new Map;for(let K of $?.limits??[]){if(K.scope!==Z&&K.scope!==P)continue;let W=z.get(K.label);if(W===void 0){z.set(K.label,K);continue}let U=K.scope===P?W:K,q=K.scope===P?K:W;z.set(K.label,U.kind==="reading"?U:q)}let X=[...z.values()].map(z8).sort(X8),Y=X.filter((K)=>K.kind==="reading"),J=Y.length>0?Y:X,G=J.length>0?Math.min(...J.map((K)=>K.checkedAt)):void 0,B=$?.budget?.kind==="reading"?Y8($.budget):void 0,H=r$($?.counters),Q=p($?.credits)?$.credits:void 0;return{scope:Z,limits:X,...G===void 0?{}:{checkedAt:G},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H},...Q===void 0?{}:{credits:Q}}}function K0($,Z){let z=$?.budget;if(z?.reached!==!0||typeof z.resetsAt!=="string")return;let X=Date.parse(z.resetsAt);if(!Number.isFinite(X)||X<=Z)return;return{resetsAt:z.resetsAt,resetAtMs:X}}function $3($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function X$($,Z){if(typeof $.resetsAt!=="string")return;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z>Z?z:void 0}class Y$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function G$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J$($){return typeof $==="number"&&Number.isFinite($)}function OZ($){return $===void 0||typeof $==="string"&&$!==""}function PZ($){return typeof $==="string"&&$!==""}function b0($,Z){return $[Z]===void 0||J$($[Z])}function Z3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function J8($){return G$($)&&OZ($.scope)&&PZ($.label)&&J$($.usedPercent)&&Z3($,"resetsAt")&&($.windowMinutes===void 0||J$($.windowMinutes)&&$.windowMinutes>0)}function G8($){return G$($)&&OZ($.scope)&&PZ($.label)}function B8($){if(!G$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&b0($,"remainingPercent")&&b0($,"usedPercent")&&Z3($,"resetsAt")&&b0($,"limit")&&b0($,"used")&&b0($,"remaining")&&Z3($,"unit")}function R0($){if(!G$($)||!J$($.checkedAt))return!1;let Z=$.readings??[],z=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(z))return!1;let X=new Set;for(let Y of Z){if(!J8(Y))return!1;let J=L0(Y.scope??P,Y.label);if(X.has(J))return!1;X.add(J)}if(!z.every(G8))return!1;return($.budget===void 0||B8($.budget))&&($.counters===void 0||o$($.counters))&&($.credits===void 0||p($.credits))}function H8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function K8($,Z,z){if(Z===void 0)return $;if($!==void 0&&z<$.checkedAt)return $;return{...Z,checkedAt:z}}function W8($,Z){let z=new Map(Object.entries($??{}));for(let[X,Y]of Object.entries(Z??{})){let J=z.get(X);if(J===void 0||Y.checkedAt>=J.checkedAt)z.set(X,Y)}return z.size===0?void 0:Object.fromEntries(z)}function Q8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function k0($,Z){let z=$===void 0?void 0:H0($);if($!==void 0&&z===void 0)throw new Y$("stored quota map is malformed");if(!R0(Z))throw new Y$("quota observation is malformed");let X=z??{limits:[]},Y=Z.checkedAt,J=new Map;for(let M of X.limits)J.set(L0(M.scope,M.label),M);let G=(M)=>{let L=J.get(M);return L===void 0||Y>=BZ(L)},B=new Set;for(let M of Z.readings??[]){let L=M.scope??P,x=L0(L,M.label);if(B.add(x),!G(x))continue;J.set(x,{scope:L,label:M.label,kind:"reading",checkedAt:Y,usedPercent:M.usedPercent,...M.resetsAt===void 0?{}:{resetsAt:M.resetsAt},...M.windowMinutes===void 0?{}:{windowMinutes:M.windowMinutes}})}for(let M of Z.coverage??[]){let L=M.scope??P,x=L0(L,M.label);if(B.has(x)||!G(x))continue;let g=J.get(x);J.set(x,g===void 0||g.kind==="absent"?{scope:L,label:M.label,kind:"absent",checkedAt:Y}:{scope:L,label:M.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:Q,counters:K,credits:W,...U}=X,q=K8(X.budget,Z.budget,Y),D=W8(X.counters,Z.counters),j=Q8(X.credits,Z.credits);return{...U,limits:[...J.values()].sort(H8),...q===void 0?{}:{budget:q},...D===void 0?{}:{counters:D},...j===void 0?{}:{credits:j}}}var U8=Object.freeze({validate:B0,decode:H0,merge:k0});function LZ($,Z,z){let X=Z.rateLimitMarks?.get($);if(X!==void 0&&z<X)return{id:$,reason:"rate-limited",until:X};let Y=Z.refreshBackoff?.get($);if(Y!==void 0&&z<Y)return{id:$,reason:"refresh-backoff",until:Y};return}function D8($,Z,z,X){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let J of z)if(!Z.limits.some((G)=>G.label===J))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:J},pullRequested:!0};let Y=Z.limits.filter($3);for(let J of Y)if(X$(J,X)===void 0)return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:J.scope,label:J.label},pullRequested:!0};for(let J of Y){let G=X$(J,X);if(G!==void 0&&typeof J.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:J.scope,label:J.label},resetsAt:J.resetsAt,resetAtMs:G}}return}function m($){let Z=$.scope??P,z=$.requiredLabels??n$,X=[],Y=[],J=[];for(let U of $.rows){let q=LZ(U.id,$,$.now);if(q){X.push(q);continue}if(U.kind==="api-key"){J.push({id:U.id,kind:U.kind});continue}let D=k(U.quota,Z),j=D8(U.id,D,z,$.now);if(j){Y.push(j);continue}J.push({id:U.id,kind:U.kind,projection:D})}let G=new Map(J.flatMap((U)=>{let q=K0(U.projection,$.now);return q?[[U.id,q]]:[]})),B=G.size>0&&G.size===J.length,H=[];for(let U of J){let q=G.get(U.id);if(q===void 0)H.push(U);else if(B)H.push({...U,lastPath:!0});else Y.push({id:U.id,stage:2,reason:"budget-spent",...q})}let Q=new Map($.rows.map((U,q)=>[U.id,q])),K=(U,q)=>(Q.get(U.id)??0)-(Q.get(q.id)??0);Y.sort(K);let W=Y.filter((U)=>("pullRequested"in U)).map((U)=>U.id);for(let U of W)$.requestPull?.(U);return{admitted:H,refused:Y,excluded:X,pulls:W}}var RZ="main";function V8($){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 B$($,Z,z=RZ){if(Z==="roster"||!$.includes(z))return[...$];let X=$.filter((Y)=>Y!==z);return Z==="main-first"?[z,...X]:[...X,z]}function z3($){let Z=m($),z=new Set(Z.admitted.map((Y)=>Y.id));return{order:B$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>z.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function q8($,Z,z){let X=Z.at(-1);if(X!==void 0){if(X.status===void 0||!z.includes(X.status))return}let Y=new Set(Z.map((J)=>J.id));return $.find((J)=>!Y.has(J))}function X3($,Z,z){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof z==="string"&&$.wireIdentity!==z)}function F8($,Z,z){let X=new Map;for(let[Y,J]of $){if(Y===z)continue;if(J.quotaCheckedAt!==Z.get(J.accountId))continue;X.set(J.accountId,(X.get(J.accountId)??0)+(J.inputBytes??0))}return X}var f0=900000,SZ=0.016666666666666666,Y3=0.000001;function H$($,Z){for(let z of[$?.checkedAt,Z])if(typeof z==="number"&&Number.isFinite(z))return z;return}function TZ($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function AZ($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,z)=>{let X=Z.windowMinutes!==void 0,Y=z.windowMinutes!==void 0;if(X!==Y)return X?-1:1;if(X&&Y)return(z.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function G3($){let Z=($.classifyStatus??TZ)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let z=H$($.quota,$.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||$.now-z>f0)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of AZ($.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 X=K0($.quota,$.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:Z}}function J3($,Z,z){let X=Math.max(0,$.remainingPercent-Z);if(X<=0)return 0;if(!$.resetsAt)return X;let Y=Date.parse($.resetsAt);if(!Number.isFinite(Y)||Y<=z)return X;let J=Math.max((Y-z)/3600000,SZ);return X/J}function xZ($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function N8($,Z){if(!$.quota)return;let z=H$($.quota,$.quotaCheckedAt);if(z===void 0||Z-z>f0)return;let X=AZ($.quota).map((G)=>J3({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))X.push(J3({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,Z));let J=X.length>0?Math.min(...X):0;return J>0?{candidate:$,quotaCheckedAt:z,weight:J}:void 0}function EZ($){let Z=$.candidates.filter((Y)=>Y.killswitchPasses!==!1);if($.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(Z.length===0)return;let z=Z.map((Y)=>N8(Y,$.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((J,G)=>{let B=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,Y3),H=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,Y3);return B-H||J.candidate.configuredOrder-G.candidate.configuredOrder||xZ(J.candidate.accountId,G.candidate.accountId)});let Y=z[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let X=[...Z].sort((Y,J)=>{let G=(Y.resetCreditsApplicable??0)>0?1:0;return((J.resetCreditsApplicable??0)>0?1:0)-G||Y.configuredOrder-J.configuredOrder||xZ(Y.accountId,J.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:H$(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function B3($){let Z=m($),z=new Map(Z.admitted.map((D)=>[D.id,D])),X=new Map(Z.refused.map((D)=>[D.id,D])),Y=new Set(Z.excluded.map((D)=>D.id)),J=new Set($.rows.map((D)=>D.id)),G=$.pin!==void 0&&X3($.pin,J,$.identities?.get($.pin.accountId));if(G&&$.pin){let D=z.get($.pin.accountId);if(D&&$.killswitch?.get(D.id)!==!1)return{outcome:"dispatch",accountId:D.id,source:"pin",...D.projection?.checkedAt===void 0?{}:{quotaCheckedAt:D.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?X.get($.pin.accountId):void 0,H=G&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Q=(D)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(D):$.rowReservePercent?.get(D.id))??$.reservePercent??{}},K=$.scope,W=$.rows.map((D,j)=>({row:D,configuredOrder:j})).filter(({row:D})=>!Y.has(D.id)).map(({row:D,configuredOrder:j})=>{let M=$.killswitch?.get(D.id),L=$.resetCreditsApplicable?.get(D.id);return{accountId:D.id,quota:D.kind==="api-key"?void 0:z.get(D.id)?.projection??k(D.quota,K),reservePercent:Q(D),configuredOrder:j,...L===void 0?{}:{resetCreditsApplicable:L},...M===void 0?{}:{killswitchPasses:M}}}),U=[],q=G?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let D=EZ({candidates:W,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!D)break;let j=X.get(D.accountId);if(j){U.push(j),W=W.filter((L)=>L.accountId!==D.accountId);continue}let M=$.identities?.get(D.accountId);return{outcome:"dispatch",accountId:D.accountId,source:D.source,...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt},pin:G&&!H?{action:"retain"}:{action:"assign",pin:{accountId:D.accountId,inputBytes:$.requestBytes,...M===void 0?{}:{wireIdentity:M},...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt}}},refusedSelections:U,admission:Z}}return{outcome:"no-admissible-account",pin:q,refusedSelections:U,admission:Z}}import{createHash as M8}from"node:crypto";var j8=86400000,_8=300000,O8=3600000,P8=60000,L8=900000,R8=300000;function Q3($){return $ instanceof Error?$.message:String($)}function x8($){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 U3($){let Z=Q3($),z=$?.status;if(typeof z==="number")return z===429||z>=500;if(!($ instanceof Error))return!1;let X=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function CZ($){return M8("sha256").update($).digest("hex")}function IZ($){let Z=CZ($.refreshToken),X=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,Y,J=$.error?.retryAfter;if(typeof J==="number"&&J>0)Y=J*1000;else if(x8($.error))Y=Math.min(O8,_8*2**Math.min(X-1,6));else Y=j8;return{message:Q3($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:X,tokenHash:Z}}function W0($,Z,z){if(!$?.nextRetryAt||$.nextRetryAt<=z)return!1;if(!Z)return!0;return $.tokenHash===CZ(Z)}function W$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function h0($){let z=($.previous?.retryCount??0)+1,X,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(U3($.error))X=Math.min(L8,P8*2**Math.min(z-1,6));else X=R8;return{message:Q3($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function x0($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function D3($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let z=Date.parse($);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{createServer as bZ}from"node:http";import{setTimeout as S8}from"node:timers/promises";var V$="app_EMoamEEZ73f0CkXaXp7hrann",D0="https://auth.openai.com",m0=1455,T8=3000,A8="cortexkit-opencode-openai-auth";function hZ($){return`${A8}/${$}`}var wZ="main",E8=`"${wZ}" is a reserved account id; choose a different label.`;function mZ($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function C8(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=mZ(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function kZ($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let z=Z[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function fZ($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let z=$["https://api.openai.com/auth"];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.chatgpt_account_id==="string"&&z.chatgpt_account_id.length>0)return z.chatgpt_account_id;let X=$.organizations;if(Array.isArray(X)){let Y=X[0];if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string"&&Y.id.length>0)return Y.id}return}function U$($){if($.id_token){let Z=kZ($.id_token),z=Z&&fZ(Z);if(z)return z}if($.access_token){let Z=kZ($.access_token);return Z?fZ(Z):void 0}return}function I8($){return typeof $==="string"&&$.toLowerCase()===wZ}function V3($){if(I8($))throw Error(E8);return $}function b8($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:V$,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${D0}/oauth/authorize?${X.toString()}`}async function k8($,Z,z){let X=await fetch(`${D0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:V$,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function f8($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var y8=`<!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>`,Q$=($)=>`<!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">${f8($)}</div>
|
|
85
|
+
</div>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`,D$=[],w0,d=new Map;function yZ($,Z){return new Promise((z,X)=>{let Y=(G)=>{$.off("listening",J),X(G)},J=()=>{$.off("error",Y),z()};$.once("error",Y),$.once("listening",J),$.listen(m0,Z)})}function vZ($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function Q0(){return d.size}function V0($){if(d.delete($),Q0()===0)U0()}async function h8(){let $=`http://localhost:${m0}/auth/callback`;if(D$.length>0)return{port:m0,redirectUri:$};if(w0)return w0;w0=(async()=>{let Z=(J,G)=>{let B=new URL(J.url||"/",`http://127.0.0.1:${m0}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),Q=B.searchParams.get("state"),K=B.searchParams.get("error"),W=B.searchParams.get("error_description");if(K){let q=W||K;if(Q){let D=d.get(Q);if(D)D.reject(Error(q)),V0(Q);else if(Q0()===0)U0()}else if(Q0()===0)U0();G.writeHead(200,{"Content-Type":"text/html"}),G.end(Q$(q));return}if(!Q){if(Q0()===0)U0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(Q$("Missing state parameter"));return}if(!H){if(Q0()===0)U0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(Q$("Missing authorization code"));return}let U=d.get(Q);if(!U){if(Q0()===0)U0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(Q$("Unknown state — authorization may have expired"));return}V0(Q),k8(H,$,U.pkce).then((q)=>U.resolve(q)).catch((q)=>U.reject(q)),G.writeHead(200,{"Content-Type":"text/html"}),G.end(y8);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),Q=H?[H]:[...d.keys()];G.writeHead(200),G.end("Login cancelled");for(let K of Q){let W=d.get(K);if(!W)continue;W.reject(Error("Login cancelled")),V0(K)}if(Q0()===0)U0();return}G.writeHead(404),G.end("Not found")},z=bZ(Z);await yZ(z,"127.0.0.1");let X=[z],Y=bZ(Z);try{await yZ(Y,"::1"),X.push(Y)}catch(J){let G=J.code;if(G!=="EADDRNOTAVAIL"&&G!=="EAFNOSUPPORT")throw vZ(z),J}return D$=X,{port:m0,redirectUri:$}})();try{return await w0}finally{w0=void 0}}function U0(){let $=D$;D$=[];for(let Z of $)vZ(Z)}function w8($,Z,z=300000,X){return new Promise((Y,J)=>{if(X?.aborted){V0(Z),J(Error("Login cancelled"));return}let G=setTimeout(()=>{if(d.get(Z))V0(Z),J(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(G),d.get(Z))V0(Z),J(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);d.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(G),X)X.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(G),X)X.removeEventListener("abort",B);J(H)}})})}async function m8($){let Z=await fetch(`${D0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":hZ($)},body:JSON.stringify({client_id:V$})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${D0}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function v8($,Z,z){let X=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(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>J)throw Error("Device authorization expired");let B=await fetch(`${D0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":hZ(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let K=await B.json(),W=await fetch(`${D0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:K.authorization_code,redirect_uri:`${D0}/deviceauth/callback`,client_id:V$,code_verifier:K.code_verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let H=J-(Date.now()-G);if(H<=0)throw Error("Device authorization expired");let Q=Math.min(X+T8,H);try{await S8(Q,void 0,{signal:z})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw Error("Device authorization cancelled");throw K}}}async function Z7($){let{label:Z,headless:z=!1,signal:X,version:Y}=$;if(V3(Z),z){let{deviceData:K,url:W,instructions:U}=await m8(Y),q=(async()=>{let D=await v8(K,Y,X),j=Date.now(),M=U$(D);return{id:V3(Z||M||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:D.access_token,refresh:D.refresh_token,expires:j+(D.expires_in??3600)*1000,enabled:!0,addedAt:j,lastUsed:j,lastRefreshedAt:j,accountId:M}})();return{url:W,instructions:U,completion:q}}let{redirectUri:J}=await h8(),G=await C8(),B=mZ(crypto.getRandomValues(new Uint8Array(32)).buffer),H=b8(J,G,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let K=await w8(G,B,void 0,X),W=Date.now(),U=U$(K);return{id:V3(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:W+(K.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:U}}finally{V0(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function q$($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let X=Z<100000000000?Z*1000:Z,Y=new Date(X);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let z=new Date($);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function q3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function gZ($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function pZ($,Z){let z=$.get(Z);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let Y=Z.slice(0,-13),J=q3($.get(`${Y}-window-minutes`)),G=q$($.get(`${Y}-reset-at`)??void 0);if(X===0&&$.get(`${Y}-window-minutes`)==="0"&&!G)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:G,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}var uZ=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function iZ($,Z){let z=$.get(Z);if(z===null)return"absent";if(z.trim()==="")return"invalid";let X=Number(z);return Number.isFinite(X)&&X>=0&&X<=100?"valid":"invalid"}function X7($){if(uZ.some((J)=>iZ($,J)==="invalid"))return{};let Z={},z=pZ($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=pZ($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;let Y=g8($);if(Y)Z.credits=Y;return Z}function lZ($,Z){let z=$.get(Z)?.trim();if(z===void 0)return;if(z.toLowerCase()==="true"||z==="1")return!0;if(z.toLowerCase()==="false"||z==="0")return!1;return}function g8($){let Z=lZ($,"x-codex-credits-has-credits"),z=lZ($,"x-codex-credits-unlimited");if(Z===void 0||z===void 0)return;let X=a($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:z,...X!==void 0?{balance:X}:{},checkedAt:Date.now()}}function Y7($){let Z=uZ.map((z)=>iZ($,z));return Z.includes("valid")&&!Z.includes("invalid")}function dZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=q3($.window_minutes),z=q$($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function J7($){let Z={},z=dZ($.rate_limits?.primary);if(z)Z.primary=z;let X=dZ($.rate_limits?.secondary);if(X)Z.secondary=X;let Y=p8($.credits);if(Y)Z.credits=Y;return Z}function p8($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let z=a(typeof Z.balance==="string"?Z.balance.trim():Z.balance);return{hasCredits:Z.has_credits,unlimited:Z.unlimited,...z!==void 0?{balance:z}:{},...typeof Z.overage_limit_reached==="boolean"?{overageLimitReached:Z.overage_limit_reached}:{},checkedAt:Date.now()}}function a($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function cZ($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=q3($.limit_window_seconds),z=q$($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function sZ($){let Z={},z=cZ($.rate_limit?.primary_window);if(z)Z.primary=z;let X=cZ($.rate_limit?.secondary_window);if(X)Z.secondary=X;let Y=gZ($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let J=gZ($.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 H=a(G.limit),Q=a(G.used),K=a(G.remaining),W=a(G.used_percent),U=a(G.remaining_percent);if(H!==void 0&&Q!==void 0&&K!==void 0&&W!==void 0&&U!==void 0)Z.spendControl={limit:H,used:Q,remaining:K,usedPercent:W,remainingPercent:U,resetsAt:q$(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 H=a(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as a9}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as l8}from"@cortexkit/claustrum-client";import{SocketClosedError as d8,SocketTimeoutError as c8,SubcCallError as u8}from"@cortexkit/subc-client";class V extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var F3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class C extends V{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function n($){if($ instanceof C||$ instanceof d8||$ instanceof c8)return"unreachable";let Z=$ instanceof l8||$ instanceof u8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(F3,Z))return"answered";return F3[Z]}import{resolve as aZ}from"node:path";import{storeIdentity as i8}from"@cortexkit/claustrum-client";import{SubcClient as nZ}from"@cortexkit/subc-client";var S0=300000,F$=300000,N3=1000;class v0{#$;#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 N${#$;#Z;#G;#B=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#G}request(){if(this.#G)return this.#B=!0,this.#G;return this.#G=(async()=>{do{this.#B=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#B)})().finally(()=>{this.#G=void 0}),this.#G}}class M${#$;#Z=new v0;#G;#B="polling";#Y;#K;#X=!1;#z;#N=!1;#J=0;constructor($){this.#$=$,this.#G=new N$(async()=>{let Z=this.#N;if(this.#N=!1,Z||this.#z!==this.#$.view())await this.#$.discover(this.#z??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#B}start(){if(this.#X||this.#Y||this.#K)return;if(typeof this.#$.client.watchScoped!=="function"){this.#W("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#K)(this.#$.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#Y;this.#Y=void 0,$?.handle.stop()}#W($,Z){if(this.#B===$)return;this.#B=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#D($,Z){this.#K=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,!this.#X)Z()},$),this.#K.unref?.()}async#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(G){if(this.#X)return;this.#$.onError?.(G),this.#q("token-unreadable");return}let z=this.#$.client.watchScoped;if(this.#X||this.#Y||!z)return;this.#Z.restart(),this.#N=$;let X,Y;try{Y=z.call(this.#$.client,(G)=>{if(this.#X||!X||this.#Y!==X)return;if(X.notices++,X.notices===1)this.#$.onReachable?.(),X.acceptedAt=(this.#$.now??Date.now)(),this.#W("watching","accepted");if(!this.#Z.continuous(G))this.#N=!0;this.#z=G.view,this.#G.request()},{enrollmentToken:Z})}catch(G){this.#$.onError?.(G),this.#q("watch-failed");return}X={handle:Y,notices:0},this.#Y=X,this.#W("polling",$?"resubscribing":"opening");let J=X;Y.closed.then((G)=>this.#H(J,G),(G)=>this.#H(J,{kind:"transport_lost",error:G}))}#H($,Z){if(this.#X||this.#Y!==$)return;if(this.#Y=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#W("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#q("refused");try{this.#$.onRefused(Z.error)}catch(z){this.#$.onError?.(z)}return}if($.notices>0){let z=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&z-$.acceptedAt>=300000)this.#J=0;let X=Math.min(1000*2**Math.min(this.#J,16),300000);this.#J++,this.#W("polling","resubscribing"),this.#D(X,()=>void this.#V(!0));return}this.#q(Z.kind)}#q($){this.#W("fallback",$),this.#D(300000,()=>void this.#V(!1))}}function rZ($){let Z=$.identity??i8($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let z,X=!1,Y,J=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),G=(async()=>{if(z=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await nZ.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),X)throw z.close(),Error("insula usage timeout");let B=await z.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await z.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([G,J])}finally{X=!0,clearTimeout(Y),z?.close()}},watchUsage(z){let X,Y,J=!1,G=(async()=>{let B,H=new Promise((K,W)=>{B=setTimeout(()=>W(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),Q=(async()=>{let K=Math.min($.handshakeTimeoutMs??3000,3000),W=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:K}):await nZ.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:K});if(X=W,J){W.close();return}let U=await W.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(J){W.close();return}Y=W.subscribe(U,{method:"usage.watch"},z)})();try{await Promise.race([Q,H])}catch(K){throw J=!0,K}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{J=!0,X?.close()});return{stop(){if(J)return;J=!0,Y?.unsubscribe(),X?.close()},closed:G}}}}var _$=60000,oZ=4*_$,s8=2*_$,M3=new Map,j$=new Map;function g0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function a8($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!g0(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 n8($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class tZ{transport;key;#$=[];#Z=!1;#G=new Set;#B=new Map;#Y=new N$(async()=>{try{let $=await this.transport.getUsage();if(!g0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>g0(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#G=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#G)this.#B.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#G.clear()}},()=>{});#K=new v0;#X="polling";#z=0;#N=0;#J=new Map;#W;#D;#V={};#H=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Y.running)return this.#Y.running;if(this.#X==="watching")return Promise.resolve();for(let[z,X]of j$)if($-X>=_$)j$.delete(z);let Z=j$.get(this.key);if(Z!==void 0&&$-Z<_$)return Promise.resolve();return j$.set(this.key,$),this.#Y.request()}watchMode(){return this.#X}watch($={}){this.#z++;let Z=$.provider;if(Z===void 0)this.#N++;else this.#J.set(Z,(this.#J.get(Z)??0)+1);if(this.#z===1)this.#V=$,this.#j();let z=!1;return()=>{if(z)return;if(z=!0,Z===void 0)this.#N--;else{let X=(this.#J.get(Z)??1)-1;if(X>0)this.#J.set(Z,X);else this.#J.delete(Z)}if(--this.#z===0)this.#q()}}#q(){if(this.#D)(this.#V.clearTimeoutImpl??clearTimeout)(this.#D);this.#D=void 0;let $=this.#W;this.#W=void 0,$?.handle?.stop(),this.#X="polling"}#F($){this.#D=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#D=void 0,this.#z>0&&!this.#W)this.#j()},$),this.#D.unref?.()}#j(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#K.restart();let Z={notices:0};this.#W=Z;let z;try{z=$.call(this.transport,(X)=>this.#x(Z,X))}catch(X){this.#O(Z,X);return}Z.handle=z,z.closed.then(()=>this.#O(Z,void 0),(X)=>this.#O(Z,X))}#x($,Z){if(this.#W!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#H=0;let z=a8(Z);if(!z)this.#K.restart();if(!(z?this.#K.continuous(z):!1)||z?.provider===void 0||this.#N>0||this.#J.has(z.provider))this.#Y.request()}#O($,Z){if(this.#W!==$)return;this.#W=void 0;let z=n8(Z);if(z==="unknown_method"||z==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let X=Math.min(N3*2**Math.min(this.#H,16),F$);this.#H++,this.#X="polling",this.#F(X);return}if(this.#X="fallback",this.#Y.request(),Z===void 0||n(Z)==="unreachable")this.#F(F$)}current($,Z,z){for(let X of this.#$){if(X.provider!==$||typeof X.account!=="string"||X.account.trim()!==Z)continue;if(X.stale!==void 0||X.errorClass!==void 0||!g0(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=oZ)continue;return{entry:X,context:{fetchedAt:Y,...typeof X.source==="string"&&{source:X.source}}}}return}lookup($,Z,z){if(!this.#Z)return{miss:"unreachable"};let X=this.#$.find((G)=>G.provider===$&&typeof G.account==="string"&&G.account.trim()===Z),Y=(X??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(X){let G=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!g0(X.usage)||!Number.isFinite(G))return{miss:"unreachable"};let B={entry:X,context:{fetchedAt:G,...typeof X.source==="string"&&{source:X.source}}};return z>=G+oZ||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#G.has($))return{miss:"absent"};let J=this.#B.get($)??z;return this.#B.set($,J),{miss:z-J>=s8?"unreachable":"cold"}}}function j3($,Z){let z=JSON.stringify([aZ($.connectionFile),aZ(Z)]),X=M3.get(z);if(!X)X={source:new tZ($,z),refs:0},M3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)M3.delete(z)}}}import{ClaustrumCredentialError as s5}from"@cortexkit/claustrum-client";function q0($){let Z=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:B,listener:H}of z)B.removeEventListener("abort",H);z.length=0},J=(B)=>{if(X||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 H=()=>J(B.reason);if(z.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)J(B.reason)}return{signal:Z.signal,dispose:Y}}import{ClaustrumCredentialError as x4}from"@cortexkit/claustrum-client";import{createHash as $9,randomBytes as Z9,randomUUID as z9}from"node:crypto";import{constants as eZ}from"node:fs";import{chmod as X9,mkdir as Y9,open as B4,readFile as O3,realpath as J9,rename as G9,stat as H4,unlink as R3}from"node:fs/promises";import{basename as K4,dirname as r,extname as $4,isAbsolute as Z4,join as x3,resolve as B9}from"node:path";import{ClaustrumCredentialError as H9,ClaustrumClient as K9,writeEnrollmentTokenFile as W9}from"@cortexkit/claustrum-client";import{lstat as o8}from"node:fs/promises";import{resolve as r8}from"node:path";async function t8($){try{let Z=await o8($);return Z.isFile()?Z:void 0}catch(Z){return Z.code==="ENOENT"?"absent":void 0}}function e8($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class _3{#$=new Map;async read($,Z,z){let X=$.map((Q)=>r8(Q)),Y=JSON.stringify(X),J=await Promise.all(X.map(t8)),G=J.every((Q)=>Q!==void 0)?J:void 0,B=this.#$.get(Y);if(G&&B&&G.every((Q,K)=>{let W=B.identities[K];return W!==void 0&&e8(Q,W)}))return z?.(G),B.value;this.#$.delete(Y);let H=await Z(X);if(G){if(this.#$.size>=64){let Q=this.#$.keys().next().value;if(Q!==void 0)this.#$.delete(Q)}this.#$.set(Y,{identities:G,value:H})}return H}}var Q9=1,P$=16384,W4=30000,S3=/^[0-9a-f]{64}$/,Q4="unknown_method",U4=new Set([Q4,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),D4=new Set(["pending_queue_full"]);function P3($){if(!($ instanceof H9))return;if(U4.has($.code))return{code:$.code,disposition:"terminal"};if(D4.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function U9($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new V("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function D9($){return K9.connect($)}function V4($){let Z=$4($)||".json",z=K4($,$4($));return{statePath:x3(r($),`${z}-state${Z}`),tokenPath:$}}function V9($){let Z=$.override?.trim();if(Z&&!Z4(Z)&&!$.cwd)throw new V("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=Z?Z4(Z)?Z:B9($.cwd,Z):x3($.stateDir,`${$.host}-enrollment.json`);return V4(z)}function q4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function O$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function F4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function p0(){return new V("invalid-state","invalid Claustrum enrollment state")}function x$($){if(!q4($)||$.version!==Q9||typeof $.proposedName!=="string"||$.proposedName.length===0)throw p0();if($.phase==="pending"){if(!S3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!O$($.createdAt)||!O$($.updatedAt))throw p0();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!F4($.tokenGeneration)||!O$($.updatedAt))throw p0();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!O$($.updatedAt))throw p0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw p0()}function T3($){if(!q4($)||!S3.test(String($.token??""))||!F4($.token_generation))throw new V("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function N4($){if(!$.isFile())throw new V("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new V("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new V("unsafe-file","Claustrum enrollment file must be owned by the current user")}function z4($){try{return JSON.parse($)}catch{throw new V("invalid-state","Claustrum enrollment file is not valid JSON")}}async function t($){if(e)try{await L3(r($));let z=await R$($,!0);if(Buffer.byteLength(z)>P$)throw new V("unsafe-file","Claustrum enrollment file is too large");return z4(z)}catch(z){if(z.code==="ENOENT")return;throw z}let Z;try{Z=await B4($,eZ.O_RDONLY|eZ.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new V("unsafe-file","Claustrum enrollment file could not be opened safely")}try{N4(await Z.stat());let z=Buffer.alloc(P$+1),{bytesRead:X}=await Z.read(z,0,z.byteLength,0);if(X>P$)throw new V("unsafe-file","Claustrum enrollment file is too large");return z4(z.subarray(0,X).toString("utf8"))}finally{await Z.close()}}function X4($,Z){let z=[];for(let X of $.split(`
|
|
88
|
+
`)){if(X.trim()===""||X.startsWith("#"))continue;let Y=X.split(":");if(Y.length!==Z||!/^[^\s:,]+$/.test(Y[0]??"")||!/^\d+$/.test(Y[2]??"")||!Number.isSafeInteger(Number(Y[2]))||Z===7&&(!/^\d+$/.test(Y[3]??"")||!Number.isSafeInteger(Number(Y[3])))||Z===4&&Y[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(Y[3]??""))return;z.push(Y)}return z}async function q9($,Z,z){try{let[X,Y]=await Promise.all([O3(z.passwdPath??"/etc/passwd","utf8"),O3(z.groupPath??"/etc/group","utf8")]),J=X4(X,7),G=X4(Y,4);if(!J||!G)return!1;let B=J.filter((W)=>Number(W[2])===$),H=G.filter((W)=>Number(W[2])===Z);if(B.length!==1||H.length!==1)return!1;let Q=B[0]?.[0],K=H[0]?.[3]??"";return(K===""||K.split(",").every((W)=>W===Q))&&!J.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function M4($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>O3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function j4($,Z={}){if(!e){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await J9($)}catch{return}let J;for(;;){let G=await H4(Y).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(J===void 0)J=X!==void 0&&await q9(z,X,Z);if((G.mode&2)!==0||G.uid!==z||G.gid!==X||!J)throw new V("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=r(Y);if(B===Y)return;Y=B}}try{await J4($,M4(Z))}catch(z){if(!(z instanceof y0))throw z;throw new V("unsafe-file",`Claustrum enrollment parent refused: ${z.path} (${z.reason??z.code}). Use a folder that other users cannot write or replace.`)}}async function L$($,Z={}){if(e){await L3($,!1,M4(Z));return}await Y9($,{recursive:!0,mode:448});let z=await H4($),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new V("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((z.mode&63)!==0)await X9($,448)}async function F0($,Z,z={}){let X=r($);await L$(X,z),await j4(X,z);let Y=`${JSON.stringify(Z)}
|
|
89
|
+
`;if(Buffer.byteLength(Y)>P$)throw new V("invalid-state","Claustrum enrollment state is too large");if(e)return G4($,Y);let J=x3(X,`.${K4($)}.${process.pid}.${z9()}.tmp`),G,B=!1;try{G=await B4(J,"wx",384),B=!0,await G.writeFile(Y,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await G9(J,$),B=!1}finally{if(await G?.close().catch(()=>{}),B)await R3(J).catch(()=>{})}}var F9=new _3;async function A3($,Z){let z=e?await Y4($,Z):await F9.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,J=$.statePath])=>Y4({tokenPath:Y,statePath:J},Z),(Y)=>{for(let J of Y)if(J!=="absent")N4(J)}),X={...z.status};if(z.usesProposedName&&X.state==="approved")X.proposedName=Z;return X}async function Y4($,Z){let z=await t($.tokenPath),X=z===void 0?void 0:T3(z),Y=await t($.statePath),J=Y===void 0?void 0:x$(Y);if(X)return{usesProposedName:J===void 0,status:{state:"approved",proposedName:J?.proposedName??Z,...J?.phase==="approved"&&J.approvedName!==void 0&&{approvedName:J.approvedName},tokenGeneration:X.token_generation}};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:o(J),usesProposedName:!1}}async function N9($,Z){let z;try{z=await A3($,Z)}catch(X){if(!(X instanceof V)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await t($.statePath);if(Y===void 0)return"unreadable";let J=x$(Y);return J.phase==="approved"&&J.proposedName===Z?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in z&&z.proposedName!==Z)return"unreadable";if(z.state==="approved"||z.state==="blocked"&&z.code==="missing_token")return"vault";return"local"}async function $0($){let Z=await t($);if(Z===void 0)throw new V("not-enrolled","Claustrum enrollment is not configured");return T3(Z)}function o($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function _4(){return new V("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class O4{#$;#Z;#G;#B;#Y;#K;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#G=$.proposedName,this.#B=$.now??Date.now,this.#Y=$.mintSecret??(()=>Z9(32).toString("hex")),this.#K=$.writeTokenFile??W9}async status(){return A3(this.#Z,this.#G)}async resetTerminal(){return P4(this.#Z,this.#G)}async#z($,Z){let z={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#B()};return await F0(this.#Z.statePath,z,this.#X),o(z)}async reconcile(){await L$(r(this.#Z.statePath),this.#X);let $=await f({name:"ceremony",path:this.#Z.statePath,ttlMs:W4,renew:!0});if(!$)return{state:"busy"};try{let Z=await t(this.#Z.tokenPath),z=Z===void 0?void 0:T3(Z),X=await t(this.#Z.statePath),Y=X===void 0?void 0:x$(X);if(Y&&Y.proposedName!==this.#G)throw _4();if(z){if(!Y||Y.phase==="pending"){let G={version:1,phase:"approved",proposedName:Y?.proposedName??this.#G,tokenGeneration:z.token_generation,updatedAt:this.#B()};await F0(this.#Z.statePath,G,this.#X),Y=G}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:z.token_generation}}if(Y?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#B()};return await F0(this.#Z.statePath,G,this.#X),o(G)}if(Y&&Y.phase!=="pending")return o(Y);if(!Y){let G=this.#B();if(Y={version:1,phase:"pending",proposedName:this.#G,requestSecret:this.#Y(),createdAt:G,updatedAt:G},!S3.test(Y.requestSecret))throw new V("invalid-state","invalid minted Claustrum enrollment secret");await F0(this.#Z.statePath,Y,this.#X)}if(!Y.requestId)try{let G=$9("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B=await this.#$.enrollPropose({name:Y.proposedName,requestSecretHash:G});Y={...Y,requestId:B.requestId,updatedAt:this.#B()},await F0(this.#Z.statePath,Y,this.#X)}catch(G){let B=P3(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};if(B.code===Q4)return await $.assertOwned(),await R3(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#z(Y,B.code)}let J=Y.requestId;if(!J)return o(Y);try{let G=await this.#$.enrollPoll({requestId:J,requestSecret:Y.requestSecret});if(G.status==="pending")return o(Y);if(G.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#B()};return await F0(this.#Z.statePath,H,this.#X),o(H)}await L$(r(this.#Z.tokenPath),this.#X),await j4(r(this.#Z.tokenPath),this.#X),await this.#K(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,updatedAt:this.#B()};return await F0(this.#Z.statePath,B,this.#X),o(B)}catch(G){let B=P3(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:J,retryCode:B.code};return this.#z(Y,B.code)}}finally{await $.release()}}}async function P4($,Z){await L$(r($.statePath));let z=await f({name:"ceremony",path:$.statePath,ttlMs:W4,renew:!0});if(!z)return"busy";try{if(await t($.tokenPath)!==void 0)return"refused-approved";let X=await t($.statePath);if(X===void 0)return"idle";let Y=x$(X);if(Y.proposedName!==Z)throw _4();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await R3($.statePath),"reset"}finally{await z.release()}}var l0="claustrum-tombstone:v1:";function S$($){return`${l0}${$}`}function E3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function T$($){return typeof $==="string"&&$.startsWith(l0)}function L4($,Z){if(!E3($)||$.type!=="oauth")return!1;return $.refresh===S$(Z)}function R4($,Z){if(L4($,Z))return"placeholder";if(E3($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!T$($.refresh))return"login";if(E3($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function M9($){let Z=R4($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new V("host-slot-login",`${$.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if($.mode==="local"&&Z==="placeholder")throw new V("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function T0($,Z){let z=!1;return(X)=>{if(z)return;if(!Z||Z.aborted)z=!0;$.warn("claustrum shutdown drain timed out",{pendingOperations:X})}}async function A0($,Z){if(!$.size)return;let z,X=!1,Y=(async()=>{while(!X&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([Y,new Promise((J)=>{z=setTimeout(()=>{X=!0,J()},2000)})]),X&&$.size)Z($.size)}finally{X=!0,clearTimeout(z)}}function S4($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function j9($,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 I3=A("claustrum");function k3($,Z,z,X=I3){let Y=S4(Z,z);return X.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:j9(Z,z)}),Y}var b3=300000,T4=60000;function C3(){return new V("invalid-material","Claustrum returned invalid credential material")}function _9($){let Z=$.trim();if(Z.startsWith("{")){let z;try{z=JSON.parse(Z)}catch{throw C3()}if(!z||typeof z!=="object")throw C3();let X=z,Y=X.access_token??X.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(l0))throw C3();return Z}function O9($,Z){let z={kind:"not-mine"};if(!$.operations.includes("read"))return z;if(!$.categories.includes(Z.category))return z;if($.credentialType!=="oauth"&&$.credentialType!=="api_key")return z;if("classify"in Z){let X={credentialId:$.id,credentialType:$.credentialType,categories:$.categories,refreshAdapter:$.refreshAdapter,...P9($)};if(X.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let Y=Z.classify(X);if(Y.kind==="not-mine")return z;if(Y.kind==="mine"&&typeof Y.member==="string")return{kind:"mine",type:$.credentialType,member:Y.member};if(Y.kind==="refused"&&typeof Y.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(Y.code)&&!Y.code.includes(`
|
|
90
|
+
`)&&Z.refusalCodes.includes(Y.code))return{kind:"refused",code:Y.code}}catch{}return{kind:"refused",code:"unclassified"}}if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?{kind:"mine",type:"oauth"}:z;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?{kind:"mine",type:"api_key"}:z;return z}function P9($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function L9($){let{grants:Z,grantTuples:z}=$;if(Z===void 0||z===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(z.map(({selectorKind:X,selector:Y,operation:J})=>Object.freeze({selectorKind:X,selector:Y,operation:J})))})}class E0{#$;#Z;#G;#B;#Y;#K;#X;#z=new WeakMap;#N=new WeakMap;#J=new Map;#W=new WeakMap;#D;#V;#H=!1;#q=new C;#F;#j=!1;#x=-1/0;#O=2000;#Q=!1;#_;#S=new Set;#U=new Set;#P;#R;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>$0(Z);else throw new V("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#B=$.family,this.#Y=$.parseIdentity,this.#K=$.requireAssertion??!1,this.#G=$.now??Date.now,this.#X=$.logger??I3,this.#P=T0(this.#X),this.#D=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#Q||this.#H)return;this.#H=!0,this.#q=$ instanceof x4?$:new C,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#T()}reachable(){if(this.#Q||!this.#H)return;if(this.#H=!1,this.#F)this.#V(this.#F);this.#F=void 0,this.#O=2000;for(let $ of this.#J.values())$.since=null;(this.#X.info??I3.info)("vault receipt serving resumed",{reason:"reachable"})}#T(){if(this.#Q||!this.#H||this.#F||this.#j)return;this.#F=this.#D(()=>{this.#F=void 0,this.#M(!0)},this.#O),this.#F.unref?.()}#M($=!1){if(this.#Q||!this.#H||this.#j)return;if(this.#G()-this.#x<1000){this.#T();return}this.#x=this.#G(),this.#j=!0,this.#b().catch(()=>{if($&&this.#H)this.#O=Math.min(this.#O*2,30000)}).finally(()=>{this.#j=!1,this.#T()})}#L($){if(this.#Q)throw new V("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#E($){this.#L($);let Z=this.#Z();this.#U.add(Z);let z;try{z=await Z}finally{this.#U.delete(Z)}if(this.#L($),!/^[0-9a-f]{64}$/.test(z.token)||!Number.isSafeInteger(z.token_generation)||z.token_generation<1)throw new V("invalid-token","Invalid Claustrum enrollment token");return z.token}async#A($,Z){this.#L(Z);let z,X;try{let Y=$();z=Z?await Promise.race([Y,new Promise((J,G)=>{let B=()=>G(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),X=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await Y}catch(Y){if(this.#L(Z),n(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof x4)throw Y;if(n(Y)==="unreachable")throw new C;throw new V("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#L(Z),this.reachable(),z}async discover($){let Z=await this.#b($);return this.#_=Z.view,Z}async#b($){let Z,z;try{z=await this.#E($)}catch(K){throw this.#J.clear(),K}try{Z=await this.#A(()=>this.#$.listScoped(z),$)}catch(K){throw this.listFailed(K),K}let X=[],Y=[],J=0,G=[],B=new Map;for(let K of Z.rows){let W=O9(K,this.#B);if(W.kind==="not-mine"){J++;continue}if(W.kind==="refused"){Y.push({...K.id.trim()&&{credentialId:K.id},code:W.code});continue}G.push({row:K,type:W.type,...W.member!==void 0&&{member:W.member}}),B.set(K.id,(B.get(K.id)??0)+1)}let H=[];for(let{row:K,type:W,member:U}of G){let q;if(!K.id.trim())q="empty credential id";else if((B.get(K.id)??0)>1)q="duplicate credential id";else if(K.accountId!==void 0&&!K.accountId.trim())q="blank account identity";else if(!K.state.trim())q="empty state";if(q){X.push({...K.id.trim()&&{credentialId:K.id},...U!==void 0&&{member:U},reason:q});continue}H.push(Object.freeze({credentialId:K.id,credentialType:W,...U!==void 0&&{member:U},...K.accountId!==void 0&&{accountIdentity:K.accountId},state:K.state,...K.email!==void 0&&{email:K.email},...K.orgName!==void 0&&{orgName:K.orgName}}))}for(let K of X)this.#X.warn("skipped malformed vault record",K);let Q=L9(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(X),..."classify"in this.#B&&{refused:Object.freeze(Y),notMine:J},...Q&&{grantReach:Q}}}listFailed($){if(n($)==="unreachable")this.transportLost($);else this.reachable(),this.#J.clear()}forget($){this.#J.delete($)}retain($){let Z=new Map($.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#J){let Y=Z.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}}keptReceiptState(){let $=null;for(let[Z,z]of this.#J){if(!this.#I(z.attempt)){this.forget(Z);continue}if(z.since!==null)$=Math.min($??z.since,z.since)}return Object.freeze({active:$!==null,since:$})}#I($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#G()>T4}async authorize($,Z,z="vault"){this.#L(Z);let{credentialId:X,credentialType:Y,accountIdentity:J}=$,G=this.#J.get(X);if(G&&(G.attempt.credentialType!==Y||G.attempt.expectedAccountIdentity!==J))this.forget(X),G=void 0;let B;try{B=await this.#E(Z)}catch(H){throw this.#J.clear(),H}if(this.#H&&G)return this.#M(),this.#C(X,G,B,z);try{let H=await this.#f({credentialId:X,credentialType:Y,accountIdentity:J},B,Z);return this.#J.set(X,{attempt:H,routeId:z,since:null}),H}catch(H){if(this.#L(Z),n(H)!=="unreachable")throw this.forget(X),H;return this.#C(X,G,B,z,H)}}#C($,Z,z,X,Y=this.#q){if(!Z||this.#J.get($)!==Z||!this.#I(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#G();let J=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#z.set(J,z),this.#W.set(J,X),J}async#f($,Z,z){if(!$.credentialId)throw new V("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:J}=$;if(this.#K&&J===void 0)throw new V("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#A(()=>this.#$.getScoped({credentialId:X,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:b3}}),z);if(G.credentialId!==void 0&&G.credentialId!==X)throw new V("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.#G()<b3))throw new V("insufficient-validity","Claustrum served credential has insufficient validity");let H=_9(G.material),Q=G.accountId?.trim()?G.accountId:void 0;if(this.#K&&(G.credentialId===void 0||Q===void 0))throw new V("identity-unasserted","Claustrum served credential did not assert its identity");let K=Q===void 0?this.#Y?.(H):void 0,W=Q??K;if(J!==void 0&&W!==void 0&&W!==J)throw new V("identity-changed","Claustrum served credential identity changed");let U=W??J,D=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":K!==void 0?"parsed":J!==void 0?"expected":"none",...J!==void 0&&{expectedAccountIdentity:J},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#z.set(D,Z),D}async reportFailure($,Z,z){if(Z!==401)return;this.#L();let X=this.#z.get($);if(!X)throw new V("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#W.get($);if(Y!==void 0){this.forget($.credentialId),this.#X.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.#N.get($);if(G)return G;let B=this.#A(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:$.recordVersion,reporterSource:z}));this.#N.set($,B);try{await B,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:z})}catch(H){throw this.#N.delete($),H}}watchRoster($){this.#L();let Z=new M$({client:this.#$,enrollmentToken:()=>this.#E(),view:$.view??(()=>this.#_),discover:async(z)=>{await $.onView(z)},onRefused:(z)=>{this.listFailed(z),$.onRefused?.(z)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#X,now:this.#G,setTimeoutImpl:this.#D,clearTimeoutImpl:this.#V});return this.#S.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#S.delete(Z),Z.stop()}}}close(){if(this.#Q)return;if(this.#Q=!0,this.#F)this.#V(this.#F);this.#F=void 0;for(let $ of this.#S)$.stop();this.#S.clear(),this.#J.clear(),this.#$.close()}async dispose($=this.#P){this.close(),this.#R??=A0(this.#U,$),await this.#R}}import{resolve as C$}from"node:path";var A4=30000,E4={now:()=>performance.now(),schedule($,Z){let z=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(z),unref:()=>z.unref?.()}}};function C4($,Z=""){let z=new Map,{observation:X}=$,Y=(B,H,Q)=>z.set(`${Z}:${B}`,{at:H,order:0,publication:{...$,observation:Q}}),J=(B,H)=>JSON.stringify([B??"all",H]),G=new Set;for(let B of X.readings??[]){let H=J(B.scope,B.label);G.add(H),Y(H,X.checkedAt,{checkedAt:X.checkedAt,readings:[{...B}]})}for(let B of X.coverage??[]){let H=J(B.scope,B.label);if(!G.has(H))Y(H,X.checkedAt,{checkedAt:X.checkedAt,coverage:[{...B}]})}if(X.budget)Y("budget",X.checkedAt,{checkedAt:X.checkedAt,budget:{...X.budget}});for(let[B,H]of Object.entries(X.counters??{}))Y(`counter:${B}`,H.checkedAt,{checkedAt:X.checkedAt,counters:{[B]:{...H}}});if(X.credits)Y("credits",X.credits.checkedAt,{checkedAt:X.checkedAt,credits:{...X.credits}});if(!z.size)Y("empty",X.checkedAt,{checkedAt:X.checkedAt});return z}import{createHash as R9}from"node:crypto";import{stat as x9}from"node:fs/promises";import{resolve as d0}from"node:path";function I4($,Z,z){if($.accountIdentity!==void 0&&z!==void 0)return $.accountIdentity===z;return $.credentialId===Z}function f3($,Z,z){return $.some((X)=>I4(X,Z,z))}function y3($,Z,z){let X={credentialId:Z,...z!==void 0&&{accountIdentity:z}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==z),X]}function h3($,Z,z){return $.filter((X)=>!Z.some((Y)=>I4(X,Y,z)))}function w3($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>v(Z).map((z)=>({credentialId:z,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function S9($,Z){let z=v(Z),X=Z.accountIdentity===void 0?-1:$.order.findIndex((J)=>J.accountIdentity===Z.accountIdentity),Y=X>=0?X:$.order.findIndex((J)=>z.includes(J.credentialId));return Y>=0?Y:1/0}var E$="vault:";function T9($){return R9("sha256").update($).digest("hex")}function A9($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function E9($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function v($){return[$.credentialId,...$.aliases??[]]}function f4($,Z,z={}){let X=z.now??Date.now(),Y=z.routePrefix??E$,J=z.reservedRouteIds??new Set,G=$?.rows??[],B=$?void 0:z.seed,H=[...$?.declined??B?.declined??[]],Q=Z.skipped.length===0,K=new Set(Z.credentials.map((N)=>N.credentialId)),W=new Set(Z.skipped.flatMap((N)=>N.credentialId===void 0?[]:[N.credentialId])),U=Z.skipped.some((N)=>N.credentialId===void 0),q=(N)=>!K.has(N)&&(W.has(N)||U),D=new Map;for(let N of G){if(N.accountIdentity===void 0)continue;for(let _ of v(N))if(!D.has(_))D.set(_,N.accountIdentity)}let j=new Map;for(let N of Z.credentials){let _=N.accountIdentity!==void 0?{credential:N,identity:N.accountIdentity,claimed:!0}:{credential:N,identity:D.get(N.credentialId),claimed:!1},u=E9(_),i=j.get(u)??[];i.push(_),j.set(u,i)}let M=new Set,L=new Set(J),x=[],g=(N,_)=>N.credential.credentialId.localeCompare(_.credential.credentialId),h=[...j.values()].map((N)=>N.toSorted(g)).sort((N,_)=>N[0]&&_[0]?g(N[0],_[0]):0);for(let N of h){let _=N[0]?.identity,u=N.filter((O)=>O.credential.state==="active"),i=u.length?u:N,d$=i.filter((O)=>O.claimed),Z$=d$.length?d$:i,c$=new Set(N.map((O)=>O.credential.credentialId)),JZ=G.find((O)=>!M.has(O)&&v(O).some((P0)=>c$.has(P0))&&(O.accountIdentity===void 0||O.accountIdentity===_)),u$=Z$.find((O)=>O.credential.credentialId===JZ?.credentialId)??Z$[0];if(!u$)continue;let b=u$.credential,w=JZ??(_===void 0?void 0:G.find((O)=>!M.has(O)&&O.accountIdentity===_));if(w)M.add(w);let G0=w?.routeId;if(!G0||J.has(G0)){let O=`${Y}${b.credentialId}${_===void 0?"":`~${T9(_).slice(0,10)}`}`;G0=O;for(let P0=2;L.has(G0);P0++)G0=`${O}~${P0}`}L.add(G0);let p6=w?v(w).filter(q):[],i$=[...new Set([...N.map((O)=>O.credential.credentialId),...p6])].filter((O)=>O!==b.credentialId).sort((O,P0)=>O.localeCompare(P0)),l6=z.mapAccount?.(b)??{};x.push({previousIndex:w?G.indexOf(w):1/0,row:{routeId:G0,credentialId:b.credentialId,credentialType:b.credentialType,..._!==void 0&&{accountIdentity:_},...i$.length&&{aliases:i$},state:b.state,label:l6.label?.trim()||A9(b),...b.email!==void 0&&{email:b.email},...b.orgName!==void 0&&{orgName:b.orgName},enabled:![b.credentialId,...i$].some((O)=>f3(H,O,_)),addedAt:w?.addedAt??X,...w?.quota!==void 0&&{quota:w.quota},...!u$.claimed&&_!==void 0&&{unclaimed:!0}}});let s$=x.at(-1);if(B&&s$)s$.previousIndex=S9(B,s$.row)}return G.forEach((N,_)=>{if(M.has(N)||!v(N).some(q))return;if(L.has(N.routeId))return;let[u,...i]=v(N).filter((c$)=>!K.has(c$));if(u===void 0)return;L.add(N.routeId);let{aliases:d$,...Z$}=N;x.push({previousIndex:_,row:{...Z$,credentialId:u,...i.length&&{aliases:i},stale:!0}})}),x.sort((N,_)=>N.previousIndex===_.previousIndex?N.row.credentialId.localeCompare(_.row.credentialId):N.previousIndex-_.previousIndex),{version:1,view:Z.view,complete:Q,...!Q&&{rejected:Z.skipped.map((N)=>({...N.credentialId!==void 0&&{credentialId:N.credentialId},reason:N.reason}))},rows:x.map((N)=>N.row),declined:H}}function m3($){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 c0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function C0($){return $===void 0||typeof $==="string"}function C9($){let Z=c0($)?H0($.quota):void 0;if(!c0($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!C0($.accountIdentity)||!C0($.email)||!C0($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((z)=>typeof z==="string"))||$.quota!==void 0&&Z===void 0||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return{...$,...Z===void 0?{}:{quota:Z}}}var I9=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function b4($){if(!Array.isArray($))return;let Z=[];for(let z of $){if(!c0(z)||!C0(z.credentialId)||typeof z.reason!=="string"||!I9.has(z.reason))return;Z.push(z)}return Z}function y4($){if(!c0($)||$.version!==1||!C0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!b4($.rejected))throw new V("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let J=C9(Y);if(!J)throw new V("invalid-state","Claustrum roster file is not valid");Z.push(J)}let z=[];for(let Y of $.declined){if(!c0(Y)||typeof Y.credentialId!=="string"||!C0(Y.accountIdentity))throw new V("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=b4($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...X&&{rejected:X},rows:Z,declined:z}}function h4($){return y4(JSON.parse(JSON.stringify($)))}async function R($){let Z;try{Z=await R$($,e)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse(Z)}catch{throw new V("invalid-state","Claustrum roster file is not valid")}return y4(z)}var w4={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},m4={name:"claustrum-roster",ttlMs:30000};async function N0($,Z,z={}){return W3($,{...w4,signal:z.signal},async(X)=>{let Y=await R($),{next:J,result:G}=await Z(Y,{assertOwned:()=>X.assertOwned()});if(J)await X.assertOwned(),await l($,J,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}});return G})}function v3($,Z){return N0($,(z)=>{let X=z?.rows.find((J)=>J.routeId===Z);if(!z||!X)throw new V("route-unavailable","Claustrum route is not in the roster");let Y=y3(z.declined,X.credentialId,X.accountIdentity);return{next:{...z,declined:Y,rows:z.rows.map((J)=>J===X?{...J,enabled:!1}:J)},result:void 0}})}function g3($,Z){return N0($,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===Z);if(!z||!X)throw new V("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:h3(z.declined,v(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function b9($){return new V("invalid-order",$)}function k9($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let z=new Set($.map((J)=>J.routeId)),X=new Set;for(let J of Z){if(typeof J!=="string")return"route ids must be an array of route ids";if(X.has(J))return`route id ${J} appears more than once`;if(!z.has(J))return`route id ${J} is not in the roster`;X.add(J)}let Y=[...z].filter((J)=>!X.has(J)).length;if(Y>0)return`the order leaves out ${Y} roster route id${Y===1?"":"s"}`;return}function p3($,Z,z={}){return N0($,(X)=>{let Y=X?.rows??[],J=k9(Y,Z);if(J)throw b9(J);let G=new Map;for(let Q of Y){let K=G.get(Q.routeId);if(K)K.push(Q);else G.set(Q.routeId,[Q])}let B=[...Z],H=B.flatMap((Q)=>G.get(Q)??[]);if(!X||H.every((Q,K)=>Q===Y[K]))return{result:{ids:B,outcome:"unchanged"}};return{next:{...X,rows:H},result:{ids:B,outcome:"reordered"}}},{...z.signal&&{signal:z.signal}})}function f9($,Z){if(!v($).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")&&v($).length===1)return"bind";return"refuse"}async function l3($,Z){let{routeId:z,observation:X,...Y}=Z;return v4($,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function v4($,Z){if(!R0(Z.observation))return!1;let z=I($,await R($));if(!Z0(z,Z).kept)return!1;return p4($,Z)}function d3($,Z){return v4($,Z)}function Z0($,Z){let z=$?.rows.find((G)=>G.routeId===Z.routeId),X=!z?"refuse":Z.receipt?f9(z,Z.receipt):z.accountIdentity!==void 0&&z.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!z||X==="refuse")return{roster:$,kept:!1};let Y=k0(z.quota,Z.observation),J=X==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((G)=>G===z?{...G,...J,quota:Y}:G)},kept:!0}}var A$=new Map;function u0($){A$.delete(d0($))}function g4($,Z){let z=d0($);if(Z instanceof V)return Z.kind==="roster-busy";if(Z instanceof K$||Z instanceof K3)return d0(Z.details.target)===z;if(Z instanceof y0){let X=d0(Z.path);return[w4.name,m4.name].some((Y)=>{let J=H3(z,Y);return X===J||X.startsWith(`${J}.`)})}return!1}var y9=4;async function k4($){try{let{dev:Z,ino:z,size:X,mtimeMs:Y}=await x9($);return{dev:Z,ino:z,size:X,mtimeMs:Y}}catch{return}}function h9($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function w9($,Z,z){for(let X=0;X<y9;X++){let Y=await k4($),J=await R($),G,B,H;try{({target:G,local:B}=Z(J));let Q=JSON.stringify(z(G));H=JSON.stringify(G)!==Q||B!==void 0&&JSON.stringify(B)!==Q}catch{return"commit"}if(!h9(Y,await k4($)))continue;if(H)return"commit";return l4($)?"commit":"unchanged"}return"commit"}async function i0($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){u0($.path);return}let z=await f({...m4,path:$.path,renew:!0});if(!z){let G=await R($.path);if($.signal?.throwIfAborted(),!G?.view)throw new V("roster-busy","Claustrum account discovery is already in progress");return G}let X=d0($.path),Y=$.listedOver,J;try{let G=await R($.path),B=Y?void 0:A$.get(X);J=B&&(B.previousView===G?.view||B.inventory.view===G?.view)?B:{inventory:await $.custody.discover($.signal),previousView:G?.view},A$.delete(X);let{inventory:H}=J;$.onInventory?.(H),$.signal?.throwIfAborted();let Q=typeof $.projection==="function"?$.projection():$.projection,K=(q)=>f4(q,H,Q),W=async()=>{return $.signal?.throwIfAborted(),await z.assertOwned(),Z()};if(await w9($.path,(q)=>{if(Y)return{target:q};let D=I($.path,q);return{target:q,...D!==q&&{local:D}}},K)==="unchanged"){if(!await W())return;return await R($.path)}return await N0($.path,async(q)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await z.assertOwned(),Y&&q?.view!==Y.view&&q?.view!==H.view)return{result:q};let D=K(q);return{...JSON.stringify(q)!==JSON.stringify(D)&&{next:D},result:D}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await z.assertOwned()}})}catch(G){if(G instanceof K$&&J&&!Y&&!$.signal?.aborted&&await Z())A$.set(X,J);throw G}finally{await z.release()}}var M0=new Map,m9=A("claustrum"),c4=100;function u4($,Z=E4){let z=C$($),X=M0.get(z);if(!X)X={path:z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},M0.set(z,X);return X}function i4($,Z,z){let X=u4($,z);X.listeners.add(Z);let Y;return()=>Y??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():c3($)})()}function v9($){return C4($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function p4($,Z){if(!R0(Z.observation))return Promise.resolve(!1);let z=u4($),X=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),Y=z.pending.get(X)??new Map;for(let[J,G]of v9(Z)){let B=Y.get(J);if(!B||G.at>=B.at){if(G.order=++z.order,G.publication.observation.coverage)G.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(J,G)}}if(Y.size)z.pending.set(X,Y);for(let J of z.listeners)J(Z);return a4(z,c4),Promise.resolve(!0)}function s4($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,z)=>Z.order-z.order)}function I($,Z){let z=M0.get(C$($));if(z)for(let X of s4(z.pending)){if(X.priorReading)Z=Z0(Z,X.priorReading).roster;Z=Z0(Z,X.publication).roster}return Z}function l4($){return!!M0.get(C$($))?.pending.size}function a4($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let z=$.draining?0:($.committedAt??-1/0)+A4-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,z),()=>{return $.timer=void 0,n4($)}),!$.draining)$.timer.unref?.()}function d4($){$.timer?.cancel(),$.timer=void 0}function n4($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([z,X])=>[z,new Map(X)]));return $.running=(async()=>{try{if(await N0($.path,(X)=>{let Y=X;for(let G of s4(Z)){if(G.priorReading)Y=Z0(Y,G.priorReading).roster;Y=Z0(Y,G.publication).roster}let J=JSON.stringify(Y)!==JSON.stringify(X);return{...J&&{next:Y},result:J}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[X,Y]of Z){let J=$.pending.get(X);for(let[G,B]of Y)if(J?.get(G)===B)J.delete(G);if(!J?.size)$.pending.delete(X)}$.failures=0}catch(z){if(!$.abort.signal.aborted&&$.failures++===0)m9.warn("vault quota publication delayed; retrying",{error:z instanceof Error?z.message:String(z)})}finally{$.running=void 0;for(let X of $.wake)X();let z=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):c4;a4($,z)}})(),$.running}async function c3($,Z=1000){let z=C$($),X=M0.get(z);if(!X)return;X.draining=!0,d4(X);let Y,J,G=new Promise((B)=>{J=()=>{if(!X.pending.size||X.abort.signal.aborted)B()},X.wake.add(J),J()});try{if(X.pending.size)n4(X);await Promise.race([G,new Promise((B)=>{Y=setTimeout(B,Math.max(0,Z))})])}finally{if(clearTimeout(Y),J)X.wake.delete(J);if(X.draining=!1,!X.listeners.size){if(X.abort.abort(),d4(X),X.pending.clear(),M0.get(z)===X)M0.delete(z)}}}var I$=1e4;function o4(){return new C}var u3;function t4($,Z){if(!u3)throw Error("ClaustrumConsumer is not initialized");return u3($,Z)}function r4(){return new V("not-active","Claustrum scoped custody is not active")}class i3{#$;#Z=new AbortController;#G;#B;#Y;#K;#X;#z;#N;#J;#W=!1;#D=new Set;#V;#H;#q;#F;#j=new Map;#x;#O;#Q;#_;#S=new WeakMap;static{u3=($,Z)=>{let z=new i3(Z);return z.#Q=$,{consumer:z,hooks:z.#f()}}}constructor($){this.#$=$,this.#G=$.logger??A("claustrum"),this.#B=T0(this.#G,this.#Z.signal),this.#O=i4($.rosterPath,(Z)=>{this.#z=Z0(this.#z,Z).roster})}#U($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#P($){return this.#D.add($),$.then(()=>this.#D.delete($),()=>this.#D.delete($)),$}async#R(){return await this.#$.isCustodyActive?.()??!0}#T($,Z){let z=q0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((X,Y)=>{let J=()=>{z.signal.removeEventListener("abort",G),z.dispose()},G=()=>{J(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",G,{once:!0}),$.then((B)=>{if(J(),z.signal.aborted)Y(z.signal.reason);else X(B)},(B)=>{J(),Y(B)}),z.signal.aborted)G()})}async#M(){if(this.#U(),this.#Y)return this.#Y;if(!this.#K){let $={timedOut:!1};this.#K=this.#L($),this.#P(this.#K)}return this.#T(this.#K)}#L($){let Z=this.#$.setTimeoutImpl??setTimeout,z=this.#$.clearTimeoutImpl??clearTimeout,X=this.#$.connect().then((G)=>{if(this.#Z.signal.aborted||$.timedOut){if(G.close(),!$.timedOut)this.#U();throw o4()}if(this.#Y=new E0({client:G,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#G,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&G.insula)this.#H=j3(G.insula,this.#$.tokenPath);return this.#Y}),Y,J=new Promise((G,B)=>{Y=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#G.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#E()}),B(o4())},this.#E()),Y.unref?.()});return Promise.race([X,J]).finally(()=>{if(Y)z(Y);this.#K=void 0})}#E(){return this.#$.connectTimeoutMs??I$}snapshot(){return this.#z}grantReach(){if(this.#Q)return this.#Q.grantReach(this.#z?.view);let $=this.#N;return $&&this.#z?.view===$.view?$.reach:void 0}watchState(){if(this.#Q)return Object.freeze({vault:this.#Q.watchMode()});return Object.freeze({vault:this.#q?.mode??"polling",...this.#$.insula&&{insula:this.#H?.source.watchMode()??"polling"}})}#A(){this.#q?.close(),this.#q=void 0,this.#F?.(),this.#F=void 0}keptReceiptState(){if(this.#Q){let $=this.#_;return $&&this.#Q.leaseLive($)?$.custody.keptReceiptState():this.#Q.keptReceiptState()}return this.#Y?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return m3(this.#z)}refresh(){if(this.#U(),this.#Q)return this.#P(this.#y(this.#Q));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#R()){if(this.#z=void 0,this.#N=void 0,this.#A(),this.#Y)this.#Y.close(),this.#P(this.#Y.dispose(this.#B));this.#Y=void 0,this.#H?.release(),this.#H=void 0;return}let $=await this.#M(),Z,z=await i0({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#R(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#U();let X=z?.view!==this.#z?.view;if(this.#z=I(this.#$.rosterPath,z),$.retain(z?.rows??[]),Z&&z?.view!==void 0)this.#N=Z.grantReach?{view:z.view,reach:Z.grantReach}:void 0;if(z&&X)this.#$.onRoster?.(z);return this.#x=(this.#$.now??Date.now)(),z})().finally(()=>{this.#X=void 0}),this.#P(this.#X),this.#X}start(){if(this.#W)return;if(this.#U(),this.#W=!0,this.#Q){this.#Q.start();return}let $=async()=>{try{if(await this.#b())await this.refresh();await this.refreshInsulaQuota(),this.#I()}catch(z){if(!this.#Z.signal.aborted)this.#$.onError?.(z)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#J=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#J=void 0,this.#P($())},Z),this.#J.unref?.()};this.#P($())}async#b(){if(this.#q?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#x===void 0||$-this.#x>=S0)return!0;return!await this.#R()}#I(){let $=this.#Y;if(this.#Z.signal.aborted||!$)return;if(this.#q??=$.watchRoster({view:()=>this.#z?.view,onView:()=>this.#P((async()=>{while(this.#X)await this.#X.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#H&&!this.#F)this.#F=this.#H.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#R())return;try{await $0(this.#$.tokenPath),await this.#M(),await this.#H?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#R())return;try{return await $0(this.#$.tokenPath),this.#C($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#R())return;try{await $0(this.#$.tokenPath);let z=I(this.#$.rosterPath,await R(this.#$.rosterPath))?.rows.find((X)=>X.routeId===$);return this.#C(z?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#R())return{miss:"unreachable"};try{await $0(this.#$.tokenPath);let X=I(this.#$.rosterPath,await R(this.#$.rosterPath))?.rows.find((G)=>G.routeId===$)?.accountIdentity;if(!X||!this.#H)return{miss:"unreachable"};let Y=this.#H.source.lookup(Z.provider,X,(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 z=await this.lookupInsulaQuotaForRoute($);if(z.miss==="cold"||z.miss==="upstream-failed"){if(this.#j.get($)!==z.miss)this.#j.set($,z.miss),this.#G.warn("skipped insula provider poll",{reason:z.miss});return}return this.#j.delete($),z.miss?Z():z.reading}#C($){if(!this.#$.insula||!$)return;let Z=this.#H?.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.#U(Z);let z=this.#z??await this.#T(this.refresh(),Z);if(!z||!await this.#R())throw this.#Y?.close(),this.#Y=void 0,this.#A(),this.#H?.release(),this.#H=void 0,new V("not-active","Claustrum scoped custody is not active");let X=I(this.#$.rosterPath,await R(this.#$.rosterPath));this.#U(Z);let Y=z.rows.find((H)=>H.routeId===$),J=X?.rows.find((H)=>H.routeId===$);if(J&&!J.enabled){if(Y)this.#Y?.forget(Y.credentialId);throw new V("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.#Y?.forget(Y.credentialId);throw new V("route-unavailable","Claustrum route is disabled, removed or changed")}let G=await this.#T(this.#M(),Z),B=q0([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()}}#f(){return{install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#z?.view;if(this.#z=I(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(z){this.#$.onError?.(z)}},reset:()=>{this.#z=void 0},roster:()=>this.#z,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#y($){let Z=await $.refresh();if(this.#U(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#z}#h($){if($&&this.#_!==$)return;this.#_?.release(),this.#_=void 0}async#k($,Z){let z=this.#_;if(z&&$.leaseLive(z))return z;this.#h();let X=await $.acquire(Z);if(this.#Z.signal.aborted)X.release(),this.#U();let Y=this.#_;if(Y&&$.leaseLive(Y))return X.release(),Y;return this.#_=X,X}async#m($,Z,z){if(this.#U(z),!this.#z)await this.#T($.refresh(),z);let X=this.#z;if(!await $.readAuthority())throw this.#h(),r4();if(this.#U(z),!X)throw new V("route-unavailable","Claustrum has no roster for this provider yet");let Y=I(this.#$.rosterPath,await R(this.#$.rosterPath));this.#U(z);let J=X.rows.find((Q)=>Q.routeId===Z),G=Y?.rows.find((Q)=>Q.routeId===Z);if(G&&!G.enabled){if(J)$.forget(J.credentialId);throw new V("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 V("route-unavailable","Claustrum route is disabled, removed or changed")}let B={credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},H=q0([this.#Z.signal,...z?[z]:[]]);try{for(let Q=0;;Q++){let K=await this.#k($,H.signal);try{let W=await K.custody.authorize(B,H.signal,Z);return this.#S.set(W,K),W}catch(W){if(Q>0||H.signal.aborted||$.leaseLive(K)||!(W instanceof V)||W.kind!=="closed")throw W;if(this.#h(K),!await $.readAuthority())throw r4()}}}finally{H.dispose()}}async reportFailure($,Z,z){if(this.#U(),this.#Q){let X=this.#S.get($);if(!X)throw new V("no-receipt","Claustrum dispatch receipt has no active owner");await X.custody.reportFailure($,Z,z);return}if(!this.#Y)throw new V("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Y.reportFailure($,Z,z)}async send($,Z,z){let X=z.signal,Y=await this.authorize($,X),J=await Z(Y,X);if(J.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,z.reporterSource??"direct"),J;if(J.status===401&&!X?.aborted){let G;try{G=await this.authorize($,X),X?.throwIfAborted()}catch(B){if(X?.aborted)throw B}if(k3(z.site,Y,G,this.#G))await J.body?.cancel().catch(()=>{}),Y=G,J=await Z(G,X)}if(J.status===401)await this.reportFailure(Y,401,z.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.#U(),await v3(this.#$.rosterPath,$),this.#z=I(this.#$.rosterPath,await R(this.#$.rosterPath)),this.#Q)this.#Q.retainUnion();else this.#Y?.retain(this.#z?.rows??[])}async accept($){this.#U(),await g3(this.#$.rosterPath,$),this.#z=I(this.#$.rosterPath,await R(this.#$.rosterPath))}async reorder($){this.#U();let Z=await p3(this.#$.rosterPath,$);return this.#z=I(this.#$.rosterPath,await R(this.#$.rosterPath)),Z}async recordQuota($,Z,z){return this.#U(),l3(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:z.credentialId,accountIdentitySource:z.accountIdentitySource,...z.accountIdentity!==void 0&&{accountIdentity:z.accountIdentity},...z.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:z.expectedAccountIdentity}})}async recordAccountQuota($,Z,z){return this.#U(),d3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:z})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new V("closed","Claustrum consumer is closed")),this.#J)(this.#$.clearTimeoutImpl??clearTimeout)(this.#J);if(this.#J=void 0,this.#A(),this.#Y)this.#Y.close(),this.#P(this.#Y.dispose(this.#B));this.#_?.release(),this.#_=void 0,this.#Q?.detach(),this.#H?.release(),this.#H=void 0,this.#z=void 0,this.#N=void 0,this.#O(),u0(this.#$.rosterPath)}async dispose(){this.close(),this.#V??=Promise.all([A0(this.#D,this.#B),this.#O()]).then(()=>{}),await this.#V}}import{createHash as g9}from"node:crypto";import{readdir as p9,stat as l9}from"node:fs/promises";import{join as s0}from"node:path";var d9=/^[a-z0-9][a-z0-9._-]{0,63}$/,c9=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,u9=/^[0-9a-f]{16}$/,e4=3;function a3($,Z=new Set){if($===null)return"null";if(typeof $==="string"||typeof $==="boolean")return JSON.stringify($);if(typeof $==="number")return Number.isFinite($)?JSON.stringify($):void 0;if(typeof $!=="object"||Z.has($))return;let z=new Set(Z).add($),X=[];if(Array.isArray($)){for(let J=0;J<$.length;J++){let G=a3($[J],z);if(G===void 0)return;X.push(G)}return`[${X.join(",")}]`}let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return;for(let J of Object.keys($).sort()){let G=a3($[J],z);if(G===void 0)return;X.push(`${JSON.stringify(J)}:${G}`)}return`{${X.join(",")}}`}function i9($,Z){let z=a3({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??E$,mapAccount:$.mapAccount?String($.mapAccount):null});if(z===void 0)throw new V("invalid-state","Claustrum hub classifierInput must be plain JSON");return g9("sha256").update(z).digest("hex").slice(0,16)}function $6($,Z){if(typeof $!=="string"||!d9.test($)||c9.test($))throw new V("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function z0($="Claustrum custody lease is closed"){return new V("closed",$)}function s3(){return new V("not-active","Claustrum scoped custody is not active")}function Z6(){return new C}function s9($,Z){return new Promise((z,X)=>{let Y=()=>X(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),$.then((J)=>{Z.removeEventListener("abort",Y),z(J)},(J)=>{Z.removeEventListener("abort",Y),X(J)}),Z.aborted)Y()})}function z6($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class X6{#$;#Z;#G;#B=new AbortController;#Y=new Map;#K=new WeakMap;#X=0;#z;#N;#J;#W;#D;#V;#H=0;#q;#F;#j;#x=!1;#O=new Set;#Q;#_;#S;constructor($){if(!$.family||!("classify"in $.family))throw new V("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=$6($.hostGeneration,"host generation"),z=$.members.map((Y)=>$6(Y,"member"));if(new Set(z).size!==z.length)throw new V("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??A("claustrum"),this.#G=T0(this.#Z,this.#B.signal),this.#_=s0($.stateDir,"rosters",Z),this.#S=i9($,z);let X=s0(this.#_,this.#S);for(let Y of z)this.#Y.set(Y,{provider:Y,path:s0(X,`${Y}.json`),closed:!1})}#U($){return this.#O.add($),$.then(()=>this.#O.delete($),()=>this.#O.delete($)),$}#P(){if(this.#B.signal.aborted)throw z0("Claustrum discovery hub is closed")}#R($){let Z=this.#Y.get($);if(!Z)throw new V("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#R($).path}member($,Z){this.#P();let z=this.#R($);if(z.hooks)throw new V("wrong-consumer","Claustrum hub member was already built");for(let B of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(B in Z)throw new V("wrong-consumer",`Claustrum hub members cannot take ${B}`);let X={provider:z.provider,start:()=>this.start(),refresh:()=>this.#v(),readAuthority:()=>this.#y(),acquire:(B)=>this.acquire(B),leaseLive:(B)=>this.#L(B),grantReach:(B)=>B!==void 0&&this.#q?.view===B?this.#q.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#g(),forget:(B)=>this.#z?.custody?.forget(B),detach:()=>{z.closed=!0}},Y={rosterPath:z.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:J,hooks:G}=t4(X,Y);return z.hooks=G,J}#T(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#z=$,$}#M($){return!$.ended&&this.#z===$&&!this.#B.signal.aborted}#L($){let Z=this.#K.get($);return!!Z&&!Z.released&&!Z.generation.ended}#E($,Z=z0()){if($.ended)return;if($.ended=!0,$.count=0,this.#z===$)this.#z=void 0;if(this.#J&&this.#K.get(this.#J)?.generation===$)this.#J=void 0;if(this.#W?.generation===$)this.#W.watch.close(),this.#W=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#U($.custody.dispose(this.#G))}#A($){if($.ended)return;if($.count--,$.count<=0)this.#E($)}#b($){let Z=this.#N;if(Z?.generation===$&&Z.promise)return Z.promise;let z={generation:$,timedOut:!1},X=this.#$.connectTimeoutMs??I$,Y,J=this.#$.connect().then((H)=>{if(z.timedOut)throw H.close(),Z6();if(!this.#M($)||$.count<=0)throw H.close(),z0("Claustrum connection is no longer wanted");return $.custody=new E0({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),G=new Promise((H,Q)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(z.timedOut=!0,!this.#M($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:X}),Q(Z6())},X),Y.unref?.()});return z.promise=this.#U(Promise.race([J,G]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),z.promise.finally(()=>{if(this.#N===z)this.#N=void 0}).catch(()=>{}),this.#N=z,z.promise}acquire($){try{if(this.#P(),$?.throwIfAborted(),this.#V===!1)throw s3()}catch(z){return Promise.reject(z)}let Z=this.#z??this.#T();return Z.count++,this.#I(Z,$,!0)}async#I($,Z,z){let X=$.custody;if(!X){let Y=q0([$.controller.signal,...Z?[Z]:[]]);try{X=await s9(this.#b($),Y.signal)}catch(J){if(!$.ended)throw this.#A($),J;return this.#C(Z,z)}finally{Y.dispose()}}if($.ended)return this.#C(Z,z);if(Z?.aborted)throw this.#A($),Z.reason;return this.#f($,X)}#C($,Z){if($?.throwIfAborted(),this.#P(),this.#V===!1)throw s3();if(!Z)throw z0();let z=this.#z??this.#T();return z.count++,this.#I(z,$,!1)}#f($,Z){let z={generation:$,custody:Z,released:!1},X=()=>{if(z.released||$.ended)throw z0()},Y=Object.freeze({authorize:async(G,B,H)=>{X();let Q=q0([$.controller.signal,...B?[B]:[]]);try{return await Z.authorize(G,Q.signal,H)}finally{Q.dispose()}},reportFailure:async(G,B,H)=>{return X(),Z.reportFailure(G,B,H)},forget:(G)=>{X(),Z.forget(G)},keptReceiptState:()=>{return X(),Z.keptReceiptState()}}),J=Object.freeze({custody:Y,generation:$.id,release:()=>{if(z.released)return;z.released=!0,this.#A($)}});return this.#K.set(J,z),J}leaseState(){let $=this.#z;return Object.freeze({generation:$?.id,count:$?.count??0})}async#y(){let $=await this.#$.isCustodyActive?.()??!0;if(this.#B.signal.aborted)return!1;let Z=this.#V;if(this.#V=$,!$&&Z!==!1)this.#h();return $}#h(){this.#H++;let $=this.#z;if($)this.#E($,s3());this.#J=void 0,this.#W?.watch.close(),this.#W=void 0,this.#q=void 0,this.#F=void 0;for(let Z of this.#Y.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),u0(Z.path)}#k(){return[...this.#Y.values()].filter(($)=>$.hooks&&!$.closed)}async#m(){let $=this.#J,Z=$&&this.#K.get($);if($&&Z&&this.#L($))return Z;this.#J=void 0;let z=await this.acquire(this.#B.signal),X=this.#J&&this.#K.get(this.#J);if(this.#J&&X&&this.#L(this.#J))return z.release(),X;this.#J=z;let Y=this.#K.get(z);if(!Y)throw z0();return Y}#v(){try{this.#P()}catch(X){return Promise.reject(X)}let $=this.#D;if($&&!$.generation?.ended)return $.promise;let Z={},z=this.#U(this.#s(Z).finally(()=>{if(this.#D===Z)this.#D=void 0}));return Z.promise=z,this.#D=Z,z}async#s($){if(!await this.#y())return;let Z=await this.#m(),z=Z.generation;if($.generation=z,!this.#M(z))return;let X=new Map;for(let B of this.#Y.values())X.set(B,await R(B.path).then((H)=>H?{file:H}:{},(H)=>H instanceof Error?H:Error(String(H))));if(!this.#M(z))return;let Y;try{Y=await Z.custody.discover(z.controller.signal)}catch(B){if(!this.#M(z))return;for(let H of this.#Y.values())if(H.pending)this.#w(H);throw B}let J=new Map,G=!0;for(let B of this.#k()){if(!this.#M(z))return;let H=B.hooks;if(!H||B.closed)continue;let Q={...Y,credentials:Y.credentials.filter((U)=>U.member===B.provider),skipped:Y.skipped.filter((U)=>U.member===B.provider)},K=X.get(B),W;try{if(!K)throw z0("Claustrum hub member has no base view");if(K instanceof Error)throw K;let U=K.file?void 0:await this.#a(B);W=await i0({path:B.path,custody:{discover:async()=>Q},isActive:()=>this.#M(z)&&this.#V===!0,signal:z.controller.signal,projection:()=>({...H.projection(),...U&&{seed:U}}),listedOver:{view:K.file?.view}})}catch(U){if(!this.#M(z))return;if(G=!1,this.#w(B),g4(B.path,U))this.#Z.debug("claustrum hub member commit refused",{member:B.provider});else J.set(B.provider,U);continue}if(!this.#M(z))return;if(W?.view!==Y.view)G=!1,this.#w(B);else B.pending=void 0;if(!W)continue;if(this.#p(H,W)){G=!1,this.#w(B);continue}if(B.seen=JSON.stringify(h4(W)),!B.closed)H.install(W)}if(!this.#M(z))return;if(this.#g(),G)this.#q=Object.freeze({view:Y.view,...Y.grantReach&&{reach:Y.grantReach},refused:Object.freeze([...Y.refused??[]]),notMine:Y.notMine??0});return this.#F=(this.#$.now??Date.now)(),{errors:J}}async#a($){let Z=`${$.provider}.json`,z=[s0(this.#_,Z)];try{for(let Y of await p9(this.#_))if(Y!==this.#S&&u9.test(Y))z.push(s0(this.#_,Y,Z))}catch{}let X;for(let Y of z)try{let J=(await l9(Y)).mtimeMs,G=await R(Y);if(G&&(!X||J>X.modified))X={modified:J,roster:G}}catch{}return X&&w3(X.roster)}#p($,Z){let z=$.projection().reservedRouteIds;return!!z?.size&&Z.rows.some((X)=>z.has(X.routeId))}#w($){let Z=($.pending?.failures??0)+1,z=Math.max(1,this.#$.pollIntervalMs??5000),X=Math.max(1,Math.ceil(S0/z)),Y=Z<=e4?1:Math.min(2**(Z-e4),X);$.pending={failures:Z,wait:Y-1}}#g(){let $=this.#z?.custody;if(!$)return;$.retain(this.#k().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#n(){let $=this.#H;for(let Z of this.#k()){let z;try{z=await R(Z.path)}catch(B){Z.hooks?.onError(B);continue}if($!==this.#H||this.#V!==!0)return;let X=Z.hooks;if(!z||!X||Z.closed)continue;let Y=JSON.stringify(z);if(Y===Z.seen)continue;let J=X.roster();if(!J||J.view!==z.view||this.#p(X,z)){Z.pending??={failures:0,wait:0};continue}let G=z6(J);if(Z.seen=Y,X.install(z),z6(X.roster())!==G)this.#g()}}#o(){let $=!1;for(let z of this.#Y.values()){if(!z.pending)continue;if(z.pending.wait<=0)$=!0;else z.pending.wait--}if(this.#W?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#F===void 0||Z-this.#F>=S0}#r(){let $=this.#J,Z=$&&this.#K.get($);if(!$||!Z||!this.#L($)||this.#V!==!0)return;let z=Z.generation;if(!this.#M(z)||this.#W?.generation===z)return;let X=Z.custody.watchRoster({view:()=>this.#q?.view,onView:()=>this.#U((async()=>{while(this.#D)await this.#D.promise.catch(()=>{});if(!this.#M(z))return;await this.#u()})()),onRefused:(Y)=>this.#d(Y),onError:(Y)=>this.#l(Y)});this.#W={generation:z,watch:X}}#l($){if(!this.#B.signal.aborted)this.#$.onError?.($)}#d($){if(this.#B.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#k())Z.hooks?.onError($)}#c($){for(let[Z,z]of $?.errors??[])this.#Y.get(Z)?.hooks?.onError(z)}async#u(){let $;try{$=await this.#v()}catch(Z){this.#d(Z);return}this.#c($)}async#i(){try{if(await this.#y()){if(await this.#n(),this.#o())await this.#u();this.#r()}}catch(Z){this.#l(Z)}if(this.#B.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#j=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#j=void 0,this.#U(this.#i())},$),this.#j.unref?.()}start(){if(this.#x)return;this.#P(),this.#x=!0,this.#U(this.#i())}async refresh(){this.#c(await this.#v())}refusals(){let $=this.#q;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#q?.reach}watchState(){let $=this.#W;return $&&this.#M($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#z?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#B.signal.aborted)return;if(this.#B.abort(z0("Claustrum discovery hub is closed")),this.#j)(this.#$.clearTimeoutImpl??clearTimeout)(this.#j);this.#j=void 0;let $=this.#z;if($)this.#E($);this.#J=void 0,this.#W?.watch.close(),this.#W=void 0}async dispose(){this.close(),this.#Q??=A0(this.#O,this.#G),await this.#Q}}var n9=1e4;async function c5($){let{connectTimeoutMs:Z,...z}=$,X=Z??n9,Y=a9.connect(z),J=!1,G,B=new Promise((H,Q)=>{G=setTimeout(()=>{J=!0,Q(new C)},X),G.unref?.()});try{let H=await Promise.race([Y,B]);return Object.assign(H,{insula:rZ($)})}catch(H){throw Y.then((Q)=>Q.close(),()=>{}),H}finally{if(!J&&G)clearTimeout(G)}}var Y6=S$("openai");function J6($){return T$($)}function j0($){if(!$||$.corrupt===!0)return!1;return J6($.refresh)}class a0 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 b$($){if(J6($))throw new a0}var o9=A("quota"),n3="primary",o3="secondary",r9="app_EMoamEEZ73f0CkXaXp7hrann",t9="https://auth.openai.com";async function Dz($){b$($.refreshToken);let Z=await $.fetchImpl(`${t9}/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:r9}).toString()});if(!Z.ok){let Y=D3(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:Y,isRefreshError:!0})}let z=await Z.json();if(!z||typeof z.access_token!=="string"||!z.access_token||typeof z.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});if(z.refresh_token!==void 0&&typeof z.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});let X=typeof z.refresh_token==="string"&&z.refresh_token?z.refresh_token:$.refreshToken;return{access:z.access_token,refresh:X,expires:$.now()+z.expires_in*1000,expiresIn:z.expires_in}}var e9="https://chatgpt.com/backend-api/wham/usage";async function Vz($){let Z=$.logger??o9,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await $.fetchImpl(e9,{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=D3(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:G})}let J=sZ(await Y.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:Y.status,elapsedMs:Date.now()-X}),J}catch(Y){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof Y?.status==="number"?Y.status:"error",elapsedMs:Date.now()-X,error:G6(Y)}),Y}}import{createHash as $1}from"node:crypto";var Z1=globalThis.setTimeout,z1=5;function n0($){let Z=$?.quota?.checkIntervalMinutes??z1;return Math.max(1,Z)*60000}function X1($){return $?.quota?.enabled!==!1}function k$($,Z){if(!$?.resetsAt)return!1;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z<=Z}function Oz($,Z,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let J=Z===n3?$?.primary:Z===o3?$?.secondary:void 0,G=J?.resetsAt?Date.parse(J.resetsAt):NaN;if(Number.isFinite(G)&&G>z)return G;return z+X}function Y1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function B6($,Z,z){if(!X1(Z))return z+n0(Z);let X=Y1(Z),Y=[];for(let J of["primary","secondary"]){let G=$?.[J];if(!G)continue;if(G.remainingPercent>=X[J])continue;let B=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=z)return z+n0(Z);Y.push(B)}if(!Y.length)return z+n0(Z);return Math.min(...Y)+60000}function J1($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function G1($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function y($){return $1("sha256").update($).digest("hex").slice(0,16)}class X0{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!==y($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let z=this.fallbacks.get($)??null;if(!Z||!z)return z;if(this.fallbackTokenFps.get($)!==y(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!H6(Z.quota))return;if(this.mainTokenFp=y($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,r3(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let z=this.fallbacks.get($)??null;if(Z&&z?.accountId&&z.accountId!==Z)return null;return z}setFallback($,Z,z,X=!1,Y){if(!X&&!H6(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}),z)this.fallbackTokenFps.set($,y(z));else this.fallbackTokenFps.delete($);if(r3(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let z=this.rateLimitedUntilMap.get($);if(z!==void 0&&z>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=y($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let z=X0.fallbackInflightKey($,Z),X=this.inflightFallbacks.get(z);if(X)return X;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(z,Y),Y}async refreshAllFallbacks($){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;if(j0(z)||!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground($){let Z=y($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale($,Z){let z=this.getFallback($,Z);if(!z)return!0;return this.now()>=z.refreshAfter}shouldRefreshOnRequestCount($){let Z=G1(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let z=J1($);if(!z)return;let X=Z?y(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:B6(z.quota,$,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=Y.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=Y,this.mainTokenFp=z.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&x0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=n0(this.storage);for(let z of $){if(z.enabled===!1)continue;if(!z.quota)continue;let X=Math.max(z.quota.primary?.checkedAt??0,z.quota.secondary?.checkedAt??0);if(X<=0)continue;let Y=this.getFallback(z.id,z.access);if(Y&&Y.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+Z,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return x0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==y(Z))return!1}return x0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,y(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let X=this.now()-this.lastApiCallAt;if(X<X0.API_CALL_GAP_MS)await new Promise((Y)=>{let J=Z1(Y,X0.API_CALL_GAP_MS-X);if(typeof J==="object"&&"unref"in J)J.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=y($);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let z=await f({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!z){let X=this.main;if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=this.now(),Y=await this._fetchQuota($),J=this.now();if(this.mainTokenFp=y($),this.main={quota:Y,refreshAfter:B6(Y,this.storage,J),checkedAt:J},r3(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,J,this.mainTokenFp,X),Y}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,Z)){let X=this.getFallback($,Z);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=await f({name:X0.quotaLockName($),ttlMs:30000,path:this.configPath});if(!z){let X=this.getFallback($,Z);if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=await this._fetchQuota(Z),Y=this.now();return this.setFallback($,{quota:X,refreshAfter:Y+n0(this.storage),checkedAt:Y},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError($,Z,z),z}finally{this.inflightFallbacks.delete(X0.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(X0.isAuthError($))return;this.mainLastApiError=h0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(X0.isAuthError(z))return;let X=y(Z),Y=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,h0({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,X)}}function H6($){return Boolean($.primary||$.secondary)}function r3($){let{primary:Z,secondary:z}=$;if(!Z&&!z)return!1;if(Z&&Z.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{createHash as B1,randomUUID as H1}from"node:crypto";import{setTimeout as K1}from"node:timers/promises";import{readFile as P1}from"node:fs/promises";var _0=A("refresh"),y$=A("accounts"),W1=1e4,Q1=15000,t3=50;function c($){return $.type==="oauth"&&$.corrupt!==!0}function U1($){let Z=$?.trim();if(!Z)return!1;try{let z=new URL(Z);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}var D1="floors-v1";function hz($){return $.costZeroing?.enabled!==!1}class h$ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var V1=[401,403,429],K6={primary:0,secondary:0},q1=!1,$Z={primary:5,secondary:10};function F($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var F1=new Set(["__proto__","constructor","prototype"]);function N1($){return $.length>0&&!F1.has($)}function M1($){return $ instanceof h$||F($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function f$($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():H1(),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 W6($){if(!F($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function j1($){if(!F($))return;let Z={};for(let Y of["primary","secondary"]){let J=$[Y];if(!F(J))continue;let G=Number(J.usedPercent),B=Number(J.remainingPercent),H=Number(J.checkedAt);if(!Number.isFinite(G)||!Number.isFinite(B)||!Number.isFinite(H))continue;let Q=typeof J.windowMinutes==="number"?J.windowMinutes:Number.NaN;Z[Y]={usedPercent:G,remainingPercent:B,checkedAt:H,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let J=typeof $[Y]==="number"?$[Y]:Number.NaN;if(Number.isFinite(J)&&J>=0)Z[Y]=J}let z=$.spendControl;if(F(z)){let Y=Number(z.limit),J=Number(z.used),G=Number(z.remaining),B=Number(z.usedPercent),H=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof z.reached==="boolean")Z.spendControl={limit:Y,used:J,remaining:G,usedPercent:B,remainingPercent:H,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=$.credits;if(F(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&(X.overageLimitReached===void 0||typeof X.overageLimitReached==="boolean")){let Y=Number(X.balance),J=typeof X.checkedAt==="number"?X.checkedAt:Number.NaN;Z.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,...typeof X.overageLimitReached==="boolean"?{overageLimitReached:X.overageLimitReached}:{},...Number.isFinite(Y)?{balance:Y}:{},...Number.isFinite(J)?{checkedAt:J}:{}}}return Object.keys(Z).length?Z:void 0}function _1($){if(!F($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!U1(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...f$($),type:"api",apiKey:z||void 0,baseURL:Z,authHeader:X}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...f$($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...f$($),type:"oauth",corrupt:!0}}return{...f$($),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:W6($.lastRefreshError),lastQuotaRefreshError:W6($.lastQuotaRefreshError),quota:j1($.quota)}}function O1($){if(!F($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!N1(z)||!F(X))continue;let Y={};if(F(X.inFlight))Y.inFlight={...X.inFlight};if(F(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))Y.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...F(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))Y.cooldownUntil=X.cooldownUntil;if(Object.keys(Y).length>0)Z[z]=Y}return Object.keys(Z).length>0?Z:void 0}var Q6=new Set;function M6($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(Q6.has(Z))return;Q6.add(Z),y$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function j6($){if(!F($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(_1).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let G of Z)if(F(G)&&typeof G.id==="string"&&G.id.trim())X.add(G.id.trim());let Y=new Set(z.map((G)=>G.id)),J=[];for(let G of X)if(!Y.has(G))J.push(G);M6(J)}return{version:1,main:{type:"opencode",provider:"openai"},routing:F($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:F($.refresh)?$.refresh:void 0,quota:F($.quota)?$.quota:void 0,reset:O1($.reset),dump:F($.dump)?$.dump:void 0,costZeroing:F($.costZeroing)?$.costZeroing:void 0,killswitch:F($.killswitch)?$.killswitch:void 0,logging:F($.logging)?$.logging:void 0,cachekeep:F($.cachekeep)?$.cachekeep:void 0,cacheKeep:F($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:z}}function _6($){if(!("claustrum"in $))return $;let{claustrum:Z,...z}=$;return z}async function Y0($){try{return{exists:!0,value:JSON.parse(await P1($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function J0($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function L1($){let Z;try{Z=(await Y0($)).value}catch{return null}return YZ(Z)}function O6($,Z){if(!F($))return $;let z=F(Z)?Z:{},X=F(z.main)?z.main:void 0,Y=F(z.accounts)?z.accounts:{},J=F($.quota)?$.quota:{},G=F($.refresh)?$.refresh:{},B=X??J,H=X??G,K=G.mainRefreshLeaseId!==void 0?{id:G.mainRefreshLeaseId,until:G.mainRefreshLeaseUntil,tokenHash:G.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((q)=>{if(!F(q))return q;let D=typeof q.id==="string"&&F(Y[q.id])?Y[q.id]:{};return{...q,...D}}):void 0;return P6({...$,refresh:J0({...G,mainLastRefreshError:G.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:K.id,mainRefreshLeaseUntil:K.until,mainRefreshLeaseTokenHash:K.tokenHash}),quota:J0({...J,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:U})}async function R1($){let Z=await Y0($.configPath);if(!Z.exists)return null;let z=await Y0($.statePath);return j6(O6(Z.value,z.value))}function P6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function x1($){return J0({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 L6($){if($.type==="api")return J0({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return J0({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function w$($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function o0($,Z,z){if(z in Z)$[z]=Z[z];else delete $[z]}function S1($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function T1($,Z){if(!S1($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var A1=300000;function U6($,Z){if($===void 0)return 0;return $>Z+A1?0:$}function E1($,Z,z){let X=Date.now(),Y=U6(Z.lastRefreshedAt,X),J=U6(z.lastRefreshedAt,X),G=Z.expires??0,B=z.expires??0,H=J>Y?z:Y>J?Z:B>G?z:G>B?Z:T1(Z,z);o0($,H,"access"),o0($,H,"refresh"),o0($,H,"expires"),o0($,H,"lastRefreshedAt"),o0($,H,"lastRefreshError")}function C1($,Z){if(!F($))return Z;let z=$,X=w$(z.quota),Y=w$(Z.quota),J=X>Y,G=J?{...z,...Z,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...Z};if(!J&&!("lastQuotaRefreshError"in Z))delete G.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete G.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||z.lastUsed>Z.lastUsed))G.lastUsed=z.lastUsed;return E1(G,z,Z),G}function R6($){let Z=$.refresh?J0({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?J0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return P6({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:z,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,cacheKeep:$.cacheKeep,mainAccountId:$.mainAccountId,accounts:$.accounts.map(x1)})}async function e0($,Z=!1){let z=Date.now(),X=z+Q1,Y=0;while(Date.now()<=X){Y++;let B=await f({name:"save",ttlMs:W1,path:$,renew:Z});if(B)return B;let H=X-Date.now();if(H<=0)break;await K1(Math.min(t3+E6(t3),H))}let J=Date.now()-z,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 ${t3}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 x6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,L6(z)]));return{version:1,main:J0({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 YZ($){if(!F($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!F(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function I1($,Z,z,X){if(!F($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],J=[];for(let G of Z){if(z.has(G))continue;if(X.has(G))continue;let B=$.accounts.find((H)=>F(H)&&typeof H.id==="string"&&H.id.trim()===G);if(!B)continue;Y.push(B),J.push(G)}return{preservedRawEntries:Y,preservedIds:J}}function b1($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!F(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function k1($,Z,z){let X=YZ($);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:J}=I1($,X,Z,z);return M6(J),Y}async function mz($,Z,z={}){let{configPath:X,statePath:Y}=Z,J=await e0(X);try{let G=await e0(Y);try{let B=await Y0(X),H=await Y0(Y),Q=(B.exists?j6(O6(B.value,H.value)):null)??f1(),K=new Set(Q.accounts.map((h)=>h.id)),W=YZ(B.value)??new Set,U=$(Q,{rawRosterIds:[...W],loadedRosterIds:[...K]})??Q,q=new Set(z.allowDrop??[]),D=k1(B.value,K,q),j=R6(U),M=new Set((Array.isArray(j.accounts)?j.accounts:[]).map((h)=>F(h)&&typeof h.id==="string"?h.id.trim():"").filter(Boolean)),L=D.filter((h)=>{if(!F(h))return!1;if(typeof h.id!=="string")return!1;return!M.has(h.id.trim())}),x=F(B.value)?B.value:{},g={..._6(x),...j,accounts:[...Array.isArray(j.accounts)?j.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return Q;if(await l(X,g),z.canWrite&&!z.canWrite())return Q;return await l(Y,x6(U)),y$.debug("account config written",{accountCount:g.accounts.length,accountIds:b1(g.accounts)}),U}finally{await G.release()}}finally{await J.release()}}function f1(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function y1($,Z){$.main=$.main??{};let z=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:w$($.main.quota),X=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:w$(Z.quota?.mainQuota);if(z>X)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function h1($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function ZZ($){if(Array.isArray($))return $.map(ZZ);if(!F($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,z])=>[Z,ZZ(z)]))}async function w1($,Z,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=Z.statePath,J=await e0(Y);try{let G=(await Y0(Y)).value,B=F(G)?{...G,version:1}:{version:1};if(z.mainQuota)y1(B,$);if(z.mainRefresh)h1(B,$);if(z.accounts){let H=z.accounts===!0?null:new Set(z.accounts),Q=await L1(Z.configPath);B.accounts={...F(B.accounts)?B.accounts:{}};for(let K of $.accounts){if(H&&!H.has(K.id))continue;if(Q&&!Q.has(K.id))continue;B.accounts[K.id]=C1(B.accounts[K.id],L6(K))}if(H){for(let K of H)if(!$.accounts.some((W)=>W.id===K))delete B.accounts[K]}if(Q){for(let K of Object.keys(B.accounts))if(!Q.has(K))delete B.accounts[K]}}if(X&&!X())return;await l(Y,ZZ(B))}finally{await J.release()}}function m1($){return $?.fallbackOn?.length?$.fallbackOn:V1}function vz($,Z){return m1(Z).includes($)}function v1($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??K6.primary,secondary:Z.secondary??Z["1w"]??K6.secondary}}function zZ($){return $?.quota?.enabled!==!1}function $$($){return $?.quota?.failClosedOnUnknownQuota??q1}function S6($,Z,z=Date.now()){if(!zZ(Z))return!0;if(!$)return!$$(Z);let X=v1(Z),Y=$$(Z);for(let J of["primary","secondary"]){let G=$[J];if(!G)continue;if(k$(G,z)){if(Y)return!1;continue}if(G.remainingPercent<X[J])return!1}return!0}function m$($){return $?.killswitch?.enabled===!0}function D6($){return{primary:$?.primary??$?.["5h"]??$Z.primary,secondary:$?.secondary??$?.["1w"]??$Z.secondary}}function gz($){return $?.cacheKeep??$?.cachekeep}function V6($){return typeof $==="number"&&Number.isFinite($)?$:0}function T6($,Z){if(!$?.killswitch)return $Z;if($.killswitch.schema===D1){let{accounts:z,defaults:X}=$.killswitch,Y=Z??"main",J=F(z)&&Object.hasOwn(z,Y)&&F(z[Y])?z[Y]:F(X)?X:void 0;return{primary:V6(J?.primary),secondary:V6(J?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return D6($.killswitch.accounts[Z]);return D6($.killswitch.main)}function A6($,Z,z,X=Date.now()){if(!m$(Z))return!0;if(!$)return!$$(Z);let Y=T6(Z,z),J=$$(Z);for(let G of["primary","secondary"]){let B=$[G];if(!B)continue;if(k$(B,X)){if(J)return!1;continue}if(B.remainingPercent<Y[G])return!1}return!0}function pz($,Z,z,X){if(!m$(X))return 300;let Y=[],J=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:H}of J){if(!H)continue;let Q=T6(X,B),K=[],W=!1;for(let U of["primary","secondary"]){let q=H[U];if(!q||k$(q,z))continue;if(q.remainingPercent>=Q[U])continue;let D=q.resetsAt?Date.parse(q.resetsAt):NaN;if(!Number.isFinite(D)||D<=z){W=!0;break}K.push(D)}if(W||K.length===0)continue;Y.push(Math.max(...K))}if(Y.length===0)return 300;let G=Math.min(...Y);return Math.max(1,Math.ceil((G-z)/1000))}function q6($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function lz($,Z){let{configPath:z,statePath:X}=Z;if(!$)return;try{let J=await Y0(z);if(J.exists&&F(J.value)&&q6(J.value))return}catch{}let Y=await e0(z);try{let J=await e0(X);try{let G=await Y0(z);if(G.exists&&F(G.value)){if(q6(G.value))return}if(!$)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let K=U$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(K)B.mainAccountId=K}let H=G.exists&&F(G.value)?G.value:{},Q={..._6(H),...R6(B)};await l(z,Q),await l(X,x6(B))}finally{await J.release()}}finally{await Y.release()}}function g1($){return $?.refresh?.enabled!==!1}function p1($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function E6($){return Math.floor(Math.random()*($+1))}function O0($,Z,z){return!$.access||!$.expires||$.expires-z<=p1(Z)}function l1($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function r0($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class C6 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 d1="common-auth-placeholder:v1:openai",I6="main";function dz($){return F($)&&$.type==="oauth"&&($.refresh===d1||$.refresh===Y6)}function cz($){return $?.accounts.find((Z)=>Z.id===I6&&Z.enabled!==!1&&c(Z))}function uz($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==I6)}}function E($,Z){let z=$.accounts.findIndex((X)=>X.id===Z.id);if(z!==-1)$.accounts[z]=Z}function t0($){return $ instanceof Error?$.message:String($)}function XZ($,Z,z){if(Z instanceof a0)return;$.lastRefreshError=IZ({error:Z,now:z,refreshToken:$.refresh,previous:$.lastRefreshError})}function e3($,Z,z){if(Z instanceof a0)return;if($.lastQuotaRefreshError=h0({error:Z,now:z,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)XZ($,Z,z)}function F6($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return Number.isFinite(z)?z>Z:!0}function c1($,Z){if(!$)return!1;return F6($.primary,Z)||F6($.secondary,Z)}function u1($,Z,z){if(!$)return!1;let X=Z?.quota?.checkIntervalMinutes??5,Y=Math.max(1,X)*60000,J=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return z-J<Y}function N6($,Z,z){return!u1($.quota,Z,z)}function i1($,Z,z,X){return U3(z)&&S6($.quota,Z,X)&&c1($.quota,X)}function s1($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var a1=60000,n1=60000,o1=600000;function r1($){return`fallback-oauth-refresh-${B1("sha256").update($).digest("base64url").slice(0,16)}`}var t1=1e4,e1=100;class $2{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($)b$($.refresh)}seedFallbackQuota($,Z){if(!this.quotaManager)return;if(!$.quota)return;let z=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(z<=0)return;let X=this.quotaManager.getFallback($.id,$.access);if(X&&X.checkedAt>=z)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:z+s1(Z),checkedAt:z},$.access,!1,$.accountId)}async load(){return R1(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await w1($,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(()=>{})},a1+E6(n1)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($){let Z=$!==void 0?$:await this.load();if(!Z)return[];let z=[],X=!1;for(let Y of Z.accounts){if(Y.enabled===!1||!c(Y))continue;if(r0(Z,Y))continue;if(j0(Y))continue;let J=!1,G=Y;try{if(O0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&W0(B,G.refresh,this.now()))throw J=!0,Error(W$(B,this.now()));try{G=await this.refreshAccount(G,Z),X=!0}catch(H){if(M1(H))continue;J=!0;let Q=Z.accounts.find((K)=>K.id===Y.id&&c(K));if(Q&&!W0(Q.lastRefreshError,Q.refresh,this.now()))XZ(Q,H,this.now()),E(Z,Q),X=!0;throw H}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))z.push(G)}catch(B){let H=l1(G,this.now());if(J){if(!H)continue}else if(!H)continue;if(i1(G,Z,B,this.now()))_0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:t0(B)}),z.push(G);else if(!$$(Z))z.push(G)}}if(X){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((J)=>{y$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:t0(J)})})}return z}async markUsed($){try{let Z=await this.load();if(!Z)return;let z=Z.accounts.find((X)=>X.id===$.id);if(!z)return;z.lastUsed=this.now(),await this.save(Z,[z.id])}catch(Z){y$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:t0(Z)})}}accountPassesQuotaPolicy($,Z){return S6($.quota,Z,this.now())}quotaPolicyAccount($){if(!this.quotaManager)return $;let Z=this.quotaManager.getFallback($.id,$.access)?.quota;return Z?{...$,quota:Z}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!g1($))return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!c(z))continue;if(r0($,z))continue;if(j0(z))continue;if(!O0(z,$,this.now()))continue;if(W0(z.lastRefreshError,z.refresh,this.now()))continue;try{_0.debug("fallback oauth background due",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),await this.refreshAccount(z,$),Z=!0}catch(X){_0.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:t0(X)}),XZ(z,X,this.now()),E($,z),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!zZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!c(z))continue;if(r0($,z))continue;if(j0(z))continue;let X=z;try{if(O0(X,$,this.now())){if(W0(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,$),Z=!0}if(x0(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,$),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):N6(X,$,this.now())))continue;await this.refreshAccountQuota(X,$),Z=!0}catch(Y){e3(z,Y,this.now()),E($,z),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),z=[];if(!Z||!zZ(Z))return{storage:Z,errors:z};if(!this.options.fetchQuotaFn)return{storage:Z,errors:z};let X=$.force??!1,Y=!1;for(let J of Z.accounts){if(J.enabled===!1||!c(J))continue;if(r0(Z,J))continue;if(j0(J))continue;let G=J;try{if(O0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&W0(B,G.refresh,this.now()))throw Error(W$(B,this.now()));G=await this.refreshAccount(G,Z),Y=!0}if(!X&&!N6(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,E(Z,G),Y=!0;continue}await this.refreshAccountQuota(G,Z),Y=!0}catch(B){e3(J,B,this.now()),E(Z,J),Y=!0,z.push({accountId:J.id,message:t0(B)})}}if(Y)await this.save(Z);return{storage:Z,errors:z}}async refreshAccount($,Z,z={}){let X=this.refreshPromises.get($.id);if(X){let G=await X;return E(Z,G),G}let Y=this.refreshAccountNow($,Z,z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let J=await Y;return E(Z,J),J}async waitForConcurrentFallbackRefresh($,Z,z,X){let Y=Date.now()+t1;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,e1));let J=await this.load(),G=J?.accounts.find((Q)=>Q.id===$.id&&c(Q));if(!G)continue;if(this.assertNotTombstoned(G),(G.access!==z.access||G.refresh!==z.refresh||(G.expires??0)>(z.expires??0)+60000)&&(X.force||!O0(G,J,this.now())))return E(Z,G),_0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G;let H=G.lastRefreshError;if(H&&W0(H,G.refresh,this.now()))throw E(Z,G),Error(W$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,z){if(z.asPoolMain||!Z)return;if(r0($,Z))throw new C6(Z.id)}async refreshAccountNow($,Z,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===$.id&&c(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!O0(Y,X,this.now()))return E(Z,Y),Y;let J=Y??$,G=await f({name:r1(J.id),ttlMs:o1,path:this.paths.configPath,renew:!0});if(!G){_0.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:J.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,J,z);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),Y=X?.accounts.find((K)=>K.id===$.id&&c(K)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!O0(Y,X,this.now()))return E(Z,Y),Y;if(!Y)throw new h$($.id);J=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});_0.debug("fallback oauth refresh request start",{pid:process.pid,accountId:J.id,force:z.force===!0,expiresInMs:J.expires?J.expires-this.now():void 0});let H=await B({refreshToken:J.refresh,fetchImpl:this.fetchImpl,now:this.now});if(J.access=H.access,J.refresh=H.refresh,J.expires=H.expires,J.lastRefreshedAt=H.expires-H.expiresIn*1000,J.lastRefreshError=void 0,E(Z,J),await this.save(Z),!(await this.load())?.accounts.some((K)=>K.id===$.id))throw new h$($.id);return _0.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 z=$;if(this.assertNotTombstoned(z),!z.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let X=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(J)=>this.quotaManager?this.quotaManager.refreshFallback(z.id,J):X({accessToken:J,fetchImpl:this.fetchImpl,now:this.now});try{if(!z.access)throw Error(`Fallback account ${$.id} has no access token`);let J=await Y(z.access);z.quota=J,z.lastQuotaRefreshError=void 0,E(Z,z),await this.save(Z)}catch(J){throw e3($,J,this.now()),E(Z,$),J}}}var b6=["primary","secondary"];function v$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function I0($){return typeof $==="number"&&Number.isFinite($)}function Z2($,Z){if(!v$(Z))return;let z=Z.usedPercent;if(!I0(z)||z<0||z>100)return;return{label:$,usedPercent:z,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...I0(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function z2($){let Z=$.spendControl;if(v$(Z)&&typeof Z.reached==="boolean"){let z=(X)=>I0(Z[X])?{[X]:Z[X]}:{};return{kind:"reading",reached:Z.reached,...z("remainingPercent"),...z("usedPercent"),...z("limit"),...z("used"),...z("remaining"),...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...typeof Z.unit==="string"?{unit:Z.unit}:{}}}if($.spendControlCleared===!0)return{kind:"cleared"};return}function X2($,Z){if(!v$($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...I0($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function az($,Z,z){if(!v$($)||!I0(Z))return;let X=[],Y=[];for(let Q of b6){let K=Z2(Q,$[Q]);if(K)X.push(K);else if(z)Y.push({label:Q})}let J=z2($),G=$.resetCreditsAvailable,B=typeof G==="number"&&Number.isSafeInteger(G)&&G>=0?{resetCredits:{value:G,checkedAt:Z}}:void 0,H=X2($.credits,Z);if(X.length===0&&Y.length===0&&!J&&!B&&!H)return;return{checkedAt:Z,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...J?{budget:J}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function k6($){if(!B0($))return;let Z=k($),z={};for(let X of b6){let Y=Z.limits.find((G)=>G.label===X&&G.kind==="reading");if(!Y||!I0(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}:{}};z[X]=J}return z.primary||z.secondary?z:void 0}var y6="main";function $X($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function ZX($,Z,z){let X=new Map;if(m$(Z))for(let Y of $)X.set(Y.id,A6(k6(Y.quota),Z,Y.id===y6?void 0:Y.id,z));return X}var zX=5,Y2=5000;function XX($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function YX($,Z=Y2){let z=$.rows.filter((G)=>G.kind==="oauth"&&$.killswitch.get(G.id)!==!1&&k(G.quota).limits.length===0);if(z.length===0)return;if(m({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((G)=>$.killswitch.get(G.id)!==!1))return;let Y=[];if(m({rows:z,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 g$($){return $.reason==="exhausted"||$.reason==="budget-spent"}function J2($,Z){if(!p($))return!1;let z=$;if(!(Z-z.checkedAt<=f0))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function p$($,Z,z){let X=(B)=>Z.killswitch.get(B)!==!1,Y=new Set(z.admitted.filter((B)=>B.lastPath!==!0&&X(B.id)).map((B)=>B.id)),J=new Map(z.refused.map((B)=>[B.id,B])),G=$.filter((B)=>{if(B.kind!=="oauth"||!X(B.id))return!1;if(J.get(B.id)?.reason!=="exhausted")return!1;let H=k(B.quota);if(K0(H,Z.now))return!1;return J2(H.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:G}}function G2($,Z=$.rows){return m({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class B2{#$=new Set;served($,Z,z){let X=G2($),Y=p$($.rows,$,X),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),z?.info("serving requests on prepaid credits",{accountId:Z,reason:"free quota used up"})}has($){return this.#$.has($)}ids(){return new Set(this.#$)}}function h6($,Z,z){if($===void 0)return{reason:"no-credential"};if(z.get($)===!1)return{reason:"killswitch"};let X=Z.excluded.find((J)=>J.id===$);if(X?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:X.until};if(X)return{reason:"no-credential"};let Y=Z.refused.find((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 f6($,Z,z){if(Z.refused.find((Y)=>!g$(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return h6($[0],Z,z)}function JX($){let Z=$.replayable!==!1,z=$.mainId===void 0?y6:$.mainId??"",X=Z?$.placement:"main-first",Y=z3({rows:$.rows,placement:X,formerMainId:z,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),J=B$($.rows.map((W)=>W.id),X,z),G=new Set(Y.admission.refused.filter((W)=>g$(W)&&$.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=J.filter((W)=>G.has(W)),H=p$($.rows,$,Y.admission),Q=Y.order.filter((W)=>H.free.has(W)),K=J.filter((W)=>H.credits.includes(W));if(!Z){let W=J.includes(z),U=W?z:Q[0]??K[0]??Y.order[0]??B[0];if(U!==void 0&&Y.order.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&K.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&G.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:W?h6(z,Y.admission,$.killswitch):f6(J,Y.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(K.length>0){let W=Y.order.length>0?Y.order:B;return{kind:"send",order:[...K,...W.filter((U)=>!K.includes(U))],lastPath:!1}}if(Y.order.length>0)return{kind:"send",order:Y.order,lastPath:!1};if(B.length>0)return{kind:"send",order:B,lastPath:!0};return{kind:"block",block:f6(J,Y.admission,$.killswitch)}}function GX($){let Z=m({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),z=new Map;for(let X of $.rows)z.set(X.id,k(X.quota));for(let X of Z.admitted)if(X.projection)z.set(X.id,X.projection);return{projections:z,excluded:new Set(Z.excluded.map((X)=>X.id))}}function w6($,Z,z){let X=z.exclude,Y=X?$.rows.filter((G)=>!X.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 B3({rows:Y,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...z.pendingBytes?{pendingBytes:z.pendingBytes}:{},rowReservePercent:(G)=>Z.reservePercent(G.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:J,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function BX($,Z,z,X){let Y=w6($,Z,{exclude:z,pendingBytes:X}),J=$.rows.filter((K)=>!z.has(K.id)),G=p$(J,$,Y.admission),B=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(B&&G.free.has(B.accountId))return B;let H=G.credits[0];if(H===void 0)return B;let Q=k(J.find((K)=>K.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function HX($,Z,z){let X=$.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},J=w6($,Z,{pin:z}),G=p$($.rows,$,J.admission),B=G.credits.includes(z),H=G.credits.some((W)=>W!==z);if(J.outcome==="dispatch"){let W=!G.free.has(J.accountId);if(J.pin.action==="assign"){if(W&&B)return{kind:"serve"};return Y}if(J.accountId!==z)return{kind:"detour"};if(W&&H)return Y;return{kind:"serve"}}let Q=J.admission.refused.find((W)=>W.id===z),K=X||Q!==void 0&&g$(Q);if(B)return{kind:"serve"};if(H)return K?Y:{kind:"detour"};if(!X&&Q&&g$(Q))return{kind:"last-path"};return{kind:"none"}}function KX($,Z,z,X){let Y=$.killswitch.get(z);return G3({quota:Z.projections.get(z),now:$.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as m6}from"node:os";import{join as v6}from"node:path";var H2=["error","warn","info","debug","trace"];function K2(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?v6(m6(),"opencode-openai-auth","opencode-openai-auth.log"):v6(m6(),"opencode-openai-auth.log"))}function W2(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&H2.includes($)?$:void 0}g6({file:K2,level:W2});if(process.once("beforeExit",async()=>{try{await l$()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>l$());
|
|
91
|
+
export{B0 as Ec,k0 as Fc,U8 as Gc,NZ as Hc,n6 as Ic,_Z as Jc,$8 as Kc,Z8 as Lc,k as Mc,RZ as Nc,V8 as Oc,B$ as Pc,q8 as Qc,X3 as Rc,F8 as Sc,A4 as Tc,E4 as Uc,_3 as Vc,j8 as Wc,x8 as Xc,CZ as Yc,IZ as Zc,W0 as _c,W$ as $c,hZ as ad,mZ as bd,C8 as cd,kZ as dd,fZ as ed,U$ as fd,b8 as gd,V0 as hd,h8 as id,w8 as jd,m8 as kd,v8 as ld,Z7 as md,X7 as nd,Y7 as od,J7 as pd,V as qd,q0 as rd,Q4 as sd,U9 as td,D9 as ud,V9 as vd,A3 as wd,N9 as xd,O4 as yd,M9 as zd,R as Ad,i3 as Bd,c5 as Cd,j0 as Dd,a0 as Ed,Dz as Fd,Vz as Gd,Oz as Hd,y as Id,X0 as Jd,c as Kd,D1 as Ld,hz as Md,$Z as Nd,N1 as Od,L1 as Pd,R1 as Qd,mz as Rd,w1 as Sd,m1 as Td,vz as Ud,S6 as Vd,m$ as Wd,gz as Xd,T6 as Yd,A6 as Zd,pz as _d,lz as $d,p1 as ae,r0 as be,I6 as ce,dz as de,cz as ee,uz as fe,o1 as ge,r1 as he,$2 as ie,az as je,k6 as ke,y6 as le,$X as me,ZX as ne,zX as oe,XX as pe,YX as qe,J2 as re,B2 as se,JX as te,GX as ue,BX as ve,HX as we,KX as xe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as n}from"node:module";var k=Object.defineProperty;var q=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var l=(b)=>b;function m(b,a){this[b]=l.bind(null,a)}var r=(b,a)=>{for(var c in a)k(b,c,{get:a[c],enumerable:!0,configurable:!0,set:m.bind(a,c)})};var t=n(import.meta.url),o=Symbol.dispose||Symbol.for("Symbol.dispose"),p=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),u=(b,a,c)=>{if(a!=null){if(typeof a!=="object"&&typeof a!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var e;if(c)e=a[p];if(e===void 0)e=a[o];if(typeof e!=="function")throw TypeError("Object not disposable");b.push([c,e,a])}else if(c)b.push([c]);return a},v=(b,a,c)=>{var e=typeof SuppressedError==="function"?SuppressedError:function(d,i,f,g){return g=Error(f),g.name="SuppressedError",g.error=d,g.suppressed=i,g},j=(d)=>a=c?new e(d,a,"An error was suppressed during disposal"):(c=!0,d),h=(d)=>{while(d=b.pop())try{var i=d[1]&&d[1].call(d[2]);if(d[0])return Promise.resolve(i).then(h,(f)=>(j(f),h()))}catch(f){j(f)}if(c)throw a};return h()};
|
|
2
|
-
export{q as
|
|
2
|
+
export{q as wf,r as xf,t as yf,u as zf,v as Af};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { _ as
|
|
2
|
-
import { S as SidebarState, y as SidebarMachineState } from "./sidebar-state-
|
|
1
|
+
import { _ as parseJwtClaims, a as RESPONSES_LITE_MODELS, g as extractAccountIdFromClaims, h as TokenResponse, l as ResetTargetIdentity, m as IdTokenClaims, n as CODEX_VERSION, o as RuntimeLayoutOptions, s as PoolLifecycleDeps, t as CODEX_USER_AGENT, u as OpenAiVault, v as AccountPaths } from "./codex-request-DohnbsFR.js";
|
|
2
|
+
import { S as SidebarState, y as SidebarMachineState } from "./sidebar-state-B1cq68UB.js";
|
|
3
3
|
import { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
|
|
4
4
|
//#region ../core/dist/provider.d.ts
|
|
5
5
|
type QuotaWindowName = string;
|
|
@@ -494,6 +494,8 @@ export declare function buildResetRedemptionDeps(): {
|
|
|
494
494
|
};
|
|
495
495
|
export declare const POOL_MIGRATION_ENABLED = true;
|
|
496
496
|
interface CodexAuthPluginOptions {
|
|
497
|
+
/** Test seams for the one-time move of the runtime files (`core/runtime-layout.ts`). */
|
|
498
|
+
runtimeLayout?: Partial<Omit<RuntimeLayoutOptions, 'version'>>;
|
|
497
499
|
/**
|
|
498
500
|
* Test seams for the background account-pool migration and adoption
|
|
499
501
|
* (`core/pool-lifecycle.ts`): its fence, timers, run functions and
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as x,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u,Z as v,_ as w,aa as y,ba as z,ca as A,da as B,ea as C,fa as D,ga as E,ha as F,ia as G,j as c,k as d,l as e}from"./index-3v868rnp.js";import"./index-g3d50jz0.js";import"./index-n7fxqgfb.js";import{dd as a,ed as b}from"./index-tvban5vp.js";import"./index-8pk9savd.js";import"./index-dzaqj248.js";import"./index-th47aqez.js";import"./index-5d4y47h8.js";import"./index-5dxpsa3t.js";import"./index-dtwgf694.js";import"./index-x7jzcvqy.js";export{D as rewriteResponsesLiteBody,B as resolveSidebarSessionId,s as poolResetTarget,a as parseJwtClaims,y as mergePushedQuotaMetadata,l as getMainRefreshLockName,x as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,G as default,t as createResetTargetResolver,j as codexOAuthModelVariantSource,h as codexOAuthModelListed,i as codexOAuthModelLimit,A as buildSidebarState,z as buildSidebarMachineState,u as buildResetRedemptionDeps,p as __resetBootQuotaSeedForTest,v as __menuContextForTest,o as __bootQuotaSeedPromiseForTest,r as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,w as POOL_MIGRATION_ENABLED,F as OpenAIAuthPlugin,C as MID_CONVERSATION_EFFORT_MODELS,m as MAIN_REFRESH_LOCK_TTL_MS,n as MAIN_REFRESH_LEASE_TTL_MS,k as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,E as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,q as AuthPersistError,f as ALLOWED_MODELS};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/rpc/port-file.d.ts
|
|
2
2
|
interface PortFileEntry {
|
|
3
3
|
port: number;
|
|
4
4
|
token: string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/commands/model.d.ts
|
|
2
2
|
/** The section slots, in the one order every renderer shows them. */
|
|
3
3
|
declare const SECTION_SLOTS: readonly ['accounts', 'quota', 'routing', 'limits', 'cache', 'diagnostics', 'extra'];
|
|
4
4
|
type SectionSlot = (typeof SECTION_SLOTS)[number];
|
package/dist/rpc/port-file.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { n as discoverPortFile, r as writePortFile, t as PortFileEntry } from "../port-file-
|
|
1
|
+
import { n as discoverPortFile, r as writePortFile$1, t as PortFileEntry } from "../port-file-DQ7-ItDK.js";
|
|
2
2
|
//#region src/rpc/port-file.d.ts
|
|
3
|
+
/** Stamp the record itself; a heartbeat with the same pid may be stale. */
|
|
4
|
+
export declare function writePortFile(dir: string, entry: Parameters<typeof writePortFile$1>[1], options?: Parameters<typeof writePortFile$1>[2]): Promise<string>;
|
|
3
5
|
export declare const isOpenaiRpcStateDir: (name: string) => boolean;
|
|
4
6
|
//#endregion
|
|
5
|
-
export { type PortFileEntry, discoverPortFile
|
|
7
|
+
export { type PortFileEntry, discoverPortFile };
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Oe as b,Pe as c}from"../index-dzaqj248.js";import{Te as a}from"../index-th47aqez.js";import"../index-5dxpsa3t.js";import"../index-dtwgf694.js";import"../index-x7jzcvqy.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
|
package/dist/rpc/protocol.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-
|
|
1
|
+
import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-CVQK-d3j.js";
|
|
2
2
|
export { type ApplyRequest, type ApplyResult, type NotifyPayload, type OpenDialogPayload, type RpcNotification, isNotifyPayload };
|
package/dist/rpc/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ff as b}from"../index-5d4y47h8.js";import"../index-5dxpsa3t.js";import"../index-x7jzcvqy.js";export{b as isNotifyPayload};
|
package/dist/rpc/rpc-client.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as createRpcClient, r as DEFAULT_RPC_TIMEOUT_MS, t as RpcClient } from "../rpc-client-
|
|
1
|
+
import { n as createRpcClient, r as DEFAULT_RPC_TIMEOUT_MS, t as RpcClient } from "../rpc-client-BQfIKrXI.js";
|
|
2
2
|
export { DEFAULT_RPC_TIMEOUT_MS, RpcClient, createRpcClient };
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ue as F,Ve as f}from"../index-th47aqez.js";import"../index-5dxpsa3t.js";import"../index-x7jzcvqy.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{sf as a,tf as b,uf as c,vf as d}from"../index-dtwgf694.js";import"../index-x7jzcvqy.js";export{a as tmpdir,d as resolveRpcDir,c as getRpcDir,b as RPC_DIRECTORY_PREFIX};
|