@cortexkit/opencode-openai-auth 1.5.0 → 1.6.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 +2 -2
- package/dist/{codex-request-BjGT9yWg.d.ts → codex-request-D_In8uaR.d.ts} +43 -26
- package/dist/{index-gmmakhbt.js → index-1qxz4s8a.js} +2 -2
- package/dist/{index-2rw81dtm.js → index-79y7w9bz.js} +1 -1
- package/dist/{index-2yszc75z.js → index-7nmdsmpp.js} +2 -2
- package/dist/{index-3y453wg4.js → index-8xq099qf.js} +2 -2
- package/dist/index-agaatt62.js +65 -0
- package/dist/{index-mhfja8yr.js → index-b0ty9qam.js} +2 -2
- package/dist/index-ge60xry3.js +90 -0
- package/dist/{index-krcqvyqf.js → index-jkpg9d1p.js} +1 -1
- package/dist/index-k5anexvs.js +69 -0
- package/dist/{index-e416r885.js → index-rf0ht3gc.js} +2 -2
- package/dist/{index-4w0nsq5s.js → index-x9nffaye.js} +1 -1
- package/dist/{index-7vkn2e46.js → index-ya9c5e4m.js} +1 -1
- package/dist/{index-djnfq652.js → index-z8bptbrk.js} +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{model-BMq5SCUB.d.ts → model-D22uj0OB.d.ts} +1 -1
- package/dist/{port-file-CjMFUWcX.d.ts → port-file-8ElfwDcq.d.ts} +1 -1
- package/dist/{protocol-BC3ndToM.d.ts → protocol-CK9guiFy.d.ts} +1 -1
- package/dist/rpc/port-file.d.ts +1 -1
- 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 +3 -3
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{sidebar-state-DfYyqiOH.d.ts → sidebar-state-Bb9L9oPq.d.ts} +4 -4
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-nyvn9866.js +1 -0
- package/dist/{token-ycw7dyev.js → token-xtq3457d.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +2 -2
- package/dist/v2/server.d.ts +2 -2
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +4 -54
- package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +39 -25
- package/src/tui-compiled/raw/shared/a910277ac43a8626-pull.js +3 -1
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +18 -3
- package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
- package/src/tui-compiled/raw/shared/e1c5e56df0ba4053-pending.js +48 -0
- package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +4 -54
- package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +39 -25
- package/src/tui-compiled/runtime/shared/a910277ac43a8626-pull.js +3 -1
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +18 -3
- package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
- package/src/tui-compiled/runtime/shared/e1c5e56df0ba4053-pending.js +48 -0
- package/dist/index-2p3gcjsa.js +0 -69
- package/dist/index-6fdmqk6p.js +0 -90
- package/dist/index-fztcacjr.js +0 -65
- package/dist/token-util-ed4az5gg.js +0 -1
package/dist/index-6fdmqk6p.js
DELETED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import{pe as m,se as A,te as s0,ve as n0}from"./index-3y453wg4.js";import{Me as T0,Ne as I,Pe as G8,Se as S6}from"./index-mhfja8yr.js";import{$e as Q0,Ve as DZ,We as i0,Ye as p4,_e as H3,df as l4}from"./index-2yszc75z.js";var P="all",f0=Object.freeze(["primary"]);function c3(Z){return Z.kind==="retired"?Z.retiredAt:Z.checkedAt}function MZ(Z,$){return JSON.stringify([Z,$])}function c(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function R(Z){return typeof Z==="number"&&Number.isFinite(Z)}function d3(Z){return typeof Z==="string"&&Z.length>0}function S(Z,$,z){return Z[$]===void 0||z(Z[$])}function H8(Z){return R(Z)&&Z>0}function b0(Z){return typeof Z==="string"}function K8(Z){if(!c(Z)||!d3(Z.scope)||!d3(Z.label))return!1;switch(Z.kind){case"reading":return R(Z.checkedAt)&&R(Z.usedPercent)&&S(Z,"resetsAt",b0)&&S(Z,"windowMinutes",H8);case"retired":return R(Z.retiredAt);case"absent":return R(Z.checkedAt);default:return!1}}function W8(Z){if(!c(Z)||!R(Z.checkedAt))return!1;if(Z.kind==="cleared")return!0;return Z.kind==="reading"&&typeof Z.reached==="boolean"&&S(Z,"remainingPercent",R)&&S(Z,"usedPercent",R)&&S(Z,"resetsAt",b0)&&S(Z,"limit",R)&&S(Z,"used",R)&&S(Z,"remaining",R)&&S(Z,"unit",b0)}function u3(Z){return c(Z)&&R(Z.value)&&Number.isInteger(Z.value)&&Z.value>=0&&R(Z.checkedAt)}function k0(Z){return c(Z)&&Object.values(Z).every(u3)}function Q8(Z){return typeof Z==="boolean"}function w(Z){return c(Z)&&typeof Z.hasCredits==="boolean"&&typeof Z.unlimited==="boolean"&&S(Z,"balance",R)&&S(Z,"overageLimitReached",Q8)&&R(Z.checkedAt)}function y0(Z){if(!c(Z))return;let $=Object.entries(Z).filter(([,z])=>u3(z));return $.length===0?void 0:Object.fromEntries($)}function YZ(Z){if(XZ(Z))return Z;if(!c(Z))return;let{counters:$,credits:z,...X}=Z;if(!XZ(X))return;let Y=y0($),G=w(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...G===void 0?{}:{credits:G}}}function XZ(Z){if(!c(Z)||!Array.isArray(Z.limits))return!1;let $=new Set;for(let z of Z.limits){if(!K8(z))return!1;let X=MZ(z.scope,z.label);if($.has(X))return!1;$.add(X)}return S(Z,"budget",W8)&&S(Z,"counters",k0)&&S(Z,"credits",w)}var a3=900000,o3="no quota reading yet",r3="no limits reported";function t3(Z){let $=Math.max(1,Math.floor(Z/60000));if($<60)return`${$}m`;if($<1440){let Y=Math.floor($/60),G=$%60;return G===0?`${Y}h`:`${Y}h${G}m`}let z=Math.floor($/1440),X=Math.floor($%1440/60);return X===0?`${z}d`:`${z}d${X}h`}function e3(Z){if(Z%1440===0)return`${Z/1440}d`;if(Z%60===0)return`${Z/60}h`;return`${Z}m`}function Z4(Z){if(Z.scope!==P||Z.windowMinutes===void 0)return Z.label;return e3(Z.windowMinutes)}function h0(Z){return Math.min(100,Math.max(0,Z))}function cZ(Z){return Math.round(h0(Z))}function i3(Z){return`${cZ(Z)}% left`}function s3(Z,$,z){let X=Z===void 0?Number.NaN:Date.parse(Z);return{...Number.isFinite(X)&&X>z?{resetIn:t3(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>$&&X<=z}}function U8(Z,$){let z=Z.windowMinutes,X=$.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(Z.scope!==$.scope){if(Z.scope===P)return-1;if($.scope===P)return 1;return Z.scope<$.scope?-1:1}return Z.label<$.label?-1:Z.label>$.label?1:0}function $4(Z,$){let{windows:z,age:X}=w0(Z,$),Y=z.map(({part:G})=>G);return X===void 0?{windows:Y}:{windows:Y,age:X}}function D8(Z){let $=z4(Z.filter(({part:z,scope:X})=>z.kind==="window"&&X!==P).map(({scope:z})=>z));for(let z of Z)z.part.short=z.part.kind==="budget"?"cr":z.scope===P?z.part.name:$.get(z.scope)??z.scope;return Z}function w0(Z,$){if(!Z)return{windows:[]};let{now:z}=$,Y=Z.limits.filter((J)=>J.kind==="reading"&&J.remainingPercent!==void 0).sort(U8).map((J)=>{let B=h0(J.remainingPercent??0);return{scope:J.scope,...J.windowMinutes===void 0?{}:{windowMinutes:J.windowMinutes},part:{kind:"window",name:Z4(J),short:"",figure:i3(J.remainingPercent??0),remainingPercent:B,checkedAt:J.checkedAt,...s3(J.resetsAt,J.checkedAt,z)}}}),G=Z.budget;if(G){let J=G.remainingPercent,B=G.reached?"credits spent":J!==void 0?`credits ${i3(J)}`:"credits available";Y.push({scope:P,spent:G.reached,part:{kind:"budget",name:"credits",short:"",figure:B,...J===void 0?{}:{remainingPercent:h0(J)},checkedAt:G.checkedAt,...s3(G.resetsAt,G.checkedAt,z)}})}if(D8(Y),Y.length>0){let J=z-Math.min(...Y.map(({part:B})=>B.checkedAt));if(J>($.staleAfterMs??a3))return{windows:Y,age:`checked ${t3(J)} ago`}}return{windows:Y}}function V8(Z,$){return w0(Z,$).age!==void 0}function n3(Z){let $=Z.slice(Z.indexOf(":")+1);return $.charAt(0).toUpperCase()+$.slice(1)}function z4(Z){let $=[...new Set(Z.map(n3))],z=new Map($.map((Y)=>[Y,2])),X=(Y)=>Y.slice(0,z.get(Y));for(;;){let Y=new Map;for(let J of $)Y.set(X(J),[...Y.get(X(J))??[],J]);let G=!1;for(let J of Y.values()){if(J.length<2)continue;for(let B of J){let H=z.get(B)??2;if(H<B.length)z.set(B,H+1),G=!0}}if(!G)break}return new Map(Z.map((Y)=>[Y,X(n3(Y))]))}var F8=2;function j8(Z){let $=Z.map((X)=>X.label.trim()||X.scope),z=z4($);return $.map((X)=>z.get(X)??X)}function q8(Z,$){if(!Z||Z.length===0)return;let z=$.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===P))return;let X=Z.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=j8(Z),G=(B)=>B.window.part.remainingPercent??0,J=[...X].sort((B,H)=>G(B)-G(H)||B.listed-H.listed).slice(0,F8).sort((B,H)=>B.listed-H.listed);return J.map((B,H)=>{let{windowMinutes:Q}=B.window,K=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[e3(Q)],`${cZ(G(B))}%`].join(" ");return H===J.length-1?`${K} left`:K})}function N8(Z,$){let{windows:z}=w0(Z,$),X=q8(Z?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:U})=>W.kind==="window"&&U===P),G=z.filter(({part:W,scope:U})=>W.kind==="window"&&U!==P),J=z.find(({part:W})=>W.kind==="budget"),B=J?.spent?0:J?.part.remainingPercent,Q=[...G.map(({part:W})=>({label:W.short,remaining:W.remainingPercent??0})),...B===void 0||J===void 0?[]:[{label:J.part.short,remaining:B}]].reduce((W,U)=>W===void 0||U.remaining<W.remaining?U:W,void 0),K=Y.map(({part:W})=>`${W.name} ${cZ(W.remainingPercent??0)}%`);if(Q)K.push(`${Q.label} ${cZ(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 X4(Z,$){if($.form==="narrow")return N8(Z,$);let z=$4(Z,$),X=($.form??"full")==="full",Y=z.windows.map((G)=>{let J=X&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${J}`});return z.age===void 0?Y:[...Y,z.age]}function M8(Z,$){let z=X4(Z,$);if(z.length>0)return z.join(" · ");return Z&&Z.limits.length>0?r3:o3}function O8(Z){if(Z===void 0)return;if(Z.unlimited)return"Unlimited";if(!Z.hasCredits)return;let{balance:$}=Z;return typeof $==="number"&&Number.isFinite($)&&$>0?`${Math.round($)} credits`:"Available"}function _8(Z){if(Z.kind==="retired")return{scope:Z.scope,label:Z.label,kind:"retired",checkedAt:Z.retiredAt};if(Z.kind==="absent")return{scope:Z.scope,label:Z.label,kind:"absent",checkedAt:Z.checkedAt};return{scope:Z.scope,label:Z.label,kind:"reading",checkedAt:Z.checkedAt,usedPercent:Z.usedPercent,remainingPercent:100-Z.usedPercent,...Z.windowMinutes===void 0?{}:{windowMinutes:Z.windowMinutes},...Z.resetsAt===void 0?{}:{resetsAt:Z.resetsAt}}}function P8(Z,$){let z=Z.windowMinutes!==void 0,X=$.windowMinutes!==void 0;if(z!==X)return z?-1:1;if(z&&X&&Z.windowMinutes!==$.windowMinutes)return($.windowMinutes??0)-(Z.windowMinutes??0);if(Z.label!==$.label)return Z.label<$.label?-1:1;return 0}function L8(Z){return{checkedAt:Z.checkedAt,reached:Z.reached,...Z.remainingPercent===void 0?{}:{remainingPercent:Z.remainingPercent},...Z.resetsAt===void 0?{}:{resetsAt:Z.resetsAt}}}function C(Z,$=P){let z=new Map;for(let K of Z?.limits??[]){if(K.scope!==$&&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(_8).sort(P8),Y=X.filter((K)=>K.kind==="reading"),G=Y.length>0?Y:X,J=G.length>0?Math.min(...G.map((K)=>K.checkedAt)):void 0,B=Z?.budget?.kind==="reading"?L8(Z.budget):void 0,H=y0(Z?.counters),Q=w(Z?.credits)?Z.credits:void 0;return{scope:$,limits:X,...J===void 0?{}:{checkedAt:J},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H},...Q===void 0?{}:{credits:Q}}}function GZ(Z,$){let z=Z?.budget;if(z?.reached!==!0||typeof z.resetsAt!=="string")return;let X=Date.parse(z.resetsAt);if(!Number.isFinite(X)||X<=$)return;return{resetsAt:z.resetsAt,resetAtMs:X}}function m0(Z){return Z.kind==="reading"&&typeof Z.usedPercent==="number"&&Number.isFinite(Z.usedPercent)&&Z.usedPercent>=100}function uZ(Z,$){if(typeof Z.resetsAt!=="string")return;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z>$?z:void 0}class iZ extends TypeError{constructor(Z){super(Z);this.name="QuotaCodecError"}}function nZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function sZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function Y4(Z){return Z===void 0||typeof Z==="string"&&Z!==""}function G4(Z){return typeof Z==="string"&&Z!==""}function SZ(Z,$){return Z[$]===void 0||sZ(Z[$])}function g0(Z,$){return Z[$]===void 0||typeof Z[$]==="string"}function R8(Z){return nZ(Z)&&Y4(Z.scope)&&G4(Z.label)&&sZ(Z.usedPercent)&&g0(Z,"resetsAt")&&(Z.windowMinutes===void 0||sZ(Z.windowMinutes)&&Z.windowMinutes>0)}function S8(Z){return nZ(Z)&&Y4(Z.scope)&&G4(Z.label)}function x8(Z){if(!nZ(Z))return!1;if(Z.kind==="cleared")return!0;return Z.kind==="reading"&&typeof Z.reached==="boolean"&&SZ(Z,"remainingPercent")&&SZ(Z,"usedPercent")&&g0(Z,"resetsAt")&&SZ(Z,"limit")&&SZ(Z,"used")&&SZ(Z,"remaining")&&g0(Z,"unit")}function OZ(Z){if(!nZ(Z)||!sZ(Z.checkedAt))return!1;let $=Z.readings??[],z=Z.coverage??[];if(!Array.isArray($)||!Array.isArray(z))return!1;let X=new Set;for(let Y of $){if(!R8(Y))return!1;let G=MZ(Y.scope??P,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(S8))return!1;return(Z.budget===void 0||x8(Z.budget))&&(Z.counters===void 0||k0(Z.counters))&&(Z.credits===void 0||w(Z.credits))}function T8(Z,$){if(Z.scope!==$.scope)return Z.scope<$.scope?-1:1;if(Z.label!==$.label)return Z.label<$.label?-1:1;return 0}function E8(Z,$,z){if($===void 0)return Z;if(Z!==void 0&&z<Z.checkedAt)return Z;return{...$,checkedAt:z}}function C8(Z,$){let z=new Map(Object.entries(Z??{}));for(let[X,Y]of Object.entries($??{})){let G=z.get(X);if(G===void 0||Y.checkedAt>=G.checkedAt)z.set(X,Y)}return z.size===0?void 0:Object.fromEntries(z)}function A8(Z,$){if($===void 0)return Z;if(Z!==void 0&&$.checkedAt<Z.checkedAt)return Z;return{...$}}function xZ(Z,$){let z=Z===void 0?void 0:YZ(Z);if(Z!==void 0&&z===void 0)throw new iZ("stored quota map is malformed");if(!OZ($))throw new iZ("quota observation is malformed");let X=z??{limits:[]},Y=$.checkedAt,G=new Map;for(let N of X.limits)G.set(MZ(N.scope,N.label),N);let J=(N)=>{let L=G.get(N);return L===void 0||Y>=c3(L)},B=new Set;for(let N of $.readings??[]){let L=N.scope??P,T=MZ(L,N.label);if(B.add(T),!J(T))continue;G.set(T,{scope:L,label:N.label,kind:"reading",checkedAt:Y,usedPercent:N.usedPercent,...N.resetsAt===void 0?{}:{resetsAt:N.resetsAt},...N.windowMinutes===void 0?{}:{windowMinutes:N.windowMinutes}})}for(let N of $.coverage??[]){let L=N.scope??P,T=MZ(L,N.label);if(B.has(T)||!J(T))continue;let p=G.get(T);G.set(T,p===void 0||p.kind==="absent"?{scope:L,label:N.label,kind:"absent",checkedAt:Y}:{scope:L,label:N.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:Q,counters:K,credits:W,...U}=X,q=E8(X.budget,$.budget,Y),D=C8(X.counters,$.counters),M=A8(X.credits,$.credits);return{...U,limits:[...G.values()].sort(T8),...q===void 0?{}:{budget:q},...D===void 0?{}:{counters:D},...M===void 0?{}:{credits:M}}}var I8=Object.freeze({validate:XZ,decode:YZ,merge:xZ});function J4(Z,$,z){let X=$.rateLimitMarks?.get(Z);if(X!==void 0&&z<X)return{id:Z,reason:"rate-limited",until:X};let Y=$.refreshBackoff?.get(Z);if(Y!==void 0&&z<Y)return{id:Z,reason:"refresh-backoff",until:Y};return}function b8(Z,$,z,X){if($.limits.length===0)return{id:Z,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of z)if(!$.limits.some((J)=>J.label===G))return{id:Z,stage:1,gate:3,reason:"unknown-window",window:{scope:$.scope,label:G},pullRequested:!0};let Y=$.limits.filter(m0);for(let G of Y)if(uZ(G,X)===void 0)return{id:Z,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of Y){let J=uZ(G,X);if(J!==void 0&&typeof G.resetsAt==="string")return{id:Z,stage:1,gate:5,reason:"exhausted",window:{scope:G.scope,label:G.label},resetsAt:G.resetsAt,resetAtMs:J}}return}function y(Z){let $=Z.scope??P,z=Z.requiredLabels??f0,X=[],Y=[],G=[];for(let U of Z.rows){let q=J4(U.id,Z,Z.now);if(q){X.push(q);continue}if(U.kind==="api-key"){G.push({id:U.id,kind:U.kind});continue}let D=C(U.quota,$),M=b8(U.id,D,z,Z.now);if(M){Y.push(M);continue}G.push({id:U.id,kind:U.kind,projection:D})}let J=new Map(G.flatMap((U)=>{let q=GZ(U.projection,Z.now);return q?[[U.id,q]]:[]})),B=J.size>0&&J.size===G.length,H=[];for(let U of G){let q=J.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(Z.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)Z.requestPull?.(U);return{admitted:H,refused:Y,excluded:X,pulls:W}}var B4="main";function f8(Z){switch(Z){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 aZ(Z,$,z=B4){if($==="roster"||!Z.includes(z))return[...Z];let X=Z.filter((Y)=>Y!==z);return $==="main-first"?[z,...X]:[...X,z]}function v0(Z){let $=y(Z),z=new Set($.admitted.map((Y)=>Y.id));return{order:aZ(Z.rows.map((Y)=>Y.id),Z.placement??"roster",Z.formerMainId).filter((Y)=>z.has(Y)&&Z.killswitch?.get(Y)!==!1),admission:$}}function k8(Z,$,z){let X=$.at(-1);if(X!==void 0){if(X.status===void 0||!z.includes(X.status))return}let Y=new Set($.map((G)=>G.id));return Z.find((G)=>!Y.has(G))}function p0(Z,$,z){if(!$.has(Z.accountId))return!1;return!(typeof Z.wireIdentity==="string"&&typeof z==="string"&&Z.wireIdentity!==z)}function y8(Z,$,z){let X=new Map;for(let[Y,G]of Z){if(Y===z)continue;if(G.quotaCheckedAt!==$.get(G.accountId))continue;X.set(G.accountId,(X.get(G.accountId)??0)+(G.inputBytes??0))}return X}var TZ=900000,K4=0.016666666666666666,l0=0.000001;function oZ(Z,$){for(let z of[Z?.checkedAt,$])if(typeof z==="number"&&Number.isFinite(z))return z;return}function W4(Z){if(Z===401||Z===403)return"permanent";if(Z===void 0||Z===0||!Number.isFinite(Z)||Z>=500&&Z<=599||Z===429)return"transient";return"healthy"}function Q4(Z){return Z.limits.filter(($)=>$.kind==="reading").sort(($,z)=>{let X=$.windowMinutes!==void 0,Y=z.windowMinutes!==void 0;if(X!==Y)return X?-1:1;if(X&&Y)return(z.windowMinutes??0)-($.windowMinutes??0);return 0})}function c0(Z){let $=(Z.classifyStatus??W4)(Z.status);if($==="permanent")return{action:"migrate",reason:"permanent"};if(!Z.quota)return{action:"retain",reason:"unknown"};let z=oZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||Z.now-z>TZ)return{action:"retain",reason:"stale"};if(Z.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of Q4(Z.quota)){let G=Y.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=0)return{action:"migrate",reason:"exhausted",window:{scope:Y.scope,label:Y.label},...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{}}}let X=GZ(Z.quota,Z.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:$}}function d0(Z,$,z){let X=Math.max(0,Z.remainingPercent-$);if(X<=0)return 0;if(!Z.resetsAt)return X;let Y=Date.parse(Z.resetsAt);if(!Number.isFinite(Y)||Y<=z)return X;let G=Math.max((Y-z)/3600000,K4);return X/G}function H4(Z,$){if(Z<$)return-1;if(Z>$)return 1;return 0}function h8(Z,$){if(!Z.quota)return;let z=oZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||$-z>TZ)return;let X=Q4(Z.quota).map((J)=>d0({remainingPercent:J.remainingPercent??Number.NaN,...J.resetsAt===void 0?{}:{resetsAt:J.resetsAt}},Z.reservePercent[J.label]??0,$)),Y=Z.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))X.push(d0({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,$));let G=X.length>0?Math.min(...X):0;return G>0?{candidate:Z,quotaCheckedAt:z,weight:G}:void 0}function U4(Z){let $=Z.candidates.filter((Y)=>Y.killswitchPasses!==!1);if(Z.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if($.length===0)return;let z=$.map((Y)=>h8(Y,Z.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((G,J)=>{let B=((Z.pendingBytes.get(G.candidate.accountId)??0)+Z.requestBytes)/Math.max(G.weight,l0),H=((Z.pendingBytes.get(J.candidate.accountId)??0)+Z.requestBytes)/Math.max(J.weight,l0);return B-H||G.candidate.configuredOrder-J.candidate.configuredOrder||H4(G.candidate.accountId,J.candidate.accountId)});let Y=z[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}Z.onEmptyWeightedSet?.();let X=[...$].sort((Y,G)=>{let J=(Y.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-J||Y.configuredOrder-G.configuredOrder||H4(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:oZ(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function u0(Z){let $=y(Z),z=new Map($.admitted.map((D)=>[D.id,D])),X=new Map($.refused.map((D)=>[D.id,D])),Y=new Set($.excluded.map((D)=>D.id)),G=new Set(Z.rows.map((D)=>D.id)),J=Z.pin!==void 0&&p0(Z.pin,G,Z.identities?.get(Z.pin.accountId));if(J&&Z.pin){let D=z.get(Z.pin.accountId);if(D&&Z.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:$}}let B=Z.pin?X.get(Z.pin.accountId):void 0,H=J&&Z.pin!==void 0&&Z.refusedPinPolicy==="move-on-confirmed-exhaustion"&&(Z.killswitch?.get(Z.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Q=(D)=>{return(typeof Z.rowReservePercent==="function"?Z.rowReservePercent(D):Z.rowReservePercent?.get(D.id))??Z.reservePercent??{}},K=Z.scope,W=Z.rows.map((D,M)=>({row:D,configuredOrder:M})).filter(({row:D})=>!Y.has(D.id)).map(({row:D,configuredOrder:M})=>{let N=Z.killswitch?.get(D.id),L=Z.resetCreditsApplicable?.get(D.id);return{accountId:D.id,quota:D.kind==="api-key"?void 0:z.get(D.id)?.projection??C(D.quota,K),reservePercent:Q(D),configuredOrder:M,...L===void 0?{}:{resetCreditsApplicable:L},...N===void 0?{}:{killswitchPasses:N}}}),U=[],q=J?{action:"retain"}:Z.pin?{action:"clear"}:{action:"none"};while(W.length>0){let D=U4({candidates:W,pendingBytes:Z.pendingBytes??new Map,requestBytes:Z.requestBytes,now:Z.now,...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}});if(!D)break;let M=X.get(D.accountId);if(M){U.push(M),W=W.filter((L)=>L.accountId!==D.accountId);continue}let N=Z.identities?.get(D.accountId);return{outcome:"dispatch",accountId:D.accountId,source:D.source,...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt},pin:J&&!H?{action:"retain"}:{action:"assign",pin:{accountId:D.accountId,inputBytes:Z.requestBytes,...N===void 0?{}:{wireIdentity:N},...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt}}},refusedSelections:U,admission:$}}return{outcome:"no-admissible-account",pin:q,refusedSelections:U,admission:$}}import{createHash as w8}from"node:crypto";var m8=86400000,g8=300000,v8=3600000,p8=60000,l8=900000,d8=300000;function a0(Z){return Z instanceof Error?Z.message:String(Z)}function c8(Z){let $=Z?.status;if(typeof $==="number")return $===429||$>=500;if(!(Z instanceof Error))return!1;return Z.name==="AbortError"||Z.name==="TimeoutError"||Z.message.includes("fetch failed")||"code"in Z&&(Z.code==="ECONNRESET"||Z.code==="ECONNREFUSED"||Z.code==="ETIMEDOUT"||Z.code==="UND_ERR_CONNECT_TIMEOUT")}function o0(Z){let $=a0(Z),z=Z?.status;if(typeof z==="number")return z===429||z>=500;if(!(Z instanceof Error))return!1;let X=Z.code;return Z.name==="AbortError"||Z.name==="TimeoutError"||$.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function D4(Z){return w8("sha256").update(Z).digest("hex")}function V4(Z){let $=D4(Z.refreshToken),X=(Z.previous?.tokenHash===$?Z.previous.retryCount??0:0)+1,Y,G=Z.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(c8(Z.error))Y=Math.min(v8,g8*2**Math.min(X-1,6));else Y=m8;return{message:a0(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+Y,retryCount:X,tokenHash:$}}function JZ(Z,$,z){if(!Z?.nextRetryAt||Z.nextRetryAt<=z)return!1;if(!$)return!0;return Z.tokenHash===D4($)}function rZ(Z,$){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((Z.nextRetryAt??$)-$)/1000))}s after: ${Z.message}`}function EZ(Z){let z=(Z.previous?.retryCount??0)+1,X,Y=Z.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(o0(Z.error))X=Math.min(l8,p8*2**Math.min(z-1,6));else X=d8;return{message:a0(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+X,retryCount:z}}function _Z(Z,$){if(!Z?.nextRetryAt||Z.nextRetryAt<=$)return!1;return!0}function r0(Z){if(!Z)return;let $=Number(Z);if(Number.isFinite($)&&$>0)return Math.ceil($);let z=Date.parse(Z);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{createServer as F4}from"node:http";import{setTimeout as u8}from"node:timers/promises";var $0="app_EMoamEEZ73f0CkXaXp7hrann",KZ="https://auth.openai.com",AZ=1455,i8=3000,s8="cortexkit-opencode-openai-auth";function M4(Z){return`${s8}/${Z}`}var O4="main",n8=`"${O4}" is a reserved account id; choose a different label.`;function _4(Z){let $=new Uint8Array(Z),z=String.fromCharCode(...$);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function a8(){let $=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=_4(await crypto.subtle.digest("SHA-256",new TextEncoder().encode($)));return{verifier:$,challenge:z}}function j4(Z){if(Z.length>16384)return;let $=Z.split(".");if($.length!==3)return;let z=$[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function q4(Z){let $=Z.chatgpt_account_id;if(typeof $==="string"&&$.length>0)return $;let z=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=Z.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 eZ(Z){if(Z.id_token){let $=j4(Z.id_token),z=$&&q4($);if(z)return z}if(Z.access_token){let $=j4(Z.access_token);return $?q4($):void 0}return}function o8(Z){return typeof Z==="string"&&Z.toLowerCase()===O4}function t0(Z){if(o8(Z))throw Error(n8);return Z}function r8(Z,$,z){let X=new URLSearchParams({response_type:"code",client_id:$0,redirect_uri:Z,scope:"openid profile email offline_access",code_challenge:$.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${KZ}/oauth/authorize?${X.toString()}`}async function t8(Z,$,z){let X=await fetch(`${KZ}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Z,redirect_uri:$,client_id:$0,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function e8(Z){return Z.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var Z9=`<!doctype html>
|
|
2
|
-
<html>
|
|
3
|
-
<head>
|
|
4
|
-
<title>CortexKit OpenAI Auth - Authorization Successful</title>
|
|
5
|
-
<style>
|
|
6
|
-
body {
|
|
7
|
-
font-family:
|
|
8
|
-
system-ui,
|
|
9
|
-
-apple-system,
|
|
10
|
-
sans-serif;
|
|
11
|
-
display: flex;
|
|
12
|
-
justify-content: center;
|
|
13
|
-
align-items: center;
|
|
14
|
-
height: 100vh;
|
|
15
|
-
margin: 0;
|
|
16
|
-
background: #131010;
|
|
17
|
-
color: #f1ecec;
|
|
18
|
-
}
|
|
19
|
-
.container {
|
|
20
|
-
text-align: center;
|
|
21
|
-
padding: 2rem;
|
|
22
|
-
}
|
|
23
|
-
h1 {
|
|
24
|
-
color: #f1ecec;
|
|
25
|
-
margin-bottom: 1rem;
|
|
26
|
-
}
|
|
27
|
-
p {
|
|
28
|
-
color: #b7b1b1;
|
|
29
|
-
}
|
|
30
|
-
</style>
|
|
31
|
-
</head>
|
|
32
|
-
<body>
|
|
33
|
-
<div class="container">
|
|
34
|
-
<h1>Authorization Successful</h1>
|
|
35
|
-
<p>You can close this window and return to OpenCode.</p>
|
|
36
|
-
</div>
|
|
37
|
-
<script>
|
|
38
|
-
setTimeout(() => window.close(), 2000)
|
|
39
|
-
</script>
|
|
40
|
-
</body>
|
|
41
|
-
</html>`,tZ=(Z)=>`<!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">${e8(Z)}</div>
|
|
85
|
-
</div>
|
|
86
|
-
</body>
|
|
87
|
-
</html>`,Z0=[],CZ,g=new Map;function N4(Z,$){return new Promise((z,X)=>{let Y=(J)=>{Z.off("listening",G),X(J)},G=()=>{Z.off("error",Y),z()};Z.once("error",Y),Z.once("listening",G),Z.listen(AZ,$)})}function P4(Z){Z.close(()=>{}),Z.closeIdleConnections?.(),setTimeout(()=>{Z.closeAllConnections?.()},25).unref?.()}function BZ(){return g.size}function WZ(Z){if(g.delete(Z),BZ()===0)HZ()}async function $9(){let Z=`http://localhost:${AZ}/auth/callback`;if(Z0.length>0)return{port:AZ,redirectUri:Z};if(CZ)return CZ;CZ=(async()=>{let $=(G,J)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${AZ}`);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=g.get(Q);if(D)D.reject(Error(q)),WZ(Q);else if(BZ()===0)HZ()}else if(BZ()===0)HZ();J.writeHead(200,{"Content-Type":"text/html"}),J.end(tZ(q));return}if(!Q){if(BZ()===0)HZ();J.writeHead(400,{"Content-Type":"text/html"}),J.end(tZ("Missing state parameter"));return}if(!H){if(BZ()===0)HZ();J.writeHead(400,{"Content-Type":"text/html"}),J.end(tZ("Missing authorization code"));return}let U=g.get(Q);if(!U){if(BZ()===0)HZ();J.writeHead(400,{"Content-Type":"text/html"}),J.end(tZ("Unknown state — authorization may have expired"));return}WZ(Q),t8(H,Z,U.pkce).then((q)=>U.resolve(q)).catch((q)=>U.reject(q)),J.writeHead(200,{"Content-Type":"text/html"}),J.end(Z9);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),Q=H?[H]:[...g.keys()];J.writeHead(200),J.end("Login cancelled");for(let K of Q){let W=g.get(K);if(!W)continue;W.reject(Error("Login cancelled")),WZ(K)}if(BZ()===0)HZ();return}J.writeHead(404),J.end("Not found")},z=F4($);await N4(z,"127.0.0.1");let X=[z],Y=F4($);try{await N4(Y,"::1"),X.push(Y)}catch(G){let J=G.code;if(J!=="EADDRNOTAVAIL"&&J!=="EAFNOSUPPORT")throw P4(z),G}return Z0=X,{port:AZ,redirectUri:Z}})();try{return await CZ}finally{CZ=void 0}}function HZ(){let Z=Z0;Z0=[];for(let $ of Z)P4($)}function z9(Z,$,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){WZ($),G(Error("Login cancelled"));return}let J=setTimeout(()=>{if(g.get($))WZ($),G(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(J),g.get($))WZ($),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);g.set($,{pkce:Z,state:$,resolve:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);G(H)}})})}async function X9(Z){let $=await fetch(`${KZ}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":M4(Z)},body:JSON.stringify({client_id:$0})});if(!$.ok)throw Error("Failed to initiate device authorization");let z=await $.json();return{deviceData:z,url:`${KZ}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function Y9(Z,$,z){let X=Math.max(parseInt(Z.interval,10)||5,1)*1000,Y=typeof Z.expires_in==="number"?Z.expires_in:parseInt(Z.expires_in||"",10),G=!Number.isNaN(Y)&&Y>0?Y*1000:900000,J=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-J>G)throw Error("Device authorization expired");let B=await fetch(`${KZ}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":M4($)},body:JSON.stringify({device_auth_id:Z.device_auth_id,user_code:Z.user_code})});if(B.ok){let K=await B.json(),W=await fetch(`${KZ}/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:`${KZ}/deviceauth/callback`,client_id:$0,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=G-(Date.now()-J);if(H<=0)throw Error("Device authorization expired");let Q=Math.min(X+i8,H);try{await u8(Q,void 0,{signal:z})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw Error("Device authorization cancelled");throw K}}}async function J2(Z){let{label:$,headless:z=!1,signal:X,version:Y}=Z;if(t0($),z){let{deviceData:K,url:W,instructions:U}=await X9(Y),q=(async()=>{let D=await Y9(K,Y,X),M=Date.now(),N=eZ(D);return{id:t0($||N||crypto.randomUUID()),label:$||void 0,type:"oauth",access:D.access_token,refresh:D.refresh_token,expires:M+(D.expires_in??3600)*1000,enabled:!0,addedAt:M,lastUsed:M,lastRefreshedAt:M,accountId:N}})();return{url:W,instructions:U,completion:q}}let{redirectUri:G}=await $9(),J=await a8(),B=_4(crypto.getRandomValues(new Uint8Array(32)).buffer),H=r8(G,J,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let K=await z9(J,B,void 0,X),W=Date.now(),U=eZ(K);return{id:t0($||U||crypto.randomUUID()),label:$||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{WZ(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function z0(Z){if(Z==null||Z==="")return;let $=typeof Z==="number"?Z:Number(Z);if(Number.isFinite($)){let X=$<100000000000?$*1000:$,Y=new Date(X);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let z=new Date(Z);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function e0(Z){let $=Number(Z);return Number.isFinite($)&&$>0?$:void 0}function L4(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function R4(Z,$){let z=Z.get($);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let Y=$.slice(0,-13),G=e0(Z.get(`${Y}-window-minutes`)),J=z0(Z.get(`${Y}-reset-at`)??void 0);if(X===0&&Z.get(`${Y}-window-minutes`)==="0"&&!J)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:J,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var E4=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function C4(Z,$){let z=Z.get($);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 H2(Z){if(E4.some((G)=>C4(Z,G)==="invalid"))return{};let $={},z=R4(Z,"x-codex-primary-used-percent");if(z)$.primary=z;let X=R4(Z,"x-codex-secondary-used-percent");if(X)$.secondary=X;let Y=G9(Z);if(Y)$.credits=Y;return $}function S4(Z,$){let z=Z.get($)?.trim();if(z===void 0)return;if(z.toLowerCase()==="true"||z==="1")return!0;if(z.toLowerCase()==="false"||z==="0")return!1;return}function G9(Z){let $=S4(Z,"x-codex-credits-has-credits"),z=S4(Z,"x-codex-credits-unlimited");if($===void 0||z===void 0)return;let X=u(Z.get("x-codex-credits-balance")?.trim());return{hasCredits:$,unlimited:z,...X!==void 0?{balance:X}:{},checkedAt:Date.now()}}function K2(Z){let $=E4.map((z)=>C4(Z,z));return $.includes("valid")&&!$.includes("invalid")}function x4(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=e0(Z.window_minutes),z=z0(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!z)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:z,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$}:{}}}function W2(Z){let $={},z=x4(Z.rate_limits?.primary);if(z)$.primary=z;let X=x4(Z.rate_limits?.secondary);if(X)$.secondary=X;let Y=J9(Z.credits);if(Y)$.credits=Y;return $}function J9(Z){if(Z===null||typeof Z!=="object")return;let $=Z;if(typeof $.has_credits!=="boolean"||typeof $.unlimited!=="boolean")return;let z=u(typeof $.balance==="string"?$.balance.trim():$.balance);return{hasCredits:$.has_credits,unlimited:$.unlimited,...z!==void 0?{balance:z}:{},...typeof $.overage_limit_reached==="boolean"?{overageLimitReached:$.overage_limit_reached}:{},checkedAt:Date.now()}}function u(Z){if(Z==null||Z==="")return;let $=Number(Z);return Number.isFinite($)&&$>=0?$:void 0}function T4(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=e0(Z.limit_window_seconds),z=z0(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!z)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:z,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$/60}:{}}}function A4(Z){let $={},z=T4(Z.rate_limit?.primary_window);if(z)$.primary=z;let X=T4(Z.rate_limit?.secondary_window);if(X)$.secondary=X;let Y=L4(Z.rate_limit_reset_credits?.available_count);if(Y!==void 0)$.resetCreditsAvailable=Y;let G=L4(Z.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)$.resetCreditsApplicable=G;let J=Z.spend_control?.individual_limit;if(Z.spend_control===null||J===null)$.spendControlCleared=!0;if(J&&typeof Z.spend_control?.reached==="boolean"){let H=u(J.limit),Q=u(J.used),K=u(J.remaining),W=u(J.used_percent),U=u(J.remaining_percent);if(H!==void 0&&Q!==void 0&&K!==void 0&&W!==void 0&&U!==void 0)$.spendControl={limit:H,used:Q,remaining:K,usedPercent:W,remainingPercent:U,resetsAt:z0(J.reset_at),unit:J.unit,source:J.source,reached:Z.spend_control.reached}}let B=Z.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let H=u(B.balance);$.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return $}import{ClaustrumClient as t9}from"@cortexkit/claustrum-client";import{resolve as I4}from"node:path";import{storeIdentity as Q9}from"@cortexkit/claustrum-client";import{SubcClient as b4}from"@cortexkit/subc-client";import{ClaustrumCredentialError as B9}from"@cortexkit/claustrum-client";import{SocketClosedError as H9,SocketTimeoutError as K9,SubcCallError as W9}from"@cortexkit/subc-client";class F extends Error{kind;constructor(Z,$){super($);this.name="ClaustrumConsumerError",this.kind=Z}}var Z3=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 QZ extends F{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function i(Z){if(Z instanceof QZ||Z instanceof H9||Z instanceof K9)return"unreachable";let $=Z instanceof B9||Z instanceof W9?Z.code:Z instanceof Error&&("code"in Z)?Z.code:void 0;if(typeof $!=="string"||!Object.hasOwn(Z3,$))return"answered";return Z3[$]}var $3=300000,X0=300000,z3=1000;class IZ{#Z;#z=0;restart(){this.#z=0}continuous(Z){let $=Z.kind==="changed"&&Z.seq===this.#z+1&&(this.#Z===void 0||Z.epoch===this.#Z);return this.#Z=Z.epoch,this.#z=Z.seq,$}}class Y0{#Z;#z;#Y;#X=!1;constructor(Z,$){this.#Z=Z,this.#z=$}get running(){return this.#Y}request(){if(this.#Y)return this.#X=!0,this.#Y;return this.#Y=(async()=>{do{this.#X=!1;try{await this.#Z()}catch(Z){this.#z(Z)}}while(this.#X)})().finally(()=>{this.#Y=void 0}),this.#Y}}class G0{#Z;#z=new IZ;#Y;#X="polling";#H;#J;#$=!1;#W;#Q=!1;#B=0;constructor(Z){this.#Z=Z,this.#Y=new Y0(async()=>{let $=this.#Q;if(this.#Q=!1,$||this.#W!==this.#Z.view())await this.#Z.discover(this.#W??"")},($)=>{if(!this.#$)this.#Z.onError?.($)})}get mode(){return this.#X}start(){if(this.#$||this.#H||this.#J)return;if(typeof this.#Z.client.watchScoped!=="function"){this.#G("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#$)return;if(this.#$=!0,this.#J)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#J);this.#J=void 0;let Z=this.#H;this.#H=void 0,Z?.handle.stop()}#G(Z,$){if(this.#X===Z)return;this.#X=Z,this.#Z.logger?.debug("claustrum vault watch",{mode:Z,reason:$}),this.#Z.onMode?.(Z)}#U(Z,$){this.#J=(this.#Z.setTimeoutImpl??setTimeout)(()=>{if(this.#J=void 0,!this.#$)$()},Z),this.#J.unref?.()}async#V(Z){let $;try{$=await this.#Z.enrollmentToken()}catch(J){if(this.#$)return;this.#Z.onError?.(J),this.#j("token-unreadable");return}let z=this.#Z.client.watchScoped;if(this.#$||this.#H||!z)return;this.#z.restart(),this.#Q=Z;let X,Y;try{Y=z.call(this.#Z.client,(J)=>{if(this.#$||!X||this.#H!==X)return;if(X.notices++,X.notices===1)this.#Z.onReachable?.(),X.acceptedAt=(this.#Z.now??Date.now)(),this.#G("watching","accepted");if(!this.#z.continuous(J))this.#Q=!0;this.#W=J.view,this.#Y.request()},{enrollmentToken:$})}catch(J){this.#Z.onError?.(J),this.#j("watch-failed");return}X={handle:Y,notices:0},this.#H=X,this.#G("polling",Z?"resubscribing":"opening");let G=X;Y.closed.then((J)=>this.#D(G,J),(J)=>this.#D(G,{kind:"transport_lost",error:J}))}#D(Z,$){if(this.#$||this.#H!==Z)return;if(this.#H=void 0,$.kind==="stopped")return;if($.kind==="transport_lost")this.#Z.onTransportLost?.();if($.kind==="unsupported"){this.#G("fallback","vault-without-watch");return}if($.kind==="refused"){this.#j("refused");try{this.#Z.onRefused($.error)}catch(z){this.#Z.onError?.(z)}return}if(Z.notices>0){let z=(this.#Z.now??Date.now)();if(Z.acceptedAt!==void 0&&z-Z.acceptedAt>=300000)this.#B=0;let X=Math.min(1000*2**Math.min(this.#B,16),300000);this.#B++,this.#G("polling","resubscribing"),this.#U(X,()=>void this.#V(!0));return}this.#j($.kind)}#j(Z){this.#G("fallback",Z),this.#U(300000,()=>void this.#V(!1))}}function k4(Z){let $=Z.identity??Q9(Z.projectRoot??process.cwd(),Z.storagePath??process.cwd());return{connectionFile:Z.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),J=(async()=>{if(z=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}):await b4.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}),X)throw z.close(),Error("insula usage timeout");let B=await z.routeOpen({kind:"management_surface",module_id:"insula"},$);return await z.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([J,G])}finally{X=!0,clearTimeout(Y),z?.close()}},watchUsage(z){let X,Y,G=!1,J=(async()=>{let B,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(Z.handshakeTimeoutMs??3000,3000),W=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:K}):await b4.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:K});if(X=W,G){W.close();return}let U=await W.routeOpen({kind:"management_surface",module_id:"insula"},$);if(G){W.close();return}Y=W.subscribe(U,{method:"usage.watch"},z)})();try{await Promise.race([Q,H])}catch(K){throw G=!0,K}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{G=!0,X?.close()});return{stop(){if(G)return;G=!0,Y?.unsubscribe(),X?.close()},closed:J}}}}var B0=60000,f4=4*B0,U9=2*B0,X3=new Map,J0=new Map;function bZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function D9(Z){let $;try{$=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Z))}catch{return}if(!bZ($)||typeof $.kind!=="string"||typeof $.epoch!=="string"||$.epoch.length===0||typeof $.seq!=="number"||!Number.isSafeInteger($.seq)||$.seq<1||$.provider!==void 0&&typeof $.provider!=="string")return;return{kind:$.kind,epoch:$.epoch,seq:$.seq,...typeof $.provider==="string"&&{provider:$.provider}}}function V9(Z){return Z instanceof Error&&"code"in Z&&typeof Z.code==="string"?Z.code:void 0}class y4{transport;key;#Z=[];#z=!1;#Y=new Set;#X=new Map;#H=new Y0(async()=>{try{let Z=await this.transport.getUsage();if(!bZ(Z)||!Array.isArray(Z.result)||Z.error!==void 0)throw Error("unavailable insula usage");this.#Z=Z.result.filter(($)=>bZ($)&&typeof $.provider==="string"),this.#z=this.#Z.length===Z.result.length&&(Z.completeProviders===void 0||Array.isArray(Z.completeProviders)&&Z.completeProviders.every(($)=>typeof $==="string")),this.#Y=new Set(this.#z&&Array.isArray(Z.completeProviders)?Z.completeProviders:[]);for(let $ of this.#Y)this.#X.delete($)}catch{this.#Z=[],this.#z=!1,this.#Y.clear()}},()=>{});#J=new IZ;#$="polling";#W=0;#Q=0;#B=new Map;#G;#U;#V={};#D=0;constructor(Z,$){this.transport=Z,this.key=$}refresh(Z){if(this.#H.running)return this.#H.running;if(this.#$==="watching")return Promise.resolve();for(let[z,X]of J0)if(Z-X>=B0)J0.delete(z);let $=J0.get(this.key);if($!==void 0&&Z-$<B0)return Promise.resolve();return J0.set(this.key,Z),this.#H.request()}watchMode(){return this.#$}watch(Z={}){this.#W++;let $=Z.provider;if($===void 0)this.#Q++;else this.#B.set($,(this.#B.get($)??0)+1);if(this.#W===1)this.#V=Z,this.#K();let z=!1;return()=>{if(z)return;if(z=!0,$===void 0)this.#Q--;else{let X=(this.#B.get($)??1)-1;if(X>0)this.#B.set($,X);else this.#B.delete($)}if(--this.#W===0)this.#j()}}#j(){if(this.#U)(this.#V.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let Z=this.#G;this.#G=void 0,Z?.handle?.stop(),this.#$="polling"}#F(Z){this.#U=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#W>0&&!this.#G)this.#K()},Z),this.#U.unref?.()}#K(){let Z=this.transport.watchUsage;if(!Z){this.#$="fallback";return}this.#$="polling",this.#J.restart();let $={notices:0};this.#G=$;let z;try{z=Z.call(this.transport,(X)=>this.#q($,X))}catch(X){this.#N($,X);return}$.handle=z,z.closed.then(()=>this.#N($,void 0),(X)=>this.#N($,X))}#q(Z,$){if(this.#G!==Z)return;if(Z.notices++,Z.notices===1)this.#$="watching";if(Z.notices===2)this.#D=0;let z=D9($);if(!z)this.#J.restart();if(!(z?this.#J.continuous(z):!1)||z?.provider===void 0||this.#Q>0||this.#B.has(z.provider))this.#H.request()}#N(Z,$){if(this.#G!==Z)return;this.#G=void 0;let z=V9($);if(z==="unknown_method"||z==="usage_watch_limit"){this.#$="fallback";return}if(Z.notices>0){let X=Math.min(z3*2**Math.min(this.#D,16),X0);this.#D++,this.#$="polling",this.#F(X);return}if(this.#$="fallback",this.#H.request(),$===void 0||i($)==="unreachable")this.#F(X0)}current(Z,$,z){for(let X of this.#Z){if(X.provider!==Z||typeof X.account!=="string"||X.account.trim()!==$)continue;if(X.stale!==void 0||X.errorClass!==void 0||!bZ(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=f4)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.#Z.find((J)=>J.provider===Z&&typeof J.account==="string"&&J.account.trim()===$),Y=(X??this.#Z.find((J)=>J.provider===Z&&J.account===void 0&&J.errorClass!==void 0))?.errorClass;if(Y==="upstream_failed")return{miss:"upstream-failed"};if(Y==="credential_absent"||Y==="credential_unusable"||Y==="credential_rejected")return{miss:"credential"};if(Y!==void 0)return{miss:"unreachable"};if(X){let J=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!bZ(X.usage)||!Number.isFinite(J))return{miss:"unreachable"};let B={entry:X,context:{fetchedAt:J,...typeof X.source==="string"&&{source:X.source}}};return z>=J+f4||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#Y.has(Z))return{miss:"absent"};let G=this.#X.get(Z)??z;return this.#X.set(Z,G),{miss:z-G>=U9?"unreachable":"cold"}}}function Y3(Z,$){let z=JSON.stringify([I4(Z.connectionFile),I4($)]),X=X3.get(z);if(!X)X={source:new y4(Z,z),refs:0},X3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)X3.delete(z)}}}import{ClaustrumCredentialError as S7}from"@cortexkit/claustrum-client";function G3(Z){let $=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},G=(B)=>{if(X||$.signal.aborted)return;$.abort(B),Y()},J=Z.find((B)=>B.aborted);if(J)return $.abort(J.reason),{signal:$.signal,dispose:Y};for(let B of Z){if($.signal.aborted)break;let H=()=>G(B.reason);if(z.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)G(B.reason)}return{signal:$.signal,dispose:Y}}import{ClaustrumCredentialError as J6}from"@cortexkit/claustrum-client";import{createHash as F9,randomBytes as j9,randomUUID as q9}from"node:crypto";import{constants as h4}from"node:fs";import{chmod as N9,mkdir as M9,open as d4,readFile as J3,realpath as O9,rename as _9,stat as c4,unlink as K3}from"node:fs/promises";import{basename as u4,dirname as n,extname as w4,isAbsolute as m4,join as W3,resolve as P9}from"node:path";import{ClaustrumCredentialError as L9,ClaustrumClient as R9,writeEnrollmentTokenFile as S9}from"@cortexkit/claustrum-client";var x9=1,K0=16384,i4=30000,Q3=/^[0-9a-f]{64}$/,s4="unknown_method",n4=new Set([s4,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),a4=new Set(["pending_queue_full"]);function B3(Z){if(!(Z instanceof L9))return;if(n4.has(Z.code))return{code:Z.code,disposition:"terminal"};if(a4.has(Z.code))return{code:Z.code,disposition:"retry"};return{code:Z.code,disposition:Z.action==="retry"?"retry":"terminal"}}function T9(Z,$){if(!/^[a-z0-9][a-z0-9-]*$/.test(Z)||!/^[a-z0-9][a-z0-9-]*$/.test($))throw new F("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${Z}-${$}`}function E9(Z){return R9.connect(Z)}function o4(Z){let $=w4(Z)||".json",z=u4(Z,w4(Z));return{statePath:W3(n(Z),`${z}-state${$}`),tokenPath:Z}}function C9(Z){let $=Z.override?.trim();if($&&!m4($)&&!Z.cwd)throw new F("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=$?m4($)?$:P9(Z.cwd,$):W3(Z.stateDir,`${Z.host}-enrollment.json`);return o4(z)}function r4(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function H0(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0}function t4(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=1}function fZ(){return new F("invalid-state","invalid Claustrum enrollment state")}function U0(Z){if(!r4(Z)||Z.version!==x9||typeof Z.proposedName!=="string"||Z.proposedName.length===0)throw fZ();if(Z.phase==="pending"){if(!Q3.test(String(Z.requestSecret??""))||Z.requestId!==void 0&&(typeof Z.requestId!=="string"||Z.requestId.length===0)||!H0(Z.createdAt)||!H0(Z.updatedAt))throw fZ();return{version:1,phase:"pending",proposedName:Z.proposedName,requestSecret:Z.requestSecret,...Z.requestId!==void 0&&{requestId:Z.requestId},createdAt:Z.createdAt,updatedAt:Z.updatedAt}}if(Z.phase==="approved"){if(Z.approvedName!==void 0&&(typeof Z.approvedName!=="string"||Z.approvedName.length===0)||!t4(Z.tokenGeneration)||!H0(Z.updatedAt))throw fZ();return{version:1,phase:"approved",proposedName:Z.proposedName,...Z.approvedName!==void 0&&{approvedName:Z.approvedName},tokenGeneration:Z.tokenGeneration,updatedAt:Z.updatedAt}}if(Z.phase==="denied"||Z.phase==="blocked"){if(Z.errorCode!==void 0&&typeof Z.errorCode!=="string"||!H0(Z.updatedAt))throw fZ();return{version:1,phase:Z.phase,proposedName:Z.proposedName,...Z.errorCode!==void 0&&{errorCode:Z.errorCode},updatedAt:Z.updatedAt}}throw fZ()}function U3(Z){if(!r4(Z)||!Q3.test(String(Z.token??""))||!t4(Z.token_generation))throw new F("invalid-token","invalid Claustrum enrollment token file");return{token:Z.token,token_generation:Z.token_generation}}function A9(Z){if(!Z.isFile())throw new F("unsafe-file","Claustrum enrollment file must be a regular file");if((Z.mode&63)!==0)throw new F("unsafe-file","Claustrum enrollment file must be owner-only");let $=process.geteuid?.();if($!==void 0&&Z.uid!==$)throw new F("unsafe-file","Claustrum enrollment file must be owned by the current user")}function g4(Z){try{return JSON.parse(Z)}catch{throw new F("invalid-state","Claustrum enrollment file is not valid JSON")}}async function a(Z){if(DZ)try{await H3(n(Z));let z=await Q0(Z,!0);if(Buffer.byteLength(z)>K0)throw new F("unsafe-file","Claustrum enrollment file is too large");return g4(z)}catch(z){if(z.code==="ENOENT")return;throw z}let $;try{$=await d4(Z,h4.O_RDONLY|h4.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new F("unsafe-file","Claustrum enrollment file could not be opened safely")}try{A9(await $.stat());let z=Buffer.alloc(K0+1),{bytesRead:X}=await $.read(z,0,z.byteLength,0);if(X>K0)throw new F("unsafe-file","Claustrum enrollment file is too large");return g4(z.subarray(0,X).toString("utf8"))}finally{await $.close()}}function v4(Z,$){let z=[];for(let X of Z.split(`
|
|
88
|
-
`)){if(X.trim()===""||X.startsWith("#"))continue;let Y=X.split(":");if(Y.length!==$||!/^[^\s:,]+$/.test(Y[0]??"")||!/^\d+$/.test(Y[2]??"")||!Number.isSafeInteger(Number(Y[2]))||$===7&&(!/^\d+$/.test(Y[3]??"")||!Number.isSafeInteger(Number(Y[3])))||$===4&&Y[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(Y[3]??""))return;z.push(Y)}return z}async function I9(Z,$,z){try{let[X,Y]=await Promise.all([J3(z.passwdPath??"/etc/passwd","utf8"),J3(z.groupPath??"/etc/group","utf8")]),G=v4(X,7),J=v4(Y,4);if(!G||!J)return!1;let B=G.filter((W)=>Number(W[2])===Z),H=J.filter((W)=>Number(W[2])===$);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))&&!G.some((W)=>Number(W[2])!==Z&&Number(W[3])===$)}catch{return!1}}function e4(Z){if(!Z.passwdPath&&!Z.groupPath)return;return{fs:{readFile:($)=>J3($==="/etc/passwd"?Z.passwdPath??$:$==="/etc/group"?Z.groupPath??$:$)}}}async function Z6(Z,$={}){if(!DZ){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await O9(Z)}catch{return}let G;for(;;){let J=await c4(Y).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0){if(G===void 0)G=X!==void 0&&await I9(z,X,$);if((J.mode&2)!==0||J.uid!==z||J.gid!==X||!G)throw new F("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=n(Y);if(B===Y)return;Y=B}}try{await p4(Z,e4($))}catch(z){if(!(z instanceof i0))throw z;throw new F("unsafe-file",`Claustrum enrollment parent refused: ${z.path} (${z.reason??z.code}). Use a folder that other users cannot write or replace.`)}}async function W0(Z,$={}){if(DZ){await H3(Z,!1,e4($));return}await M9(Z,{recursive:!0,mode:448});let z=await c4(Z),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new F("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((z.mode&63)!==0)await N9(Z,448)}async function UZ(Z,$,z={}){let X=n(Z);await W0(X,z),await Z6(X,z);let Y=`${JSON.stringify($)}
|
|
89
|
-
`;if(Buffer.byteLength(Y)>K0)throw new F("invalid-state","Claustrum enrollment state is too large");if(DZ)return l4(Z,Y);let G=W3(X,`.${u4(Z)}.${process.pid}.${q9()}.tmp`),J,B=!1;try{J=await d4(G,"wx",384),B=!0,await J.writeFile(Y,"utf8"),await J.chmod(384),await J.sync(),await J.close(),J=void 0,await _9(G,Z),B=!1}finally{if(await J?.close().catch(()=>{}),B)await K3(G).catch(()=>{})}}async function D3(Z,$){let z=await a(Z.tokenPath),X=z===void 0?void 0:U3(z),Y=await a(Z.statePath),G=Y===void 0?void 0:U0(Y);if(X)return{state:"approved",proposedName:G?.proposedName??$,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:X.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return s(G)}async function b9(Z,$){let z;try{z=await D3(Z,$)}catch(X){if(!(X instanceof F)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await a(Z.statePath);if(Y===void 0)return"unreadable";let G=U0(Y);return G.phase==="approved"&&G.proposedName===$?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in z&&z.proposedName!==$)return"unreadable";if(z.state==="approved"||z.state==="blocked"&&z.code==="missing_token")return"vault";return"local"}async function o(Z){let $=await a(Z);if($===void 0)throw new F("not-enrolled","Claustrum enrollment is not configured");return U3($)}function s(Z){if(Z.phase==="pending")return{state:"pending",proposedName:Z.proposedName,...Z.requestId!==void 0&&{requestId:Z.requestId}};if(Z.phase==="approved")return{state:"approved",proposedName:Z.proposedName,...Z.approvedName!==void 0&&{approvedName:Z.approvedName},tokenGeneration:Z.tokenGeneration};if(Z.phase==="denied")return{state:"denied",proposedName:Z.proposedName};return{state:"blocked",proposedName:Z.proposedName,code:Z.errorCode??"unknown"}}function $6(){return new F("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class z6{#Z;#z;#Y;#X;#H;#J;#$;constructor(Z){this.#$=Z.ancestorOptions??{},this.#Z=Z.client,this.#z=Z.paths,this.#Y=Z.proposedName,this.#X=Z.now??Date.now,this.#H=Z.mintSecret??(()=>j9(32).toString("hex")),this.#J=Z.writeTokenFile??S9}async status(){return D3(this.#z,this.#Y)}async resetTerminal(){return X6(this.#z,this.#Y)}async#W(Z,$){let z={version:1,phase:"blocked",proposedName:Z.proposedName,errorCode:$,updatedAt:this.#X()};return await UZ(this.#z.statePath,z,this.#$),s(z)}async reconcile(){await W0(n(this.#z.statePath),this.#$);let Z=await A({name:"ceremony",path:this.#z.statePath,ttlMs:i4,renew:!0});if(!Z)return{state:"busy"};try{let $=await a(this.#z.tokenPath),z=$===void 0?void 0:U3($),X=await a(this.#z.statePath),Y=X===void 0?void 0:U0(X);if(Y&&Y.proposedName!==this.#Y)throw $6();if(z){if(!Y||Y.phase==="pending"){let J={version:1,phase:"approved",proposedName:Y?.proposedName??this.#Y,tokenGeneration:z.token_generation,updatedAt:this.#X()};await UZ(this.#z.statePath,J,this.#$),Y=J}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:z.token_generation}}if(Y?.phase==="approved"){let J={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await UZ(this.#z.statePath,J,this.#$),s(J)}if(Y&&Y.phase!=="pending")return s(Y);if(!Y){let J=this.#X();if(Y={version:1,phase:"pending",proposedName:this.#Y,requestSecret:this.#H(),createdAt:J,updatedAt:J},!Q3.test(Y.requestSecret))throw new F("invalid-state","invalid minted Claustrum enrollment secret");await UZ(this.#z.statePath,Y,this.#$)}if(!Y.requestId)try{let J=F9("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B=await this.#Z.enrollPropose({name:Y.proposedName,requestSecretHash:J});Y={...Y,requestId:B.requestId,updatedAt:this.#X()},await UZ(this.#z.statePath,Y,this.#$)}catch(J){let B=B3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};if(B.code===s4)return await Z.assertOwned(),await K3(this.#z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#W(Y,B.code)}let G=Y.requestId;if(!G)return s(Y);try{let J=await this.#Z.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(J.status==="pending")return s(Y);if(J.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#X()};return await UZ(this.#z.statePath,H,this.#$),s(H)}await W0(n(this.#z.tokenPath),this.#$),await Z6(n(this.#z.tokenPath),this.#$),await this.#J(this.#z.tokenPath,{token:J.token,token_generation:J.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:J.name,tokenGeneration:J.tokenGeneration,updatedAt:this.#X()};return await UZ(this.#z.statePath,B,this.#$),s(B)}catch(J){let B=B3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:B.code};return this.#W(Y,B.code)}}finally{await Z.release()}}}async function X6(Z,$){await W0(n(Z.statePath));let z=await A({name:"ceremony",path:Z.statePath,ttlMs:i4,renew:!0});if(!z)return"busy";try{if(await a(Z.tokenPath)!==void 0)return"refused-approved";let X=await a(Z.statePath);if(X===void 0)return"idle";let Y=U0(X);if(Y.proposedName!==$)throw $6();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await K3(Z.statePath),"reset"}finally{await z.release()}}var kZ="claustrum-tombstone:v1:";function D0(Z){return`${kZ}${Z}`}function V3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function V0(Z){return typeof Z==="string"&&Z.startsWith(kZ)}function Y6(Z,$){if(!V3(Z)||Z.type!=="oauth")return!1;return Z.refresh===D0($)}function G6(Z,$){if(Y6(Z,$))return"placeholder";if(V3(Z)&&Z.type==="oauth"&&typeof Z.refresh==="string"&&Z.refresh.length>0&&!V0(Z.refresh))return"login";if(V3(Z)&&Z.type==="api"&&typeof Z.key==="string"&&Z.key.length>0)return"login";return"empty"}function f9(Z){let $=G6(Z.auth,Z.provider);if(Z.mode==="custody"&&$==="login")throw new F("host-slot-login",`${Z.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if(Z.mode==="local"&&$==="placeholder")throw new F("host-slot-placeholder",`${Z.provider} host slot holds the vault placeholder; sign in to use local accounts`);return $}function B6(Z,$){return $!==void 0&&!$.fromKeptReceipt&&!Z.fromKeptReceipt&&$.credentialId===Z.credentialId&&$.accountIdentity===Z.accountIdentity&&$.recordVersion!==Z.recordVersion}function k9(Z,$){if($===void 0)return"reauthorize-failed";if($.credentialId!==Z.credentialId)return"credential-changed";if($.accountIdentity!==Z.accountIdentity)return"account-changed";if($.recordVersion===Z.recordVersion)return"version-unchanged";return"rotated"}var j3=I("claustrum");function N3(Z,$,z,X=j3){let Y=B6($,z);return X.debug("scoped 401 re-authorized",{site:Z,credentialId:$.credentialId,servedVersion:$.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:k9($,z)}),Y}var q3=300000,H6=60000;function F3(){return new F("invalid-material","Claustrum returned invalid credential material")}function y9(Z){let $=Z.trim();if($.startsWith("{")){let z;try{z=JSON.parse($)}catch{throw F3()}if(!z||typeof z!=="object")throw F3();let X=z,Y=X.access_token??X.access;$=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test($)||$.startsWith(kZ))throw F3();return $}function h9(Z,$){if(!Z.operations.includes("read"))return;if(!Z.categories.includes($.category))return;if(Z.credentialType==="oauth")return Z.refreshAdapter===$.refreshAdapter?"oauth":void 0;if(Z.credentialType==="api_key"&&$.apiKeys)return Z.refreshAdapter===void 0?"api_key":void 0;return}function w9(Z){let{grants:$,grantTuples:z}=Z;if($===void 0||z===void 0)return;return Object.freeze({grants:$,tuples:Object.freeze(z.map(({selectorKind:X,selector:Y,operation:G})=>Object.freeze({selectorKind:X,selector:Y,operation:G})))})}class F0{#Z;#z;#Y;#X;#H;#J;#$;#W=new WeakMap;#Q=new WeakMap;#B=new Map;#G=new WeakMap;#U;#V;#D=!1;#j=new QZ;#F;#K=!1;#q=-1/0;#N=2000;#M=!1;#_;#P=new Set;constructor(Z){let $=Z.tokenPath;if(Z.readToken)this.#z=Z.readToken;else if($)this.#z=()=>o($);else throw new F("not-enrolled","Claustrum enrollment token path is required");this.#Z=Z.client,this.#X=Z.family,this.#H=Z.parseIdentity,this.#J=Z.requireAssertion??!1,this.#Y=Z.now??Date.now,this.#$=Z.logger??j3,this.#U=Z.setTimeoutImpl??setTimeout,this.#V=Z.clearTimeoutImpl??clearTimeout}transportLost(Z){if(this.#M||this.#D)return;this.#D=!0,this.#j=Z instanceof J6?Z:new QZ,this.#$.warn("serving kept vault receipt",{reason:"unreachable"}),this.#L()}reachable(){if(this.#M||!this.#D)return;if(this.#D=!1,this.#F)this.#V(this.#F);this.#F=void 0,this.#N=2000;for(let Z of this.#B.values())Z.since=null;(this.#$.info??j3.info)("vault receipt serving resumed",{reason:"reachable"})}#L(){if(this.#M||!this.#D||this.#F||this.#K)return;this.#F=this.#U(()=>{this.#F=void 0,this.#R(!0)},this.#N),this.#F.unref?.()}#R(Z=!1){if(this.#M||!this.#D||this.#K)return;if(this.#Y()-this.#q<1000){this.#L();return}this.#q=this.#Y(),this.#K=!0,this.#T().catch(()=>{if(Z&&this.#D)this.#N=Math.min(this.#N*2,30000)}).finally(()=>{this.#K=!1,this.#L()})}#O(Z){if(this.#M)throw new F("closed","Claustrum scoped custody is closed");Z?.throwIfAborted()}async#S(Z){this.#O(Z);let $=await this.#z();if(this.#O(Z),!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new F("invalid-token","Invalid Claustrum enrollment token");return $.token}async#x(Z,$){this.#O($);let z,X;try{let Y=Z();z=$?await Promise.race([Y,new Promise((G,J)=>{let B=()=>J($.reason);if($.addEventListener("abort",B,{once:!0}),X=()=>$.removeEventListener("abort",B),$.aborted)B()})]):await Y}catch(Y){if(this.#O($),i(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof J6)throw Y;if(i(Y)==="unreachable")throw new QZ;throw new F("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#O($),this.reachable(),z}async discover(Z){let $=await this.#T(Z);return this.#_=$.view,$}async#T(Z){let $,z;try{z=await this.#S(Z)}catch(H){throw this.#B.clear(),H}try{$=await this.#x(()=>this.#Z.listScoped(z),Z)}catch(H){throw this.listFailed(H),H}let X=[],Y=[],G=new Map;for(let H of $.rows){let Q=h9(H,this.#X);if(!Q)continue;Y.push({row:H,type:Q}),G.set(H.id,(G.get(H.id)??0)+1)}let J=[];for(let{row:H,type:Q}of Y){let K;if(!H.id.trim())K="empty credential id";else if((G.get(H.id)??0)>1)K="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())K="blank account identity";else if(!H.state.trim())K="empty state";if(K){X.push({...H.id.trim()&&{credentialId:H.id},reason:K});continue}J.push(Object.freeze({credentialId:H.id,credentialType:Q,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of X)this.#$.warn("skipped malformed vault record",H);let B=w9($);return{view:$.view,credentials:Object.freeze(J),skipped:Object.freeze(X),...B&&{grantReach:B}}}listFailed(Z){if(i(Z)==="unreachable")this.transportLost(Z);else this.reachable(),this.#B.clear()}forget(Z){this.#B.delete(Z)}retain(Z){let $=new Map(Z.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#B){let Y=$.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}}keptReceiptState(){let Z=null;for(let[$,z]of this.#B){if(!this.#E(z.attempt)){this.forget($);continue}if(z.since!==null)Z=Math.min(Z??z.since,z.since)}return Object.freeze({active:Z!==null,since:Z})}#E(Z){return Z.expiresAtMs===null?Z.credentialType==="api_key":Z.expiresAtMs-this.#Y()>H6}async authorize(Z,$,z="vault"){this.#O($);let{credentialId:X,credentialType:Y,accountIdentity:G}=Z,J=this.#B.get(X);if(J&&(J.attempt.credentialType!==Y||J.attempt.expectedAccountIdentity!==G))this.forget(X),J=void 0;let B;try{B=await this.#S($)}catch(H){throw this.#B.clear(),H}if(this.#D&&J)return this.#R(),this.#C(X,J,B,z);try{let H=await this.#A({credentialId:X,credentialType:Y,accountIdentity:G},B,$);return this.#B.set(X,{attempt:H,routeId:z,since:null}),H}catch(H){if(this.#O($),i(H)!=="unreachable")throw this.forget(X),H;return this.#C(X,J,B,z,H)}}#C(Z,$,z,X,Y=this.#j){if(!$||this.#B.get(Z)!==$||!this.#E($.attempt))throw this.forget(Z),Y;if($.since===null)$.since=this.#Y();let G=Object.freeze(Object.defineProperty({...$.attempt,fromKeptReceipt:!0},"accessToken",{value:$.attempt.accessToken,enumerable:!1}));return this.#W.set(G,z),this.#G.set(G,X),G}async#A(Z,$,z){if(!Z.credentialId)throw new F("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:G}=Z;if(this.#J&&G===void 0)throw new F("identity-unasserted","Claustrum dispatch requires a known account identity");let J=await this.#x(()=>this.#Z.getScoped({credentialId:X,enrollmentToken:$,...Y==="oauth"&&{minTtlMs:q3}}),z);if(J.credentialId!==void 0&&J.credentialId!==X)throw new F("identity-changed","Claustrum served credential identity changed");let B=J.expiresAtMs;if(!Number.isSafeInteger(J.recordVersion)||J.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#Y()<q3))throw new F("insufficient-validity","Claustrum served credential has insufficient validity");let H=y9(J.material),Q=J.accountId?.trim()?J.accountId:void 0;if(this.#J&&(J.credentialId===void 0||Q===void 0))throw new F("identity-unasserted","Claustrum served credential did not assert its identity");let K=Q===void 0?this.#H?.(H):void 0,W=Q??K;if(G!==void 0&&W!==void 0&&W!==G)throw new F("identity-changed","Claustrum served credential identity changed");let U=W??G,D=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":K!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...J.credentialId!==void 0&&{assertedCredentialId:J.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...J.projectId!==void 0&&{projectId:J.projectId},recordVersion:J.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#W.set(D,$),D}async reportFailure(Z,$,z){if($!==401)return;this.#O();let X=this.#W.get(Z);if(!X)throw new F("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#G.get(Z);if(Y!==void 0){this.forget(Z.credentialId),this.#$.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let G=this.#B.get(Z.credentialId);if(G&&G.attempt.recordVersion===Z.recordVersion)this.forget(Z.credentialId);let J=this.#Q.get(Z);if(J)return J;let B=this.#x(()=>this.#Z.reportAuthFailureScoped({credentialId:Z.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:Z.recordVersion,reporterSource:z}));this.#Q.set(Z,B);try{await B,this.#$.debug("scoped 401 reported",{credentialId:Z.credentialId,recordVersion:Z.recordVersion,reporterSource:z})}catch(H){throw this.#Q.delete(Z),H}}watchRoster(Z){this.#O();let $=new G0({client:this.#Z,enrollmentToken:()=>this.#S(),view:Z.view??(()=>this.#_),discover:async(z)=>{await Z.onView(z)},onRefused:(z)=>{this.listFailed(z),Z.onRefused?.(z)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:Z.onError,onMode:Z.onMode,logger:this.#$,now:this.#Y,setTimeoutImpl:this.#U,clearTimeoutImpl:this.#V});return this.#P.add($),$.start(),{get mode(){return $.mode},close:()=>{this.#P.delete($),$.stop()}}}close(){if(this.#M)return;if(this.#M=!0,this.#F)this.#V(this.#F);this.#F=void 0;for(let Z of this.#P)Z.stop();this.#P.clear(),this.#B.clear(),this.#Z.close()}}import{resolve as I3}from"node:path";import{createHash as m9}from"node:crypto";import{resolve as Q6}from"node:path";function K6(Z,$,z){if(Z.accountIdentity!==void 0&&z!==void 0)return Z.accountIdentity===z;return Z.credentialId===$}function M3(Z,$,z){return Z.some((X)=>K6(X,$,z))}function O3(Z,$,z){let X={credentialId:$,...z!==void 0&&{accountIdentity:z}};return[...Z.filter((Y)=>Y.credentialId!==$||Y.accountIdentity!==z),X]}function _3(Z,$,z){return Z.filter((X)=>!$.some((Y)=>K6(X,Y,z)))}var U6="vault:";function g9(Z){return m9("sha256").update(Z).digest("hex")}function v9(Z){let $=Z.credentialId.split(":");return($.length>=3?$.slice(2).join(":").trim():void 0)||Z.email||Z.credentialId}function p9(Z){return Z.identity!==void 0?`identity:${Z.identity}`:`credential:${Z.credential.credentialId}`}function r(Z){return[Z.credentialId,...Z.aliases??[]]}function D6(Z,$,z={}){let X=z.now??Date.now(),Y=z.routePrefix??U6,G=z.reservedRouteIds??new Set,J=Z?.rows??[],B=[...Z?.declined??[]],H=$.skipped.length===0,Q=new Set($.credentials.map((V)=>V.credentialId)),K=new Set($.skipped.flatMap((V)=>V.credentialId===void 0?[]:[V.credentialId])),W=$.skipped.some((V)=>V.credentialId===void 0),U=(V)=>!Q.has(V)&&(K.has(V)||W),q=new Map;for(let V of J){if(V.accountIdentity===void 0)continue;for(let O of r(V))if(!q.has(O))q.set(O,V.accountIdentity)}let D=new Map;for(let V of $.credentials){let O=V.accountIdentity!==void 0?{credential:V,identity:V.accountIdentity,claimed:!0}:{credential:V,identity:q.get(V.credentialId),claimed:!1},l=p9(O),d=D.get(l)??[];d.push(O),D.set(l,d)}let M=new Set,N=new Set(G),L=[],T=(V,O)=>V.credential.credentialId.localeCompare(O.credential.credentialId),p=[...D.values()].map((V)=>V.toSorted(T)).sort((V,O)=>V[0]&&O[0]?T(V[0],O[0]):0);for(let V of p){let O=V[0]?.identity,l=V.filter((_)=>_.credential.state==="active"),d=l.length?l:V,E0=d.filter((_)=>_.claimed),dZ=E0.length?E0:d,C0=new Set(V.map((_)=>_.credential.credentialId)),l3=J.find((_)=>!M.has(_)&&r(_).some((NZ)=>C0.has(NZ))&&(_.accountIdentity===void 0||_.accountIdentity===O)),A0=dZ.find((_)=>_.credential.credentialId===l3?.credentialId)??dZ[0];if(!A0)continue;let E=A0.credential,k=l3??(O===void 0?void 0:J.find((_)=>!M.has(_)&&_.accountIdentity===O));if(k)M.add(k);let zZ=k?.routeId;if(!zZ||G.has(zZ)){let _=`${Y}${E.credentialId}${O===void 0?"":`~${g9(O).slice(0,10)}`}`;zZ=_;for(let NZ=2;N.has(zZ);NZ++)zZ=`${_}~${NZ}`}N.add(zZ);let J8=k?r(k).filter(U):[],I0=[...new Set([...V.map((_)=>_.credential.credentialId),...J8])].filter((_)=>_!==E.credentialId).sort((_,NZ)=>_.localeCompare(NZ)),B8=z.mapAccount?.(E)??{};L.push({previousIndex:k?J.indexOf(k):1/0,row:{routeId:zZ,credentialId:E.credentialId,credentialType:E.credentialType,...O!==void 0&&{accountIdentity:O},...I0.length&&{aliases:I0},state:E.state,label:B8.label?.trim()||v9(E),...E.email!==void 0&&{email:E.email},...E.orgName!==void 0&&{orgName:E.orgName},enabled:![E.credentialId,...I0].some((_)=>M3(B,_,O)),addedAt:k?.addedAt??X,...k?.quota!==void 0&&{quota:k.quota},...!A0.claimed&&O!==void 0&&{unclaimed:!0}}})}return J.forEach((V,O)=>{if(M.has(V)||!r(V).some(U))return;if(N.has(V.routeId))return;let[l,...d]=r(V).filter((C0)=>!Q.has(C0));if(l===void 0)return;N.add(V.routeId);let{aliases:E0,...dZ}=V;L.push({previousIndex:O,row:{...dZ,credentialId:l,...d.length&&{aliases:d},stale:!0}})}),L.sort((V,O)=>V.previousIndex===O.previousIndex?V.row.credentialId.localeCompare(O.row.credentialId):V.previousIndex-O.previousIndex),{version:1,view:$.view,complete:H,...!H&&{rejected:$.skipped.map((V)=>({...V.credentialId!==void 0&&{credentialId:V.credentialId},reason:V.reason}))},rows:L.map((V)=>V.row),declined:B}}function P3(Z){return(Z?.rows??[]).filter(($)=>$.enabled&&$.state==="active").map(($)=>({id:$.routeId,kind:$.credentialType==="oauth"?"oauth":"api-key",...$.quota!==void 0&&{quota:$.quota}}))}function yZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function PZ(Z){return Z===void 0||typeof Z==="string"}function l9(Z){let $=yZ(Z)?YZ(Z.quota):void 0;if(!yZ(Z)||typeof Z.routeId!=="string"||typeof Z.credentialId!=="string"||Z.credentialType!=="oauth"&&Z.credentialType!=="api_key"||typeof Z.state!=="string"||typeof Z.label!=="string"||typeof Z.enabled!=="boolean"||typeof Z.addedAt!=="number"||!PZ(Z.accountIdentity)||!PZ(Z.email)||!PZ(Z.orgName)||Z.aliases!==void 0&&(!Array.isArray(Z.aliases)||!Z.aliases.every((z)=>typeof z==="string"))||Z.quota!==void 0&&$===void 0||Z.stale!==void 0&&Z.stale!==!0||Z.unclaimed!==void 0&&Z.unclaimed!==!0)return;return{...Z,...$===void 0?{}:{quota:$}}}var d9=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function W6(Z){if(!Array.isArray(Z))return;let $=[];for(let z of Z){if(!yZ(z)||!PZ(z.credentialId)||typeof z.reason!=="string"||!d9.has(z.reason))return;$.push(z)}return $}function c9(Z){if(!yZ(Z)||Z.version!==1||!PZ(Z.view)||!Array.isArray(Z.rows)||!Array.isArray(Z.declined)||Z.complete!==void 0&&typeof Z.complete!=="boolean"||Z.rejected!==void 0&&!W6(Z.rejected))throw new F("invalid-state","Claustrum roster file is not valid");let $=[];for(let Y of Z.rows){let G=l9(Y);if(!G)throw new F("invalid-state","Claustrum roster file is not valid");$.push(G)}let z=[];for(let Y of Z.declined){if(!yZ(Y)||typeof Y.credentialId!=="string"||!PZ(Y.accountIdentity))throw new F("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=W6(Z.rejected);return{version:1,...typeof Z.view==="string"&&{view:Z.view},complete:Z.complete!==!1,...X&&{rejected:X},rows:$,declined:z}}async function b(Z){let $;try{$=await Q0(Z,DZ)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse($)}catch{throw new F("invalid-state","Claustrum roster file is not valid")}return c9(z)}var u9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},i9={name:"claustrum-roster",ttlMs:30000};async function VZ(Z,$,z={}){return n0(Z,{...u9,signal:z.signal},async(X)=>{let Y=await b(Z),{next:G,result:J}=await $(Y,{assertOwned:()=>X.assertOwned()});if(G)await X.assertOwned(),await m(Z,G,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}});return J})}function L3(Z,$){return VZ(Z,(z)=>{let X=z?.rows.find((G)=>G.routeId===$);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");let Y=O3(z.declined,X.credentialId,X.accountIdentity);return{next:{...z,declined:Y,rows:z.rows.map((G)=>G===X?{...G,enabled:!1}:G)},result:void 0}})}function R3(Z,$){return VZ(Z,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===$);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:_3(z.declined,r(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function s9(Z){return new F("invalid-order",Z)}function n9(Z,$){if(!Array.isArray($))return"route ids must be an array of route ids";let z=new Set(Z.map((G)=>G.routeId)),X=new Set;for(let G of $){if(typeof G!=="string")return"route ids must be an array of route ids";if(X.has(G))return`route id ${G} appears more than once`;if(!z.has(G))return`route id ${G} is not in the roster`;X.add(G)}let Y=[...z].filter((G)=>!X.has(G)).length;if(Y>0)return`the order leaves out ${Y} roster route id${Y===1?"":"s"}`;return}function S3(Z,$,z={}){return VZ(Z,(X)=>{let Y=X?.rows??[],G=n9(Y,$);if(G)throw s9(G);let J=new Map;for(let Q of Y){let K=J.get(Q.routeId);if(K)K.push(Q);else J.set(Q.routeId,[Q])}let B=[...$],H=B.flatMap((Q)=>J.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 a9(Z,$){if(!r(Z).includes($.credentialId))return"refuse";if(Z.unclaimed&&($.accountIdentitySource==="expected"||$.accountIdentitySource==="none"))return"refuse";if(Z.accountIdentity===$.accountIdentity)return"hold";if(Z.accountIdentity===void 0&&$.expectedAccountIdentity===void 0&&$.accountIdentity!==void 0&&($.accountIdentitySource==="asserted"||$.accountIdentitySource==="parsed")&&r(Z).length===1)return"bind";return"refuse"}async function x3(Z,$){let{routeId:z,observation:X,...Y}=$;return V6(Z,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function V6(Z,$){if(!OZ($.observation))return!1;let z=h(Z,await b(Z));if(!t(z,$).kept)return!1;return F6(Z,$)}function T3(Z,$){return V6(Z,$)}function t(Z,$){let z=Z?.rows.find((J)=>J.routeId===$.routeId),X=!z?"refuse":$.receipt?a9(z,$.receipt):z.accountIdentity!==void 0&&z.accountIdentity===$.accountIdentity?"hold":"refuse";if(!Z||!z||X==="refuse")return{roster:Z,kept:!1};let Y=xZ(z.quota,$.observation),G=X==="bind"?{accountIdentity:$.accountIdentity,unclaimed:!0}:{};return{roster:{...Z,rows:Z.rows.map((J)=>J===z?{...J,...G,quota:Y}:J)},kept:!0}}var j0=new Map;function E3(Z){j0.delete(Q6(Z))}async function C3(Z){Z.signal?.throwIfAborted();let $=async()=>await Z.isActive?.()??!0;if(!await $()){E3(Z.path);return}let z=await A({...i9,path:Z.path,renew:!0});if(!z){let G=await b(Z.path);if(Z.signal?.throwIfAborted(),!G?.view)throw new F("roster-busy","Claustrum account discovery is already in progress");return G}let X=Q6(Z.path),Y;try{let G=await b(Z.path),J=j0.get(X);Y=J&&(J.previousView===G?.view||J.inventory.view===G?.view)?J:{inventory:await Z.custody.discover(Z.signal),previousView:G?.view},j0.delete(X);let{inventory:B}=Y;return Z.onInventory?.(B),Z.signal?.throwIfAborted(),await VZ(Z.path,async(H)=>{if(!await $())return{result:void 0};Z.signal?.throwIfAborted(),await z.assertOwned();let Q=typeof Z.projection==="function"?Z.projection():Z.projection,K=D6(H,B,Q);return{...JSON.stringify(H)!==JSON.stringify(K)&&{next:K},result:K}},{beforePublish:async()=>{Z.signal?.throwIfAborted(),await z.assertOwned()}})}catch(G){if(G instanceof s0&&Y&&!Z.signal?.aborted&&await $())j0.set(X,Y);throw G}finally{await z.release()}}var LZ=new Map,o9=I("claustrum"),j6=100;function q6(Z){let $=I3(Z),z=LZ.get($);if(!z)z={path:$,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,failures:0,draining:!1,order:0},LZ.set($,z);return z}function N6(Z,$){let z=q6(Z);z.listeners.add($);let X;return()=>X??=(()=>{return z.listeners.delete($),z.listeners.size?Promise.resolve():A3(Z)})()}function r9(Z){let $=new Map,{observation:z}=Z,X=JSON.stringify([Z.routeId,Z.receipt?.credentialId,Z.receipt?.accountIdentitySource,Z.receipt?.expectedAccountIdentity]),Y=(B,H,Q)=>$.set(`${X}:${B}`,{at:H,order:0,publication:{...Z,observation:Q}}),G=(B,H)=>JSON.stringify([B??"all",H]),J=new Set;for(let B of z.readings??[]){let H=G(B.scope,B.label);J.add(H),Y(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...B}]})}for(let B of z.coverage??[]){let H=G(B.scope,B.label);if(!J.has(H))Y(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...B}]})}if(z.budget)Y("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[B,H]of Object.entries(z.counters??{}))Y(`counter:${B}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[B]:{...H}}});if(z.credits)Y("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!$.size)Y("empty",z.checkedAt,{checkedAt:z.checkedAt});return $}function F6(Z,$){if(!OZ($.observation))return Promise.resolve(!1);let z=q6(Z),X=JSON.stringify([$.accountIdentity??null,$.accountIdentity===void 0?$.routeId:null]),Y=z.pending.get(X)??new Map;for(let[G,J]of r9($)){let B=Y.get(G);if(!B||J.at>=B.at){if(J.order=++z.order,J.publication.observation.coverage)J.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(G,J)}}if(Y.size)z.pending.set(X,Y);for(let G of z.listeners)G($);return O6(z,j6),Promise.resolve(!0)}function M6(Z){return[...Z.values()].flatMap(($)=>[...$.values()]).sort(($,z)=>$.order-z.order)}function h(Z,$){let z=LZ.get(I3(Z));if(z)for(let X of M6(z.pending)){if(X.priorReading)$=t($,X.priorReading).roster;$=t($,X.publication).roster}return $}function O6(Z,$){if(Z.running||Z.timer||!Z.pending.size||Z.abort.signal.aborted)return;if(Z.timer=setTimeout(()=>{Z.timer=void 0,_6(Z)},$),!Z.draining)Z.timer.unref?.()}function _6(Z){if(Z.running||Z.abort.signal.aborted)return;let $=new Map([...Z.pending].map(([z,X])=>[z,new Map(X)]));Z.running=(async()=>{try{await VZ(Z.path,(z)=>{let X=z;for(let Y of M6($)){if(Y.priorReading)X=t(X,Y.priorReading).roster;X=t(X,Y.publication).roster}return{...X!==z&&{next:X},result:void 0}},{signal:Z.abort.signal});for(let[z,X]of $){let Y=Z.pending.get(z);for(let[G,J]of X)if(Y?.get(G)===J)Y.delete(G);if(!Y?.size)Z.pending.delete(z)}Z.failures=0}catch(z){if(!Z.abort.signal.aborted&&Z.failures++===0)o9.warn("vault quota publication delayed; retrying",{error:z instanceof Error?z.message:String(z)})}finally{Z.running=void 0;for(let X of Z.wake)X();let z=Z.failures?Math.min(5000,100*2**Math.min(Z.failures,6))*(0.5+Math.random()):j6;O6(Z,z)}})()}async function A3(Z,$=1000){let z=I3(Z),X=LZ.get(z);if(!X)return;X.draining=!0,clearTimeout(X.timer),X.timer=void 0;let Y,G,J=new Promise((B)=>{G=()=>{if(!X.pending.size||X.abort.signal.aborted)B()},X.wake.add(G),G()});try{if(X.pending.size)_6(X);await Promise.race([J,new Promise((B)=>{Y=setTimeout(B,Math.max(0,$))})])}finally{if(clearTimeout(Y),G)X.wake.delete(G);if(X.draining=!1,!X.listeners.size){if(X.abort.abort(),clearTimeout(X.timer),X.pending.clear(),LZ.get(z)===X)LZ.delete(z)}}}class P6{#Z;#z=new AbortController;#Y;#X;#H;#J;#$;#W;#Q;#B=!1;#G;#U;#V;#D=new Map;#j;#F;constructor(Z){this.#Z=Z,this.#Y=Z.logger??I("claustrum"),this.#F=N6(Z.rosterPath,($)=>{this.#$=t(this.#$,$).roster})}#K(Z){this.#z.signal.throwIfAborted(),Z?.throwIfAborted()}async#q(){return await this.#Z.isCustodyActive?.()??!0}#N(Z,$){let z=G3([this.#z.signal,...$?[$]:[]]);return new Promise((X,Y)=>{let G=()=>{z.signal.removeEventListener("abort",J),z.dispose()},J=()=>{G(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",J,{once:!0}),Z.then((B)=>{if(G(),z.signal.aborted)Y(z.signal.reason);else X(B)},(B)=>{G(),Y(B)}),z.signal.aborted)J()})}async#M(){if(this.#K(),this.#X)return this.#X;if(!this.#H)this.#H=this.#Z.connect().then((Z)=>{if(this.#z.signal.aborted)Z.close(),this.#K();if(this.#X=new F0({client:Z,family:this.#Z.family,tokenPath:this.#Z.tokenPath,parseIdentity:this.#Z.parseIdentity,requireAssertion:this.#Z.requireAssertion,now:this.#Z.now,logger:this.#Y,setTimeoutImpl:this.#Z.setTimeoutImpl,clearTimeoutImpl:this.#Z.clearTimeoutImpl}),this.#Z.insula&&Z.insula)this.#G=Y3(Z.insula,this.#Z.tokenPath);return this.#X}).finally(()=>{this.#H=void 0});return this.#N(this.#H)}snapshot(){return this.#$}grantReach(){let Z=this.#W;return Z&&this.#$?.view===Z.view?Z.reach:void 0}watchState(){return Object.freeze({vault:this.#U?.mode??"polling",...this.#Z.insula&&{insula:this.#G?.source.watchMode()??"polling"}})}#_(){this.#U?.close(),this.#U=void 0,this.#V?.(),this.#V=void 0}keptReceiptState(){return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return P3(this.#$)}refresh(){if(this.#K(),this.#J)return this.#J;return this.#J=(async()=>{if(!await this.#q()){this.#$=void 0,this.#W=void 0,this.#_(),this.#X?.close(),this.#X=void 0,this.#G?.release(),this.#G=void 0;return}let Z=await this.#M(),$,z=await C3({path:this.#Z.rosterPath,custody:Z,onInventory:(Y)=>{$=Y},isActive:()=>this.#q(),signal:this.#z.signal,projection:()=>({reservedRouteIds:new Set(this.#Z.reservedRouteIds?.()??[]),routePrefix:this.#Z.routePrefix,mapAccount:this.#Z.mapAccount,now:(this.#Z.now??Date.now)()})});this.#K();let X=z?.view!==this.#$?.view;if(this.#$=h(this.#Z.rosterPath,z),Z.retain(z?.rows??[]),$&&z?.view!==void 0)this.#W=$.grantReach?{view:z.view,reach:$.grantReach}:void 0;if(z&&X)this.#Z.onRoster?.(z);return this.#j=(this.#Z.now??Date.now)(),z})().finally(()=>{this.#J=void 0}),this.#J}start(){if(this.#B)return;this.#K(),this.#B=!0;let Z=async()=>{try{if(await this.#P())await this.refresh();await this.refreshInsulaQuota(),this.#L()}catch(z){if(!this.#z.signal.aborted)this.#Z.onError?.(z)}if(this.#z.signal.aborted)return;let $=this.#Z.pollIntervalMs??5000;if($<=0)return;this.#Q=(this.#Z.setTimeoutImpl??setTimeout)(()=>{this.#Q=void 0,Z()},$),this.#Q.unref?.()};Z()}async#P(){if(this.#U?.mode!=="watching")return!0;let Z=(this.#Z.now??Date.now)();if(this.#j===void 0||Z-this.#j>=$3)return!0;return!await this.#q()}#L(){let Z=this.#X;if(this.#z.signal.aborted||!Z)return;if(this.#U??=Z.watchRoster({view:()=>this.#$?.view,onView:async()=>{while(this.#J)await this.#J.catch(()=>{});await this.refresh()},onRefused:($)=>this.#Z.onError?.($),onError:($)=>{if(!this.#z.signal.aborted)this.#Z.onError?.($)}}),this.#Z.insula&&this.#G&&!this.#V)this.#V=this.#G.source.watch({provider:this.#Z.insula.provider,setTimeoutImpl:this.#Z.setTimeoutImpl,clearTimeoutImpl:this.#Z.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#Z.insula||this.#z.signal.aborted||!await this.#q())return;try{await o(this.#Z.tokenPath),await this.#M(),await this.#G?.source.refresh((this.#Z.now??Date.now)())}catch{}}async cachedInsulaQuota(Z){if(!this.#Z.insula||this.#z.signal.aborted||!await this.#q())return;try{return await o(this.#Z.tokenPath),this.#R(Z.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute(Z){if(!this.#Z.insula||this.#z.signal.aborted||!await this.#q())return;try{await o(this.#Z.tokenPath);let z=h(this.#Z.rosterPath,await b(this.#Z.rosterPath))?.rows.find((X)=>X.routeId===Z);return this.#R(z?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute(Z){let $=this.#Z.insula;if(!$||this.#z.signal.aborted||!await this.#q())return{miss:"unreachable"};try{await o(this.#Z.tokenPath);let X=h(this.#Z.rosterPath,await b(this.#Z.rosterPath))?.rows.find((J)=>J.routeId===Z)?.accountIdentity;if(!X||!this.#G)return{miss:"unreachable"};let Y=this.#G.source.lookup($.provider,X,(this.#Z.now??Date.now)()),G=Y.reading&&$.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute(Z,$){let z=await this.lookupInsulaQuotaForRoute(Z);if(z.miss==="cold"||z.miss==="upstream-failed"){if(this.#D.get(Z)!==z.miss)this.#D.set(Z,z.miss),this.#Y.warn("skipped insula provider poll",{reason:z.miss});return}return this.#D.delete(Z),z.miss?$():z.reading}#R(Z){if(!this.#Z.insula||!Z)return;let $=this.#G?.source.current(this.#Z.insula.provider,Z,(this.#Z.now??Date.now)());return $?this.#Z.insula.normalize($.entry,$.context):void 0}async authorize(Z,$){this.#K($);let z=this.#$??await this.#N(this.refresh(),$);if(!z||!await this.#q())throw this.#X?.close(),this.#X=void 0,this.#_(),this.#G?.release(),this.#G=void 0,new F("not-active","Claustrum scoped custody is not active");let X=h(this.#Z.rosterPath,await b(this.#Z.rosterPath));this.#K($);let Y=z.rows.find((H)=>H.routeId===Z),G=X?.rows.find((H)=>H.routeId===Z);if(G&&!G.enabled){if(Y)this.#X?.forget(Y.credentialId);throw new F("route-declined","Claustrum route is disabled")}if(!Y||!G||G.state!=="active"||G.credentialId!==Y.credentialId||G.accountIdentity!==Y.accountIdentity||G.credentialType!==Y.credentialType){if(Y)this.#X?.forget(Y.credentialId);throw new F("route-unavailable","Claustrum route is disabled, removed or changed")}let J=await this.#N(this.#M(),$),B=G3([this.#z.signal,...$?[$]:[]]);try{return await J.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},B.signal,Z)}finally{B.dispose()}}async reportFailure(Z,$,z){if(this.#K(),!this.#X)throw new F("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure(Z,$,z)}async send(Z,$,z){let X=z.signal,Y=await this.authorize(Z,X),G=await $(Y,X);if(G.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,z.reporterSource??"direct"),G;if(G.status===401&&!X?.aborted){let J;try{J=await this.authorize(Z,X),X?.throwIfAborted()}catch(B){if(X?.aborted)throw B}if(N3(z.site,Y,J,this.#Y))await G.body?.cancel().catch(()=>{}),Y=J,G=await $(J,X)}if(G.status===401)await this.reportFailure(Y,401,z.reporterSource??"direct").catch((J)=>this.#Z.onError?.(J)),Promise.resolve().then(()=>this.refresh()).catch((J)=>{if(!this.#z.signal.aborted)this.#Z.onError?.(J)});return G}async decline(Z){this.#K(),await L3(this.#Z.rosterPath,Z),this.#$=h(this.#Z.rosterPath,await b(this.#Z.rosterPath)),this.#X?.retain(this.#$?.rows??[])}async accept(Z){this.#K(),await R3(this.#Z.rosterPath,Z),this.#$=h(this.#Z.rosterPath,await b(this.#Z.rosterPath))}async reorder(Z){this.#K();let $=await S3(this.#Z.rosterPath,Z);return this.#$=h(this.#Z.rosterPath,await b(this.#Z.rosterPath)),$}async recordQuota(Z,$,z){return this.#K(),x3(this.#Z.rosterPath,{routeId:Z,observation:$,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.#K(),T3(this.#Z.rosterPath,{routeId:Z,accountIdentity:$,observation:z})}close(){if(this.#z.signal.aborted)return;if(this.#z.abort(new F("closed","Claustrum consumer is closed")),this.#Q)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0,this.#_(),this.#X?.close(),this.#G?.release(),this.#G=void 0,this.#$=void 0,this.#W=void 0,this.#F(),E3(this.#Z.rosterPath)}async dispose(){this.close(),await this.#F()}}async function P7(Z){let $=await t9.connect(Z);return Object.assign($,{insula:k4(Z)})}var L6=D0("openai");function R6(Z){return V0(Z)}function FZ(Z){if(!Z||Z.corrupt===!0)return!1;return R6(Z.refresh)}class hZ 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 q0(Z){if(R6(Z))throw new hZ}var e9=I("quota"),b3="primary",f3="secondary",Z$="app_EMoamEEZ73f0CkXaXp7hrann",$$="https://auth.openai.com";async function c7(Z){q0(Z.refreshToken);let $=await Z.fetchImpl(`${$$}/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:Z.refreshToken,client_id:Z$}).toString()});if(!$.ok){let Y=r0($.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${$.status}`),{status:$.status,retryAfter:Y,isRefreshError:!0})}let z=await $.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:$.status,isRefreshError:!0});if(z.refresh_token!==void 0&&typeof z.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});let X=typeof z.refresh_token==="string"&&z.refresh_token?z.refresh_token:Z.refreshToken;return{access:z.access_token,refresh:X,expires:Z.now()+z.expires_in*1000,expiresIn:z.expires_in}}var z$="https://chatgpt.com/backend-api/wham/usage";async function u7(Z){let $=Z.logger??e9,z=Z.accountKey??"unknown",X=Date.now();$.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await Z.fetchImpl(z$,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${Z.accessToken}`,"chatgpt-account-id":Z.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Y.ok){let J=r0(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:J})}let G=A4(await Y.json());return $.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:Y.status,elapsedMs:Date.now()-X}),G}catch(Y){throw $.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof Y?.status==="number"?Y.status:"error",elapsedMs:Date.now()-X,error:S6(Y)}),Y}}import{createHash as X$}from"node:crypto";var Y$=globalThis.setTimeout,G$=5;function wZ(Z){let $=Z?.quota?.checkIntervalMinutes??G$;return Math.max(1,$)*60000}function J$(Z){return Z?.quota?.enabled!==!1}function N0(Z,$){if(!Z?.resetsAt)return!1;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z<=$}function t7(Z,$,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=$===b3?Z?.primary:$===f3?Z?.secondary:void 0,J=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(J)&&J>z)return J;return z+X}function B$(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??15,secondary:$.secondary??$["1w"]??10}}function x6(Z,$,z){if(!J$($))return z+wZ($);let X=B$($),Y=[];for(let G of["primary","secondary"]){let J=Z?.[G];if(!J)continue;if(J.remainingPercent>=X[G])continue;let B=J.resetsAt?Date.parse(J.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=z)return z+wZ($);Y.push(B)}if(!Y.length)return z+wZ($);return Math.min(...Y)+60000}function H$(Z){if(!Z?.quota?.mainQuota||!Z.quota.mainQuotaCheckedAt)return null;return{quota:Z.quota.mainQuota,checkedAt:Z.quota.mainQuotaCheckedAt,tokenFingerprint:Z.quota.mainQuotaToken}}function K$(Z){let $=Z?.quota?.refreshEveryNRequests;return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):0}function f(Z){return X$("sha256").update(Z).digest("hex").slice(0,16)}class e{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(Z){this.storage=Z.storage,this.fetchImpl=Z.fetchImpl??fetch,this.configPath=Z.configPath,this.now=Z.now??Date.now,this.fetchQuotaFn=Z.fetchQuotaFn,this.onMainQuotaFetched=Z.onMainQuotaFetched,this.onApiError=Z.onApiError,this.seedMainFromStorage(Z.storage),this.seedMainBackoffFromStorage(Z.storage)}getMain(Z){if(Z&&this.main&&this.mainTokenFp&&this.mainTokenFp!==f(Z))this.main=null,this.mainTokenFp=null;return this.main}getFallback(Z,$){let z=this.fallbacks.get(Z)??null;if(!$||!z)return z;if(this.fallbackTokenFps.get(Z)!==f($))return this.fallbacks.delete(Z),this.fallbackTokenFps.delete(Z),null;return z}getAllFallbacks(){return this.fallbacks}setMain(Z,$,z,X=!1){if(!X&&!T6($.quota))return;if(this.mainTokenFp=f(Z),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=$,k3($.quota))this.clearRateLimited("main")}peekMainForPolicy(Z){if(Z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z)return null;return this.main}peekFallbackForPolicy(Z,$){let z=this.fallbacks.get(Z)??null;if($&&z?.accountId&&z.accountId!==$)return null;return z}setFallback(Z,$,z,X=!1,Y){if(!X&&!T6($.quota))return;let G=this.fallbacks.get(Z)?.accountId;if(Y&&G&&Y!==G)this.clearRateLimited(Z);let J=Y??G;if(this.fallbacks.set(Z,{...$,accountId:J}),z)this.fallbackTokenFps.set(Z,f(z));else this.fallbackTokenFps.delete(Z);if(k3($.quota))this.clearRateLimited(Z)}markRateLimited(Z,$){let z=this.rateLimitedUntilMap.get(Z);if(z!==void 0&&z>$)return;this.rateLimitedUntilMap.set(Z,$)}isRateLimited(Z){let $=this.rateLimitedUntilMap.get(Z);return $!==void 0&&this.now()<$}rateLimitedUntil(Z){return this.rateLimitedUntilMap.get(Z)}clearRateLimited(Z){this.rateLimitedUntilMap.delete(Z)}async refreshMain(Z){let $=f(Z);if(this.mainTokenFp&&this.mainTokenFp!==$)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===$)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=$,this.inflightMain=this._fetchMain(Z),this.inflightMain}async refreshFallback(Z,$){let z=e.fallbackInflightKey(Z,$),X=this.inflightFallbacks.get(z);if(X)return X;if(this.isFallbackBackedOff(Z,$)){let G=this.getFallback(Z,$);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let Y=this._fetchFallback(Z,$);return this.inflightFallbacks.set(z,Y),Y}async refreshAllFallbacks(Z){let $=this.now();for(let z of Z){if(z.enabled===!1)continue;if(FZ(z)||!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&$<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground(Z){let $=f(Z);if(this.inflightMain&&this.inflightMainFp===$)return;if(this.isBackedOff())return;this.refreshMain(Z).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(Z){let $=K$(this.storage);if($<=0)return!1;return Z>0&&Z%$===0}needsRefresh(Z){return this.isMainStale()||this.shouldRefreshOnRequestCount(Z)}updateStorage(Z){this.storage=Z,this.seedMainFromStorage(Z),this.seedMainBackoffFromStorage(Z)}seedMainFromStorage(Z,$){let z=H$(Z);if(!z)return;let X=$?f($):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:x6(z.quota,Z,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,Z?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=Z.mainAccountId}}seedMainBackoffFromStorage(Z){let $=Z?.quota?.mainLastQuotaApiError;this.mainLastApiError=$&&_Z($,this.now())?$:void 0}seedFallbacksFromAccounts(Z){let $=wZ(this.storage);for(let z of Z){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+$,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return _Z(this.mainLastApiError,this.now())}isFallbackBackedOff(Z,$){if($){if(this.fallbackErrorTokenFps.get(Z)!==f($))return!1}return _Z(this.fallbackApiErrors.get(Z),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(Z,$){return JSON.stringify([Z,f($)])}static quotaLockName(Z){return`opencode-fallback-quota-refresh-${Z.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(Z){let $=async()=>{let X=this.now()-this.lastApiCallAt;if(X<e.API_CALL_GAP_MS)await new Promise((Y)=>{let G=Y$(Y,e.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),Z()},z=this.apiGate.then($,$);return this.apiGate=z.catch(()=>{}),z}async _fetchMain(Z){let $=f(Z);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 A({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(Z),G=this.now();if(this.mainTokenFp=f(Z),this.main={quota:Y,refreshAfter:x6(Y,this.storage,G),checkedAt:G},k3(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,G,this.mainTokenFp,X),Y}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===$)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 A({name:e.quotaLockName(Z),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($),Y=this.now();return this.setFallback(Z,{quota:X,refreshAfter:Y+wZ(this.storage),checkedAt:Y},$,!0),this.fallbackApiErrors.delete(Z),this.fallbackErrorTokenFps.delete(Z),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError(Z,$,z),z}finally{this.inflightFallbacks.delete(e.fallbackInflightKey(Z,$))}})}async _fetchQuota(Z){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(Z){return Z?.status===401}_handleMainFetchError(Z){if(e.isAuthError(Z))return;this.mainLastApiError=EZ({error:Z,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(Z,$,z){if(e.isAuthError(z))return;let X=f($),Y=this.fallbackErrorTokenFps.get(Z)===X?this.fallbackApiErrors.get(Z):void 0;this.fallbackApiErrors.set(Z,EZ({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set(Z,X)}}function T6(Z){return Boolean(Z.primary||Z.secondary)}function k3(Z){let{primary:$,secondary:z}=Z;if(!$&&!z)return!1;if($&&$.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{createHash as W$,randomUUID as Q$}from"node:crypto";import{setTimeout as U$}from"node:timers/promises";import{readFile as S$}from"node:fs/promises";var jZ=I("refresh"),O0=I("accounts"),D$=1e4,V$=15000,y3=50;function v(Z){return Z.type==="oauth"&&Z.corrupt!==!0}function F$(Z){let $=Z?.trim();if(!$)return!1;try{let z=new URL($);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}var j$="floors-v1";function D5(Z){return Z.costZeroing?.enabled!==!1}class _0 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(Z){super(`Fallback account ${Z} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var q$=[401,403,429],E6={primary:0,secondary:0},N$=!1,w3={primary:5,secondary:10};function j(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var M$=new Set(["__proto__","constructor","prototype"]);function O$(Z){return Z.length>0&&!M$.has(Z)}function _$(Z){return Z instanceof _0||j(Z)&&Z.name==="AccountRemovedDuringRefreshError"&&Z.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function M0(Z){return{id:typeof Z.id==="string"&&Z.id.trim()?Z.id.trim():Q$(),label:typeof Z.label==="string"?Z.label:void 0,enabled:typeof Z.enabled==="boolean"?Z.enabled:void 0,addedAt:typeof Z.addedAt==="number"?Z.addedAt:void 0,lastUsed:typeof Z.lastUsed==="number"?Z.lastUsed:void 0,accountId:typeof Z.accountId==="string"?Z.accountId:void 0}}function C6(Z){if(!j(Z))return;if(typeof Z.message!=="string")return;let $=Number(Z.checkedAt);if(!Number.isFinite($))return;let z=Number(Z.nextRetryAt),X=Number(Z.retryCount);return{message:Z.message,checkedAt:$,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof Z.tokenHash==="string"?Z.tokenHash:void 0}}function P$(Z){if(!j(Z))return;let $={};for(let Y of["primary","secondary"]){let G=Z[Y];if(!j(G))continue;let J=Number(G.usedPercent),B=Number(G.remainingPercent),H=Number(G.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(B)||!Number.isFinite(H))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;$[Y]={usedPercent:J,remainingPercent:B,checkedAt:H,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof Z[Y]==="number"?Z[Y]:Number.NaN;if(Number.isFinite(G)&&G>=0)$[Y]=G}let z=Z.spendControl;if(j(z)){let Y=Number(z.limit),G=Number(z.used),J=Number(z.remaining),B=Number(z.usedPercent),H=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof z.reached==="boolean")$.spendControl={limit:Y,used:G,remaining:J,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=Z.credits;if(j(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&(X.overageLimitReached===void 0||typeof X.overageLimitReached==="boolean")){let Y=Number(X.balance),G=typeof X.checkedAt==="number"?X.checkedAt:Number.NaN;$.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,...typeof X.overageLimitReached==="boolean"?{overageLimitReached:X.overageLimitReached}:{},...Number.isFinite(Y)?{balance:Y}:{},...Number.isFinite(G)?{checkedAt:G}:{}}}return Object.keys($).length?$:void 0}function L$(Z){if(!j(Z))return null;if(Z.type==="api"){let $=typeof Z.baseURL==="string"?Z.baseURL.trim():"",z=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!F$($))return null;let X=Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...M0(Z),type:"api",apiKey:z||void 0,baseURL:$,authHeader:X}}if(Z.type!=="oauth")return null;if(Z.corrupt===!0){if(typeof Z.id!=="string"||!Z.id.trim())return null;return{...M0(Z),type:"oauth",corrupt:!0}}if(typeof Z.refresh!=="string"||!Z.refresh.trim()){if(!Object.hasOwn(Z,"refresh")||typeof Z.id!=="string"||!Z.id.trim())return null;return{...M0(Z),type:"oauth",corrupt:!0}}return{...M0(Z),type:"oauth",access:typeof Z.access==="string"?Z.access:void 0,refresh:Z.refresh,expires:typeof Z.expires==="number"?Z.expires:void 0,lastRefreshedAt:typeof Z.lastRefreshedAt==="number"?Z.lastRefreshedAt:void 0,lastRefreshError:C6(Z.lastRefreshError),lastQuotaRefreshError:C6(Z.lastQuotaRefreshError),quota:P$(Z.quota)}}function R$(Z){if(!j(Z))return;let $=Object.create(null);for(let[z,X]of Object.entries(Z)){if(!O$(z)||!j(X))continue;let Y={};if(j(X.inFlight))Y.inFlight={...X.inFlight};if(j(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,...j(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]=Y}return Object.keys($).length>0?$:void 0}var A6=new Set;function w6(Z){if(Z.length===0)return;let $=JSON.stringify([...Z].sort());if(A6.has($))return;A6.add($),O0.warn("account load-dropped, preserved on disk",{droppedIds:Z})}function m6(Z){if(!j(Z)||!Array.isArray(Z.accounts))return null;let $=Z.accounts,z=$.map(L$).filter((X)=>X!=null);if(z.length<$.length){let X=new Set;for(let J of $)if(j(J)&&typeof J.id==="string"&&J.id.trim())X.add(J.id.trim());let Y=new Set(z.map((J)=>J.id)),G=[];for(let J of X)if(!Y.has(J))G.push(J);w6(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:j(Z.routing)?Z.routing:void 0,fallbackOn:Array.isArray(Z.fallbackOn)?Z.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:j(Z.refresh)?Z.refresh:void 0,quota:j(Z.quota)?Z.quota:void 0,reset:R$(Z.reset),dump:j(Z.dump)?Z.dump:void 0,costZeroing:j(Z.costZeroing)?Z.costZeroing:void 0,killswitch:j(Z.killswitch)?Z.killswitch:void 0,logging:j(Z.logging)?Z.logging:void 0,cachekeep:j(Z.cachekeep)?Z.cachekeep:void 0,cacheKeep:j(Z.cacheKeep)?Z.cacheKeep:void 0,mainAccountId:typeof Z.mainAccountId==="string"?Z.mainAccountId:void 0,accounts:z}}function g6(Z){if(!("claustrum"in Z))return Z;let{claustrum:$,...z}=Z;return z}async function ZZ(Z){try{return{exists:!0,value:JSON.parse(await S$(Z,"utf8"))}}catch($){if($.code==="ENOENT")return{exists:!1,value:null};throw $}}function $Z(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}async function x$(Z){let $;try{$=(await ZZ(Z)).value}catch{return null}return p3($)}function v6(Z,$){if(!j(Z))return Z;let z=j($)?$:{},X=j(z.main)?z.main:void 0,Y=j(z.accounts)?z.accounts:{},G=j(Z.quota)?Z.quota:{},J=j(Z.refresh)?Z.refresh:{},B=X??G,H=X??J,K=J.mainRefreshLeaseId!==void 0?{id:J.mainRefreshLeaseId,until:J.mainRefreshLeaseUntil,tokenHash:J.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray(Z.accounts)?Z.accounts.map((q)=>{if(!j(q))return q;let D=typeof q.id==="string"&&j(Y[q.id])?Y[q.id]:{};return{...q,...D}}):void 0;return p6({...Z,refresh:$Z({...J,mainLastRefreshError:J.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:K.id,mainRefreshLeaseUntil:K.until,mainRefreshLeaseTokenHash:K.tokenHash}),quota:$Z({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:U})}async function T$(Z){let $=await ZZ(Z.configPath);if(!$.exists)return null;let z=await ZZ(Z.statePath);return m6(v6($.value,z.value))}function p6(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}function E$(Z){return $Z({id:Z.id,label:Z.label,type:Z.type,corrupt:Z.type==="oauth"&&Z.corrupt===!0?!0:void 0,enabled:Z.enabled,addedAt:Z.addedAt,accountId:Z.accountId,baseURL:Z.type==="api"?Z.baseURL:void 0,authHeader:Z.type==="api"?Z.authHeader:void 0})}function l6(Z){if(Z.type==="api")return $Z({apiKey:Z.apiKey,lastUsed:Z.lastUsed});if(Z.corrupt)return{};return $Z({access:Z.access,refresh:Z.refresh,expires:Z.expires,lastUsed:Z.lastUsed,lastRefreshedAt:Z.lastRefreshedAt,lastRefreshError:Z.lastRefreshError,lastQuotaRefreshError:Z.lastQuotaRefreshError,quota:Z.quota})}function P0(Z){return Math.max(Z?.primary?.checkedAt??0,Z?.secondary?.checkedAt??0)}function mZ(Z,$,z){if(z in $)Z[z]=$[z];else delete Z[z]}function C$(Z,$){return Z.access===$.access&&Z.refresh===$.refresh&&Z.expires===$.expires&&Z.lastRefreshedAt===$.lastRefreshedAt}function A$(Z,$){if(!C$(Z,$))return $;if(!("lastRefreshError"in $))return Z;if(!("lastRefreshError"in Z))return $;return($.lastRefreshError?.checkedAt??0)>(Z.lastRefreshError?.checkedAt??0)?$:Z}var I$=300000;function I6(Z,$){if(Z===void 0)return 0;return Z>$+I$?0:Z}function b$(Z,$,z){let X=Date.now(),Y=I6($.lastRefreshedAt,X),G=I6(z.lastRefreshedAt,X),J=$.expires??0,B=z.expires??0,H=G>Y?z:Y>G?$:B>J?z:J>B?$:A$($,z);mZ(Z,H,"access"),mZ(Z,H,"refresh"),mZ(Z,H,"expires"),mZ(Z,H,"lastRefreshedAt"),mZ(Z,H,"lastRefreshError")}function f$(Z,$){if(!j(Z))return $;let z=Z,X=P0(z.quota),Y=P0($.quota),G=X>Y,J=G?{...z,...$,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...$};if(!G&&!("lastQuotaRefreshError"in $))delete J.lastQuotaRefreshError;if(!("lastRefreshError"in $))delete J.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof $.lastUsed!=="number"||z.lastUsed>$.lastUsed))J.lastUsed=z.lastUsed;return b$(J,z,$),J}function d6(Z){let $=Z.refresh?$Z({enabled:Z.refresh.enabled,refreshBeforeExpiryMinutes:Z.refresh.refreshBeforeExpiryMinutes}):void 0,z=Z.quota?$Z({enabled:Z.quota.enabled,checkIntervalMinutes:Z.quota.checkIntervalMinutes,refreshEveryNRequests:Z.quota.refreshEveryNRequests,minimumRemaining:Z.quota.minimumRemaining,failClosedOnUnknownQuota:Z.quota.failClosedOnUnknownQuota}):void 0;return p6({version:1,main:Z.main,routing:Z.routing,fallbackOn:Z.fallbackOn,refresh:$,quota:z,reset:Z.reset,dump:Z.dump,costZeroing:Z.costZeroing,killswitch:Z.killswitch,logging:Z.logging,cachekeep:Z.cachekeep,cacheKeep:Z.cacheKeep,mainAccountId:Z.mainAccountId,accounts:Z.accounts.map(E$)})}async function pZ(Z,$=!1){let z=Date.now(),X=z+V$,Y=0;while(Date.now()<=X){Y++;let B=await A({name:"save",ttlMs:D$,path:Z,renew:$});if(B)return B;let H=X-Date.now();if(H<=0)break;await U$(Math.min(y3+n6(y3),H))}let G=Date.now()-z,J=Math.round(G/Math.max(1,Y));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${Z} (${Y} attempts, ~${J}ms apart; retry interval is ${y3}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 c6(Z){let $=Object.fromEntries(Z.accounts.map((z)=>[z.id,l6(z)]));return{version:1,main:$Z({quota:Z.quota?.mainQuota,quotaCheckedAt:Z.quota?.mainQuotaCheckedAt,quotaToken:Z.quota?.mainQuotaToken,lastQuotaApiError:Z.quota?.mainLastQuotaApiError,lastRefreshError:Z.refresh?.mainLastRefreshError,refreshLeaseId:Z.refresh?.mainRefreshLeaseId,refreshLeaseUntil:Z.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:Z.refresh?.mainRefreshLeaseTokenHash}),accounts:$}}function p3(Z){if(!j(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let z of Z.accounts){if(!j(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;$.add(X)}return $}function k$(Z,$,z,X){if(!j(Z)||!Array.isArray(Z.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],G=[];for(let J of $){if(z.has(J))continue;if(X.has(J))continue;let B=Z.accounts.find((H)=>j(H)&&typeof H.id==="string"&&H.id.trim()===J);if(!B)continue;Y.push(B),G.push(J)}return{preservedRawEntries:Y,preservedIds:G}}function y$(Z){if(!Array.isArray(Z))return[];let $=[];for(let z of Z){if(!j(z))continue;if(typeof z.id!=="string")continue;$.push(z.id)}return $}function h$(Z,$,z){let X=p3(Z);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=k$(Z,X,$,z);return w6(G),Y}async function F5(Z,$,z={}){let{configPath:X,statePath:Y}=$,G=await pZ(X);try{let J=await pZ(Y);try{let B=await ZZ(X),H=await ZZ(Y),Q=(B.exists?m6(v6(B.value,H.value)):null)??w$(),K=new Set(Q.accounts.map((V)=>V.id)),W=p3(B.value)??new Set,U=Z(Q,{rawRosterIds:[...W],loadedRosterIds:[...K]})??Q,q=new Set(z.allowDrop??[]),D=h$(B.value,K,q),M=d6(U),N=new Set((Array.isArray(M.accounts)?M.accounts:[]).map((V)=>j(V)&&typeof V.id==="string"?V.id.trim():"").filter(Boolean)),L=D.filter((V)=>{if(!j(V))return!1;if(typeof V.id!=="string")return!1;return!N.has(V.id.trim())}),T=j(B.value)?B.value:{},p={...g6(T),...M,accounts:[...Array.isArray(M.accounts)?M.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return Q;if(await m(X,p),z.canWrite&&!z.canWrite())return Q;return await m(Y,c6(U)),O0.debug("account config written",{accountCount:p.accounts.length,accountIds:y$(p.accounts)}),U}finally{await J.release()}}finally{await G.release()}}function w$(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function m$(Z,$){Z.main=Z.main??{};let z=typeof Z.main.quotaCheckedAt==="number"?Z.main.quotaCheckedAt:P0(Z.main.quota),X=typeof $.quota?.mainQuotaCheckedAt==="number"?$.quota.mainQuotaCheckedAt:P0($.quota?.mainQuota);if(z>X)return;Z.main.quota=$.quota?.mainQuota,Z.main.quotaCheckedAt=$.quota?.mainQuotaCheckedAt,Z.main.quotaToken=$.quota?.mainQuotaToken,Z.main.lastQuotaApiError=$.quota?.mainLastQuotaApiError}function g$(Z,$){Z.main=Z.main??{},Z.main.lastRefreshError=$.refresh?.mainLastRefreshError,Z.main.refreshLeaseId=$.refresh?.mainRefreshLeaseId,Z.main.refreshLeaseUntil=$.refresh?.mainRefreshLeaseUntil,Z.main.refreshLeaseTokenHash=$.refresh?.mainRefreshLeaseTokenHash}function m3(Z){if(Array.isArray(Z))return Z.map(m3);if(!j(Z))return Z;return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0).map(([$,z])=>[$,m3(z)]))}async function v$(Z,$,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=$.statePath,G=await pZ(Y);try{let J=(await ZZ(Y)).value,B=j(J)?{...J,version:1}:{version:1};if(z.mainQuota)m$(B,Z);if(z.mainRefresh)g$(B,Z);if(z.accounts){let H=z.accounts===!0?null:new Set(z.accounts),Q=await x$($.configPath);B.accounts={...j(B.accounts)?B.accounts:{}};for(let K of Z.accounts){if(H&&!H.has(K.id))continue;if(Q&&!Q.has(K.id))continue;B.accounts[K.id]=f$(B.accounts[K.id],l6(K))}if(H){for(let K of H)if(!Z.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 m(Y,m3(B))}finally{await G.release()}}function p$(Z){return Z?.fallbackOn?.length?Z.fallbackOn:q$}function j5(Z,$){return p$($).includes(Z)}function l$(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??E6.primary,secondary:$.secondary??$["1w"]??E6.secondary}}function g3(Z){return Z?.quota?.enabled!==!1}function lZ(Z){return Z?.quota?.failClosedOnUnknownQuota??N$}function u6(Z,$,z=Date.now()){if(!g3($))return!0;if(!Z)return!lZ($);let X=l$($),Y=lZ($);for(let G of["primary","secondary"]){let J=Z[G];if(!J)continue;if(N0(J,z)){if(Y)return!1;continue}if(J.remainingPercent<X[G])return!1}return!0}function L0(Z){return Z?.killswitch?.enabled===!0}function b6(Z){return{primary:Z?.primary??Z?.["5h"]??w3.primary,secondary:Z?.secondary??Z?.["1w"]??w3.secondary}}function q5(Z){return Z?.cacheKeep??Z?.cachekeep}function f6(Z){return typeof Z==="number"&&Number.isFinite(Z)?Z:0}function i6(Z,$){if(!Z?.killswitch)return w3;if(Z.killswitch.schema===j$){let{accounts:z,defaults:X}=Z.killswitch,Y=$??"main",G=j(z)&&Object.hasOwn(z,Y)&&j(z[Y])?z[Y]:j(X)?X:void 0;return{primary:f6(G?.primary),secondary:f6(G?.secondary)}}if($&&Z.killswitch.accounts?.[$])return b6(Z.killswitch.accounts[$]);return b6(Z.killswitch.main)}function s6(Z,$,z,X=Date.now()){if(!L0($))return!0;if(!Z)return!lZ($);let Y=i6($,z),G=lZ($);for(let J of["primary","secondary"]){let B=Z[J];if(!B)continue;if(N0(B,X)){if(G)return!1;continue}if(B.remainingPercent<Y[J])return!1}return!0}function N5(Z,$,z,X){if(!L0(X))return 300;let Y=[],G=[{accountId:void 0,quota:Z},...$];for(let{accountId:B,quota:H}of G){if(!H)continue;let Q=i6(X,B),K=[],W=!1;for(let U of["primary","secondary"]){let q=H[U];if(!q||N0(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 J=Math.min(...Y);return Math.max(1,Math.ceil((J-z)/1000))}function k6(Z){return typeof Z.version==="number"&&Array.isArray(Z.accounts)}async function M5(Z,$){let{configPath:z,statePath:X}=$;if(!Z)return;try{let G=await ZZ(z);if(G.exists&&j(G.value)&&k6(G.value))return}catch{}let Y=await pZ(z);try{let G=await pZ(X);try{let J=await ZZ(z);if(J.exists&&j(J.value)){if(k6(J.value))return}if(!Z)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(Z.access){let K=eZ({id_token:"",access_token:Z.access,refresh_token:Z.refresh});if(K)B.mainAccountId=K}let H=J.exists&&j(J.value)?J.value:{},Q={...g6(H),...d6(B)};await m(z,Q),await m(X,c6(B))}finally{await G.release()}}finally{await Y.release()}}function d$(Z){return Z?.refresh?.enabled!==!1}function c$(Z){return(Z?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function n6(Z){return Math.floor(Math.random()*(Z+1))}function qZ(Z,$,z){return!Z.access||!Z.expires||Z.expires-z<=c$($)}function u$(Z,$){return Boolean(Z.access&&typeof Z.expires==="number"&&Z.expires>$)}function gZ(Z,$){return Boolean(Z?.mainAccountId&&$.accountId&&$.accountId===Z.mainAccountId)}class a6 extends Error{constructor(Z){super(`Refusing to refresh account ${Z}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}var i$="common-auth-placeholder:v1:openai",o6="main";function O5(Z){return j(Z)&&Z.type==="oauth"&&(Z.refresh===i$||Z.refresh===L6)}function _5(Z){return Z?.accounts.find(($)=>$.id===o6&&$.enabled!==!1&&v($))}function P5(Z){if(!Z)return Z;return{...Z,accounts:Z.accounts.filter(($)=>$.id!==o6)}}function x(Z,$){let z=Z.accounts.findIndex((X)=>X.id===$.id);if(z!==-1)Z.accounts[z]=$}function vZ(Z){return Z instanceof Error?Z.message:String(Z)}function v3(Z,$,z){if($ instanceof hZ)return;Z.lastRefreshError=V4({error:$,now:z,refreshToken:Z.refresh,previous:Z.lastRefreshError})}function h3(Z,$,z){if($ instanceof hZ)return;if(Z.lastQuotaRefreshError=EZ({error:$,now:z,previous:Z.lastQuotaRefreshError}),$?.isRefreshError===!0)v3(Z,$,z)}function y6(Z,$){if(!Z)return!1;if(!Z.resetsAt)return!0;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)?z>$:!0}function s$(Z,$){if(!Z)return!1;return y6(Z.primary,$)||y6(Z.secondary,$)}function n$(Z,$,z){if(!Z)return!1;let X=$?.quota?.checkIntervalMinutes??5,Y=Math.max(1,X)*60000,G=Math.max(Z.primary?.checkedAt??0,Z.secondary?.checkedAt??0);return z-G<Y}function h6(Z,$,z){return!n$(Z.quota,$,z)}function a$(Z,$,z,X){return o0(z)&&u6(Z.quota,$,X)&&s$(Z.quota,X)}function o$(Z){let $=Z?.quota?.checkIntervalMinutes??5;return Math.max(1,$)*60000}var r$=60000,t$=60000,e$=600000;function Z1(Z){return`fallback-oauth-refresh-${W$("sha256").update(Z).digest("base64url").slice(0,16)}`}var $1=1e4,z1=100;class X1{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(Z){this.options=Z,this.now=Z.now??Date.now,this.fetchImpl=Z.fetchImpl??fetch,this.paths=Z.paths,this.quotaManager=Z.quotaManager??null,this.onFallbackStorageChanged=Z.onFallbackStorageChanged}assertNotTombstoned(Z){if(Z)q0(Z.refresh)}seedFallbackQuota(Z,$){if(!this.quotaManager)return;if(!Z.quota)return;let z=Math.max(Z.quota.primary?.checkedAt??0,Z.quota.secondary?.checkedAt??0);if(z<=0)return;let X=this.quotaManager.getFallback(Z.id,Z.access);if(X&&X.checkedAt>=z)return;this.quotaManager.setFallback(Z.id,{quota:Z.quota,refreshAfter:z+o$($),checkedAt:z},Z.access,!1,Z.accountId)}async load(){return T$(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save(Z,$){await v$(Z,this.paths,{accounts:$??!0},this.options.canWrite)}startBackgroundRefresh(){let Z=async()=>{if(await this.options.backgroundRefreshPaused?.())return;if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(Z().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{Z().catch(()=>{})},r$+n6(t$)),"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(Z){let $=Z!==void 0?Z:await this.load();if(!$)return[];let z=[],X=!1;for(let Y of $.accounts){if(Y.enabled===!1||!v(Y))continue;if(gZ($,Y))continue;if(FZ(Y))continue;let G=!1,J=Y;try{if(qZ(J,$,this.now())){let B=J.lastRefreshError;if(B&&JZ(B,J.refresh,this.now()))throw G=!0,Error(rZ(B,this.now()));try{J=await this.refreshAccount(J,$),X=!0}catch(H){if(_$(H))continue;G=!0;let Q=$.accounts.find((K)=>K.id===Y.id&&v(K));if(Q&&!JZ(Q.lastRefreshError,Q.refresh,this.now()))v3(Q,H,this.now()),x($,Q),X=!0;throw H}}if(this.seedFallbackQuota(J,$),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),$))z.push(J)}catch(B){let H=u$(J,this.now());if(G){if(!H)continue}else if(!H)continue;if(a$(J,$,B,this.now()))jZ.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:vZ(B)}),z.push(J);else if(!lZ($))z.push(J)}}if(X){let Y=structuredClone($);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{O0.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:vZ(G)})})}return z}async markUsed(Z){try{let $=await this.load();if(!$)return;let z=$.accounts.find((X)=>X.id===Z.id);if(!z)return;z.lastUsed=this.now(),await this.save($,[z.id])}catch($){O0.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:Z.id,error:vZ($)})}}accountPassesQuotaPolicy(Z,$){return u6(Z.quota,$,this.now())}quotaPolicyAccount(Z){if(!this.quotaManager)return Z;let $=this.quotaManager.getFallback(Z.id,Z.access)?.quota;return $?{...Z,quota:$}:Z}async refreshDueAccounts(){let Z=await this.load();if(!Z||!d$(Z))return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!v(z))continue;if(gZ(Z,z))continue;if(FZ(z))continue;if(!qZ(z,Z,this.now()))continue;if(JZ(z.lastRefreshError,z.refresh,this.now()))continue;try{jZ.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){jZ.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:vZ(X)}),v3(z,X,this.now()),x(Z,z),$=!0}}if($)await this.save(Z)}async refreshQuotaForDueAccounts(){let Z=await this.load();if(!Z||!g3(Z))return;if(!this.options.fetchQuotaFn)return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!v(z))continue;if(gZ(Z,z))continue;if(FZ(z))continue;let X=z;try{if(qZ(X,Z,this.now())){if(JZ(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,Z),$=!0}if(_Z(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,Z),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):h6(X,Z,this.now())))continue;await this.refreshAccountQuota(X,Z),$=!0}catch(Y){h3(z,Y,this.now()),x(Z,z),$=!0}}if($)await this.save(Z),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(Z={}){let $=await this.load(),z=[];if(!$||!g3($))return{storage:$,errors:z};if(!this.options.fetchQuotaFn)return{storage:$,errors:z};let X=Z.force??!1,Y=!1;for(let G of $.accounts){if(G.enabled===!1||!v(G))continue;if(gZ($,G))continue;if(FZ(G))continue;let J=G;try{if(qZ(J,$,this.now())){let B=J.lastRefreshError;if(B&&JZ(B,J.refresh,this.now()))throw Error(rZ(B,this.now()));J=await this.refreshAccount(J,$),Y=!0}if(!X&&!h6(J,$,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,x($,J),Y=!0;continue}await this.refreshAccountQuota(J,$),Y=!0}catch(B){h3(G,B,this.now()),x($,G),Y=!0,z.push({accountId:G.id,message:vZ(B)})}}if(Y)await this.save($);return{storage:$,errors:z}}async refreshAccount(Z,$,z={}){let X=this.refreshPromises.get(Z.id);if(X){let J=await X;return x($,J),J}let Y=this.refreshAccountNow(Z,$,z).finally(()=>{this.refreshPromises.delete(Z.id)});this.refreshPromises.set(Z.id,Y);let G=await Y;return x($,G),G}async waitForConcurrentFallbackRefresh(Z,$,z,X){let Y=Date.now()+$1;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,z1));let G=await this.load(),J=G?.accounts.find((Q)=>Q.id===Z.id&&v(Q));if(!J)continue;if(this.assertNotTombstoned(J),(J.access!==z.access||J.refresh!==z.refresh||(J.expires??0)>(z.expires??0)+60000)&&(X.force||!qZ(J,G,this.now())))return x($,J),jZ.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let H=J.lastRefreshError;if(H&&JZ(H,J.refresh,this.now()))throw x($,J),Error(rZ(H,this.now()))}return null}assertNotShieldedMainRow(Z,$,z){if(z.asPoolMain||!$)return;if(gZ(Z,$))throw new a6($.id)}async refreshAccountNow(Z,$,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===Z.id&&v(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!qZ(Y,X,this.now()))return x($,Y),Y;let G=Y??Z,J=await A({name:Z1(G.id),ttlMs:e$,path:this.paths.configPath,renew:!0});if(!J){jZ.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let B=await this.waitForConcurrentFallbackRefresh(Z,$,G,z);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),Y=X?.accounts.find((K)=>K.id===Z.id&&v(K)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!qZ(Y,X,this.now()))return x($,Y),Y;if(!Y)throw new _0(Z.id);G=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});jZ.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:z.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let H=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=H.access,G.refresh=H.refresh,G.expires=H.expires,G.lastRefreshedAt=H.expires-H.expiresIn*1000,G.lastRefreshError=void 0,x($,G),await this.save($),!(await this.load())?.accounts.some((K)=>K.id===Z.id))throw new _0(Z.id);return jZ.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await J.release()}}async refreshAccountQuota(Z,$){let z=Z;if(this.assertNotTombstoned(z),!z.access)throw Error(`Fallback account ${Z.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let X=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(G)=>this.quotaManager?this.quotaManager.refreshFallback(z.id,G):X({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!z.access)throw Error(`Fallback account ${Z.id} has no access token`);let G=await Y(z.access);z.quota=G,z.lastQuotaRefreshError=void 0,x($,z),await this.save($)}catch(G){throw h3(Z,G,this.now()),x($,Z),G}}}var r6=["primary","secondary"];function R0(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function RZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function Y1(Z,$){if(!R0($))return;let z=$.usedPercent;if(!RZ(z)||z<0||z>100)return;return{label:Z,usedPercent:z,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...RZ($.windowMinutes)&&$.windowMinutes>0?{windowMinutes:$.windowMinutes}:{}}}function G1(Z){let $=Z.spendControl;if(R0($)&&typeof $.reached==="boolean"){let z=(X)=>RZ($[X])?{[X]:$[X]}:{};return{kind:"reading",reached:$.reached,...z("remainingPercent"),...z("usedPercent"),...z("limit"),...z("used"),...z("remaining"),...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...typeof $.unit==="string"?{unit:$.unit}:{}}}if(Z.spendControlCleared===!0)return{kind:"cleared"};return}function J1(Z,$){if(!R0(Z)||typeof Z.hasCredits!=="boolean"||typeof Z.unlimited!=="boolean")return;return{hasCredits:Z.hasCredits,unlimited:Z.unlimited,...RZ(Z.balance)&&Z.balance>=0?{balance:Z.balance}:{},...typeof Z.overageLimitReached==="boolean"?{overageLimitReached:Z.overageLimitReached}:{},checkedAt:$}}function S5(Z,$,z){if(!R0(Z)||!RZ($))return;let X=[],Y=[];for(let Q of r6){let K=Y1(Q,Z[Q]);if(K)X.push(K);else if(z)Y.push({label:Q})}let G=G1(Z),J=Z.resetCreditsAvailable,B=typeof J==="number"&&Number.isSafeInteger(J)&&J>=0?{resetCredits:{value:J,checkedAt:$}}:void 0,H=J1(Z.credits,$);if(X.length===0&&Y.length===0&&!G&&!B&&!H)return;return{checkedAt:$,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function t6(Z){if(!XZ(Z))return;let $=C(Z),z={};for(let X of r6){let Y=$.limits.find((J)=>J.label===X&&J.kind==="reading");if(!Y||!RZ(Y.usedPercent))continue;let G={usedPercent:Y.usedPercent,remainingPercent:100-Y.usedPercent,checkedAt:Y.checkedAt,...Y.resetsAt!==void 0?{resetsAt:Y.resetsAt}:{},...Y.windowMinutes!==void 0?{windowMinutes:Y.windowMinutes}:{}};z[X]=G}return z.primary||z.secondary?z:void 0}var Z8="main";function I5(Z){return Z.find(($)=>$.id.startsWith("vault:")&&$.credentialId==="chatgpt:openai")?.id??null}function b5(Z,$,z){let X=new Map;if(L0($))for(let Y of Z)X.set(Y.id,s6(t6(Y.quota),$,Y.id===Z8?void 0:Y.id,z));return X}var f5=5,B1=5000;function k5(Z){if(Z==="ordered")return"roster";return Z==="fallback-first"?"fallback-first":"main-first"}function y5(Z,$=B1){let z=Z.rows.filter((J)=>J.kind==="oauth"&&Z.killswitch.get(J.id)!==!1&&C(J.quota).limits.length===0);if(z.length===0)return;if(y({rows:Z.rows,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:()=>{}}).admitted.some((J)=>Z.killswitch.get(J.id)!==!1))return;let Y=[];if(y({rows:z,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:(J)=>{let B=Z.requestPull(J);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let G;return Promise.race([Promise.all(Y),new Promise((J)=>{G=setTimeout(J,$)})]).then(()=>{}).finally(()=>clearTimeout(G))}function S0(Z){return Z.reason==="exhausted"||Z.reason==="budget-spent"}function H1(Z,$){if(!w(Z))return!1;let z=Z;if(!($-z.checkedAt<=TZ))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function x0(Z,$,z){let X=(B)=>$.killswitch.get(B)!==!1,Y=new Set(z.admitted.filter((B)=>B.lastPath!==!0&&X(B.id)).map((B)=>B.id)),G=new Map(z.refused.map((B)=>[B.id,B])),J=Z.filter((B)=>{if(B.kind!=="oauth"||!X(B.id))return!1;if(G.get(B.id)?.reason!=="exhausted")return!1;let H=C(B.quota);if(GZ(H,$.now))return!1;return H1(H.credits,$.now)}).map((B)=>B.id);return{free:Y,credits:J}}function K1(Z,$=Z.rows){return y({rows:$,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:()=>{}})}class W1{#Z=new Set;served(Z,$,z){let X=K1(Z),Y=x0(Z.rows,Z,X),G=new Set(Y.credits);if(Y.free.has($)){this.#Z.clear();return}for(let J of[...this.#Z])if(!G.has(J))this.#Z.delete(J);if(!G.has($)||this.#Z.has($))return;this.#Z.add($),z?.info("serving requests on prepaid credits",{accountId:$,reason:"free quota used up"})}has(Z){return this.#Z.has(Z)}ids(){return new Set(this.#Z)}}function $8(Z,$,z){if(Z===void 0)return{reason:"no-credential"};if(z.get(Z)===!1)return{reason:"killswitch"};let X=$.excluded.find((G)=>G.id===Z);if(X?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:X.until};if(X)return{reason:"no-credential"};let Y=$.refused.find((G)=>G.id===Z);if(Y&&"resetAtMs"in Y)return{reason:"quota-exhausted",resetAtMs:Y.resetAtMs};if(Y)return{reason:"quota-unknown"};return{reason:"no-credential"}}function e6(Z,$,z){if($.refused.find((Y)=>!S0(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return $8(Z[0],$,z)}function h5(Z){let $=Z.replayable!==!1,z=Z.mainId===void 0?Z8:Z.mainId??"",X=$?Z.placement:"main-first",Y=v0({rows:Z.rows,placement:X,formerMainId:z,killswitch:Z.killswitch,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,now:Z.now,requestPull:Z.requestPull}),G=aZ(Z.rows.map((W)=>W.id),X,z),J=new Set(Y.admission.refused.filter((W)=>S0(W)&&Z.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=G.filter((W)=>J.has(W)),H=x0(Z.rows,Z,Y.admission),Q=Y.order.filter((W)=>H.free.has(W)),K=G.filter((W)=>H.credits.includes(W));if(!$){let W=G.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&&J.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:W?$8(z,Y.admission,Z.killswitch):e6(G,Y.admission,Z.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:e6(G,Y.admission,Z.killswitch)}}function w5(Z){let $=y({rows:Z.rows,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,now:Z.now,requestPull:Z.requestPull}),z=new Map;for(let X of Z.rows)z.set(X.id,C(X.quota));for(let X of $.admitted)if(X.projection)z.set(X.id,X.projection);return{projections:z,excluded:new Set($.excluded.map((X)=>X.id))}}function z8(Z,$,z){let X=z.exclude,Y=X?Z.rows.filter((J)=>!X.has(J.id)):Z.rows,G=new Map;for(let J of Y){let B=$.resetCredits(J.id);if(B!==void 0)G.set(J.id,B)}return u0({rows:Y,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:Z.requestPull,killswitch:Z.killswitch,requestBytes:$.requestBytes,...z.pendingBytes?{pendingBytes:z.pendingBytes}:{},rowReservePercent:(J)=>$.reservePercent(J.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}})}function m5(Z,$,z,X){let Y=z8(Z,$,{exclude:z,pendingBytes:X}),G=Z.rows.filter((K)=>!z.has(K.id)),J=x0(G,Z,Y.admission),B=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(B&&J.free.has(B.accountId))return B;let H=J.credits[0];if(H===void 0)return B;let Q=C(G.find((K)=>K.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function g5(Z,$,z){let X=Z.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},G=z8(Z,$,{pin:z}),J=x0(Z.rows,Z,G.admission),B=J.credits.includes(z),H=J.credits.some((W)=>W!==z);if(G.outcome==="dispatch"){let W=!J.free.has(G.accountId);if(G.pin.action==="assign"){if(W&&B)return{kind:"serve"};return Y}if(G.accountId!==z)return{kind:"detour"};if(W&&H)return Y;return{kind:"serve"}}let Q=G.admission.refused.find((W)=>W.id===z),K=X||Q!==void 0&&S0(Q);if(B)return{kind:"serve"};if(H)return K?Y:{kind:"detour"};if(!X&&Q&&S0(Q))return{kind:"last-path"};return{kind:"none"}}function v5(Z,$,z,X){let Y=Z.killswitch.get(z);return c0({quota:$.projections.get(z),now:Z.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as X8}from"node:os";import{join as Y8}from"node:path";var Q1=["error","warn","info","debug","trace"];function U1(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?Y8(X8(),"opencode-openai-auth","opencode-openai-auth.log"):Y8(X8(),"opencode-openai-auth.log"))}function D1(){let Z=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return Z&&Q1.includes(Z)?Z:void 0}G8({file:U1,level:D1});if(process.once("beforeExit",async()=>{try{await T0()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>T0());
|
|
90
|
-
export{XZ as xc,xZ as yc,I8 as zc,Z4 as Ac,V8 as Bc,X4 as Cc,M8 as Dc,O8 as Ec,C as Fc,B4 as Gc,f8 as Hc,aZ as Ic,k8 as Jc,p0 as Kc,y8 as Lc,m8 as Mc,c8 as Nc,D4 as Oc,V4 as Pc,JZ as Qc,rZ as Rc,M4 as Sc,_4 as Tc,a8 as Uc,j4 as Vc,q4 as Wc,eZ as Xc,r8 as Yc,WZ as Zc,$9 as _c,z9 as $c,X9 as ad,Y9 as bd,J2 as cd,H2 as dd,K2 as ed,W2 as fd,F as gd,G3 as hd,s4 as id,T9 as jd,E9 as kd,C9 as ld,D3 as md,b9 as nd,z6 as od,f9 as pd,b as qd,P6 as rd,P7 as sd,FZ as td,hZ as ud,c7 as vd,u7 as wd,t7 as xd,f as yd,e as zd,v as Ad,j$ as Bd,D5 as Cd,w3 as Dd,O$ as Ed,x$ as Fd,T$ as Gd,F5 as Hd,v$ as Id,p$ as Jd,j5 as Kd,u6 as Ld,L0 as Md,q5 as Nd,i6 as Od,s6 as Pd,N5 as Qd,M5 as Rd,c$ as Sd,gZ as Td,o6 as Ud,O5 as Vd,_5 as Wd,P5 as Xd,e$ as Yd,Z1 as Zd,X1 as _d,S5 as $d,t6 as ae,Z8 as be,I5 as ce,b5 as de,f5 as ee,k5 as fe,y5 as ge,H1 as he,W1 as ie,h5 as je,w5 as ke,m5 as le,g5 as me,v5 as ne};
|