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