@cortexkit/opencode-openai-auth 1.16.0 → 1.17.0

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