@cortexkit/opencode-openai-auth 1.22.0 → 1.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/index-0p8r7cpy.js +60 -0
  3. package/dist/{index-8bt81cys.js → index-3ya2s179.js} +2 -2
  4. package/dist/{index-6afhs2jq.js → index-49ncs7dr.js} +2 -2
  5. package/dist/{index-b3bgqy7r.js → index-4ktepxn1.js} +2 -2
  6. package/dist/index-7hy72nfy.js +79 -0
  7. package/dist/{index-67twdyyz.js → index-bd18sfjj.js} +11 -11
  8. package/dist/{index-0wh22s62.js → index-d0g5g290.js} +1 -1
  9. package/dist/{index-1k8a281v.js → index-drm4dk5y.js} +2 -2
  10. package/dist/{index-mepr345k.js → index-j700j6at.js} +1 -1
  11. package/dist/{index-677jqrrt.js → index-p81hxfe6.js} +1 -1
  12. package/dist/{index-xbhtpa9s.js → index-px1t650b.js} +2 -2
  13. package/dist/{index-9tg5xx9a.js → index-q2czrasr.js} +1 -1
  14. package/dist/{index-vaf4mqd1.js → index-td4g5dc9.js} +2 -2
  15. package/dist/{index-w6kars9d.js → index-wjp3q15r.js} +1 -1
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +1 -1
  18. package/dist/openai-auth.schema.json +274 -27
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.js +1 -1
  21. package/dist/rpc/rpc-client.js +1 -1
  22. package/dist/rpc/rpc-dir.js +1 -1
  23. package/dist/{runtime-layout-DdxprfY1.d.ts → runtime-layout-B07ApQZL.d.ts} +1 -1
  24. package/dist/sidebar-state.js +1 -1
  25. package/dist/{token-92yc9q7w.js → token-hczqrmmz.js} +1 -1
  26. package/dist/token-util-9t4ma4jz.js +1 -0
  27. package/dist/tui-preferences.js +1 -1
  28. package/dist/v2/server.d.ts +7 -6
  29. package/dist/v2/server.js +4 -4
  30. package/package.json +6 -6
  31. package/src/tui-compiled/raw/shared/58bc35a3cd459085-define.js +10 -1
  32. package/src/tui-compiled/raw/shared/87f6e22d4fc34918-resolve.js +10 -5
  33. package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +10 -0
  34. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +1 -1
  35. package/src/tui-compiled/raw/shared/fe02abeadc535f77-rows.js +8 -3
  36. package/src/tui-compiled/runtime/shared/58bc35a3cd459085-define.js +10 -1
  37. package/src/tui-compiled/runtime/shared/87f6e22d4fc34918-resolve.js +10 -5
  38. package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +10 -0
  39. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +1 -1
  40. package/src/tui-compiled/runtime/shared/fe02abeadc535f77-rows.js +8 -3
  41. package/dist/index-dw1nh7dk.js +0 -60
  42. package/dist/index-ney54jhs.js +0 -79
  43. package/dist/token-util-g8e70a6j.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Ag as B0,Dg as g,Eg as q$,Fg as e,Gg as M$,Hg as b3,Ig as I0,Jg as oZ,Mg as h3}from"./index-6afhs2jq.js";import{bh as A1,dh as E1,eh as xZ,fh as AZ,hh as F3}from"./index-w6kars9d.js";import{ph as p}from"./index-vaf4mqd1.js";import{Bh as W9,qh as W0,rh as G0,uh as Q9,wh as g0,xh as WZ}from"./index-b3bgqy7r.js";var E="all",hZ=Object.freeze(["primary"]);function B8($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function r0($,Z){return JSON.stringify([$,Z])}function q0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function m($){return typeof $==="number"&&Number.isFinite($)}function G8($){return typeof $==="string"&&$.length>0}function v($,Z,X){return $[Z]===void 0||X($[Z])}function S1($){return m($)&&$>0}function wZ($){return typeof $==="string"}function C1($){if(!q0($)||!G8($.scope)||!G8($.label))return!1;switch($.kind){case"reading":return m($.checkedAt)&&m($.usedPercent)&&v($,"resetsAt",wZ)&&v($,"windowMinutes",S1);case"retired":return m($.retiredAt);case"absent":return m($.checkedAt);default:return!1}}function I1($){if(!q0($)||!m($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&v($,"remainingPercent",m)&&v($,"usedPercent",m)&&v($,"resetsAt",wZ)&&v($,"limit",m)&&v($,"used",m)&&v($,"remaining",m)&&v($,"unit",wZ)}function H8($){return q0($)&&m($.value)&&Number.isInteger($.value)&&$.value>=0&&m($.checkedAt)}function mZ($){return q0($)&&Object.values($).every(H8)}function b1($){return typeof $==="boolean"}function J0($){return q0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&v($,"balance",m)&&v($,"overageLimitReached",b1)&&m($.checkedAt)}function vZ($){if(!q0($))return;let Z=Object.entries($).filter(([,X])=>H8(X));return Z.length===0?void 0:Object.fromEntries(Z)}function S0($){if(E0($))return $;if(!q0($))return;let{counters:Z,credits:X,...z}=$;if(!E0(z))return;let Y=vZ(Z),J=J0(X)?X:void 0;return{...z,...Y===void 0?{}:{counters:Y},...J===void 0?{}:{credits:J}}}function E0($){if(!q0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!C1(X))return!1;let z=r0(X.scope,X.label);if(Z.has(z))return!1;Z.add(z)}return v($,"budget",I1)&&v($,"counters",mZ)&&v($,"credits",J0)}var D8=900000,V8="no quota reading yet",N8="no limits reported";function q8($){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 gZ($){if($.scope!==E||$.windowMinutes===void 0)return $.label;return M8($.windowMinutes)}function pZ($){return Math.min(100,Math.max(0,$))}function d$($){return Math.round(pZ($))}function K8($){return`${d$($)}% left`}function Q8($,Z,X){let z=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(z)&&z>X?{resetIn:q8(z-X)}:{},resetSinceReading:Number.isFinite(z)&&z>Z&&z<=X}}function k1($,Z){let X=$.windowMinutes,z=Z.windowMinutes;if(X!==void 0&&z!==void 0&&X!==z)return X-z;if(X===void 0!==(z===void 0))return X===void 0?1:-1;if($.scope!==Z.scope){if($.scope===E)return-1;if(Z.scope===E)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function f1($){let Z=_8($.filter(({part:X,scope:z})=>X.kind==="window"&&z!==E).map(({scope:X})=>X));for(let X of $)X.part.short=X.part.kind==="budget"?"cr":X.scope===E?X.part.name:Z.get(X.scope)??X.scope;return $}function W8($){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||W8(H))).sort(k1).map((H)=>{let K=W8(H)?{kind:"window",reading:"known",name:gZ(H),short:"",figure:K8(H.remainingPercent),remainingPercent:pZ(H.remainingPercent),checkedAt:H.checkedAt,...Q8(H.resetsAt,H.checkedAt,z)}:{kind:"window",reading:"unknown",name:gZ(H),short:"",figure:"no reading",resetSinceReading:!1};return{scope:H.scope,...H.windowMinutes===void 0?{}:{windowMinutes:H.windowMinutes},part:K}}),G=$.budget;if(G){let H=G.remainingPercent,K=G.reached?"credits spent":H!==void 0?`credits ${K8(H)}`:"credits available";J.push({scope:E,spent:G.reached,part:{kind:"budget",reading:"known",name:"credits",short:"",figure:K,...H===void 0?{}:{remainingPercent:pZ(H)},checkedAt:G.checkedAt,...Q8(G.resetsAt,G.checkedAt,z)}})}f1(J);let B=J.flatMap(({part:H})=>H.reading==="known"&&H.checkedAt!==void 0?[H.checkedAt]:[]);if(B.length>0){let H=z-Math.min(...B);if(H>(Z.staleAfterMs??D8))return{windows:J,age:`checked ${q8(H)} ago`}}return{windows:J}}function y1($,Z){return lZ($,Z).age!==void 0}function U8($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function _8($){let Z=[...new Set($.map(U8))],X=new Map(Z.map((Y)=>[Y,2])),z=(Y)=>Y.slice(0,X.get(Y));for(;;){let Y=new Map;for(let G of Z)Y.set(z(G),[...Y.get(z(G))??[],G]);let J=!1;for(let G of Y.values()){if(G.length<2)continue;for(let B of G){let H=X.get(B)??2;if(H<B.length)X.set(B,H+1),J=!0}}if(!J)break}return new Map($.map((Y)=>[Y,z(U8(Y))]))}var w1=2;function h1($){let Z=$.map((z)=>z.label.trim()||z.scope),X=_8(Z);return Z.map((z)=>X.get(z)??z)}function m1($,Z){if(!$||$.length===0)return;let X=Z.filter(({part:B})=>B.kind==="window");if(X.some(({scope:B})=>B===E))return;let z=$.flatMap((B,H)=>{let W=X.filter(({scope:Q})=>Q===B.scope).reduce((Q,U)=>Q===void 0||(U.part.remainingPercent??0)<(Q.part.remainingPercent??0)?U:Q,void 0);return W?[{group:B,listed:H,window:W}]:[]});if(z.length===0)return;let Y=h1($),J=(B)=>B.window.part.remainingPercent??0,G=[...z].sort((B,H)=>J(B)-J(H)||B.listed-H.listed).slice(0,w1).sort((B,H)=>B.listed-H.listed);return G.map((B,H)=>{let{windowMinutes:K}=B.window,W=[Y[B.listed]??B.group.scope,...K===void 0?[]:[M8(K)],`${d$(J(B))}%`].join(" ");return H===G.length-1?`${W} left`:W})}function v1($,Z){let{windows:X}=lZ($,Z),z=m1($?.groups,X);if(z)return z;let Y=X.filter(({part:Q,scope:U})=>Q.kind==="window"&&U===E),J=X.filter(({part:Q,scope:U})=>Q.kind==="window"&&U!==E),G=X.find(({part:Q})=>Q.kind==="budget"),B=G?.spent?0:G?.part.remainingPercent,K=[...J.map(({part:Q})=>({label:Q.short,remaining:Q.remainingPercent??0})),...B===void 0||G===void 0?[]:[{label:G.part.short,remaining:B}]].reduce((Q,U)=>Q===void 0||U.remaining<Q.remaining?U:Q,void 0),W=Y.map(({part:Q})=>`${Q.name} ${d$(Q.remainingPercent??0)}%`);if(K)W.push(`${K.label} ${d$(K.remaining)}%`);if(W.length===0)return X.map(({part:Q})=>Q.figure);return W.map((Q,U)=>U===W.length-1?`${Q} left`:Q)}function F8($,Z){if(Z.form==="narrow")return v1($,Z);let{windows:X,age:z}=lZ($,Z),Y=(Z.form??"full")==="full",J=X.map(({part:G})=>{let B=Y&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${B}`});return z===void 0?J:[...J,z]}function g1($,Z){let X=F8($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?N8:V8}function p1($){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 l1($){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 d1($,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 c1($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function s($,Z=E){let X=new Map;for(let W of $?.limits??[]){if(W.scope!==Z&&W.scope!==E)continue;let Q=X.get(W.label);if(Q===void 0){X.set(W.label,W);continue}let U=W.scope===E?Q:W,D=W.scope===E?W:Q;X.set(W.label,U.kind==="reading"?U:D)}let z=[...X.values()].map(l1).sort(d1),Y=z.filter((W)=>W.kind==="reading"),J=Y.length>0?Y:z,G=J.length>0?Math.min(...J.map((W)=>W.checkedAt)):void 0,B=$?.budget?.kind==="reading"?c1($.budget):void 0,H=vZ($?.counters),K=J0($?.credits)?$.credits:void 0;return{scope:Z,limits:z,...G===void 0?{}:{checkedAt:G},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H},...K===void 0?{}:{credits:K}}}function C0($,Z){let X=$?.budget;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let z=Date.parse(X.resetsAt);if(!Number.isFinite(z)||z<=Z)return;return{resetsAt:X.resetsAt,resetAtMs:z}}function c$($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function U$($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}class u$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function s$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function i$($){return typeof $==="number"&&Number.isFinite($)}function L8($){return $===void 0||typeof $==="string"&&$!==""}function O8($){return typeof $==="string"&&$!==""}function D$($,Z){return $[Z]===void 0||i$($[Z])}function dZ($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function u1($){return s$($)&&L8($.scope)&&O8($.label)&&i$($.usedPercent)&&dZ($,"resetsAt")&&($.windowMinutes===void 0||i$($.windowMinutes)&&$.windowMinutes>0)}function i1($){return s$($)&&L8($.scope)&&O8($.label)}function s1($){if(!s$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&D$($,"remainingPercent")&&D$($,"usedPercent")&&dZ($,"resetsAt")&&D$($,"limit")&&D$($,"used")&&D$($,"remaining")&&dZ($,"unit")}function t0($){if(!s$($)||!i$($.checkedAt))return!1;let Z=$.readings??[],X=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(X))return!1;let z=new Set;for(let Y of Z){if(!u1(Y))return!1;let J=r0(Y.scope??E,Y.label);if(z.has(J))return!1;z.add(J)}if(!X.every(i1))return!1;return($.budget===void 0||s1($.budget))&&($.counters===void 0||mZ($.counters))&&($.credits===void 0||J0($.credits))}function a1($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function n1($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function o1($,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 r1($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function V$($,Z){let X=$===void 0?void 0:S0($);if($!==void 0&&X===void 0)throw new u$("stored quota map is malformed");if(!t0(Z))throw new u$("quota observation is malformed");let z=X??{limits:[]},Y=Z.checkedAt,J=new Map;for(let q of z.limits)J.set(r0(q.scope,q.label),q);let G=(q)=>{let R=J.get(q);return R===void 0||Y>=B8(R)},B=new Set;for(let q of Z.readings??[]){let R=q.scope??E,x=r0(R,q.label);if(B.add(x),!G(x))continue;J.set(x,{scope:R,label:q.label,kind:"reading",checkedAt:Y,usedPercent:q.usedPercent,...q.resetsAt===void 0?{}:{resetsAt:q.resetsAt},...q.windowMinutes===void 0?{}:{windowMinutes:q.windowMinutes}})}for(let q of Z.coverage??[]){let R=q.scope??E,x=r0(R,q.label);if(B.has(x)||!G(x))continue;let L=J.get(x);J.set(x,L===void 0||L.kind==="absent"?{scope:R,label:q.label,kind:"absent",checkedAt:Y}:{scope:R,label:q.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:K,counters:W,credits:Q,...U}=z,D=n1(z.budget,Z.budget,Y),V=o1(z.counters,Z.counters),_=r1(z.credits,Z.credits);return{...U,limits:[...J.values()].sort(a1),...D===void 0?{}:{budget:D},...V===void 0?{}:{counters:V},..._===void 0?{}:{credits:_}}}var t1=Object.freeze({validate:E0,decode:S0,merge:V$});function P8($,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 e1($,Z,X,z,Y){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of X)if(!Z.limits.some((B)=>B.label===G))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:G},pullRequested:!0};let J=Z.limits.filter(c$);for(let G of J)if(U$(G,z)===void 0&&!Y.some((B)=>B.scope===G.scope&&B.label===G.label))return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of J){let B=U$(G,z);if(B!==void 0&&typeof G.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:G.scope,label:G.label},resetsAt:G.resetsAt,resetAtMs:B}}return}function t($){let Z=$.scope??E,X=$.requiredLabels??hZ,z=[],Y=[],J=[],G=new Set;for(let D of $.rows){let V=P8(D.id,$,$.now);if(V){z.push(V);continue}if(D.kind==="api-key"){J.push({id:D.id,kind:D.kind});continue}let _=s(D.quota,Z),q=$.liftedWindows?.get(D.id)??[];if(_.limits.some((x)=>c$(x)&&U$(x,$.now)===void 0&&q.some((L)=>L.scope===x.scope&&L.label===x.label)))G.add(D.id);let R=e1(D.id,_,X,$.now,q);if(R){Y.push(R);continue}J.push({id:D.id,kind:D.kind,projection:_})}let B=new Map(J.flatMap((D)=>{let V=C0(D.projection,$.now);return V?[[D.id,V]]:[]})),H=B.size>0&&B.size===J.length,K=[];for(let D of J){let V=B.get(D.id);if(V===void 0)K.push(D);else if(H)K.push({...D,lastPath:!0});else Y.push({id:D.id,stage:2,reason:"budget-spent",...V})}let W=new Map($.rows.map((D,V)=>[D.id,V])),Q=(D,V)=>(W.get(D.id)??0)-(W.get(V.id)??0);Y.sort(Q);for(let D of Y)if("pullRequested"in D)G.add(D.id);let U=$.rows.filter((D)=>G.has(D.id)).map((D)=>D.id);for(let D of U)$.requestPull?.(D);return{admitted:K,refused:Y,excluded:z,pulls:U}}var j8="main";function $2($){switch($){case"sticky-balanced":return{mode:"sticky-balanced",placement:"roster"};case"main-first":return{mode:"ordered",placement:"main-first"};case"fallback-first":return{mode:"ordered",placement:"fallback-first"};default:return{mode:"ordered",placement:"roster"}}}function a$($,Z,X=j8){if(Z==="roster"||!$.includes(X))return[...$];let z=$.filter((Y)=>Y!==X);return Z==="main-first"?[X,...z]:[...z,X]}function cZ($){let Z=t($),X=new Set(Z.admitted.map((Y)=>Y.id));return{order:a$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>X.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function Z2($,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 uZ($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function X2($,Z,X){let z=new Map;for(let[Y,J]of $){if(Y===X)continue;if(J.quotaCheckedAt!==Z.get(J.accountId))continue;z.set(J.accountId,(z.get(J.accountId)??0)+(J.inputBytes??0))}return z}var N$=900000,T8=0.016666666666666666,iZ=0.000001;function n$($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function x8($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function A8($){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 aZ($){let Z=($.classifyStatus??x8)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=n$($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>N$)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of A8($.quota)){let J=Y.remainingPercent;if(typeof J==="number"&&Number.isFinite(J)&&J<=0)return{action:"migrate",reason:"exhausted",window:{scope:Y.scope,label:Y.label},...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{}}}let z=C0($.quota,$.now);if(z)return{action:"migrate",reason:"exhausted",resetsAt:z.resetsAt};return{action:"retain",reason:Z}}function sZ($,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,T8);return z/J}function R8($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function z2($,Z){if(!$.quota)return;let X=n$($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>N$)return;let z=A8($.quota).map((G)=>sZ({remainingPercent:G.remainingPercent??Number.NaN,...G.resetsAt===void 0?{}:{resetsAt:G.resetsAt}},$.reservePercent[G.label]??0,Z)),Y=$.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))z.push(sZ({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 E8($){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)=>z2(Y,$.now)).filter((Y)=>Y!==void 0);if(X.length>0){X.sort((J,G)=>{let B=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,iZ),H=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,iZ);return B-H||J.candidate.configuredOrder-G.candidate.configuredOrder||R8(J.candidate.accountId,G.candidate.accountId)});let Y=X[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let z=[...Z].sort((Y,J)=>{let G=(Y.resetCreditsApplicable??0)>0?1:0;return((J.resetCreditsApplicable??0)>0?1:0)-G||Y.configuredOrder-J.configuredOrder||R8(Y.accountId,J.accountId)})[0];if(!z)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:z.accountId,quotaCheckedAt:n$(z.quota,z.quotaCheckedAt),source:"mode-fallback"}}function nZ($){let Z=t($),X=new Map(Z.admitted.map((V)=>[V.id,V])),z=new Map(Z.refused.map((V)=>[V.id,V])),Y=new Set(Z.excluded.map((V)=>V.id)),J=new Set($.rows.map((V)=>V.id)),G=$.pin!==void 0&&uZ($.pin,J,$.identities?.get($.pin.accountId));if(G&&$.pin){let V=X.get($.pin.accountId);if(V&&$.killswitch?.get(V.id)!==!1)return{outcome:"dispatch",accountId:V.id,source:"pin",...V.projection?.checkedAt===void 0?{}:{quotaCheckedAt:V.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?z.get($.pin.accountId):void 0,H=G&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),K=(V)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(V):$.rowReservePercent?.get(V.id))??$.reservePercent??{}},W=$.scope,Q=$.rows.map((V,_)=>({row:V,configuredOrder:_})).filter(({row:V})=>!Y.has(V.id)).map(({row:V,configuredOrder:_})=>{let q=$.killswitch?.get(V.id),R=$.resetCreditsApplicable?.get(V.id);return{accountId:V.id,quota:V.kind==="api-key"?void 0:X.get(V.id)?.projection??s(V.quota,W),reservePercent:K(V),configuredOrder:_,...R===void 0?{}:{resetCreditsApplicable:R},...q===void 0?{}:{killswitchPasses:q}}}),U=[],D=G?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(Q.length>0){let V=E8({candidates:Q,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!V)break;let _=z.get(V.accountId);if(_){U.push(_),Q=Q.filter((R)=>R.accountId!==V.accountId);continue}let q=$.identities?.get(V.accountId);return{outcome:"dispatch",accountId:V.accountId,source:V.source,...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt},pin:G&&!H?{action:"retain"}:{action:"assign",pin:{accountId:V.accountId,inputBytes:$.requestBytes,...q===void 0?{}:{wireIdentity:q},...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt}}},refusedSelections:U,admission:Z}}return{outcome:"no-admissible-account",pin:D,refusedSelections:U,admission:Z}}import{createHash as Y2}from"node:crypto";var J2=86400000,G2=300000,B2=3600000,H2=60000,K2=900000,Q2=300000;function rZ($){return $ instanceof Error?$.message:String($)}function W2($){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 S8($){return Y2("sha256").update($).digest("hex")}function C8($){let Z=S8($.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(W2($.error))Y=Math.min(B2,G2*2**Math.min(z-1,6));else Y=J2;return{message:rZ($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:z,tokenHash:Z}}function b0($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===S8(Z)}function o$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function _$($){let X=($.previous?.retryCount??0)+1,z,Y=$.error?.retryAfter;if(typeof Y==="number"&&Y>0)z=Y*1000;else if(tZ($.error))z=Math.min(K2,H2*2**Math.min(X-1,6));else z=Q2;return{message:rZ($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:X}}function e0($,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 I8}from"node:http";import{setTimeout as U2}from"node:timers/promises";var $Z="app_EMoamEEZ73f0CkXaXp7hrann",y0="https://auth.openai.com",L$=1455,D2=3000,V2="cortexkit-opencode-openai-auth";function y8($){return`${V2}/${$}`}var w8="main",N2=`"${w8}" is a reserved account id; choose a different label.`;function h8($){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=h8(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function b8($){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 k8($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let X=$["https://api.openai.com/auth"];if(X&&typeof X==="object"&&!Array.isArray(X)&&typeof X.chatgpt_account_id==="string"&&X.chatgpt_account_id.length>0)return X.chatgpt_account_id;let z=$.organizations;if(Array.isArray(z)){let Y=z[0];if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string"&&Y.id.length>0)return Y.id}return}function t$($){if($.id_token){let Z=b8($.id_token),X=Z&&k8(Z);if(X)return X}if($.access_token){let Z=b8($.access_token);return Z?k8(Z):void 0}return}function M2($){return typeof $==="string"&&$.toLowerCase()===w8}function $6($){if(M2($))throw Error(N2);return $}function _2($,Z,X){let z=new URLSearchParams({response_type:"code",client_id:$Z,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:X,originator:"opencode"});return`${y0}/oauth/authorize?${z.toString()}`}async function F2($,Z,X){let z=await fetch(`${y0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:$Z,code_verifier:X.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function L2($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var O2=`<!doctype html>
1
+ import{Eg as B0,Hg as g,Ig as q$,Jg as e,Kg as _$,Lg as b3,Mg as I0,Ng as oZ,Qg as h3}from"./index-49ncs7dr.js";import{fh as A1,hh as E1,ih as AZ,jh as EZ,lh as F3}from"./index-wjp3q15r.js";import{th as p}from"./index-td4g5dc9.js";import{Ah as g0,Bh as UZ,Fh as W9,uh as W0,vh as G0,yh as Q9}from"./index-4ktepxn1.js";var E="all",hZ=Object.freeze(["primary"]);function B8($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function e0($,Z){return JSON.stringify([$,Z])}function q0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function m($){return typeof $==="number"&&Number.isFinite($)}function G8($){return typeof $==="string"&&$.length>0}function v($,Z,X){return $[Z]===void 0||X($[Z])}function S1($){return m($)&&$>0}function wZ($){return typeof $==="string"}function C1($){if(!q0($)||!G8($.scope)||!G8($.label))return!1;switch($.kind){case"reading":return m($.checkedAt)&&m($.usedPercent)&&v($,"resetsAt",wZ)&&v($,"windowMinutes",S1);case"retired":return m($.retiredAt);case"absent":return m($.checkedAt);default:return!1}}function I1($){if(!q0($)||!m($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&v($,"remainingPercent",m)&&v($,"usedPercent",m)&&v($,"resetsAt",wZ)&&v($,"limit",m)&&v($,"used",m)&&v($,"remaining",m)&&v($,"unit",wZ)}function H8($){return q0($)&&m($.value)&&Number.isInteger($.value)&&$.value>=0&&m($.checkedAt)}function mZ($){return q0($)&&Object.values($).every(H8)}function b1($){return typeof $==="boolean"}function J0($){return q0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&v($,"balance",m)&&v($,"overageLimitReached",b1)&&m($.checkedAt)}function vZ($){if(!q0($))return;let Z=Object.entries($).filter(([,X])=>H8(X));return Z.length===0?void 0:Object.fromEntries(Z)}function S0($){if(M0($))return $;if(!q0($))return;let{counters:Z,credits:X,...z}=$;if(!M0(z))return;let Y=vZ(Z),J=J0(X)?X:void 0;return{...z,...Y===void 0?{}:{counters:Y},...J===void 0?{}:{credits:J}}}function M0($){if(!q0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!C1(X))return!1;let z=e0(X.scope,X.label);if(Z.has(z))return!1;Z.add(z)}return v($,"budget",I1)&&v($,"counters",mZ)&&v($,"credits",J0)}var D8=900000,V8="no quota reading yet",N8="no limits reported";function M8($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let Y=Math.floor(Z/60),J=Z%60;return J===0?`${Y}h`:`${Y}h${J}m`}let X=Math.floor(Z/1440),z=Math.floor(Z%1440/60);return z===0?`${X}d`:`${X}d${z}h`}function q8($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function gZ($){if($.scope!==E||$.windowMinutes===void 0)return $.label;return q8($.windowMinutes)}function pZ($){return Math.min(100,Math.max(0,$))}function c$($){return Math.round(pZ($))}function K8($){return`${c$($)}% left`}function Q8($,Z,X){let z=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(z)&&z>X?{resetIn:M8(z-X)}:{},resetSinceReading:Number.isFinite(z)&&z>Z&&z<=X}}function k1($,Z){let X=$.windowMinutes,z=Z.windowMinutes;if(X!==void 0&&z!==void 0&&X!==z)return X-z;if(X===void 0!==(z===void 0))return X===void 0?1:-1;if($.scope!==Z.scope){if($.scope===E)return-1;if(Z.scope===E)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function f1($){let Z=_8($.filter(({part:X,scope:z})=>X.kind==="window"&&z!==E).map(({scope:X})=>X));for(let X of $)X.part.short=X.part.kind==="budget"?"cr":X.scope===E?X.part.name:Z.get(X.scope)??X.scope;return $}function W8($){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||W8(H))).sort(k1).map((H)=>{let K=W8(H)?{kind:"window",reading:"known",name:gZ(H),short:"",figure:K8(H.remainingPercent),remainingPercent:pZ(H.remainingPercent),checkedAt:H.checkedAt,...Q8(H.resetsAt,H.checkedAt,z)}:{kind:"window",reading:"unknown",name:gZ(H),short:"",figure:"no reading",resetSinceReading:!1};return{scope:H.scope,...H.windowMinutes===void 0?{}:{windowMinutes:H.windowMinutes},part:K}}),G=$.budget;if(G){let H=G.remainingPercent,K=G.reached?"credits spent":H!==void 0?`credits ${K8(H)}`:"credits available";J.push({scope:E,spent:G.reached,part:{kind:"budget",reading:"known",name:"credits",short:"",figure:K,...H===void 0?{}:{remainingPercent:pZ(H)},checkedAt:G.checkedAt,...Q8(G.resetsAt,G.checkedAt,z)}})}f1(J);let B=J.flatMap(({part:H})=>H.reading==="known"&&H.checkedAt!==void 0?[H.checkedAt]:[]);if(B.length>0){let H=z-Math.min(...B);if(H>(Z.staleAfterMs??D8))return{windows:J,age:`checked ${M8(H)} ago`}}return{windows:J}}function y1($,Z){return lZ($,Z).age!==void 0}function U8($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function _8($){let Z=[...new Set($.map(U8))],X=new Map(Z.map((Y)=>[Y,2])),z=(Y)=>Y.slice(0,X.get(Y));for(;;){let Y=new Map;for(let G of Z)Y.set(z(G),[...Y.get(z(G))??[],G]);let J=!1;for(let G of Y.values()){if(G.length<2)continue;for(let B of G){let H=X.get(B)??2;if(H<B.length)X.set(B,H+1),J=!0}}if(!J)break}return new Map($.map((Y)=>[Y,z(U8(Y))]))}var w1=2;function h1($){let Z=$.map((z)=>z.label.trim()||z.scope),X=_8(Z);return Z.map((z)=>X.get(z)??z)}function m1($,Z){if(!$||$.length===0)return;let X=Z.filter(({part:B})=>B.kind==="window");if(X.some(({scope:B})=>B===E))return;let z=$.flatMap((B,H)=>{let W=X.filter(({scope:Q})=>Q===B.scope).reduce((Q,U)=>Q===void 0||(U.part.remainingPercent??0)<(Q.part.remainingPercent??0)?U:Q,void 0);return W?[{group:B,listed:H,window:W}]:[]});if(z.length===0)return;let Y=h1($),J=(B)=>B.window.part.remainingPercent??0,G=[...z].sort((B,H)=>J(B)-J(H)||B.listed-H.listed).slice(0,w1).sort((B,H)=>B.listed-H.listed);return G.map((B,H)=>{let{windowMinutes:K}=B.window,W=[Y[B.listed]??B.group.scope,...K===void 0?[]:[q8(K)],`${c$(J(B))}%`].join(" ");return H===G.length-1?`${W} left`:W})}function v1($,Z){let{windows:X}=lZ($,Z),z=m1($?.groups,X);if(z)return z;let Y=X.filter(({part:Q,scope:U})=>Q.kind==="window"&&U===E),J=X.filter(({part:Q,scope:U})=>Q.kind==="window"&&U!==E),G=X.find(({part:Q})=>Q.kind==="budget"),B=G?.spent?0:G?.part.remainingPercent,K=[...J.map(({part:Q})=>({label:Q.short,remaining:Q.remainingPercent??0})),...B===void 0||G===void 0?[]:[{label:G.part.short,remaining:B}]].reduce((Q,U)=>Q===void 0||U.remaining<Q.remaining?U:Q,void 0),W=Y.map(({part:Q})=>`${Q.name} ${c$(Q.remainingPercent??0)}%`);if(K)W.push(`${K.label} ${c$(K.remaining)}%`);if(W.length===0)return X.map(({part:Q})=>Q.figure);return W.map((Q,U)=>U===W.length-1?`${Q} left`:Q)}function F8($,Z){if(Z.form==="narrow")return v1($,Z);let{windows:X,age:z}=lZ($,Z),Y=(Z.form??"full")==="full",J=X.map(({part:G})=>{let B=Y&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${B}`});return z===void 0?J:[...J,z]}function g1($,Z){let X=F8($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?N8:V8}function p1($){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 l1($){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 d1($,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 c1($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function u($,Z=E){let X=new Map;for(let W of $?.limits??[]){if(W.scope!==Z&&W.scope!==E)continue;let Q=X.get(W.label);if(Q===void 0){X.set(W.label,W);continue}let U=W.scope===E?Q:W,D=W.scope===E?W:Q;X.set(W.label,U.kind==="reading"?U:D)}let z=[...X.values()].map(l1).sort(d1),Y=z.filter((W)=>W.kind==="reading"),J=Y.length>0?Y:z,G=J.length>0?Math.min(...J.map((W)=>W.checkedAt)):void 0,B=$?.budget?.kind==="reading"?c1($.budget):void 0,H=vZ($?.counters),K=J0($?.credits)?$.credits:void 0;return{scope:Z,limits:z,...G===void 0?{}:{checkedAt:G},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H},...K===void 0?{}:{credits:K}}}function C0($,Z){let X=$?.budget;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let z=Date.parse(X.resetsAt);if(!Number.isFinite(z)||z<=Z)return;return{resetsAt:X.resetsAt,resetAtMs:z}}function u$($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function D$($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}class i$ extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function a$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function s$($){return typeof $==="number"&&Number.isFinite($)}function L8($){return $===void 0||typeof $==="string"&&$!==""}function O8($){return typeof $==="string"&&$!==""}function V$($,Z){return $[Z]===void 0||s$($[Z])}function dZ($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function u1($){return a$($)&&L8($.scope)&&O8($.label)&&s$($.usedPercent)&&dZ($,"resetsAt")&&($.windowMinutes===void 0||s$($.windowMinutes)&&$.windowMinutes>0)}function i1($){return a$($)&&L8($.scope)&&O8($.label)}function s1($){if(!a$($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&V$($,"remainingPercent")&&V$($,"usedPercent")&&dZ($,"resetsAt")&&V$($,"limit")&&V$($,"used")&&V$($,"remaining")&&dZ($,"unit")}function $$($){if(!a$($)||!s$($.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(!u1(Y))return!1;let J=e0(Y.scope??E,Y.label);if(z.has(J))return!1;z.add(J)}if(!X.every(i1))return!1;return($.budget===void 0||s1($.budget))&&($.counters===void 0||mZ($.counters))&&($.credits===void 0||J0($.credits))}function a1($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function n1($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function o1($,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 r1($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function N$($,Z){let X=$===void 0?void 0:S0($);if($!==void 0&&X===void 0)throw new i$("stored quota map is malformed");if(!$$(Z))throw new i$("quota observation is malformed");let z=X??{limits:[]},Y=Z.checkedAt,J=new Map;for(let M of z.limits)J.set(e0(M.scope,M.label),M);let G=(M)=>{let R=J.get(M);return R===void 0||Y>=B8(R)},B=new Set;for(let M of Z.readings??[]){let R=M.scope??E,x=e0(R,M.label);if(B.add(x),!G(x))continue;J.set(x,{scope:R,label:M.label,kind:"reading",checkedAt:Y,usedPercent:M.usedPercent,...M.resetsAt===void 0?{}:{resetsAt:M.resetsAt},...M.windowMinutes===void 0?{}:{windowMinutes:M.windowMinutes}})}for(let M of Z.coverage??[]){let R=M.scope??E,x=e0(R,M.label);if(B.has(x)||!G(x))continue;let L=J.get(x);J.set(x,L===void 0||L.kind==="absent"?{scope:R,label:M.label,kind:"absent",checkedAt:Y}:{scope:R,label:M.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:K,counters:W,credits:Q,...U}=z,D=n1(z.budget,Z.budget,Y),V=o1(z.counters,Z.counters),_=r1(z.credits,Z.credits);return{...U,limits:[...J.values()].sort(a1),...D===void 0?{}:{budget:D},...V===void 0?{}:{counters:V},..._===void 0?{}:{credits:_}}}var t1=Object.freeze({validate:M0,decode:S0,merge:N$});function P8($,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 e1($,Z,X,z,Y){if(Z.limits.length===0)return{id:$,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of X)if(!Z.limits.some((B)=>B.label===G))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:G},pullRequested:!0};let J=Z.limits.filter(u$);for(let G of J)if(D$(G,z)===void 0&&!Y.some((B)=>B.scope===G.scope&&B.label===G.label))return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of J){let B=D$(G,z);if(B!==void 0&&typeof G.resetsAt==="string")return{id:$,stage:1,gate:5,reason:"exhausted",window:{scope:G.scope,label:G.label},resetsAt:G.resetsAt,resetAtMs:B}}return}function t($){let Z=$.scope??E,X=$.requiredLabels??hZ,z=[],Y=[],J=[],G=new Set;for(let D of $.rows){let V=P8(D.id,$,$.now);if(V){z.push(V);continue}if(D.kind==="api-key"){J.push({id:D.id,kind:D.kind});continue}let _=u(D.quota,Z),M=$.liftedWindows?.get(D.id)??[];if(_.limits.some((x)=>u$(x)&&D$(x,$.now)===void 0&&M.some((L)=>L.scope===x.scope&&L.label===x.label)))G.add(D.id);let R=e1(D.id,_,X,$.now,M);if(R){Y.push(R);continue}J.push({id:D.id,kind:D.kind,projection:_})}let B=new Map(J.flatMap((D)=>{let V=C0(D.projection,$.now);return V?[[D.id,V]]:[]})),H=B.size>0&&B.size===J.length,K=[];for(let D of J){let V=B.get(D.id);if(V===void 0)K.push(D);else if(H)K.push({...D,lastPath:!0});else Y.push({id:D.id,stage:2,reason:"budget-spent",...V})}let W=new Map($.rows.map((D,V)=>[D.id,V])),Q=(D,V)=>(W.get(D.id)??0)-(W.get(V.id)??0);Y.sort(Q);for(let D of Y)if("pullRequested"in D)G.add(D.id);let U=$.rows.filter((D)=>G.has(D.id)).map((D)=>D.id);for(let D of U)$.requestPull?.(D);return{admitted:K,refused:Y,excluded:z,pulls:U}}var j8="main";function $2($){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 n$($,Z,X=j8){if(Z==="roster"||!$.includes(X))return[...$];let z=$.filter((Y)=>Y!==X);return Z==="main-first"?[X,...z]:[...z,X]}function cZ($){let Z=t($),X=new Set(Z.admitted.map((Y)=>Y.id));return{order:n$($.rows.map((Y)=>Y.id),$.placement??"roster",$.formerMainId).filter((Y)=>X.has(Y)&&$.killswitch?.get(Y)!==!1),admission:Z}}function Z2($,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 uZ($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function X2($,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,T8=0.016666666666666666,iZ=0.000001;function o$($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function x8($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function A8($){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 aZ($){let Z=($.classifyStatus??x8)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=o$($.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 A8($.quota)){let J=Y.remainingPercent;if(typeof J==="number"&&Number.isFinite(J)&&J<=0)return{action:"migrate",reason:"exhausted",window:{scope:Y.scope,label:Y.label},...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{}}}let z=C0($.quota,$.now);if(z)return{action:"migrate",reason:"exhausted",resetsAt:z.resetsAt};return{action:"retain",reason:Z}}function sZ($,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,T8);return z/J}function R8($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function z2($,Z){if(!$.quota)return;let X=o$($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>M$)return;let z=A8($.quota).map((G)=>sZ({remainingPercent:G.remainingPercent??Number.NaN,...G.resetsAt===void 0?{}:{resetsAt:G.resetsAt}},$.reservePercent[G.label]??0,Z)),Y=$.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))z.push(sZ({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 E8($){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)=>z2(Y,$.now)).filter((Y)=>Y!==void 0);if(X.length>0){X.sort((J,G)=>{let B=(($.pendingBytes.get(J.candidate.accountId)??0)+$.requestBytes)/Math.max(J.weight,iZ),H=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,iZ);return B-H||J.candidate.configuredOrder-G.candidate.configuredOrder||R8(J.candidate.accountId,G.candidate.accountId)});let Y=X[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let z=[...Z].sort((Y,J)=>{let G=(Y.resetCreditsApplicable??0)>0?1:0;return((J.resetCreditsApplicable??0)>0?1:0)-G||Y.configuredOrder-J.configuredOrder||R8(Y.accountId,J.accountId)})[0];if(!z)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:z.accountId,quotaCheckedAt:o$(z.quota,z.quotaCheckedAt),source:"mode-fallback"}}function nZ($){let Z=t($),X=new Map(Z.admitted.map((V)=>[V.id,V])),z=new Map(Z.refused.map((V)=>[V.id,V])),Y=new Set(Z.excluded.map((V)=>V.id)),J=new Set($.rows.map((V)=>V.id)),G=$.pin!==void 0&&uZ($.pin,J,$.identities?.get($.pin.accountId));if(G&&$.pin){let V=X.get($.pin.accountId);if(V&&$.killswitch?.get(V.id)!==!1)return{outcome:"dispatch",accountId:V.id,source:"pin",...V.projection?.checkedAt===void 0?{}:{quotaCheckedAt:V.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?z.get($.pin.accountId):void 0,H=G&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),K=(V)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(V):$.rowReservePercent?.get(V.id))??$.reservePercent??{}},W=$.scope,Q=$.rows.map((V,_)=>({row:V,configuredOrder:_})).filter(({row:V})=>!Y.has(V.id)).map(({row:V,configuredOrder:_})=>{let M=$.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??u(V.quota,W),reservePercent:K(V),configuredOrder:_,...R===void 0?{}:{resetCreditsApplicable:R},...M===void 0?{}:{killswitchPasses:M}}}),U=[],D=G?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(Q.length>0){let V=E8({candidates:Q,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!V)break;let _=z.get(V.accountId);if(_){U.push(_),Q=Q.filter((R)=>R.accountId!==V.accountId);continue}let M=$.identities?.get(V.accountId);return{outcome:"dispatch",accountId:V.accountId,source:V.source,...V.quotaCheckedAt===void 0?{}:{quotaCheckedAt:V.quotaCheckedAt},pin:G&&!H?{action:"retain"}:{action:"assign",pin:{accountId:V.accountId,inputBytes:$.requestBytes,...M===void 0?{}:{wireIdentity:M},...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 Y2}from"node:crypto";var J2=86400000,G2=300000,B2=3600000,H2=60000,K2=900000,Q2=300000;function rZ($){return $ instanceof Error?$.message:String($)}function W2($){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 S8($){return Y2("sha256").update($).digest("hex")}function C8($){let Z=S8($.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(W2($.error))Y=Math.min(B2,G2*2**Math.min(z-1,6));else Y=J2;return{message:rZ($.error),checkedAt:$.now,nextRetryAt:$.now+Y,retryCount:z,tokenHash:Z}}function b0($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===S8(Z)}function r$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function F$($){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(K2,H2*2**Math.min(X-1,6));else z=Q2;return{message:rZ($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:X}}function Z$($,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 I8}from"node:http";import{setTimeout as U2}from"node:timers/promises";var ZZ="app_EMoamEEZ73f0CkXaXp7hrann",y0="https://auth.openai.com",O$=1455,D2=3000,V2="cortexkit-opencode-openai-auth";function y8($){return`${V2}/${$}`}var w8="main",N2=`"${w8}" is a reserved account id; choose a different label.`;function h8($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function M2(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),X=h8(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function b8($){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 k8($){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 e$($){if($.id_token){let Z=b8($.id_token),X=Z&&k8(Z);if(X)return X}if($.access_token){let Z=b8($.access_token);return Z?k8(Z):void 0}return}function q2($){return typeof $==="string"&&$.toLowerCase()===w8}function $6($){if(q2($))throw Error(N2);return $}function _2($,Z,X){let z=new URLSearchParams({response_type:"code",client_id:ZZ,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:X,originator:"opencode"});return`${y0}/oauth/authorize?${z.toString()}`}async function F2($,Z,X){let z=await fetch(`${y0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:ZZ,code_verifier:X.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function L2($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var O2=`<!doctype html>
2
2
  <html>
3
3
  <head>
4
4
  <title>CortexKit OpenAI Auth - Authorization Successful</title>
@@ -38,7 +38,7 @@ import{Ag as B0,Dg as g,Eg as q$,Fg as e,Gg as M$,Hg as b3,Ig as I0,Jg as oZ,Mg
38
38
  setTimeout(() => window.close(), 2000)
39
39
  </script>
40
40
  </body>
41
- </html>`,r$=($)=>`<!doctype html>
41
+ </html>`,t$=($)=>`<!doctype html>
42
42
  <html>
43
43
  <head>
44
44
  <title>CortexKit OpenAI Auth - Authorization Failed</title>
@@ -84,18 +84,18 @@ import{Ag as B0,Dg as g,Eg as q$,Fg as e,Gg as M$,Hg as b3,Ig as I0,Jg as oZ,Mg
84
84
  <div class="error">${L2($)}</div>
85
85
  </div>
86
86
  </body>
87
- </html>`,e$=[],F$,H0=new Map;function f8($,Z){return new Promise((X,z)=>{let Y=(G)=>{$.off("listening",J),z(G)},J=()=>{$.off("error",Y),X()};$.once("error",Y),$.once("listening",J),$.listen(L$,Z)})}function m8($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function k0(){return H0.size}function w0($){if(H0.delete($),k0()===0)f0()}async function P2(){let $=`http://localhost:${L$}/auth/callback`;if(e$.length>0)return{port:L$,redirectUri:$};if(F$)return F$;F$=(async()=>{let Z=(J,G)=>{let B=new URL(J.url||"/",`http://127.0.0.1:${L$}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),K=B.searchParams.get("state"),W=B.searchParams.get("error"),Q=B.searchParams.get("error_description");if(W){let D=Q||W;if(K){let V=H0.get(K);if(V)V.reject(Error(D)),w0(K);else if(k0()===0)f0()}else if(k0()===0)f0();G.writeHead(200,{"Content-Type":"text/html"}),G.end(r$(D));return}if(!K){if(k0()===0)f0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(r$("Missing state parameter"));return}if(!H){if(k0()===0)f0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(r$("Missing authorization code"));return}let U=H0.get(K);if(!U){if(k0()===0)f0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(r$("Unknown state — authorization may have expired"));return}w0(K),F2(H,$,U.pkce).then((D)=>U.resolve(D)).catch((D)=>U.reject(D)),G.writeHead(200,{"Content-Type":"text/html"}),G.end(O2);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),K=H?[H]:[...H0.keys()];G.writeHead(200),G.end("Login cancelled");for(let W of K){let Q=H0.get(W);if(!Q)continue;Q.reject(Error("Login cancelled")),w0(W)}if(k0()===0)f0();return}G.writeHead(404),G.end("Not found")},X=I8(Z);await f8(X,"127.0.0.1");let z=[X],Y=I8(Z);try{await f8(Y,"::1"),z.push(Y)}catch(J){let G=J.code;if(G!=="EADDRNOTAVAIL"&&G!=="EAFNOSUPPORT")throw m8(X),J}return e$=z,{port:L$,redirectUri:$}})();try{return await F$}finally{F$=void 0}}function f0(){let $=e$;e$=[];for(let Z of $)m8(Z)}function j2($,Z,X=300000,z){return new Promise((Y,J)=>{if(z?.aborted){w0(Z),J(Error("Login cancelled"));return}let G=setTimeout(()=>{if(H0.get(Z))w0(Z),J(Error("OAuth callback timeout — authorization took too long"))},X),B=()=>{if(clearTimeout(G),H0.get(Z))w0(Z),J(Error("Login cancelled"))};if(z)z.addEventListener("abort",B);H0.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(G),z)z.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(G),z)z.removeEventListener("abort",B);J(H)}})})}async function R2($){let Z=await fetch(`${y0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y8($)},body:JSON.stringify({client_id:$Z})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${y0}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function T2($,Z,X){let z=Math.max(parseInt($.interval,10)||5,1)*1000,Y=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),J=!Number.isNaN(Y)&&Y>0?Y*1000:900000,G=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>J)throw Error("Device authorization expired");let B=await fetch(`${y0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y8(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let W=await B.json(),Q=await fetch(`${y0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:W.authorization_code,redirect_uri:`${y0}/deviceauth/callback`,client_id:$Z,code_verifier:W.code_verifier}).toString()});if(!Q.ok)throw Error(`Token exchange failed: ${Q.status}`);return await Q.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let H=J-(Date.now()-G);if(H<=0)throw Error("Device authorization expired");let K=Math.min(z+D2,H);try{await U2(K,void 0,{signal:X})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function lX($){let{label:Z,headless:X=!1,signal:z,version:Y}=$;if($6(Z),X){let{deviceData:W,url:Q,instructions:U}=await R2(Y),D=(async()=>{let V=await T2(W,Y,z),_=Date.now(),q=t$(V);return{id:$6(Z||q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:_+(V.expires_in??3600)*1000,enabled:!0,addedAt:_,lastUsed:_,lastRefreshedAt:_,accountId:q}})();return{url:Q,instructions:U,completion:D}}let{redirectUri:J}=await P2(),G=await q2(),B=h8(crypto.getRandomValues(new Uint8Array(32)).buffer),H=_2(J,G,B),K=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let W=await j2(G,B,void 0,z),Q=Date.now(),U=t$(W);return{id:$6(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:W.access_token,refresh:W.refresh_token,expires:Q+(W.expires_in??3600)*1000,enabled:!0,addedAt:Q,lastUsed:Q,lastRefreshedAt:Q,accountId:U}}finally{w0(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:K}}function ZZ($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let z=Z<100000000000?Z*1000:Z,Y=new Date(z);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let X=new Date($);return Number.isNaN(X.getTime())?void 0:X.toISOString()}function Z6($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function v8($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function g8($,Z){let X=$.get(Z);if(X===null||X.trim()==="")return;let z=Number(X);if(!Number.isFinite(z)||z<0||z>100)return;let Y=Z.slice(0,-13),J=Z6($.get(`${Y}-window-minutes`)),G=ZZ($.get(`${Y}-reset-at`)??void 0);if(z===0&&$.get(`${Y}-window-minutes`)==="0"&&!G)return;return{usedPercent:z,remainingPercent:100-z,resetsAt:G,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}var c8=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function u8($,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 cX($){if(c8.some((J)=>u8($,J)==="invalid"))return{};let Z={},X=g8($,"x-codex-primary-used-percent");if(X)Z.primary=X;let z=g8($,"x-codex-secondary-used-percent");if(z)Z.secondary=z;let Y=x2($);if(Y)Z.credits=Y;return Z}function p8($,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 x2($){let Z=p8($,"x-codex-credits-has-credits"),X=p8($,"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 uX($){let Z=c8.map((X)=>u8($,X));return Z.includes("valid")&&!Z.includes("invalid")}function l8($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=Z6($.window_minutes),X=ZZ($.reset_at);if($.used_percent===0&&Z===void 0&&!X)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:X,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function iX($){let Z={},X=l8($.rate_limits?.primary);if(X)Z.primary=X;let z=l8($.rate_limits?.secondary);if(z)Z.secondary=z;let Y=A2($.credits);if(Y)Z.credits=Y;return Z}function A2($){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 d8($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=Z6($.limit_window_seconds),X=ZZ($.reset_at);if($.used_percent===0&&Z===void 0&&!X)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:X,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function i8($){let Z={},X=d8($.rate_limit?.primary_window);if(X)Z.primary=X;let z=d8($.rate_limit?.secondary_window);if(z)Z.secondary=z;let Y=v8($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let J=v8($.rate_limit_reset_credits?.applicable_available_count);if(J!==void 0)Z.resetCreditsApplicable=J;let G=$.spend_control?.individual_limit;if($.spend_control===null||G===null)Z.spendControlCleared=!0;if(G&&typeof $.spend_control?.reached==="boolean"){let H=M0(G.limit),K=M0(G.used),W=M0(G.remaining),Q=M0(G.used_percent),U=M0(G.remaining_percent);if(H!==void 0&&K!==void 0&&W!==void 0&&Q!==void 0&&U!==void 0)Z.spendControl={limit:H,used:K,remaining:W,usedPercent:Q,remainingPercent:U,resetsAt:ZZ(G.reset_at),unit:G.unit,source:G.source,reached:$.spend_control.reached}}let B=$.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let H=M0(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as d4}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as E2}from"@cortexkit/claustrum-client";import{SocketClosedError as S2,SocketTimeoutError as C2,SubcCallError as I2}from"@cortexkit/subc-client";class N 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 S extends N{reason;constructor($){super("unavailable","Claustrum vault could not be reached");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function a($){if($ instanceof S||$ instanceof S2||$ instanceof C2)return"unreachable";let Z=$ instanceof E2||$ instanceof I2?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(X6,Z))return"answered";return X6[Z]}import{storeIdentity as a8}from"@cortexkit/claustrum-client";var n8=a8.length!==1,s8=a8;function o8($){let Z=$.storagePath??process.cwd();return n8?s8($.projectRoot??process.cwd(),Z):s8(Z)}function XZ($){if(n8)return $;let{projectRoot:Z,...X}=$;return X}import{resolve as r8}from"node:path";import{SubcClient as t8}from"@cortexkit/subc-client";var $$=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 YZ{#$;#Z;#J;#G=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#J}request(){if(this.#J)return this.#G=!0,this.#J;return this.#J=(async()=>{do{this.#G=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#G)})().finally(()=>{this.#J=void 0}),this.#J}}class JZ{#$;#Z=new O$;#J;#G="polling";#z;#K;#Y=!1;#X;#W=!1;#Q=0;constructor($){this.#$=$,this.#J=new YZ(async()=>{let Z=this.#W;if(this.#W=!1,Z||this.#X!==this.#$.view())await this.#$.discover(this.#X??"")},(Z)=>{if(!this.#Y)this.#$.onError?.(Z)})}get mode(){return this.#G}start(){if(this.#Y||this.#z||this.#K)return;if(typeof this.#$.client.watchScoped!=="function"){this.#U("fallback","client-without-watch");return}this.#O(!1)}stop(){if(this.#Y)return;if(this.#Y=!0,this.#K)(this.#$.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#z;this.#z=void 0,$?.handle.stop()}#U($,Z){if(this.#G===$)return;this.#G=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#N($,Z){this.#K=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,!this.#Y)Z()},$),this.#K.unref?.()}async#O($){let Z;try{Z=await this.#$.enrollmentToken()}catch(G){if(this.#Y)return;this.#$.onError?.(G),this.#L("token-unreadable");return}let X=this.#$.client.watchScoped;if(this.#Y||this.#z||!X)return;this.#Z.restart(),this.#W=$;let z,Y;try{Y=X.call(this.#$.client,(G)=>{if(this.#Y||!z||this.#z!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#U("watching","accepted");if(!this.#Z.continuous(G))this.#W=!0;this.#X=G.view,this.#J.request()},{enrollmentToken:Z})}catch(G){this.#$.onError?.(G),this.#L("watch-failed");return}z={handle:Y,notices:0},this.#z=z,this.#U("polling",$?"resubscribing":"opening");let J=z;Y.closed.then((G)=>this.#B(J,G),(G)=>this.#B(J,{kind:"transport_lost",error:G}))}#B($,Z){if(this.#Y||this.#z!==$)return;if(this.#z=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#U("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#L("refused");try{this.#$.onRefused(Z.error)}catch(X){this.#$.onError?.(X)}return}if($.notices>0){let X=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&X-$.acceptedAt>=300000)this.#Q=0;let z=Math.min(1000*2**Math.min(this.#Q,16),300000);this.#Q++,this.#U("polling","resubscribing"),this.#N(z,()=>void this.#O(!0));return}this.#L(Z.kind)}#L($){this.#U("fallback",$),this.#N(300000,()=>void this.#O(!1))}}function $9($){let Z=$.identity??o8($);return{connectionFile:$.connectionFile,async getUsage(){let X,z=!1,Y,J=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),G=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await t8.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),z)throw X.close(),Error("insula usage timeout");let B=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([G,J])}finally{z=!0,clearTimeout(Y),X?.close()}},watchUsage(X){let z,Y,J=!1,G=(async()=>{let B,H=new Promise((W,Q)=>{B=setTimeout(()=>Q(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),K=(async()=>{let W=Math.min($.handshakeTimeoutMs??3000,3000),Q=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:W}):await t8.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:W});if(z=Q,J){Q.close();return}let U=await Q.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(J){Q.close();return}Y=Q.subscribe(U,{method:"usage.watch"},X)})();try{await Promise.race([K,H])}catch(W){throw J=!0,W}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{J=!0,z?.close()});return{stop(){if(J)return;J=!0,Y?.unsubscribe(),z?.close()},closed:G}}}}var BZ=60000,e8=4*BZ,b2=2*BZ,Y6=new Map,GZ=new Map;function Z$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function k2($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!Z$(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function f2($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class Z9{transport;key;#$=[];#Z=!1;#J=new Set;#G=new Map;#z=new YZ(async()=>{try{let $=await this.transport.getUsage();if(!Z$($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>Z$(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#J=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#J)this.#G.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#J.clear()}},()=>{});#K=new O$;#Y="polling";#X=0;#W=0;#Q=new Map;#U;#N;#O={};#B=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#z.running)return this.#z.running;if(this.#Y==="watching")return Promise.resolve();for(let[X,z]of GZ)if($-z>=BZ)GZ.delete(X);let Z=GZ.get(this.key);if(Z!==void 0&&$-Z<BZ)return Promise.resolve();return GZ.set(this.key,$),this.#z.request()}watchMode(){return this.#Y}watch($={}){this.#X++;let Z=$.provider;if(Z===void 0)this.#W++;else this.#Q.set(Z,(this.#Q.get(Z)??0)+1);if(this.#X===1)this.#O=$,this.#P();let X=!1;return()=>{if(X)return;if(X=!0,Z===void 0)this.#W--;else{let z=(this.#Q.get(Z)??1)-1;if(z>0)this.#Q.set(Z,z);else this.#Q.delete(Z)}if(--this.#X===0)this.#L()}}#L(){if(this.#N)(this.#O.clearTimeoutImpl??clearTimeout)(this.#N);this.#N=void 0;let $=this.#U;this.#U=void 0,$?.handle?.stop(),this.#Y="polling"}#_($){this.#N=(this.#O.setTimeoutImpl??setTimeout)(()=>{if(this.#N=void 0,this.#X>0&&!this.#U)this.#P()},$),this.#N.unref?.()}#P(){let $=this.transport.watchUsage;if(!$){this.#Y="fallback";return}this.#Y="polling",this.#K.restart();let Z={notices:0};this.#U=Z;let X;try{X=$.call(this.transport,(z)=>this.#j(Z,z))}catch(z){this.#T(Z,z);return}Z.handle=X,X.closed.then(()=>this.#T(Z,void 0),(z)=>this.#T(Z,z))}#j($,Z){if(this.#U!==$)return;if($.notices++,$.notices===1)this.#Y="watching";if($.notices===2)this.#B=0;let X=k2(Z);if(!X)this.#K.restart();if(!(X?this.#K.continuous(X):!1)||X?.provider===void 0||this.#W>0||this.#Q.has(X.provider))this.#z.request()}#T($,Z){if(this.#U!==$)return;this.#U=void 0;let X=f2(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.#B,16),zZ);this.#B++,this.#Y="polling",this.#_(z);return}if(this.#Y="fallback",this.#z.request(),Z===void 0||a(Z)==="unreachable")this.#_(zZ)}current($,Z,X){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!Z$(z.usage))continue;let Y=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||X-Y>=e8)continue;return{entry:z,context:{fetchedAt:Y,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,X){if(!this.#Z)return{miss:"unreachable"};let z=this.#$.find((G)=>G.provider===$&&typeof G.account==="string"&&G.account.trim()===Z),Y=(z??this.#$.find((G)=>G.provider===$&&G.account===void 0&&G.errorClass!==void 0))?.errorClass;if(Y==="upstream_failed")return{miss:"upstream-failed"};if(Y==="credential_absent"||Y==="credential_unusable"||Y==="credential_rejected")return{miss:"credential"};if(Y!==void 0)return{miss:"unreachable"};if(z){let G=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Z$(z.usage)||!Number.isFinite(G))return{miss:"unreachable"};let B={entry:z,context:{fetchedAt:G,...typeof z.source==="string"&&{source:z.source}}};if(z.stale!==void 0&&(!Z$(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:B};return X>=G+e8||z.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#J.has($))return{miss:"absent"};let J=this.#G.get($)??X;return this.#G.set($,J),{miss:X-J>=b2?"unreachable":"cold"}}}function J6($,Z){let X=JSON.stringify([r8($.connectionFile),r8(Z)]),z=Y6.get(X);if(!z)z={source:new Z9($,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 tY}from"@cortexkit/claustrum-client";function h0($){let Z=new AbortController,X=[],z=!1,Y=()=>{if(z)return;z=!0;for(let{source:B,listener:H}of X)B.removeEventListener("abort",H);X.length=0},J=(B)=>{if(z||Z.signal.aborted)return;Z.abort(B),Y()},G=$.find((B)=>B.aborted);if(G)return Z.abort(G.reason),{signal:Z.signal,dispose:Y};for(let B of $){if(Z.signal.aborted)break;let H=()=>J(B.reason);if(X.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)J(B.reason)}return{signal:Z.signal,dispose:Y}}import{channel as Q4}from"node:diagnostics_channel";import{ClaustrumCredentialError as _6}from"@cortexkit/claustrum-client";import{createHash as u2,randomBytes as i2,randomUUID as s2}from"node:crypto";import{constants as z9}from"node:fs";import{chmod as a2,mkdir as n2,open as U9,readFile as H6,realpath as o2,rename as r2,stat as D9,unlink as Q6}from"node:fs/promises";import{basename as V9,dirname as L0,extname as Y9,isAbsolute as J9,join as W6,resolve as t2}from"node:path";import{ClaustrumCredentialError as N9,ClaustrumClient as e2,writeEnrollmentTokenFile as $4}from"@cortexkit/claustrum-client";import{lstat as y2,stat as w2}from"node:fs/promises";import{resolve as h2}from"node:path";async function m2($,Z){try{let X=await Z($);return X.isFile()?X:void 0}catch(X){return X.code==="ENOENT"?"absent":void 0}}function v2($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class _0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks?(Z)=>($.stat??w2)(Z):(Z)=>($.lstat??y2)(Z)}async read($,Z,X){let z=$.map((K)=>h2(K)),Y=JSON.stringify(z),J=await Promise.all(z.map((K)=>m2(K,this.#$))),G=J.every((K)=>K!==void 0)?J:void 0,B=this.#Z.get(Y);if(G&&B&&G.every((K,W)=>{let Q=B.identities[W];return Q!==void 0&&v2(K,Q)}))return X?.(G),B.value;this.#Z.delete(Y);let H=await Z(z);if(G){if(this.#Z.size>=64){let K=this.#Z.keys().next().value;if(K!==void 0)this.#Z.delete(K)}this.#Z.set(Y,{identities:G,value:H})}return H}}import{ClaustrumCredentialError as g2}from"@cortexkit/claustrum-client";var p2="Served by Thalamus",l2="This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.",X9=new WeakSet;function G6($){return X9.has($)}function b(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function B6($){if(typeof $!=="object"||$===null)return $;let Z=$;if(typeof Z.code==="string"&&(Z.class==="transient"||Z.class==="permanent"||Z.class==="auth_required"||Z.class==="context_overflow")&&(Z.action==="gone"||Z.action==="reauth"||Z.action==="retry"||Z.action==="reduce_and_retry"))return new g2(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&a(Object.assign(Error(),{code:Z.code}))==="unreachable")return new S(Z.reason==="host-accessor-missing"||Z.reason==="host-accessor-failed"?Z.reason:void 0);return $}function P$($){try{return $()}catch(Z){throw B6(Z)}}async function K0($){try{return await $()}catch(Z){throw B6(Z)}}function d2($){let Z=$.watchScoped?.bind($),X=$.reportUsageScoped?.bind($),z=$.reportCondition?.bind($),Y=$.clearCondition?.bind($);return{listScoped:(...J)=>K0(()=>$.listScoped(...J)),getScoped:(...J)=>K0(()=>$.getScoped(...J)),reportAuthFailureScoped:(...J)=>K0(()=>$.reportAuthFailureScoped(...J)),close:()=>P$(()=>$.close()),...Z&&{watchScoped:(...J)=>{let G=P$(()=>Z(...J));return{stop:()=>P$(()=>G.stop()),closed:K0(async()=>{let B=await G.closed;return B.kind==="refused"||B.kind==="transport_lost"?{...B,error:B6(B.error)}:B})}}},...X&&{reportUsageScoped:(...J)=>K0(()=>X(...J))},...z&&{reportCondition:(...J)=>K0(()=>z(...J))},...Y&&{clearCondition:(...J)=>K0(()=>Y(...J))},...$.insula&&{insula:c2($.insula)}}}function c2($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>K0(()=>$.getUsage()),...Z&&{watchUsage:(...X)=>{let z=P$(()=>Z(...X));return{stop:()=>P$(()=>z.stop()),closed:K0(()=>z.closed)}}}}}function m0($){if(!b()||!$)throw new S;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z==="function"){let X=d2(Z($));return X9.add(X),X}}catch{throw new S("host-accessor-failed")}throw new S("host-accessor-missing")}var Z4=1,KZ=16384,q9=30000,U6=/^[0-9a-f]{64}$/,M9="unknown_method",_9=new Set([M9,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),F9=new Set(["pending_queue_full"]);function K6($){if(!($ instanceof N9))return;if(_9.has($.code))return{code:$.code,disposition:"terminal"};if(F9.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function X4($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new N("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function L9($){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(!QZ(Z)||Object.keys(Z).length!==2||Z.operation!=="read"&&Z.operation!=="list"||!QZ(Z.selector))return!1;let X=Object.keys(Z.selector),z=X[0];return X.length===1&&(z==="category"||z==="exact")&&typeof Z.selector[z]==="string"&&Z.selector[z].trim().length>0})}function Q0($){return{...$.requestedGrants!==void 0&&{requestedGrants:$.requestedGrants},...$.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:$.requestedGrantsStatus}}}function z4($){return e2.connect(XZ($))}function O9($){let Z=Y9($)||".json",X=V9($,Y9($));return{statePath:W6(L0($),`${X}-state${Z}`),tokenPath:$}}function Y4($){let Z=$.override?.trim();if(Z&&!J9(Z)&&!$.cwd)throw new N("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?J9(Z)?Z:t2($.cwd,Z):W6($.stateDir,`${$.host}-enrollment.json`);return O9(X)}function QZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function HZ($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function P9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function j$(){return new N("invalid-state","invalid Claustrum enrollment state")}function UZ($){if(!QZ($)||$.version!==Z4||typeof $.proposedName!=="string"||$.proposedName.length===0)throw j$();if($.phase==="pending"){let Z=G9($);if(!U6.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!HZ($.createdAt)||!HZ($.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=G9($);if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!P9($.tokenGeneration)||!HZ($.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"||!HZ($.updatedAt))throw j$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw j$()}function G9($){if($.requestedGrants!==void 0&&!D6($.requestedGrants)||$.requestedGrantsStatus!==void 0&&($.requestedGrants===void 0||$.requestedGrantsStatus!=="sent"&&$.requestedGrantsStatus!=="dropped"))return{};return Q0($)}function V6($){if(!QZ($)||!U6.test(String($.token??""))||!P9($.token_generation))throw new N("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function j9($){if(!$.isFile())throw new N("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new N("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new N("unsafe-file","Claustrum enrollment file must be owned by the current user")}function B9($){try{return JSON.parse($)}catch{throw new N("invalid-state","Claustrum enrollment file is not valid JSON")}}async function O0($){if(W0)try{await g0(L0($));let X=await WZ($,!0);if(Buffer.byteLength(X)>KZ)throw new N("unsafe-file","Claustrum enrollment file is too large");return B9(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await U9($,z9.O_RDONLY|z9.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new N("unsafe-file","Claustrum enrollment file could not be opened safely")}try{j9(await Z.stat());let X=Buffer.alloc(KZ+1),{bytesRead:z}=await Z.read(X,0,X.byteLength,0);if(z>KZ)throw new N("unsafe-file","Claustrum enrollment file is too large");return B9(X.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function H9($,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 J4($,Z,X){try{let[z,Y]=await Promise.all([H6(X.passwdPath??"/etc/passwd","utf8"),H6(X.groupPath??"/etc/group","utf8")]),J=H9(z,7),G=H9(Y,4);if(!J||!G)return!1;let B=J.filter((Q)=>Number(Q[2])===$),H=G.filter((Q)=>Number(Q[2])===Z);if(B.length!==1||H.length!==1)return!1;let K=B[0]?.[0],W=H[0]?.[3]??"";return(W===""||W.split(",").every((Q)=>Q===K))&&!J.some((Q)=>Number(Q[2])!==$&&Number(Q[3])===Z)}catch{return!1}}function R9($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>H6(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function T9($,Z={}){if(!W0){let X=process.geteuid?.();if(X===void 0)return;let z=process.getegid?.(),Y;try{Y=await o2($)}catch{return}let J;for(;;){let G=await D9(Y).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(J===void 0)J=z!==void 0&&await J4(X,z,Z);if((G.mode&2)!==0||G.uid!==X||G.gid!==z||!J)throw new N("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=L0(Y);if(B===Y)return;Y=B}}try{await Q9($,R9(Z))}catch(X){if(!(X instanceof G0))throw X;throw new N("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function X$($,Z={},X="enrollment directory"){if(W0){await g0($,!1,R9(Z));return}await n2($,{recursive:!0,mode:448});let z=await D9($),Y=process.geteuid?.();if(Y!==void 0&&z.uid!==Y)throw new N("unsafe-file",`Claustrum ${X} must be owned by the current user`);if((z.mode&63)!==0)await a2($,448)}async function v0($,Z,X={}){let z=L0($);await X$(z,X),await T9(z,X);let Y=`${JSON.stringify(Z)}
89
- `;if(Buffer.byteLength(Y)>KZ)throw new N("invalid-state","Claustrum enrollment state is too large");if(W0)return W9($,Y);let J=W6(z,`.${V9($)}.${process.pid}.${s2()}.tmp`),G,B=!1;try{G=await U9(J,"wx",384),B=!0,await G.writeFile(Y,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await r2(J,$),B=!1}finally{if(await G?.close().catch(()=>{}),B)await Q6(J).catch(()=>{})}}var G4=new _0;async function N6($,Z){let X=W0?await K9($,Z):await G4.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,J=$.statePath])=>K9({tokenPath:Y,statePath:J},Z),(Y)=>{for(let J of Y)if(J!=="absent")j9(J)}),z={...X.status};if(X.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function K9($,Z){let X=await O0($.tokenPath),z=X===void 0?void 0:V6(X),Y=await O0($.statePath),J=Y===void 0?void 0:UZ(Y);if(z)return{usesProposedName:J===void 0,status:{state:"approved",proposedName:J?.proposedName??Z,...J?.phase==="approved"&&J.approvedName!==void 0&&{approvedName:J.approvedName},tokenGeneration:z.token_generation,...J&&(J.phase==="approved"||J.phase==="pending")&&Q0(J)}};if(!J)return{status:{state:"idle"},usesProposedName:!1};if(J.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:J.proposedName,code:"missing_token"}};return{status:F0(J),usesProposedName:!1}}async function x9($,Z){let X;try{X=await N6($,Z)}catch(z){if(!(z instanceof N)||z.kind!=="invalid-state"&&z.kind!=="invalid-token")return"unreadable";try{let Y=await O0($.statePath);if(Y===void 0)return"unreadable";let J=UZ(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 B4($,Z){if(b())return"host";return x9($,Z)}async function P0($){let Z=await O0($);if(Z===void 0)throw new N("not-enrolled","Claustrum enrollment is not configured");return V6(Z)}function F0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId},...Q0($)};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,...Q0($)};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function A9(){return new N("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class E9{#$;#Z;#J;#G;#z;#K;#Y;#X;#W;constructor($){if($.displayName!==void 0&&!L9($.displayName))throw new N("invalid-state","invalid Claustrum enrollment display name");if($.requestedGrants!==void 0&&!D6($.requestedGrants))throw new N("invalid-state","invalid Claustrum enrollment requested grants");this.#z=$.requestedGrants?.map((Z)=>({selector:{...Z.selector},operation:Z.operation})),this.#W=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#J=$.proposedName,this.#G=$.displayName,this.#K=$.now??Date.now,this.#Y=$.mintSecret??(()=>i2(32).toString("hex")),this.#X=$.writeTokenFile??$4}async status(){return N6(this.#Z,this.#J)}async resetTerminal(){return S9(this.#Z,this.#J)}async#Q($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#K()};return await v0(this.#Z.statePath,X,this.#W),F0(X)}async reconcile(){await X$(L0(this.#Z.statePath),this.#W);let $=await g({name:"ceremony",path:this.#Z.statePath,ttlMs:q9,renew:!0});if(!$)return{state:"busy"};try{let Z=await O0(this.#Z.tokenPath),X=Z===void 0?void 0:V6(Z),z=await O0(this.#Z.statePath),Y=z===void 0?void 0:UZ(z);if(Y&&Y.proposedName!==this.#J)throw A9();if(X){if(!Y||Y.phase==="pending"){let G={version:1,phase:"approved",proposedName:Y?.proposedName??this.#J,tokenGeneration:X.token_generation,...Y&&Q0(Y),updatedAt:this.#K()};await v0(this.#Z.statePath,G,this.#W),Y=G}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:X.token_generation,...Y.phase==="approved"&&Q0(Y)}}if(Y?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#K()};return await v0(this.#Z.statePath,G,this.#W),F0(G)}if(Y&&Y.phase!=="pending")return F0(Y);if(!Y){let G=this.#K();if(Y={version:1,phase:"pending",proposedName:this.#J,requestSecret:this.#Y(),createdAt:G,updatedAt:G,...this.#z!==void 0&&{requestedGrants:this.#z}},!U6.test(Y.requestSecret))throw new N("invalid-state","invalid minted Claustrum enrollment secret");await v0(this.#Z.statePath,Y,this.#W)}if(!Y.requestId)try{let G=u2("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B={name:Y.proposedName,requestSecretHash:G},H,K=Y.requestedGrantsStatus;try{if(H=await this.#$.enrollPropose({...B,...this.#G!==void 0&&{displayName:this.#G},...Y.requestedGrants!==void 0&&{requestedGrants:Y.requestedGrants}}),Y.requestedGrants!==void 0)K="sent"}catch(W){if(this.#G===void 0&&Y.requestedGrants===void 0||!(W instanceof N9)||W.code!=="invalid_params")throw W;if(H=await this.#$.enrollPropose(B),Y.requestedGrants!==void 0)K="dropped"}Y={...Y,requestId:H.requestId,updatedAt:this.#K(),...K!==void 0&&{requestedGrantsStatus:K}},await v0(this.#Z.statePath,Y,this.#W)}catch(G){let B=K6(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code,...Q0(Y)};if(B.code===M9)return await $.assertOwned(),await Q6(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#Q(Y,B.code)}let J=Y.requestId;if(!J)return F0(Y);try{let G=await this.#$.enrollPoll({requestId:J,requestSecret:Y.requestSecret});if(G.status==="pending")return F0(Y);if(G.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#K()};return await v0(this.#Z.statePath,H,this.#W),F0(H)}await X$(L0(this.#Z.tokenPath),this.#W),await T9(L0(this.#Z.tokenPath),this.#W),await this.#X(this.#Z.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,...Q0(Y),updatedAt:this.#K()};return await v0(this.#Z.statePath,B,this.#W),F0(B)}catch(G){let B=K6(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:J,retryCode:B.code,...Q0(Y)};return this.#Q(Y,B.code)}}finally{await $.release()}}}async function S9($,Z){await X$(L0($.statePath));let X=await g({name:"ceremony",path:$.statePath,ttlMs:q9,renew:!0});if(!X)return"busy";try{if(await O0($.tokenPath)!==void 0)return"refused-approved";let z=await O0($.statePath);if(z===void 0)return"idle";let Y=UZ(z);if(Y.proposedName!==Z)throw A9();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 DZ($){return`${R$}${$}`}function q6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function VZ($){return typeof $==="string"&&$.startsWith(R$)}function C9($,Z){if(!q6($)||$.type!=="oauth")return!1;return $.refresh===DZ(Z)}function I9($,Z){if(C9($,Z))return"placeholder";if(q6($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!VZ($.refresh))return"login";if(q6($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function H4($){let Z=I9($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new N("host-slot-login",`${$.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if($.mode==="local"&&Z==="placeholder")throw new N("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function z$($,Z){let X=!1;return(z)=>{if(X)return;if(!Z||Z.aborted)X=!0;$.warn("claustrum shutdown drain timed out",{pendingOperations:z})}}async function Y$($,Z){if(!$.size)return;let X,z=!1,Y=(async()=>{while(!z&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([Y,new Promise((J)=>{X=setTimeout(()=>{z=!0,J()},2000)})]),z&&$.size)Z($.size)}finally{z=!0,clearTimeout(X)}}import{ClaustrumCredentialError as K4}from"@cortexkit/claustrum-client";function b9($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class M6{options;#$=new Map;#Z=new Map;#J=new Set;#G;#z;#K=!1;#Y=!1;#X=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#z!==void 0,dropped:this.#X}}report($,Z){if(this.#K||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#X++;return}if(!b9(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(!b9(z)||"credentialId"in z||"vouched"in z||typeof z.observedAtMs!=="number"||!Number.isFinite(z.observedAtMs))throw Error("invalid reading");if(z.observedAtMs<=(this.#Z.get($)??-1/0)){this.#X++;return}if(this.#$.has($))this.#X++;if(this.#Z.set($,z.observedAtMs),this.#$.set($,z),!this.#G&&!this.#z)this.#G=this.options.setTimeout(()=>{this.#G=void 0,this.#W()},1000),this.#G.unref?.()}catch{this.#X++}}forget($){if(this.#$.delete($))this.#X++;this.#Z.delete($)}#W(){if(this.#z||!this.#$.size||this.#Y)return this.#z;let $=Promise.resolve().then(async()=>{while(!this.#Y&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[X,z]=Z;this.#$.delete(X);try{let Y=await this.options.token();if(this.#Y||!this.options.owns(X)){if(!this.#Y)this.#X++;continue}await this.options.client.reportUsageScoped?.({credentialId:X,reading:z,enrollmentToken:Y})}catch(Y){if(!this.#Y)this.#X++;this.#Q(Y)}}});return this.#z=$,$.finally(()=>{this.#z=void 0}),$}#Q($){let Z="transport_error";try{if($ instanceof K4)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#J.has(Z))return;this.#J.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#K=!0,this.#G)this.options.clearTimeout(this.#G);return this.#G=void 0,this.#W()}drop(){this.#Y=!0,this.#X+=this.#$.size+(this.#z?1:0),this.#z=void 0,this.#$.clear(),this.#Z.clear()}}function y9($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function W4($,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 L6=p("claustrum");function k9($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new N("invalid-token","Invalid Claustrum enrollment token");return $.token}var j0=Q4("common-auth.claustrum.phases");function P6($,Z,X,z=L6){let Y=y9(Z,X);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:Y,reason:W4(Z,X)}),Y}var O6=300000,w9=60000,h9=1e4,m9=60000;function F6(){return new N("invalid-material","Claustrum returned invalid credential material")}function U4($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw F6()}if(!X||typeof X!=="object")throw F6();let z=X,Y=z.access_token??z.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(R$))throw F6();return Z}function D4($,Z){let X={kind:"not-mine"};if(!$.operations.includes("read"))return X;if(!$.categories.includes(Z.category))return X;if("classify"in Z){let J=f9($),G;switch(J.authMethod){case"apikey":G="api_key";break;case"chatgpt":case"antigravity":case"oauth":G="oauth";break;default:return{kind:"refused",code:"unknown-auth-method"}}let B={credentialId:$.id,credentialType:G,categories:$.categories,refreshAdapter:$.refreshAdapter,...J};if(B.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let H=Z.classify(B);if(H.kind==="not-mine")return X;if(H.kind==="mine"&&typeof H.member==="string")return{kind:"mine",type:G,member:H.member};if(H.kind==="refused"&&typeof H.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(H.code)&&!H.code.includes(`
90
- `)&&Z.refusalCodes.includes(H.code))return{kind:"refused",code:H.code}}catch{}return{kind:"refused",code:"unclassified"}}let z=$.credentialType;if(z==="oauth"){if($.refreshAdapter!==Z.refreshAdapter)return X}else if(z==="api_key"){if(!Z.apiKeys||$.refreshAdapter!==void 0)return X}else return X;let{authMethod:Y}=f9($,{includeProviderIds:!1});if(Y!==void 0){if(!(z==="oauth"?Y==="chatgpt"||Y==="antigravity"||Y==="oauth":Y==="apikey"))return{kind:"refused",code:"unknown-auth-method"}}return{kind:"mine",type:z}}function f9($,{includeProviderIds:Z=!0}={}){let X=$;return{providerIds:Z?X.providerIds:void 0,authMethod:X.authMethod}}function v9($){return $==="provider_verification_required"||$==="provider_ineligible"}function V4($){let Z=$.condition;if(!Z)return;let{reason:X,sinceMs:z}=Z;if(v9(X)&&Number.isSafeInteger(z)&&z>0)return Object.freeze({reason:X,sinceMs:z});return}function N4($){if(typeof $!=="string")return;try{if(new URL($).protocol==="https:")return $}catch{}return}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 J${#$;#Z;#J;#G;#z;#K;#Y;#X=new WeakMap;#W=new WeakMap;#Q=new Map;#U=new Map;#N=!1;#O=0;#B=new Map;#L=new WeakMap;#_;#P=new Map;#j;#T;#H=!1;#R=0;#x=!1;#V=new S;#q=new Map;#M;#A=!1;#I=-1/0;#y=2000;#D=!1;#E;#b=new Map;#S=new Set;#C=new Set;#w;#m;#l;constructor($){if(b()&&$.client&&!G6($.client))throw new S;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>P0(Z);else if(b())this.#Z=async()=>{throw new N("not-enrolled","Claustrum enrollment token path is required")};else throw new N("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client??m0($.pluginId),this.#G=$.family,this.#z=$.parseIdentity,this.#K=$.requireAssertion??!1,this.#J=$.now??Date.now,this.#Y=$.logger??L6,this.#w=z$(this.#Y),this.#j=$.setTimeoutImpl??setTimeout,this.#T=$.clearTimeoutImpl??clearTimeout;let X=()=>this.#$;this.#_=new M6({client:{get reportUsageScoped(){let z=X();return z.reportUsageScoped?.bind(z)}},owns:(z)=>this.#P.has(z),token:async()=>b()?"":k9(await this.#Z()),logger:this.#Y,setTimeout:this.#j,clearTimeout:this.#T})}replaceClient($){if(this.#F(),$===this.#$)return;if(b()&&!G6($))throw new S;this.#$=$,this.#N=!1;for(let Z of this.#S)Z.restart()}transportLost($){if(this.#D||this.#H)return;this.#H=!0,this.#R=this.#J(),this.#x=!1,this.#V=$ instanceof _6?$:new S($ instanceof S?$.reason:void 0),this.#Y.warn("serving kept vault receipt",{reason:"unreachable"}),this.#k()}reachable(){if(this.#D||!this.#H)return;if(this.#H=!1,this.#M)this.#T(this.#M);this.#M=void 0,this.#y=2000;for(let $ of this.#B.values())$.since=null;(this.#Y.info??L6.info)("vault receipt serving resumed",{reason:"reachable"})}#k(){if(this.#D||!this.#H||this.#M||this.#A)return;this.#M=this.#j(()=>{this.#M=void 0,this.#h(!0)},this.#y),this.#M.unref?.()}#h($=!1){if(this.#D||!this.#H||this.#A)return;if(this.#J()-this.#I<1000){this.#k();return}this.#I=this.#J(),this.#A=!0,this.#i().catch(()=>{if($&&this.#H)this.#y=Math.min(this.#y*2,30000)}).finally(()=>{this.#A=!1,this.#k()})}#F($){if(this.#D)throw new N("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#v($){if(this.#F($),b())return"";if(j0.hasSubscribers)j0.publish({logger:this.#Y,phase:"token read begin"});let Z=this.#Z();this.#C.add(Z);let X;try{X=await Z}finally{if(this.#C.delete(Z),j0.hasSubscribers)j0.publish({logger:this.#Y,phase:"token read end"})}return this.#F($),k9(X)}async#f($,Z){this.#F(Z);let X,z;try{let Y=$();X=Z?await Promise.race([Y,new Promise((J,G)=>{let B=()=>G(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),z=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await Y}catch(Y){if(this.#F(Z),a(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof _6)throw Y;if(a(Y)==="unreachable")throw new S(Y instanceof S?Y.reason:void 0);throw new N("unavailable","Claustrum scoped operation failed")}finally{z?.()}return this.#F(Z),this.reachable(),X}async discover($){let Z=await this.#i($);this.#E=Z.view,this.#b.clear();for(let{credentialId:X,condition:z}of Z.credentials)if(z)this.#b.set(X,z);return Z}async#i($){let Z,X;try{X=await this.#v($)}catch(Q){throw this.#B.clear(),this.#d(),Q}if(j0.hasSubscribers)j0.publish({logger:this.#Y,phase:"list scoped begin"});try{Z=await this.#f(()=>this.#$.listScoped(X),$)}catch(Q){throw this.listFailed(Q),Q}finally{if(j0.hasSubscribers)j0.publish({logger:this.#Y,phase:"list scoped end"})}let z=[],Y=[],J=0,G=[],B=new Map;for(let Q of Z.rows){let U=D4(Q,this.#G);if(U.kind==="not-mine"){J++;continue}if(U.kind==="refused"){Y.push({...Q.id.trim()&&{credentialId:Q.id},code:U.code});continue}G.push({row:Q,type:U.type,...U.member!==void 0&&{member:U.member}}),B.set(Q.id,(B.get(Q.id)??0)+1)}let H=[];for(let{row:Q,type:U,member:D}of G){let V;if(!Q.id.trim())V="empty credential id";else if((B.get(Q.id)??0)>1)V="duplicate credential id";else if(Q.accountId!==void 0&&!Q.accountId.trim())V="blank account identity";else if(!Q.state.trim())V="empty state";if(V){z.push({...Q.id.trim()&&{credentialId:Q.id},...D!==void 0&&{member:D},reason:V});continue}let _=V4(Q);H.push(Object.freeze({credentialId:Q.id,credentialType:U,...D!==void 0&&{member:D},...Q.accountId!==void 0&&{accountIdentity:Q.accountId},state:Q.state,...Q.email!==void 0&&{email:Q.email},...Q.orgName!==void 0&&{orgName:Q.orgName},..._&&{condition:_}}))}for(let Q of z)this.#Y.warn("skipped malformed vault record",Q);let K=q4(Z),W="classify"in this.#G;return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),...(W||Y.length>0)&&{refused:Object.freeze(Y)},...W&&{notMine:J},...K&&{grantReach:K}}}listFailed($){if(a($)==="unreachable")this.transportLost($);else this.reachable(),this.#B.clear(),this.#d()}forget($){this.#B.delete($),this.#P.delete($),this.#_.forget($)}#d(){for(let $ of this.#P.keys())this.#_.forget($);this.#P.clear()}retain($){let Z=new Map($.map((X)=>[X.credentialId,X]));for(let[X,z]of this.#B){let Y=Z.get(X);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==z.attempt.credentialType||Y.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(X)}for(let[X,z]of this.#P){let Y=Z.get(X);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==z.credentialType||Y.accountIdentity!==z.accountIdentity)this.forget(X)}}keptReceiptState(){let $=null;for(let[Z,X]of this.#B){if(!this.#c(X.attempt)){this.forget(Z);continue}if(X.since!==null)$=Math.min($??X.since,X.since)}return Object.freeze({active:$!==null,since:$})}#c($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#J()>w9}async authorize($,Z,X="vault"){this.#F(Z);let z=this.#J(),{credentialId:Y,credentialType:J,accountIdentity:G}=$,B=this.#B.get(Y);if(B&&(B.attempt.credentialType!==J||B.attempt.expectedAccountIdentity!==G||!this.#c(B.attempt)))this.forget(Y),B=void 0;let H;try{H=await this.#v(Z)}catch(K){throw this.#B.clear(),this.#d(),K}if(this.#H&&B)return this.#h(),this.#g(Y,B,H,X);try{let K;try{if(this.#H&&this.#q.has(this.#s({credentialId:Y,credentialType:J,accountIdentity:G},H)))throw this.#V;K=await this.#p({credentialId:Y,credentialType:J,accountIdentity:G},H,Z)}catch(W){if(this.#F(Z),a(W)!=="unreachable"||B)throw W;K=await this.#o({credentialId:Y,credentialType:J,accountIdentity:G},H,z,W,Z)}return this.#B.set(Y,{attempt:K,routeId:X,since:null}),this.#P.set(Y,{...$}),K}catch(K){if(this.#F(Z),a(K)!=="unreachable")throw this.forget(Y),K;return this.#g(Y,B,H,X,K)}}#s($,Z){return JSON.stringify([$.credentialId,$.credentialType,$.accountIdentity,Z])}async#o($,Z,X,z,Y){let J=h9-(this.#J()-X);if(J<=0||this.#x||this.#J()-this.#R>=m9)throw z;let G=this.#s($,Z),B=this.#q.get(G);if(!B){let Q=new AbortController,U={controller:Q,users:0,error:z,pending:Promise.resolve().then(async()=>{let V=250;for(;;){await this.#u(V,Q.signal);try{return await this.#p($,Z,Q.signal)}catch(_){if(this.#F(Q.signal),a(_)!=="unreachable")throw _;U.error=_,V=Math.min(V*2,1000)}}})};B=U,this.#q.set(G,B);let D=()=>{if(this.#q.get(G)===U)this.#q.delete(G)};B.pending.then(D,D)}let H=B;H.users++;let K,W;try{let Q=await Promise.race([H.pending,new Promise((D,V)=>{if(K=this.#j(()=>{if(this.#H)this.#x=!0;V(H.error)},J),K.unref?.(),Y){if(W=()=>V(Y.reason),Y.addEventListener("abort",W,{once:!0}),Y.aborted)W()}})]);this.#F(Y);let U=Object.freeze(Object.defineProperty({...Q},"accessToken",{value:Q.accessToken,enumerable:!1}));return this.#X.set(U,{token:Z}),U}finally{if(K)this.#T(K);if(W)Y?.removeEventListener("abort",W);if(--H.users===0){if(H.controller.abort(),this.#q.get(G)===H)this.#q.delete(G)}}}#u($,Z){return this.#F(Z),new Promise((X,z)=>{let Y=()=>{this.#T(J),Z.removeEventListener("abort",Y),z(Z.reason)},J=this.#j(()=>{Z.removeEventListener("abort",Y),X()},$);if(J.unref?.(),Z.addEventListener("abort",Y,{once:!0}),Z.aborted)Y()})}#g($,Z,X,z,Y=this.#V){if(!Z||this.#B.get($)!==Z||!this.#c(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#J();let J=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#X.set(J,this.#X.get(Z.attempt)??{token:X}),this.#L.set(J,z),J}async#p($,Z,X){if(!$.credentialId)throw new N("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:Y,accountIdentity:J}=$;if(this.#K&&J===void 0)throw new N("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#f(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:O6}}),X);if(G.credentialId!==void 0&&G.credentialId!==z)throw new N("identity-changed","Claustrum served credential identity changed");let B=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#J()<O6))throw new N("insufficient-validity","Claustrum served credential has insufficient validity");let H=U4(G.material),K=G.accountId?.trim()?G.accountId:void 0;if(this.#K&&(G.credentialId===void 0||K===void 0))throw new N("identity-unasserted","Claustrum served credential did not assert its identity");let W=K===void 0?this.#z?.(H):void 0,Q=K??W;if(J!==void 0&&Q!==void 0&&Q!==J)throw new N("identity-changed","Claustrum served credential identity changed");let U=Q??J,V=Object.freeze(Object.defineProperty({credentialId:z,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:K!==void 0?"asserted":W!==void 0?"parsed":J!==void 0?"expected":"none",...J!==void 0&&{expectedAccountIdentity:J},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...K!==void 0&&{assertedAccountIdentity:K},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#X.set(V,{token:Z}),V}async reportFailure($,Z,X){if(Z!==401)return;this.#F();let z=this.#X.get($);if(!z)throw new N("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#L.get($);if(Y!==void 0){this.forget($.credentialId),this.#Y.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let J=this.#B.get($.credentialId);if(J&&J.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let G=this.#W.get($);if(G)return G;let B=this.#f(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#W.set($,B);try{await B,this.#Y.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(H){throw this.#W.delete($),H}}reportCondition($,Z){let X=this.#X.get($);if(!X)return Promise.reject(new N("no-receipt","Claustrum condition report requires an original dispatch receipt"));let{reason:z,providerStatus:Y}=Z??{};if(this.#D||this.#L.has($)||Y!==403||!v9(z))return Promise.resolve("skipped");let{credentialId:J,recordVersion:G}=$,B=z==="provider_verification_required"?N4(Z.actionUrl):void 0;return this.#a(this.#Q,JSON.stringify([J,G,z]),{credentialId:J,recordVersion:G,reason:z},(H)=>H.reportCondition?.({credentialId:J,recordVersion:G,reason:z,providerStatus:Y,...B!==void 0&&{actionUrl:B},enrollmentToken:X.token}))}clearCondition($){let Z=this.#X.get($);if(!Z)return Promise.reject(new N("no-receipt","Claustrum condition clear requires an original dispatch receipt"));if(this.#D||this.#L.has($))return Promise.resolve("skipped");let{credentialId:X,recordVersion:z}=$,Y=this.#b.get(X);if(!Y)return Promise.resolve("skipped");return this.#a(this.#U,JSON.stringify([X,Y.sinceMs]),{credentialId:X,recordVersion:z,reason:Y.reason},(J)=>J.clearCondition?.({credentialId:X,recordVersion:z,enrollmentToken:Z.token}))}#a($,Z,X,z){let Y=$.get(Z);if(Y)return Y;if(this.#N)return Promise.resolve("unsupported");let J=Promise.resolve().then(async()=>{let G=this.#$;if(this.#N)return"unsupported";try{let B=z(G);if(!B)return"unsupported";if(await B===!1)this.#n("scoped login condition not cleared",X);return"reported"}catch(B){if(B instanceof _6&&B.code==="unknown_method"){if(G===this.#$)this.#N=!0;return"unsupported"}return this.#n("scoped login condition update failed",X),"failed"}});return $.set(Z,J),this.#O++,this.#C.add(J),J.then(()=>{this.#O--,this.#C.delete(J)}),J}#n($,Z){try{this.#Y.debug($,Z)}catch{}}watchRoster($){this.#F();let Z=$.view??(()=>this.#E),X,z,Y=(G=!1)=>{let B=new JZ({client:this.#$,enrollmentToken:()=>this.#v(),view:()=>G?void 0:Z(),discover:async(H)=>{while(X)await X.catch(()=>{});if(z!==B)return;G=!1,X=Promise.resolve().then(()=>$.onView(H));try{await X}finally{X=void 0}},onRefused:(H)=>{this.listFailed(H),$.onRefused?.(H)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#Y,now:this.#J,setTimeoutImpl:this.#j,clearTimeoutImpl:this.#T});return B};z=Y();let J={restart:()=>{let G=z.mode;if(z.stop(),z=Y(!0),G!==z.mode)$.onMode?.(z.mode);z.start()},stop:()=>z.stop()};return this.#S.add(J),z.start(),{get mode(){return z.mode},close:()=>{this.#S.delete(J),z.stop()}}}reportUsage($){if(this.#D)return;try{this.#_.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#_.state()}close(){if(this.#D)return;this.#D=!0;for(let X of this.#q.values())X.controller.abort();if(this.#q.clear(),this.#M)this.#T(this.#M);this.#M=void 0;for(let X of this.#S)X.stop();this.#S.clear(),this.#B.clear();let $=this.#_.close(),Z=$!==void 0||this.#O>0;if($)this.#C.add($),$.then(()=>this.#C.delete($));if(!Z)this.#$.close();this.#l=Y$(this.#C,(X)=>(this.#m??this.#w)(X)).finally(()=>{if(this.#_.drop(),this.#P.clear(),Z)this.#$.close()})}async dispose($=this.#w){this.#m=$,this.close(),await this.#l}}import{resolve as MZ}from"node:path";var g9=30000,p9={now:()=>performance.now(),schedule($,Z){let X=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(X),unref:()=>X.unref?.()}}};function l9($,Z=""){let X=new Map,{observation:z}=$,Y=(B,H,K)=>X.set(`${Z}:${B}`,{at:H,order:0,publication:{...$,observation:K}}),J=(B,H)=>JSON.stringify([B??"all",H]),G=new Set;for(let B of z.readings??[]){let H=J(B.scope,B.label);G.add(H),Y(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...B}]})}for(let B of z.coverage??[]){let H=J(B.scope,B.label);if(!G.has(H))Y(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...B}]})}if(z.budget)Y("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[B,H]of Object.entries(z.counters??{}))Y(`counter:${B}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[B]:{...H}}});if(z.credits)Y("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!X.size)Y("empty",z.checkedAt,{checkedAt:z.checkedAt});return X}import{createHash as M4}from"node:crypto";import{stat as _4}from"node:fs/promises";import{resolve as T$}from"node:path";function d9($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function j6($,Z,X){return $.some((z)=>d9(z,Z,X))}function R6($,Z,X){let z={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==X),z]}function T6($,Z,X){return $.filter((z)=>!Z.some((Y)=>d9(z,Y,X)))}function A6($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>$0(Z).map((X)=>({credentialId:X,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function F4($,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 qZ="vault:";function L4($){return M4("sha256").update($).digest("hex")}function O4($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function P4($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function $0($){return[$.credentialId,...$.aliases??[]]}function i9($,Z,X={}){let z=X.now??Date.now(),Y=X.routePrefix??qZ,J=X.reservedRouteIds??new Set,G=$?.rows??[],B=$?void 0:X.seed,H=[...$?.declined??B?.declined??[]],K=Z.skipped.length===0,W=new Set(Z.credentials.map((F)=>F.credentialId)),Q=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),U=Z.skipped.some((F)=>F.credentialId===void 0),D=(F)=>!W.has(F)&&(Q.has(F)||U),V=new Map;for(let F of G){if(F.accountIdentity===void 0)continue;for(let P of $0(F))if(!V.has(P))V.set(P,F.accountIdentity)}let _=new Map;for(let F of Z.credentials){let P=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:V.get(F.credentialId),claimed:!1},w=P4(P),d=_.get(w)??[];d.push(P),_.set(w,d)}let q=new Set,R=new Set(J),x=[],L=(F,P)=>F.credential.credentialId.localeCompare(P.credential.credentialId),O=[..._.values()].map((F)=>F.toSorted(L)).sort((F,P)=>F[0]&&P[0]?L(F[0],P[0]):0);for(let F of O){let P=F[0]?.identity,w=F.filter((T)=>T.credential.state==="active"),d=w.length?w:F,s0=d.filter((T)=>T.claimed),i=s0.length?s0:d,a0=new Set(F.map((T)=>T.credential.credentialId)),l$=G.find((T)=>!q.has(T)&&$0(T).some((o0)=>a0.has(o0))&&(T.accountIdentity===void 0||T.accountIdentity===P)),n0=i.find((T)=>T.credential.credentialId===l$?.credentialId)??i[0];if(!n0)continue;let h=n0.credential,c=l$??(P===void 0?void 0:G.find((T)=>!q.has(T)&&T.accountIdentity===P));if(c)q.add(c);let r=c?.routeId;if(!r||J.has(r)){let T=`${Y}${h.credentialId}${P===void 0?"":`~${L4(P).slice(0,10)}`}`;r=T;for(let o0=2;R.has(r);o0++)r=`${T}~${o0}`}R.add(r);let I=c?$0(c).filter(D):[],y=[...new Set([...F.map((T)=>T.credential.credentialId),...I])].filter((T)=>T!==h.credentialId).sort((T,o0)=>T.localeCompare(o0)),N0=X.mapAccount?.(h)??{};x.push({previousIndex:c?G.indexOf(c):1/0,row:{routeId:r,credentialId:h.credentialId,credentialType:h.credentialType,...P!==void 0&&{accountIdentity:P},...y.length&&{aliases:y},state:h.state,label:N0.label?.trim()||O4(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...y].some((T)=>j6(H,T,P)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!n0.claimed&&P!==void 0&&{unclaimed:!0}}});let Y0=x.at(-1);if(B&&Y0)Y0.previousIndex=F4(B,Y0.row)}return G.forEach((F,P)=>{if(q.has(F)||!$0(F).some(D))return;if(R.has(F.routeId))return;let[w,...d]=$0(F).filter((a0)=>!W.has(a0));if(w===void 0)return;R.add(F.routeId);let{aliases:s0,...i}=F;x.push({previousIndex:P,row:{...i,credentialId:w,...d.length&&{aliases:d},stale:!0}})}),x.sort((F,P)=>F.previousIndex===P.previousIndex?F.row.credentialId.localeCompare(P.row.credentialId):F.previousIndex-P.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:K,...!K&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:x.map((F)=>F.row),declined:H}}function E6($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function x$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function G$($){return $===void 0||typeof $==="string"}function j4($){let Z=x$($)?S0($.quota):void 0;if(!x$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!G$($.accountIdentity)||!G$($.email)||!G$($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((X)=>typeof X==="string"))||$.quota!==void 0&&Z===void 0||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return{...$,...Z===void 0?{}:{quota:Z}}}var R4=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function c9($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!x$(X)||!G$(X.credentialId)||typeof X.reason!=="string"||!R4.has(X.reason))return;Z.push(X)}return Z}function s9($){if(!x$($)||$.version!==1||!G$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!c9($.rejected))throw new N("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let J=j4(Y);if(!J)throw new N("invalid-state","Claustrum roster file is not valid");Z.push(J)}let X=[];for(let Y of $.declined){if(!x$(Y)||typeof Y.credentialId!=="string"||!G$(Y.accountIdentity))throw new N("invalid-state","Claustrum roster file is not valid");X.push(Y)}let z=c9($.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 S6($){return s9(JSON.parse(JSON.stringify($)))}var T4=new _0({followSymlinks:!0});async function f($){if(W0)return x6($);let Z=await T4.read([$],([X=$])=>x6(X));return structuredClone(Z)}async function x6($){let Z;try{Z=await WZ($,W0)}catch(z){if(z.code==="ENOENT")return;throw z}let X;try{X=JSON.parse(Z)}catch{throw new N("invalid-state","Claustrum roster file is not valid")}return s9(X)}var a9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},n9={name:"claustrum-roster",ttlMs:30000};async function p0($,Z,X={}){return I0($,{...a9,signal:X.signal},async(z)=>{let Y=await x6($),{next:J,result:G}=await Z(Y,{assertOwned:()=>z.assertOwned()});if(J){await z.assertOwned();try{await B0($,J,{beforeRename:async()=>{await X.beforePublish?.(),X.signal?.throwIfAborted(),await z.assertOwned()}})}catch(B){if(B&&typeof B==="object"&&"published"in B&&B.published===!0)X.onPublished?.();throw B}X.onPublished?.()}return G})}function C6($,Z){return p0($,(X)=>{let z=X?.rows.find((J)=>J.routeId===Z);if(!X||!z)throw new N("route-unavailable","Claustrum route is not in the roster");let Y=R6(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 I6($,Z){return p0($,(X)=>{let z=X?.rows.find((Y)=>Y.routeId===Z);if(!X||!z)throw new N("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:T6(X.declined,$0(z),z.accountIdentity),rows:X.rows.map((Y)=>Y===z?{...Y,enabled:!0}:Y)},result:void 0}})}function x4($){return new N("invalid-order",$)}function A4($,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 b6($,Z,X={}){return p0($,(z)=>{let Y=z?.rows??[],J=A4(Y,Z);if(J)throw x4(J);let G=new Map;for(let K of Y){let W=G.get(K.routeId);if(W)W.push(K);else G.set(K.routeId,[K])}let B=[...Z],H=B.flatMap((K)=>G.get(K)??[]);if(!z||H.every((K,W)=>K===Y[W]))return{result:{ids:B,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:B,outcome:"reordered"}}},{...X.signal&&{signal:X.signal}})}function E4($,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 k6($,Z){let{routeId:X,observation:z,...Y}=Z;return o9($,{routeId:X,observation:z,accountIdentity:Y.accountIdentity,receipt:Y})}async function o9($,Z){if(!t0(Z.observation))return!1;let X=u($,await f($));if(!R0(X,Z).kept)return!1;return t9($,Z)}function f6($,Z){return o9($,Z)}function R0($,Z){let X=$?.rows.find((G)=>G.routeId===Z.routeId),z=!X?"refuse":Z.receipt?E4(X,Z.receipt):X.accountIdentity!==void 0&&X.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!X||z==="refuse")return{roster:$,kept:!1};let Y=V$(X.quota,Z.observation),J=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((G)=>G===X?{...G,...J,quota:Y}:G)},kept:!0}}var NZ=new Map;function A$($){NZ.delete(T$($))}function r9($,Z){let X=T$($);if(Z instanceof N)return Z.kind==="roster-busy";if(Z instanceof e||Z instanceof M$)return T$(Z.details.target)===X;if(Z instanceof G0){let z=T$(Z.path);return[a9.name,n9.name].some((Y)=>{let J=q$(X,Y);return z===J||z.startsWith(`${J}.`)})}return!1}var S4=4;async function u9($){try{let{dev:Z,ino:X,size:z,mtimeMs:Y}=await _4($);return{dev:Z,ino:X,size:z,mtimeMs:Y}}catch{return}}function C4($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function I4($,Z,X){for(let z=0;z<S4;z++){let Y=await u9($),J=await f($),G,B,H;try{({target:G,local:B}=Z(J));let K=JSON.stringify(X(G));H=JSON.stringify(G)!==K||B!==void 0&&JSON.stringify(B)!==K}catch{return"commit"}if(!C4(Y,await u9($)))continue;if(H)return"commit";return e9($)?"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({...n9,path:$.path,renew:!0});if(!X){let G=await f($.path);if($.signal?.throwIfAborted(),!G?.view)throw new N("roster-busy","Claustrum account discovery is already in progress");return G}let z=T$($.path),Y=$.listedOver,J;try{let G=await f($.path),B=Y?void 0:NZ.get(z);J=B&&(B.previousView===G?.view||B.inventory.view===G?.view)?B:{inventory:await $.custody.discover($.signal),previousView:G?.view},NZ.delete(z);let{inventory:H}=J;$.onInventory?.(H),$.signal?.throwIfAborted();let K=typeof $.projection==="function"?$.projection():$.projection,W=(D)=>i9(D,H,K),Q=async()=>{return $.signal?.throwIfAborted(),await X.assertOwned(),Z()};if(await I4($.path,(D)=>{if(Y)return{target:D};let V=u($.path,D);return{target:D,...V!==D&&{local:V}}},W)==="unchanged"){if(!await Q())return;return await f($.path)}return await p0($.path,async(D)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await X.assertOwned(),Y&&D?.view!==Y.view&&D?.view!==H.view)return{result:D};let V=W(D);return{...JSON.stringify(D)!==JSON.stringify(V)&&{next:V},result:V}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await X.assertOwned()}})}catch(G){if(G instanceof e&&J&&!Y&&!$.signal?.aborted&&await Z())NZ.set(z,J);throw G}finally{await X.release($.signal)}}var l0=new Map,b4=p("claustrum"),Z3=100;function X3($,Z=p9){let X=MZ($),z=l0.get(X);if(!z)z={path:X,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},l0.set(X,z);return z}function z3($,Z,X){let z=X3($,X);z.listeners.add(Z);let Y;return()=>Y??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():y6($)})()}function k4($){return l9($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function t9($,Z){if(!t0(Z.observation))return Promise.resolve(!1);let X=X3($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),Y=X.pending.get(z)??new Map;for(let[J,G]of k4(Z)){let B=Y.get(J);if(!B||G.at>=B.at){if(G.order=++X.order,G.publication.observation.coverage)G.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(J,G)}}if(Y.size)X.pending.set(z,Y);for(let J of X.listeners)J(Z);return J3(X,Z3),Promise.resolve(!0)}function Y3($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,X)=>Z.order-X.order)}function u($,Z){let X=l0.get(MZ($));if(X)for(let z of Y3(X.pending)){if(z.priorReading)Z=R0(Z,z.priorReading).roster;Z=R0(Z,z.publication).roster}return Z}function e9($){return!!l0.get(MZ($))?.pending.size}function J3($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let X=$.draining?0:($.committedAt??-1/0)+g9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,X),()=>{return $.timer=void 0,G3($)}),!$.draining)$.timer.unref?.()}function $3($){$.timer?.cancel(),$.timer=void 0}function G3($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([X,z])=>[X,new Map(z)]));return $.running=(async()=>{try{if(await p0($.path,(z)=>{let Y=z;for(let G of Y3(Z)){if(G.priorReading)Y=R0(Y,G.priorReading).roster;Y=R0(Y,G.publication).roster}let J=JSON.stringify(Y)!==JSON.stringify(z);return{...J&&{next:Y},result:J}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[z,Y]of Z){let J=$.pending.get(z);for(let[G,B]of Y)if(J?.get(G)===B)J.delete(G);if(!J?.size)$.pending.delete(z)}$.failures=0}catch(X){if(!$.abort.signal.aborted&&$.failures++===0)b4.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()):Z3;J3($,X)}})(),$.running}async function y6($,Z=1000){let X=MZ($),z=l0.get(X);if(!z)return;z.draining=!0,$3(z);let Y,J,G=new Promise((B)=>{J=()=>{if(!z.pending.size||z.abort.signal.aborted)B()},z.wake.add(J),J()});try{if(z.pending.size)G3(z);await Promise.race([G,new Promise((B)=>{Y=setTimeout(B,Math.max(0,Z))})])}finally{if(clearTimeout(Y),J)z.wake.delete(J);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),$3(z),z.pending.clear(),l0.get(X)===z)l0.delete(X)}}}var _Z=1e4;function B3(){return new S}var w6;function K3($,Z){if(!w6)throw Error("ClaustrumConsumer is not initialized");return w6($,Z)}function H3(){return new N("not-active","Claustrum scoped custody is not active")}class h6{#$;#Z=new AbortController;#J;#G;#z;#K;#Y;#X;#W;#Q;#U=!1;#N=new Set;#O;#B;#L;#_;#P=new Map;#j;#T;#H;#R;#x=new WeakMap;static{w6=($,Z)=>{let X=new h6(Z);return X.#H=$,{consumer:X,hooks:X.#m()}}}constructor($){this.#$=$,this.#J=$.logger??p("claustrum"),this.#G=z$(this.#J,this.#Z.signal),this.#T=z3($.rosterPath,(Z)=>{this.#X=R0(this.#X,Z).roster})}#V($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#q($){return this.#N.add($),$.then(()=>this.#N.delete($),()=>this.#N.delete($)),$}async#M(){if(b())return!0;return await this.#$.isCustodyActive?.()??!0}#A($,Z){let X=h0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,Y)=>{let J=()=>{X.signal.removeEventListener("abort",G),X.dispose()},G=()=>{J(),Y(X.signal.reason)};if(X.signal.addEventListener("abort",G,{once:!0}),$.then((B)=>{if(J(),X.signal.aborted)Y(X.signal.reason);else z(B)},(B)=>{J(),Y(B)}),X.signal.aborted)G()})}async#I(){if(this.#V(),this.#z)return this.#z;if(!this.#K){let $={timedOut:!1};this.#K=this.#y($),this.#q(this.#K)}return this.#A(this.#K)}#y($){let Z=this.#$.setTimeoutImpl??setTimeout,X=this.#$.clearTimeoutImpl??clearTimeout,z=(!b()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>m0(this.#$.pluginId))).then((G)=>{if(this.#Z.signal.aborted||$.timedOut){if(G.close(),!$.timedOut)this.#V();throw B3()}if(this.#z=new J$({client:G,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#J,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&G.insula)this.#B=J6(G.insula,this.#$.tokenPath);return this.#z}),Y,J=new Promise((G,B)=>{Y=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#J.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#D()}),B(B3())},this.#D()),Y.unref?.()});return Promise.race([z,J]).finally(()=>{if(Y)X(Y);this.#K=void 0})}#D(){return this.#$.connectTimeoutMs??_Z}snapshot(){return this.#X}grantReach(){if(this.#H)return this.#H.grantReach(this.#X?.view);let $=this.#W;return $&&this.#X?.view===$.view?$.reach:void 0}watchState(){if(this.#H)return Object.freeze({vault:this.#H.watchMode()});return Object.freeze({vault:this.#L?.mode??"polling",...this.#$.insula&&{insula:this.#B?.source.watchMode()??"polling"}})}#E(){this.#L?.close(),this.#L=void 0,this.#_?.(),this.#_=void 0}keptReceiptState(){if(this.#H){let $=this.#R;return $&&this.#H.leaseLive($)?$.custody.keptReceiptState():this.#H.keptReceiptState()}return this.#z?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return E6(this.#X)}refresh(){if(this.#V(),this.#H)return this.#q(this.#l(this.#H));if(this.#Y)return this.#Y;return this.#Y=(async()=>{if(!await this.#M()){if(this.#X=void 0,this.#W=void 0,this.#E(),this.#z)this.#z.close(),this.#q(this.#z.dispose(this.#G));this.#z=void 0,this.#B?.release(),this.#B=void 0;return}let $=await this.#I(),Z,X=await E$({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#M(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#V();let z=X?.view!==this.#X?.view;if(this.#X=u(this.#$.rosterPath,X),$.retain(X?.rows??[]),Z&&X?.view!==void 0)this.#W=Z.grantReach?{view:X.view,reach:Z.grantReach}:void 0;if(X&&z)this.#$.onRoster?.(X);return this.#j=(this.#$.now??Date.now)(),X})().finally(()=>{this.#Y=void 0}),this.#q(this.#Y),this.#b(this.#Y),this.#Y}#b($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#U)return;if(this.#V(),this.#U=!0,this.#H){this.#H.start();return}let $=async()=>{try{if(await this.#S())await this.refresh();await this.refreshInsulaQuota(),this.#C()}catch(X){if(!this.#Z.signal.aborted)this.#$.onError?.(X)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Q=void 0,this.#q($())},Z),this.#Q.unref?.()};this.#q($())}async#S(){if(this.#L?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#j===void 0||$-this.#j>=$$)return!0;return!await this.#M()}#C(){let $=this.#z;if(this.#Z.signal.aborted||!$)return;if(this.#L??=$.watchRoster({view:()=>this.#X?.view,onView:()=>this.#q((async()=>{while(this.#Y)await this.#Y.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#B&&!this.#_)this.#_=this.#B.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#M())return;try{if(!b())await P0(this.#$.tokenPath);await this.#I(),await this.#B?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#M())return;try{if(!b())await P0(this.#$.tokenPath);return this.#w($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#M())return;try{if(!b())await P0(this.#$.tokenPath);let X=u(this.#$.rosterPath,await f(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#w(X?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#M())return{miss:"unreachable"};try{if(!b())await P0(this.#$.tokenPath);let z=u(this.#$.rosterPath,await f(this.#$.rosterPath))?.rows.find((G)=>G.routeId===$)?.accountIdentity;if(!z||!this.#B)return{miss:"unreachable"};let Y=this.#B.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),J=Y.reading&&Z.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...J!==void 0&&{reading:J}};return J===void 0?{miss:"unreachable"}:{reading:J}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let X=await this.lookupInsulaQuotaForRoute($);if(X.miss==="cold"||X.miss==="upstream-failed"){if(this.#P.get($)!==X.miss)this.#P.set($,X.miss),this.#J.warn("skipped insula provider poll",{reason:X.miss});return}return this.#P.delete($),X.miss?Z():X.reading}#w($){if(!this.#$.insula||!$)return;let Z=this.#B?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#H)return this.#v(this.#H,$,Z);this.#V(Z);let X=this.#X??await this.#A(this.refresh(),Z);if(!X||!await this.#M())throw this.#z?.close(),this.#z=void 0,this.#E(),this.#B?.release(),this.#B=void 0,new N("not-active","Claustrum scoped custody is not active");let z=u(this.#$.rosterPath,await f(this.#$.rosterPath));this.#V(Z);let Y=X.rows.find((H)=>H.routeId===$),J=z?.rows.find((H)=>H.routeId===$);if(J&&!J.enabled){if(Y)this.#z?.forget(Y.credentialId);throw new N("route-declined","Claustrum route is disabled")}if(!Y||!J||J.state!=="active"||J.credentialId!==Y.credentialId||J.accountIdentity!==Y.accountIdentity||J.credentialType!==Y.credentialType){if(Y)this.#z?.forget(Y.credentialId);throw new N("route-unavailable","Claustrum route is disabled, removed or changed")}let G=await this.#A(this.#I(),Z),B=h0([this.#Z.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:J.credentialId,credentialType:J.credentialType,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity}},B.signal,$)}finally{B.dispose()}}#m(){return{discovery:($)=>{let Z=this.#H;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let X=this.#q($.then((z)=>this.#k(Z,z)));this.#b(X)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#X?.view;if(this.#X=u(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(X){this.#$.onError?.(X)}},reset:()=>{this.#X=void 0},roster:()=>this.#X,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#l($){let Z=await $.refresh();return this.#k($,Z)}#k($,Z){if(this.#V(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#X}#h($){if($&&this.#R!==$)return;this.#R?.release(),this.#R=void 0}async#F($,Z){let X=this.#R;if(X&&$.leaseLive(X))return X;this.#h();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#V();let Y=this.#R;if(Y&&$.leaseLive(Y))return z.release(),Y;return this.#R=z,z}async#v($,Z,X){if(this.#V(X),!this.#X)await this.#A($.refresh(),X);let z=this.#X;if(!await $.readAuthority())throw this.#h(),H3();if(this.#V(X),!z)throw new N("route-unavailable","Claustrum has no roster for this provider yet");let Y=u(this.#$.rosterPath,await f(this.#$.rosterPath));this.#V(X);let J=z.rows.find((K)=>K.routeId===Z),G=Y?.rows.find((K)=>K.routeId===Z);if(G&&!G.enabled){if(J)$.forget(J.credentialId);throw new N("route-declined","Claustrum route is disabled")}if(!J||!G||G.state!=="active"||G.credentialId!==J.credentialId||G.accountIdentity!==J.accountIdentity||G.credentialType!==J.credentialType){if(J)$.forget(J.credentialId);throw new N("route-unavailable","Claustrum route is disabled, removed or changed")}let B={credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},H=h0([this.#Z.signal,...X?[X]:[]]);try{for(let K=0;;K++){let W=await this.#F($,H.signal);try{let Q=await W.custody.authorize(B,H.signal,Z);return this.#x.set(Q,W),Q}catch(Q){if(K>0||H.signal.aborted||$.leaseLive(W)||!(Q instanceof N)||Q.kind!=="closed")throw Q;if(this.#h(W),!await $.readAuthority())throw H3()}}}finally{H.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#X?.rows.find((X)=>X.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#H){if(this.#R&&this.#H.leaseLive(this.#R))this.#R.custody.reportUsage($)}else this.#z?.reportUsage($)}catch{}}usageReportState(){try{return(this.#H?this.#R?.custody:this.#z)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,X){if(this.#V(),this.#H){let z=this.#x.get($);if(!z)throw new N("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,X);return}if(!this.#z)throw new N("no-receipt","Claustrum dispatch receipt has no active owner");await this.#z.reportFailure($,Z,X)}#f($){let Z=this.#H?this.#x.get($)?.custody:this.#z;if(!Z)throw new N("no-receipt","Claustrum dispatch receipt has no active owner");return Z}async reportCondition($,Z){if(this.#Z.signal.aborted)return"skipped";return this.#f($).reportCondition($,Z)}async clearCondition($){if(this.#Z.signal.aborted)return"skipped";return this.#f($).clearCondition($)}async send($,Z,X){let z=X.signal,Y=await this.authorize($,z),J=await Z(Y,z);if(J.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,X.reporterSource??"direct"),J;if(J.status===401&&!z?.aborted){let G;try{G=await this.authorize($,z),z?.throwIfAborted()}catch(B){if(z?.aborted)throw B}if(P6(X.site,Y,G,this.#J))await J.body?.cancel().catch(()=>{}),Y=G,J=await Z(G,z)}if(J.status===401)await this.reportFailure(Y,401,X.reporterSource??"direct").catch((G)=>this.#$.onError?.(G)),Promise.resolve().then(()=>this.refresh()).catch((G)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(G)});return J}async decline($){if(this.#V(),await C6(this.#$.rosterPath,$),this.#X=u(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#H?.publishRoster(this.#X);if(this.#H)this.#H.retainUnion();else this.#z?.retain(this.#X?.rows??[])}async accept($){if(this.#V(),await I6(this.#$.rosterPath,$),this.#X=u(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#H?.publishRoster(this.#X)}async reorder($){this.#V();let Z=await b6(this.#$.rosterPath,$);if(this.#X=u(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#H?.publishRoster(this.#X);return Z}async recordQuota($,Z,X){return this.#V(),k6(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:X.credentialId,accountIdentitySource:X.accountIdentitySource,...X.accountIdentity!==void 0&&{accountIdentity:X.accountIdentity},...X.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:X.expectedAccountIdentity}})}async recordAccountQuota($,Z,X){return this.#V(),f6(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new N("closed","Claustrum consumer is closed")),this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);if(this.#Q=void 0,this.#E(),this.#z)this.#z.close(),this.#q(this.#z.dispose(this.#G));this.#R?.release(),this.#R=void 0,this.#H?.detach(),this.#B?.release(),this.#B=void 0,this.#X=void 0,this.#W=void 0,this.#T(),A$(this.#$.rosterPath)}async dispose(){this.close(),this.#O??=Promise.all([Y$(this.#N,this.#G),this.#T()]).then(()=>{}),await this.#O}}import{createHash as f4}from"node:crypto";import{channel as Q3}from"node:diagnostics_channel";import{readdir as y4,stat as w4}from"node:fs/promises";import{dirname as h4,join as B$,resolve as W3}from"node:path";var FZ=new Map,m4=/^[a-z0-9][a-z0-9._-]{0,63}$/,v4=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,g4=/^[0-9a-f]{16}$/,U3=3;function v6($,Z=new Set){if($===null)return"null";if(typeof $==="string"||typeof $==="boolean")return JSON.stringify($);if(typeof $==="number")return Number.isFinite($)?JSON.stringify($):void 0;if(typeof $!=="object"||Z.has($))return;let X=new Set(Z).add($),z=[];if(Array.isArray($)){for(let J=0;J<$.length;J++){let G=v6($[J],X);if(G===void 0)return;z.push(G)}return`[${z.join(",")}]`}let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return;for(let J of Object.keys($).sort()){let G=v6($[J],X);if(G===void 0)return;z.push(`${JSON.stringify(J)}:${G}`)}return`{${z.join(",")}}`}function p4($,Z){let X=v6({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??qZ,mapAccount:$.mapAccount?String($.mapAccount):null});if(X===void 0)throw new N("invalid-state","Claustrum hub classifierInput must be plain JSON");return f4("sha256").update(X).digest("hex").slice(0,16)}function D3($,Z){if(typeof $!=="string"||!m4.test($)||v4.test($))throw new N("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function T0($="Claustrum custody lease is closed"){return new N("closed",$)}function m6(){return new N("not-active","Claustrum scoped custody is not active")}function V3(){return new S}function l4($,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 N3($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class q3{#$;#Z;#J;#G=new AbortController;#z=new Map;#K=new WeakMap;#Y=0;#X;#W;#Q;#U;#N;#O=new Set;#B;#L=0;#_;#P;#j;#T=!1;#H=new Set;#R;#x;#V;constructor($){if(!$.family||!("classify"in $.family))throw new N("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=D3($.hostGeneration,"host generation"),X=$.members.map((Y)=>D3(Y,"member"));if(new Set(X).size!==X.length)throw new N("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??p("claustrum"),this.#J=z$(this.#Z,this.#G.signal),this.#x=B$($.stateDir,"rosters",Z),this.#V=p4($,X);let z=B$(this.#x,this.#V);for(let Y of X)this.#z.set(Y,{provider:Y,path:B$(z,`${Y}.json`),closed:!1})}#q($){return this.#H.add($),$.then(()=>this.#H.delete($),()=>this.#H.delete($)),$}#M(){if(this.#G.signal.aborted)throw T0("Claustrum discovery hub is closed")}#A($){let Z=this.#z.get($);if(!Z)throw new N("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#A($).path}member($,Z){this.#M();let X=this.#A($);if(X.hooks)throw new N("wrong-consumer","Claustrum hub member was already built");for(let Q of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(Q in Z)throw new N("wrong-consumer",`Claustrum hub members cannot take ${Q}`);let z={provider:X.provider,start:()=>this.start(),refresh:()=>this.#f(),readAuthority:()=>this.#k(),acquire:(Q)=>this.acquire(Q),leaseLive:(Q)=>this.#E(Q),grantReach:(Q)=>Q!==void 0&&this.#_?.view===Q?this.#_.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#p(),publishRoster:(Q)=>this.#I(X,Q),forget:(Q)=>this.#X?.custody?.forget(Q),detach:()=>{X.closed=!0,X.releaseRoster?.()}},Y={rosterPath:X.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:J,hooks:G}=K3(z,Y);X.hooks=G;let B=W3(X.path),H=FZ.get(B)??new Set,K=(Q)=>{if(X.closed||this.#B!==!0||!this.#X||!this.#D(this.#X)||!G.roster()||this.#u(G,Q))return;if(X.seen=JSON.stringify(S6(Q)),G.install(Q),Q.view!==this.#_?.view)X.pending??={failures:0,wait:0};this.#p()};H.add(K),X.receiveRoster=K,FZ.set(B,H);let W=!0;return X.releaseRoster=()=>{if(!W)return;if(W=!1,H.delete(K),!H.size)FZ.delete(B)},J}#I($,Z){let X=this.#X;if($.closed||!X||!this.#D(X))return;$.seen=JSON.stringify(S6(Z)),$.hooks?.install(Z);for(let z of FZ.get(W3($.path))??[]){if(!this.#D(X))return;if(z!==$.receiveRoster)z(Z)}}#y(){let $={id:++this.#Y,count:0,ended:!1,controller:new AbortController};return this.#X=$,$}#D($){return!$.ended&&this.#X===$&&!this.#G.signal.aborted}#E($){let Z=this.#K.get($);return!!Z&&!Z.released&&!Z.generation.ended}#b($,Z=T0()){if($.ended)return;if($.ended=!0,$.count=0,this.#X===$)this.#X=void 0;if(this.#Q&&this.#K.get(this.#Q)?.generation===$)this.#Q=void 0;if(this.#U?.generation===$)this.#U.watch.close(),this.#U=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#q($.custody.dispose(this.#J))}#S($){if($.ended)return;if($.count--,$.count<=0)this.#b($)}#C($){let Z=this.#W;if(Z?.generation===$&&Z.promise)return Z.promise;let X={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??_Z,Y,J=(!b()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>m0(this.#$.pluginId))).then((H)=>{if(X.timedOut)throw H.close(),V3();if(!this.#D($)||$.count<=0)throw H.close(),T0("Claustrum connection is no longer wanted");return $.custody=new J$({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),G=new Promise((H,K)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(X.timedOut=!0,!this.#D($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),K(V3())},z),Y.unref?.()});return X.promise=this.#q(Promise.race([J,G]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),X.promise.finally(()=>{if(this.#W===X)this.#W=void 0}).catch(()=>{}),this.#W=X,X.promise}acquire($){try{if(this.#M(),$?.throwIfAborted(),this.#B===!1)throw m6()}catch(X){return Promise.reject(X)}let Z=this.#X??this.#y();return Z.count++,this.#w(Z,$,!0)}async#w($,Z,X){let z=$.custody;if(!z){let Y=h0([$.controller.signal,...Z?[Z]:[]]);try{z=await l4(this.#C($),Y.signal)}catch(J){if(!$.ended)throw this.#S($),J;return this.#m(Z,X)}finally{Y.dispose()}}if($.ended)return this.#m(Z,X);if(Z?.aborted)throw this.#S($),Z.reason;return this.#l($,z)}#m($,Z){if($?.throwIfAborted(),this.#M(),this.#B===!1)throw m6();if(!Z)throw T0();let X=this.#X??this.#y();return X.count++,this.#w(X,$,!1)}#l($,Z){let X={generation:$,custody:Z,released:!1},z=()=>{if(X.released||$.ended)throw T0()},Y=Object.freeze({authorize:async(G,B,H)=>{z();let K=h0([$.controller.signal,...B?[B]:[]]);try{return await Z.authorize(G,K.signal,H)}finally{K.dispose()}},reportFailure:async(G,B,H)=>{return z(),Z.reportFailure(G,B,H)},reportCondition:async(G,B)=>{if(X.released||$.ended)return"skipped";return Z.reportCondition(G,B)},clearCondition:async(G)=>{if(X.released||$.ended)return"skipped";return Z.clearCondition(G)},reportUsage:(G)=>{if(!X.released&&!$.ended)Z.reportUsage(G)},usageReportState:()=>{return z(),Z.usageReportState()},forget:(G)=>{z(),Z.forget(G)},keptReceiptState:()=>{return z(),Z.keptReceiptState()}}),J=Object.freeze({custody:Y,generation:$.id,release:()=>{if(X.released)return;X.released=!0,this.#S($)}});return this.#K.set(J,X),J}leaseState(){let $=this.#X;return Object.freeze({generation:$?.id,count:$?.count??0})}async#k(){let $=b()||(await this.#$.isCustodyActive?.()??!0);if(this.#G.signal.aborted)return!1;let Z=this.#B;if(this.#B=$,!$&&Z!==!1)this.#h();return $}#h(){this.#L++;let $=this.#X;if($)this.#b($,m6());this.#Q=void 0,this.#U?.watch.close(),this.#U=void 0,this.#_=void 0,this.#P=void 0;for(let Z of this.#z.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),A$(Z.path)}#F(){return[...this.#z.values()].filter(($)=>$.hooks&&!$.closed)}async#v(){let $=this.#Q,Z=$&&this.#K.get($);if($&&Z&&this.#E($))return Z;this.#Q=void 0;let X=await this.acquire(this.#G.signal),z=this.#Q&&this.#K.get(this.#Q);if(this.#Q&&z&&this.#E(this.#Q))return X.release(),z;this.#Q=X;let Y=this.#K.get(X);if(!Y)throw T0();return Y}#f(){try{this.#M()}catch(z){return Promise.reject(z)}let $=this.#N;if($&&!$.generation?.ended)return $.promise;let Z={},X=this.#q(this.#i(Z).finally(()=>{if(this.#N===Z)this.#N=void 0}));Z.promise=X,this.#N=Z;for(let z of this.#F())z.hooks?.discovery(X);return X}async#i($){if(!await this.#k())return;let Z=await this.#v(),X=Z.generation;if($.generation=X,!this.#D(X))return;let z=await this.#s().then(()=>{return},(Q)=>Q instanceof Error?Q:Error(String(Q)));if(await this.#c(),!this.#D(X))return;let Y=new Map(await Promise.all([...this.#z.values()].map(async(Q)=>[Q,await f(Q.path).then((U)=>U?{file:U}:{},(U)=>U instanceof Error?U:Error(String(U)))])));if(!this.#D(X))return;let J;try{J=await Z.custody.discover(X.controller.signal)}catch(Q){if(!this.#D(X))return;for(let U of this.#z.values())if(U.pending)this.#g(U);throw Q}if(!this.#D(X))return;let G=this.#F(),B=Promise.all(G.map((Q)=>Q.hooks&&!Q.closed?this.#d(Q,Q.hooks,J,z??Y.get(Q),X):void 0));this.#O.add(B);let H;try{H=await B}finally{this.#O.delete(B)}if(!this.#D(X))return;let K=new Map,W=!0;for(let[Q,U]of G.entries()){let D=U.hooks,V=H[Q];if(!D||!V)continue;if("error"in V){let{error:q}=V;if(W=!1,this.#g(U),r9(U.path,q))this.#Z.debug("claustrum hub member commit refused",{member:U.provider});else K.set(U.provider,q);continue}let{roster:_}=V;if(!this.#D(X))return;if(_?.view!==J.view)W=!1,this.#g(U);else U.pending=void 0;if(!_)continue;if(this.#u(D,_)){W=!1,this.#g(U);continue}this.#I(U,_)}if(!this.#D(X))return;if(this.#p(),W)this.#_=Object.freeze({view:J.view,...J.grantReach&&{reach:J.grantReach},refused:Object.freeze([...J.refused??[]]),notMine:J.notMine??0});return this.#P=(this.#$.now??Date.now)(),{errors:K}}async#d($,Z,X,z,Y){let J={...X,credentials:X.credentials.filter((G)=>G.member===$.provider),skipped:X.skipped.filter((G)=>G.member===$.provider)};try{if(!z)throw T0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let G;if(!z.file){let H=Q3("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{G=await this.#o($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await E$({path:$.path,custody:{discover:async()=>J},isActive:()=>this.#D(Y)&&this.#B===!0,signal:Y.controller.signal,projection:()=>({...Z.projection(),...G&&{seed:G}}),listedOver:{view:z.file?.view}})}}catch(G){return{error:G}}}async#c(){if(!this.#O.size)return;let $=Q3("common-auth.claustrum.phases"),Z=(X)=>{if($.hasSubscribers)$.publish({logger:this.#Z,phase:X})};Z("earlier fan-out drain begin");try{while(this.#O.size)await Promise.allSettled([...this.#O])}finally{Z("earlier fan-out drain end")}}async#s(){for(let $ of[h4(this.#x),this.#x,B$(this.#x,this.#V)])await X$($,{},"roster directory")}async#o($){let Z=`${$.provider}.json`,X=[B$(this.#x,Z)];try{for(let Y of await y4(this.#x))if(Y!==this.#V&&g4.test(Y))X.push(B$(this.#x,Y,Z))}catch{}let z;for(let Y of X)try{let J=(await w4(Y)).mtimeMs,G=await f(Y);if(G&&(!z||J>z.modified))z={modified:J,roster:G}}catch{}return z&&A6(z.roster)}#u($,Z){let X=$.projection().reservedRouteIds;return!!X?.size&&Z.rows.some((z)=>X.has(z.routeId))}#g($){let Z=($.pending?.failures??0)+1,X=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil($$/X)),Y=Z<=U3?1:Math.min(2**(Z-U3),z);$.pending={failures:Z,wait:Y-1}}#p(){let $=this.#X?.custody;if(!$)return;$.retain(this.#F().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#a(){let $=this.#L;for(let Z of this.#F()){let X;try{X=await f(Z.path)}catch(B){Z.hooks?.onError(B);continue}if($!==this.#L||this.#B!==!0)return;let z=Z.hooks;if(!X||!z||Z.closed)continue;let Y=JSON.stringify(X);if(Y===Z.seen)continue;let J=z.roster();if(!J||J.view!==X.view||this.#u(z,X)){Z.pending??={failures:0,wait:0};continue}let G=N3(J);if(Z.seen=Y,this.#I(Z,X),N3(z.roster())!==G)this.#p()}}#n(){let $=!1;for(let X of this.#z.values()){if(!X.pending)continue;if(X.pending.wait<=0)$=!0;else X.pending.wait--}if(this.#U?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#P===void 0||Z-this.#P>=$$}#X0(){let $=this.#Q,Z=$&&this.#K.get($);if(!$||!Z||!this.#E($)||this.#B!==!0)return;let X=Z.generation;if(!this.#D(X)||this.#U?.generation===X)return;let z=Z.custody.watchRoster({view:()=>this.#_?.view,onView:()=>this.#q((async()=>{while(this.#N)await this.#N.promise.catch(()=>{});if(!this.#D(X))return;await this.#$0()})()),onRefused:(Y)=>this.#t(Y),onError:(Y)=>this.#r(Y)});this.#U={generation:X,watch:z}}#r($){if(!this.#G.signal.aborted)this.#$.onError?.($)}#t($){if(this.#G.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#F())Z.hooks?.onError($)}#e($){for(let[Z,X]of $?.errors??[])this.#z.get(Z)?.hooks?.onError(X)}async#$0(){let $;try{$=await this.#f()}catch(Z){this.#t(Z);return}this.#e($)}async#Z0(){try{if(await this.#k()){if(await this.#a(),this.#n())await this.#$0();this.#X0()}}catch(Z){this.#r(Z)}if(this.#G.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#j=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#j=void 0,this.#q(this.#Z0())},$),this.#j.unref?.()}start(){if(this.#T)return;this.#M(),this.#T=!0,this.#q(this.#Z0())}async refresh(){this.#e(await this.#f())}refusals(){let $=this.#_;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#_?.reach}watchState(){let $=this.#U;return $&&this.#D($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#X?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#G.signal.aborted)return;this.#G.abort(T0("Claustrum discovery hub is closed"));for(let Z of this.#z.values())Z.releaseRoster?.();if(this.#j)(this.#$.clearTimeoutImpl??clearTimeout)(this.#j);this.#j=void 0;let $=this.#X;if($)this.#b($);this.#Q=void 0,this.#U?.watch.close(),this.#U=void 0}async dispose(){this.close(),this.#R??=Y$(this.#H,this.#J),await this.#R}}var c4=1e4;async function nY($){let{connectTimeoutMs:Z,...X}=$,z=Z??c4,Y=d4.connect(XZ(X)),J=!1,G,B=new Promise((H,K)=>{G=setTimeout(()=>{J=!0,K(new S)},z),G.unref?.()});try{let H=await Promise.race([Y,B]);return Object.assign(H,{insula:$9($)})}catch(H){throw Y.then((K)=>K.close(),()=>{}),H}finally{if(!J&&G)clearTimeout(G)}}var M3=DZ("openai");function _3($){return VZ($)}function d0($){if(!$||$.corrupt===!0)return!1;return _3($.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 LZ($){if(_3($))throw new S$}var u4=p("quota"),g6="primary",p6="secondary",i4="app_EMoamEEZ73f0CkXaXp7hrann",s4="https://auth.openai.com";async function FJ($){LZ($.refreshToken);let Z=await $.fetchImpl(`${s4}/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:i4}).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 a4="https://chatgpt.com/backend-api/wham/usage";async function LJ($){let Z=$.logger??u4,X=$.accountKey??"unknown",z=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let Y=await $.fetchImpl(a4,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Y.ok){let G=eZ(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:G})}let J=i8(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:F3(Y)}),Y}}import{createHash as n4}from"node:crypto";var o4=globalThis.setTimeout,r4=5;function C$($){let Z=$?.quota?.checkIntervalMinutes??r4;return Math.max(1,Z)*60000}function t4($){return $?.quota?.enabled!==!1}function OZ($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function AJ($,Z,X,z,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>X)return Y;let J=Z===g6?$?.primary:Z===p6?$?.secondary:void 0,G=J?.resetsAt?Date.parse(J.resetsAt):NaN;if(Number.isFinite(G)&&G>X)return G;return X+z}function e4($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function L3($,Z,X){if(!t4(Z))return X+C$(Z);let z=e4(Z),Y=[];for(let J of["primary","secondary"]){let G=$?.[J];if(!G)continue;if(G.remainingPercent>=z[J])continue;let B=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=X)return X+C$(Z);Y.push(B)}if(!Y.length)return X+C$(Z);return Math.min(...Y)+60000}function $7($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function Z7($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function n($){return n4("sha256").update($).digest("hex").slice(0,16)}class x0{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;configPath;constructor($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath,this.now=$.now??Date.now,this.fetchQuotaFn=$.fetchQuotaFn,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==n($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let X=this.fallbacks.get($)??null;if(!Z||!X)return X;if(this.fallbackTokenFps.get($)!==n(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,z=!1){if(!z&&!O3(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,l6(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&&!O3(Z.quota))return;let J=this.fallbacks.get($)?.accountId;if(Y&&J&&Y!==J)this.clearRateLimited($);let G=Y??J;if(this.fallbacks.set($,{...Z,accountId:G}),X)this.fallbackTokenFps.set($,n(X));else this.fallbackTokenFps.delete($);if(l6(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let X=this.rateLimitedUntilMap.get($);if(X!==void 0&&X>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=n($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let X=x0.fallbackInflightKey($,Z),z=this.inflightFallbacks.get(X);if(z)return z;if(this.isFallbackBackedOff($,Z)){let J=this.getFallback($,Z);if(J)return J.quota;throw Error("Quota API rate-limited — try again later")}let Y=this._fetchFallback($,Z);return this.inflightFallbacks.set(X,Y),Y}async refreshAllFallbacks($){let Z=this.now();for(let X of $){if(X.enabled===!1)continue;if(d0(X)||!X.access)continue;let z=this.getFallback(X.id,X.access);if(z&&Z<z.refreshAfter)continue;try{await this.refreshFallback(X.id,X.access)}catch{}}}refreshMainInBackground($){let Z=n($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale($,Z){let X=this.getFallback($,Z);if(!X)return!0;return this.now()>=X.refreshAfter}shouldRefreshOnRequestCount($){let Z=Z7(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=$7($);if(!X)return;let z=Z?n(Z):null;if(z&&X.tokenFingerprint&&X.tokenFingerprint!==z)return;let Y={quota:X.quota,refreshAfter:L3(X.quota,$,X.checkedAt),checkedAt:X.checkedAt};if(this.main&&this.main.checkedAt>=Y.checkedAt&&(!z||!this.mainTokenFp||this.mainTokenFp===z))return;if(this.main=Y,this.mainTokenFp=X.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&e0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=C$(this.storage);for(let X of $){if(X.enabled===!1)continue;if(!X.quota)continue;let z=Math.max(X.quota.primary?.checkedAt??0,X.quota.secondary?.checkedAt??0);if(z<=0)continue;let Y=this.getFallback(X.id,X.access);if(Y&&Y.checkedAt>=z)continue;this.setFallback(X.id,{quota:X.quota,refreshAfter:z+Z,checkedAt:z},X.access,!1,X.accountId)}}isBackedOff(){return e0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==n(Z))return!1}return e0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,n(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let z=this.now()-this.lastApiCallAt;if(z<x0.API_CALL_GAP_MS)await new Promise((Y)=>{let J=o4(Y,x0.API_CALL_GAP_MS-z);if(typeof J==="object"&&"unref"in J)J.unref()});return this.lastApiCallAt=this.now(),$()},X=this.apiGate.then(Z,Z);return this.apiGate=X.catch(()=>{}),X}async _fetchMain($){let Z=n($);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let X=await g({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!X){let z=this.main;if(z&&this.now()<z.refreshAfter)return z.quota;throw Error("Quota refresh is already in progress")}try{let z=this.now(),Y=await this._fetchQuota($),J=this.now();if(this.mainTokenFp=n($),this.main={quota:Y,refreshAfter:L3(Y,this.storage,J),checkedAt:J},l6(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,J,this.mainTokenFp,z),Y}catch(z){throw this._handleMainFetchError(z),z}finally{await X.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,Z)){let z=this.getFallback($,Z);if(z)return z.quota;throw Error("Quota API rate-limited — try again later")}let X=await g({name:x0.quotaLockName($),ttlMs:30000,path:this.configPath});if(!X){let z=this.getFallback($,Z);if(z&&this.now()<z.refreshAfter)return z.quota;throw Error("Quota refresh is already in progress")}try{let z=await this._fetchQuota(Z),Y=this.now();return this.setFallback($,{quota:z,refreshAfter:Y+C$(this.storage),checkedAt:Y},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),z}finally{await X.release()}}catch(X){throw this._handleFallbackFetchError($,Z,X),X}finally{this.inflightFallbacks.delete(x0.fallbackInflightKey($,Z))}})}async _fetchQuota($){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:$,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError($){return $?.status===401}_handleMainFetchError($){if(x0.isAuthError($))return;this.mainLastApiError=_$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(x0.isAuthError(X))return;let z=n(Z),Y=this.fallbackErrorTokenFps.get($)===z?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,_$({error:X,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,z)}}function O3($){return Boolean($.primary||$.secondary)}function l6($){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 u7,randomUUID as i7}from"node:crypto";import{setTimeout as s7}from"node:timers/promises";import{createHash as h7}from"node:crypto";import{existsSync as m7,realpathSync as c3}from"node:fs";import{homedir as u3}from"node:os";import{basename as v7,dirname as g7,join as p7,posix as l7,resolve as r6,win32 as d7}from"node:path";function X7(){return Object.freeze({kind:"boolean"})}function z7({min:$,max:Z}={}){return Object.freeze({kind:"integer",min:$,max:Z})}function Y7({min:$,max:Z}={}){return Object.freeze({kind:"number",min:$,max:Z})}function J7(){return Object.freeze({kind:"string"})}function G7($){return Object.freeze({kind:"oneOf",values:Object.freeze([...$])})}function B7($){return c0({kind:"list",item:$})}function H7($){return c0({kind:"object",fields:{...$}})}function k($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let Z=Object.getPrototypeOf($);return Z===Object.prototype||Z===null}function o($,Z,X={}){switch($.kind){case"boolean":return typeof Z==="boolean";case"integer":case"number":return typeof Z==="number"&&Number.isFinite(Z)&&($.kind!=="integer"||Number.isInteger(Z))&&($.min===void 0||Z>=$.min)&&($.max===void 0||Z<=$.max);case"string":return typeof Z==="string";case"oneOf":return typeof Z==="string"&&$.values.includes(Z);case"list":return Array.isArray(Z)&&Array.from(Z).every((z)=>o($.item,z,{...X,completeObjects:!0}));case"object":return k(Z)&&Object.entries(Z).every(([z,Y])=>Object.hasOwn($.fields,z)?o($.fields[z],Y,X):X.allowUnknownFields===!0)&&(!X.completeObjects||Object.keys($.fields).every((z)=>Object.hasOwn(Z,z)));case"record":return k(Z)&&Object.values(Z).every((z)=>o($.value,z,{...X,completeObjects:!0}))}}function c0($){if($&&typeof $==="object"){for(let Z of Object.values($))c0(Z);Object.freeze($)}return $}function K7($){for(let[Z,X]of Object.entries($.settings)){if(Z==="schema_version"||Z==="$schema")throw TypeError(`Reserved setting name: ${Z}`);if(!/^[a-z][a-z0-9_]*$/.test(Z)||/\s/.test(Z))throw TypeError(`Setting name must be snake_case: ${Z}`);if(Z==="sidebar"&&X.value.kind!=="object")throw TypeError("The sidebar setting must use an object descriptor");if(X.overrides!==void 0&&(X.value.kind==="object"||X.value.kind==="record"))throw TypeError(`Object and record settings cannot use overrides: ${Z}`);if(!Object.hasOwn(X,"default")||!o(X.value,X.default,{completeObjects:!0}))throw TypeError(`Invalid default for setting: ${Z}`)}return c0({plugin:$.plugin,settings:Object.fromEntries(Object.entries($.settings).map(([Z,X])=>[Z,structuredClone({...X,project:X.project??"user-only"})]))})}function P3($,Z){if(Z==="default")return!0;if(Z==="opencode"||Z==="pi")return $.host===!0;return $.model===!0}import{join as j7,resolve as i6}from"node:path";import*as C from"node:fs/promises";var Q7={readFile:C.readFile,stat:C.stat,lstat:C.lstat,readlink:C.readlink,realpath:C.realpath,open:C.open,rename:C.rename,link:C.link,unlink:C.unlink,mkdir:C.mkdir,readdir:C.readdir},j={...Q7};import{parseTree as W7}from"jsonc-parser";function U0($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function d6($,Z=()=>{},X=[]){if($.type==="object"){let z={};for(let Y of $.children??[]){let[J,G]=Y.children??[];if(!J||!G)continue;let B=J.value,H=[...X,B];if(Object.hasOwn(z,B))Z(H);U0(z,B,d6(G,Z,H))}return z}if($.type==="array")return($.children??[]).map((z,Y)=>d6(z,Z,[...X,String(Y)]));return $.value}function H$($){let Z=$.startsWith("\uFEFF"),X=Z?$.slice(1):$;if(/^[\x20\t\r\n]*$/.test(X))return{parseable:!0,text:X,hasBom:Z,tree:void 0,value:{},duplicateKeyPaths:[],hasDuplicates:!1};let z=[],Y=W7(X,z,{allowTrailingComma:!0});if(z.length||Y?.type!=="object")return{parseable:!1,text:X,hasBom:Z,tree:Y,errors:z};let J=new Map,G=d6(Y,(B)=>{J.set(JSON.stringify(B),B)});return{parseable:!0,text:X,hasBom:Z,tree:Y,value:G,duplicateKeyPaths:[...J.values()],hasDuplicates:J.size>0}}function j3($,Z,X,z){if(!X||!Object.hasOwn(X.settings,Z))return;let Y=X.settings[Z];if($.overrides===void 0||!k(Y))return Y;let{model:J,host:G}=z;if($.overrides.model&&J!==void 0&&J!=="default"&&J!=="opencode"&&J!=="pi"&&Object.hasOwn(Y,J))return Y[J];if($.overrides.host&&(G==="opencode"||G==="pi")&&Object.hasOwn(Y,G))return Y[G];return Object.hasOwn(Y,"default")?Y.default:void 0}function R3($,Z){if($.kind!=="object")return Z.find((z)=>z!==void 0);let X={};for(let[z,Y]of Object.entries($.fields)){let J=Z.map((G)=>k(G)&&Object.hasOwn(G,z)?G[z]:void 0);U0(X,z,R3(Y,J))}return X}function T3($,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(j3(Y,Z,z.project,X));return J.push(j3(Y,Z,z.user,X)),J.push(Y.default),structuredClone(R3(Y.value,J))}function I$($,Z,X,z,Y,J){let G=()=>{return J(X,"invalid-value"),{valid:!1}};if($.kind==="object"){if(!k(Z))return G();let B={},H=!0;for(let[K,W]of Object.entries(Z)){if(!Object.hasOwn($.fields,K)){J([...X,K],Y);continue}let Q=I$($.fields[K],W,[...X,K],z,Y,J);if(Q.valid)U0(B,K,Q.value);else H=!1}if(z){for(let K of Object.keys($.fields))if(!Object.hasOwn(Z,K))J([...X,K],"invalid-value"),H=!1}return H||!z?{valid:!0,value:B}:{valid:!1}}if($.kind==="list"){if(!Array.isArray(Z))return G();let B=[],H=!0;for(let[K,W]of Z.entries()){let Q=I$($.item,W,[...X,String(K)],!0,Y,J);if(Q.valid)B.push(Q.value);else H=!1}return H?{valid:!0,value:B}:{valid:!1}}if($.kind==="record"){if(!k(Z))return G();let B={},H=!0;for(let[K,W]of Object.entries(Z)){let Q=I$($.value,W,[...X,K],!0,Y,J);if(Q.valid)U0(B,K,Q.value);else H=!1}return H?{valid:!0,value:B}:{valid:!1}}return o($,Z)?{valid:!0,value:Z}:G()}function x3($,Z,X){let z=[],Y=new Set,J=(K,W)=>{let Q=JSON.stringify([K,W]);if(Y.has(Q))return;Y.add(Q),z.push({file:{...Z},keyPath:[...K],reason:W})},G={file:{...Z},settings:{},entries:z,schemaVersion:1,newer:!1,hasDuplicates:X.parseable&&X.hasDuplicates,parsed:X};if(!X.parseable)return J([],"unparseable"),G;for(let K of X.duplicateKeyPaths)J(K,"duplicate-key");let B=X.value;if(Object.hasOwn(B,"schema_version")){let K=B.schema_version;if(typeof K==="number"&&Number.isInteger(K)&&K>=1)G.schemaVersion=K,G.newer=K>1;else J(["schema_version"],"invalid-schema-version")}let H=G.newer?"newer-version-key-ignored":"unknown-key";for(let[K,W]of Object.entries(B)){if(K==="schema_version"||K==="$schema")continue;if(!Object.hasOwn($.settings,K)){J([K],H);continue}let Q=$.settings[K];if(!Q)continue;if(Z.kind!=="user"&&Q.project!=="allowed"){J([K],"user-only-in-project");continue}if(k(W)&&Q.overrides!==void 0){let D={};for(let[V,_]of Object.entries(W)){if(!P3(Q.overrides,V)){J([K,V],"override-not-allowed");continue}let q=I$(Q.value,_,[K,V],!1,H,J);if(q.valid)U0(D,V,q.value)}U0(G.settings,K,D);continue}if(k(W)&&Q.value.kind!=="object"&&Q.value.kind!=="record"){J([K],"override-not-allowed");continue}let U=I$(Q.value,W,[K],!1,H,J);if(U.valid)U0(G.settings,K,U.value)}return G}import{dirname as P7}from"node:path";import{isDeepStrictEqual as A3}from"node:util";import{applyEdits as c6,createScanner as D7,findNodeAtLocation as k$,modify as V7}from"jsonc-parser";var U7=Object.freeze(["settings-unparseable","settings-newer-version","settings-invalid-value","settings-busy","settings-unavailable"]);class A extends Error{code;name="SettingsRefusal";constructor($,Z,X){super(Z,X);this.code=$}}var A0={CommaToken:5,LineCommentTrivia:12,BlockCommentTrivia:13,Trivia:15,EOF:17};function Z0(){throw new A("settings-invalid-value","The settings edit does not match its declared value")}function b$($){let Z=H$($);if(!Z.parseable||Z.hasDuplicates)throw new A("settings-unparseable","Settings must be an object without duplicate keys");return Z}function C3($,Z){let X=$;for(let z of Z)if(X.kind==="object"&&Object.hasOwn(X.fields,z))X=X.fields[z];else if(X.kind==="record")X=X.value;else Z0();return X}function N7($,Z,X,{host:z,model:Y},J){if(J!==void 0)return J==="default"&&!k(X)?[Z]:[Z,J];if($.overrides!==void 0&&k(X)){if($.overrides.model&&Y!==void 0&&Y!=="default"&&Y!=="opencode"&&Y!=="pi"&&Object.hasOwn(X,Y))return[Z,Y];if($.overrides.host&&(z==="opencode"||z==="pi")&&Object.hasOwn(X,z))return[Z,z];return[Z,"default"]}return[Z]}function q7($,Z,X){let z=$,Y=[...Z];for(let J of X){if(z.kind==="record"||z.kind==="list")break;z=C3(z,[J]),Y.push(J)}return{path:Y,descriptor:z}}function M7($,Z){for(let X=1;X<Z.length;X++){let z=$.tree&&k$($.tree,Z.slice(0,X));if(z&&z.type!=="object")Z0()}}function _7($,Z){let X=$.tree&&k$($.tree,[Z]);if(!X)Z0();let z=$.text.slice(X.offset,X.offset+X.length);return b$(c6($.text,[{offset:X.offset,length:X.length,content:`{ "default": ${z} }`}]))}function E3($,Z,X){let z=Z&&k$(Z,X)?.parent,Y=z?.parent;if(z?.type!=="property"||!Y?.children)return $;let J=D7($,!1),G=z.offset+z.length,B=Y.children.indexOf(z),K=Y.children[B+1]?.offset??Y.offset+Y.length-1,W;J.setPosition(G);while(J.getPosition()<K){let q=J.scan();if(q===A0.CommaToken){W={start:J.getTokenOffset(),end:J.getPosition()};break}if(q===A0.EOF)break}if(!W&&B>0){let q=Y.children[B-1];J.setPosition(q.offset+q.length);while(J.getPosition()<z.offset){let R=J.scan();if(R===A0.CommaToken){W={start:J.getTokenOffset(),end:J.getPosition()};break}if(R===A0.EOF)break}}let Q=G;J.setPosition(G);while(J.getPosition()<K){let q=J.scan();if(q===A0.Trivia||q===A0.CommaToken)continue;if(q!==A0.LineCommentTrivia&&q!==A0.BlockCommentTrivia)break;if(Q=J.getPosition(),/[\r\n]/.test(J.getTokenValue()))break}if(W&&W.start>=G&&!/[\r\n]/.test($.slice(G,W.start)))Q=Math.max(Q,W.end);let U=Math.max($.lastIndexOf(`
91
- `,z.offset-1),$.lastIndexOf("\r",z.offset-1))+1,D=z.offset,V=/^[\t ]*(\r\n|\r|\n)/.exec($.slice(Q));if(/^[\t ]*$/.test($.slice(U,z.offset))&&V)D=U,Q+=V[0].length;let _=[{offset:D,length:Q-D,content:""}];if(W&&(W.start<D||W.start>=Q))_.push({offset:W.start,length:W.end-W.start,content:""});return c6($,_)}function I3($,Z,X,z){for(let B of X){if(!Object.hasOwn($.settings,B.setting))Z0();let H=$.settings[B.setting];if(B.level!==void 0){if(B.path!==void 0)Z0();if(B.level==="default"){if(H.overrides===void 0)Z0()}else if(B.level!=="opencode"&&B.level!=="pi"||!H.overrides?.host)Z0()}if(B.path!==void 0&&H.value.kind!=="object"&&H.value.kind!=="record")Z0();let K=C3(H.value,B.path??[]);if(B.remove!==!0&&!o(K,B.value))Z0()}let Y=b$(Z),J=Y,G=[];for(let B of X){let H=$.settings[B.setting];if(B.level!==void 0&&B.level!=="default"&&!k(J.value[B.setting])){if(B.remove===!0)continue;if(Object.hasOwn(J.value,B.setting))J=_7(J,B.setting);for(let D of G)if(D.path.length===1&&D.path[0]===B.setting)D.path.push("default")}let K=B.path!==void 0?[B.setting]:N7(H,B.setting,J.value[B.setting],z,B.level),W=[...K,...B.path??[]];M7(J,W),G.push(q7(H.value,K,B.path??[]));let Q=J.tree&&k$(J.tree,W),U;if(B.remove===!0){if(!Q)continue;U=E3(J.text,J.tree,W);let D=b$(U),V=D.value[B.setting];if(K.length===2&&k(V)&&Object.keys(V).length===0)U=E3(U,D.tree,[B.setting]),D=b$(U);J=D}else{if(Q&&A3(S3(J.value,W),B.value))continue;U=c6(J.text,V7(J.text,W,B.value,{formattingOptions:{insertSpaces:!0,tabSize:2}})),J=b$(U)}}for(let B of G)if(J.tree&&k$(J.tree,B.path)&&!o(B.descriptor,S3(J.value,B.path),{allowUnknownFields:!0}))Z0();if(A3(Y.value,J.value))return{outcome:"unchanged",text:Y.text,hasBom:Y.hasBom};return{outcome:"updated",text:J.text,hasBom:Y.hasBom}}function S3($,Z){let X=$;for(let z of Z){if(!k(X)||!Object.hasOwn(X,z))return;X=X[z]}return X}function PZ($,Z,X){if($ instanceof e||b3($,Z,X))throw new A("settings-busy",`Settings lock is busy: ${Z}`,{cause:$});if($ instanceof G0&&($.stage==="safe-parent"||$.stage==="directory"))throw new A("settings-unavailable",`Settings lock folder is unavailable: ${Z}`,{cause:$});throw $}import{randomUUID as F7}from"node:crypto";var L7,O7=new Set(["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS"]);async function k3($){let{target:Z,text:X,hasBom:z,existingMode:Y,lock:J,logger:G}=$,B=$.platform??process.platform,H=`${Z}.${F7()}.tmp`,K=!1,W=!1;try{let Q=await j.open(H,"wx",420);K=!0;try{if(await Q.writeFile(`${z?"\uFEFF":""}${X}`,"utf8"),B!=="win32"&&Y!==void 0)await Q.chmod(Y&511);await Q.sync()}finally{await Q.close()}if(await L7?.("staged",{target:Z,temp:H}),await J.assertOwned(),Y!==void 0){try{await j.rename(H,Z)}catch(U){if(B==="win32"&&["EPERM","EACCES","EBUSY"].includes(U.code??""))throw new A("settings-busy",`Settings file is busy: ${Z}`,{cause:U});throw U}W=!0}else{try{await j.link(H,Z)}catch(U){let D=U.code??"";if(D==="EEXIST")throw new A("settings-busy",`Settings file appeared before publication: ${Z}`,{cause:U});if(O7.has(D))throw new A("settings-unavailable",`Settings file cannot be created on this filesystem: ${Z}`,{cause:U});throw U}W=!0;try{await j.unlink(H)}catch(U){G?.warn("Settings temp cleanup failed after publication",{target:Z,temp:H,error:U})}}return{outcome:"updated"}}finally{if(K&&!W)await j.unlink(H).catch(()=>{})}}var u6=Object.freeze({name:"settings-write",ttlMs:1e4,timeoutMs:2000,renew:!0});function jZ($,Z){throw new A("settings-unavailable",`Settings file is unavailable: ${$}`,{cause:Z})}async function f3($){try{return await oZ($,j)}catch(Z){jZ($,Z)}}async function y3($,Z,X,z){if(Z.separateInstall)throw new A("settings-unavailable","Settings are unavailable for a separate install");let Y=P7(Z.file);try{if(!Z.createMissing)await j.stat(Y);else if(process.platform==="win32")await g0(Y);else await j.mkdir(Y,{recursive:!0,mode:448})}catch(B){jZ(Z.file,B)}let J=await f3(Z.file),G;try{return await I0(J,{...u6,timeoutMs:Z.lockTimeoutMs??u6.timeoutMs},async(B)=>{try{if(await f3(Z.file)!==J)throw new A("settings-busy",`Settings target changed while locking: ${Z.file}`);let H,K,W=!1;try{H=await j.readFile(J,"utf8")}catch(_){if(_.code!=="ENOENT"||!Z.createMissing)jZ(J,_);W=!0,H=""}if(!W)try{K=(await j.stat(J)).mode}catch(_){jZ(J,_)}let Q=H$(H);if(!Q.parseable||Q.hasDuplicates)throw new A("settings-unparseable","Settings must be an object without duplicate keys");let U=Q.value.schema_version;if(Number.isInteger(U)&&U>1)throw new A("settings-newer-version","Settings were written by a newer version");if(typeof X==="function"){let _=X(c0(W?{status:"missing"}:{status:"ready",document:structuredClone(Q.value)}));if(_!==null&&(typeof _==="object"||typeof _==="function")&&"then"in _&&typeof _.then==="function")throw new A("settings-invalid-value","Settings update plans must be synchronous");X=_}if(!Q.tree)H=`${Q.hasBom?"\uFEFF":""}// ${$.plugin} settings
87
+ </html>`,$Z=[],L$,H0=new Map;function f8($,Z){return new Promise((X,z)=>{let Y=(G)=>{$.off("listening",J),z(G)},J=()=>{$.off("error",Y),X()};$.once("error",Y),$.once("listening",J),$.listen(O$,Z)})}function m8($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function k0(){return H0.size}function w0($){if(H0.delete($),k0()===0)f0()}async function P2(){let $=`http://localhost:${O$}/auth/callback`;if($Z.length>0)return{port:O$,redirectUri:$};if(L$)return L$;L$=(async()=>{let Z=(J,G)=>{let B=new URL(J.url||"/",`http://127.0.0.1:${O$}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),K=B.searchParams.get("state"),W=B.searchParams.get("error"),Q=B.searchParams.get("error_description");if(W){let D=Q||W;if(K){let V=H0.get(K);if(V)V.reject(Error(D)),w0(K);else if(k0()===0)f0()}else if(k0()===0)f0();G.writeHead(200,{"Content-Type":"text/html"}),G.end(t$(D));return}if(!K){if(k0()===0)f0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(t$("Missing state parameter"));return}if(!H){if(k0()===0)f0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(t$("Missing authorization code"));return}let U=H0.get(K);if(!U){if(k0()===0)f0();G.writeHead(400,{"Content-Type":"text/html"}),G.end(t$("Unknown state — authorization may have expired"));return}w0(K),F2(H,$,U.pkce).then((D)=>U.resolve(D)).catch((D)=>U.reject(D)),G.writeHead(200,{"Content-Type":"text/html"}),G.end(O2);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),K=H?[H]:[...H0.keys()];G.writeHead(200),G.end("Login cancelled");for(let W of K){let Q=H0.get(W);if(!Q)continue;Q.reject(Error("Login cancelled")),w0(W)}if(k0()===0)f0();return}G.writeHead(404),G.end("Not found")},X=I8(Z);await f8(X,"127.0.0.1");let z=[X],Y=I8(Z);try{await f8(Y,"::1"),z.push(Y)}catch(J){let G=J.code;if(G!=="EADDRNOTAVAIL"&&G!=="EAFNOSUPPORT")throw m8(X),J}return $Z=z,{port:O$,redirectUri:$}})();try{return await L$}finally{L$=void 0}}function f0(){let $=$Z;$Z=[];for(let Z of $)m8(Z)}function j2($,Z,X=300000,z){return new Promise((Y,J)=>{if(z?.aborted){w0(Z),J(Error("Login cancelled"));return}let G=setTimeout(()=>{if(H0.get(Z))w0(Z),J(Error("OAuth callback timeout — authorization took too long"))},X),B=()=>{if(clearTimeout(G),H0.get(Z))w0(Z),J(Error("Login cancelled"))};if(z)z.addEventListener("abort",B);H0.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(G),z)z.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(G),z)z.removeEventListener("abort",B);J(H)}})})}async function R2($){let Z=await fetch(`${y0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y8($)},body:JSON.stringify({client_id:ZZ})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${y0}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function T2($,Z,X){let z=Math.max(parseInt($.interval,10)||5,1)*1000,Y=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),J=!Number.isNaN(Y)&&Y>0?Y*1000:900000,G=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>J)throw Error("Device authorization expired");let B=await fetch(`${y0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y8(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let W=await B.json(),Q=await fetch(`${y0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:W.authorization_code,redirect_uri:`${y0}/deviceauth/callback`,client_id:ZZ,code_verifier:W.code_verifier}).toString()});if(!Q.ok)throw Error(`Token exchange failed: ${Q.status}`);return await Q.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let H=J-(Date.now()-G);if(H<=0)throw Error("Device authorization expired");let K=Math.min(z+D2,H);try{await U2(K,void 0,{signal:X})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function lX($){let{label:Z,headless:X=!1,signal:z,version:Y}=$;if($6(Z),X){let{deviceData:W,url:Q,instructions:U}=await R2(Y),D=(async()=>{let V=await T2(W,Y,z),_=Date.now(),M=e$(V);return{id:$6(Z||M||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:_+(V.expires_in??3600)*1000,enabled:!0,addedAt:_,lastUsed:_,lastRefreshedAt:_,accountId:M}})();return{url:Q,instructions:U,completion:D}}let{redirectUri:J}=await P2(),G=await M2(),B=h8(crypto.getRandomValues(new Uint8Array(32)).buffer),H=_2(J,G,B),K=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let W=await j2(G,B,void 0,z),Q=Date.now(),U=e$(W);return{id:$6(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:W.access_token,refresh:W.refresh_token,expires:Q+(W.expires_in??3600)*1000,enabled:!0,addedAt:Q,lastUsed:Q,lastRefreshedAt:Q,accountId:U}}finally{w0(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:K}}function XZ($){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 v8($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function g8($,Z){let X=$.get(Z);if(X===null||X.trim()==="")return;let z=Number(X);if(!Number.isFinite(z)||z<0||z>100)return;let Y=Z.slice(0,-13),J=Z6($.get(`${Y}-window-minutes`)),G=XZ($.get(`${Y}-reset-at`)??void 0);if(z===0&&$.get(`${Y}-window-minutes`)==="0"&&!G)return;return{usedPercent:z,remainingPercent:100-z,resetsAt:G,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}var c8=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function u8($,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 cX($){if(c8.some((J)=>u8($,J)==="invalid"))return{};let Z={},X=g8($,"x-codex-primary-used-percent");if(X)Z.primary=X;let z=g8($,"x-codex-secondary-used-percent");if(z)Z.secondary=z;let Y=x2($);if(Y)Z.credits=Y;return Z}function p8($,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 x2($){let Z=p8($,"x-codex-credits-has-credits"),X=p8($,"x-codex-credits-unlimited");if(Z===void 0||X===void 0)return;let z=_0($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:X,...z!==void 0?{balance:z}:{},checkedAt:Date.now()}}function uX($){let Z=c8.map((X)=>u8($,X));return Z.includes("valid")&&!Z.includes("invalid")}function l8($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=Z6($.window_minutes),X=XZ($.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 iX($){let Z={},X=l8($.rate_limits?.primary);if(X)Z.primary=X;let z=l8($.rate_limits?.secondary);if(z)Z.secondary=z;let Y=A2($.credits);if(Y)Z.credits=Y;return Z}function A2($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let X=_0(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 _0($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function d8($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=Z6($.limit_window_seconds),X=XZ($.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 i8($){let Z={},X=d8($.rate_limit?.primary_window);if(X)Z.primary=X;let z=d8($.rate_limit?.secondary_window);if(z)Z.secondary=z;let Y=v8($.rate_limit_reset_credits?.available_count);if(Y!==void 0)Z.resetCreditsAvailable=Y;let J=v8($.rate_limit_reset_credits?.applicable_available_count);if(J!==void 0)Z.resetCreditsApplicable=J;let G=$.spend_control?.individual_limit;if($.spend_control===null||G===null)Z.spendControlCleared=!0;if(G&&typeof $.spend_control?.reached==="boolean"){let H=_0(G.limit),K=_0(G.used),W=_0(G.remaining),Q=_0(G.used_percent),U=_0(G.remaining_percent);if(H!==void 0&&K!==void 0&&W!==void 0&&Q!==void 0&&U!==void 0)Z.spendControl={limit:H,used:K,remaining:W,usedPercent:Q,remainingPercent:U,resetsAt:XZ(G.reset_at),unit:G.unit,source:G.source,reached:$.spend_control.reached}}let B=$.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let H=_0(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as d4}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as E2}from"@cortexkit/claustrum-client";import{SocketClosedError as S2,SocketTimeoutError as C2,SubcCallError as I2}from"@cortexkit/subc-client";class N 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 S extends N{reason;constructor($){super("unavailable","Claustrum vault could not be reached");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function a($){if($ instanceof S||$ instanceof S2||$ instanceof C2)return"unreachable";let Z=$ instanceof E2||$ instanceof I2?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(X6,Z))return"answered";return X6[Z]}import{storeIdentity as a8}from"@cortexkit/claustrum-client";var n8=a8.length!==1,s8=a8;function o8($){let Z=$.storagePath??process.cwd();return n8?s8($.projectRoot??process.cwd(),Z):s8(Z)}function zZ($){if(n8)return $;let{projectRoot:Z,...X}=$;return X}import{resolve as r8}from"node:path";import{SubcClient as t8}from"@cortexkit/subc-client";var X$=300000,YZ=300000,z6=1000;class P${#$;#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 JZ{#$;#Z;#J;#G=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#J}request(){if(this.#J)return this.#G=!0,this.#J;return this.#J=(async()=>{do{this.#G=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#G)})().finally(()=>{this.#J=void 0}),this.#J}}class GZ{#$;#Z=new P$;#J;#G="polling";#z;#K;#Y=!1;#X;#W=!1;#Q=0;constructor($){this.#$=$,this.#J=new JZ(async()=>{let Z=this.#W;if(this.#W=!1,Z||this.#X!==this.#$.view())await this.#$.discover(this.#X??"")},(Z)=>{if(!this.#Y)this.#$.onError?.(Z)})}get mode(){return this.#G}start(){if(this.#Y||this.#z||this.#K)return;if(typeof this.#$.client.watchScoped!=="function"){this.#U("fallback","client-without-watch");return}this.#O(!1)}stop(){if(this.#Y)return;if(this.#Y=!0,this.#K)(this.#$.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#z;this.#z=void 0,$?.handle.stop()}#U($,Z){if(this.#G===$)return;this.#G=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#N($,Z){this.#K=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,!this.#Y)Z()},$),this.#K.unref?.()}async#O($){let Z;try{Z=await this.#$.enrollmentToken()}catch(G){if(this.#Y)return;this.#$.onError?.(G),this.#L("token-unreadable");return}let X=this.#$.client.watchScoped;if(this.#Y||this.#z||!X)return;this.#Z.restart(),this.#W=$;let z,Y;try{Y=X.call(this.#$.client,(G)=>{if(this.#Y||!z||this.#z!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#U("watching","accepted");if(!this.#Z.continuous(G))this.#W=!0;this.#X=G.view,this.#J.request()},{enrollmentToken:Z})}catch(G){this.#$.onError?.(G),this.#L("watch-failed");return}z={handle:Y,notices:0},this.#z=z,this.#U("polling",$?"resubscribing":"opening");let J=z;Y.closed.then((G)=>this.#B(J,G),(G)=>this.#B(J,{kind:"transport_lost",error:G}))}#B($,Z){if(this.#Y||this.#z!==$)return;if(this.#z=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#U("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#L("refused");try{this.#$.onRefused(Z.error)}catch(X){this.#$.onError?.(X)}return}if($.notices>0){let X=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&X-$.acceptedAt>=300000)this.#Q=0;let z=Math.min(1000*2**Math.min(this.#Q,16),300000);this.#Q++,this.#U("polling","resubscribing"),this.#N(z,()=>void this.#O(!0));return}this.#L(Z.kind)}#L($){this.#U("fallback",$),this.#N(300000,()=>void this.#O(!1))}}function $9($){let Z=$.identity??o8($);return{connectionFile:$.connectionFile,async getUsage(){let X,z=!1,Y,J=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),G=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await t8.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),z)throw X.close(),Error("insula usage timeout");let B=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([G,J])}finally{z=!0,clearTimeout(Y),X?.close()}},watchUsage(X){let z,Y,J=!1,G=(async()=>{let B,H=new Promise((W,Q)=>{B=setTimeout(()=>Q(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),K=(async()=>{let W=Math.min($.handshakeTimeoutMs??3000,3000),Q=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:W}):await t8.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:W});if(z=Q,J){Q.close();return}let U=await Q.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(J){Q.close();return}Y=Q.subscribe(U,{method:"usage.watch"},X)})();try{await Promise.race([K,H])}catch(W){throw J=!0,W}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{J=!0,z?.close()});return{stop(){if(J)return;J=!0,Y?.unsubscribe(),z?.close()},closed:G}}}}var HZ=60000,e8=4*HZ,b2=2*HZ,Y6=new Map,BZ=new Map;function z$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function k2($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!z$(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function f2($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class Z9{transport;key;#$=[];#Z=!1;#J=new Set;#G=new Map;#z=new JZ(async()=>{try{let $=await this.transport.getUsage();if(!z$($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>z$(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#J=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#J)this.#G.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#J.clear()}},()=>{});#K=new P$;#Y="polling";#X=0;#W=0;#Q=new Map;#U;#N;#O={};#B=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#z.running)return this.#z.running;if(this.#Y==="watching")return Promise.resolve();for(let[X,z]of BZ)if($-z>=HZ)BZ.delete(X);let Z=BZ.get(this.key);if(Z!==void 0&&$-Z<HZ)return Promise.resolve();return BZ.set(this.key,$),this.#z.request()}watchMode(){return this.#Y}watch($={}){this.#X++;let Z=$.provider;if(Z===void 0)this.#W++;else this.#Q.set(Z,(this.#Q.get(Z)??0)+1);if(this.#X===1)this.#O=$,this.#P();let X=!1;return()=>{if(X)return;if(X=!0,Z===void 0)this.#W--;else{let z=(this.#Q.get(Z)??1)-1;if(z>0)this.#Q.set(Z,z);else this.#Q.delete(Z)}if(--this.#X===0)this.#L()}}#L(){if(this.#N)(this.#O.clearTimeoutImpl??clearTimeout)(this.#N);this.#N=void 0;let $=this.#U;this.#U=void 0,$?.handle?.stop(),this.#Y="polling"}#_($){this.#N=(this.#O.setTimeoutImpl??setTimeout)(()=>{if(this.#N=void 0,this.#X>0&&!this.#U)this.#P()},$),this.#N.unref?.()}#P(){let $=this.transport.watchUsage;if(!$){this.#Y="fallback";return}this.#Y="polling",this.#K.restart();let Z={notices:0};this.#U=Z;let X;try{X=$.call(this.transport,(z)=>this.#j(Z,z))}catch(z){this.#T(Z,z);return}Z.handle=X,X.closed.then(()=>this.#T(Z,void 0),(z)=>this.#T(Z,z))}#j($,Z){if(this.#U!==$)return;if($.notices++,$.notices===1)this.#Y="watching";if($.notices===2)this.#B=0;let X=k2(Z);if(!X)this.#K.restart();if(!(X?this.#K.continuous(X):!1)||X?.provider===void 0||this.#W>0||this.#Q.has(X.provider))this.#z.request()}#T($,Z){if(this.#U!==$)return;this.#U=void 0;let X=f2(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.#B,16),YZ);this.#B++,this.#Y="polling",this.#_(z);return}if(this.#Y="fallback",this.#z.request(),Z===void 0||a(Z)==="unreachable")this.#_(YZ)}current($,Z,X){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!z$(z.usage))continue;let Y=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||X-Y>=e8)continue;return{entry:z,context:{fetchedAt:Y,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,X){if(!this.#Z)return{miss:"unreachable"};let z=this.#$.find((G)=>G.provider===$&&typeof G.account==="string"&&G.account.trim()===Z),Y=(z??this.#$.find((G)=>G.provider===$&&G.account===void 0&&G.errorClass!==void 0))?.errorClass;if(Y==="upstream_failed")return{miss:"upstream-failed"};if(Y==="credential_absent"||Y==="credential_unusable"||Y==="credential_rejected")return{miss:"credential"};if(Y!==void 0)return{miss:"unreachable"};if(z){let G=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!z$(z.usage)||!Number.isFinite(G))return{miss:"unreachable"};let B={entry:z,context:{fetchedAt:G,...typeof z.source==="string"&&{source:z.source}}};if(z.stale!==void 0&&(!z$(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:B};return X>=G+e8||z.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#J.has($))return{miss:"absent"};let J=this.#G.get($)??X;return this.#G.set($,J),{miss:X-J>=b2?"unreachable":"cold"}}}function J6($,Z){let X=JSON.stringify([r8($.connectionFile),r8(Z)]),z=Y6.get(X);if(!z)z={source:new Z9($,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 tY}from"@cortexkit/claustrum-client";function h0($){let Z=new AbortController,X=[],z=!1,Y=()=>{if(z)return;z=!0;for(let{source:B,listener:H}of X)B.removeEventListener("abort",H);X.length=0},J=(B)=>{if(z||Z.signal.aborted)return;Z.abort(B),Y()},G=$.find((B)=>B.aborted);if(G)return Z.abort(G.reason),{signal:Z.signal,dispose:Y};for(let B of $){if(Z.signal.aborted)break;let H=()=>J(B.reason);if(X.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)J(B.reason)}return{signal:Z.signal,dispose:Y}}import{channel as Q4}from"node:diagnostics_channel";import{ClaustrumCredentialError as _6}from"@cortexkit/claustrum-client";import{createHash as u2,randomBytes as i2,randomUUID as s2}from"node:crypto";import{constants as z9}from"node:fs";import{chmod as a2,mkdir as n2,open as U9,readFile as H6,realpath as o2,rename as r2,stat as D9,unlink as Q6}from"node:fs/promises";import{basename as V9,dirname as O0,extname as Y9,isAbsolute as J9,join as W6,resolve as t2}from"node:path";import{ClaustrumCredentialError as N9,ClaustrumClient as e2,writeEnrollmentTokenFile as $4}from"@cortexkit/claustrum-client";import{lstat as y2,stat as w2}from"node:fs/promises";import{resolve as h2}from"node:path";async function m2($,Z){try{let X=await Z($);return X.isFile()?X:void 0}catch(X){return X.code==="ENOENT"?"absent":void 0}}function v2($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class F0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks?(Z)=>($.stat??w2)(Z):(Z)=>($.lstat??y2)(Z)}async read($,Z,X){let z=$.map((K)=>h2(K)),Y=JSON.stringify(z),J=await Promise.all(z.map((K)=>m2(K,this.#$))),G=J.every((K)=>K!==void 0)?J:void 0,B=this.#Z.get(Y);if(G&&B&&G.every((K,W)=>{let Q=B.identities[W];return Q!==void 0&&v2(K,Q)}))return X?.(G),B.value;this.#Z.delete(Y);let H=await Z(z);if(G){if(this.#Z.size>=64){let K=this.#Z.keys().next().value;if(K!==void 0)this.#Z.delete(K)}this.#Z.set(Y,{identities:G,value:H})}return H}}import{ClaustrumCredentialError as g2}from"@cortexkit/claustrum-client";var p2="Served by Thalamus",l2="This host gets its vault accounts from Thalamus, so it can't connect to the vault itself.",X9=new WeakSet;function G6($){return X9.has($)}function b(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function B6($){if(typeof $!=="object"||$===null)return $;let Z=$;if(typeof Z.code==="string"&&(Z.class==="transient"||Z.class==="permanent"||Z.class==="auth_required"||Z.class==="context_overflow")&&(Z.action==="gone"||Z.action==="reauth"||Z.action==="retry"||Z.action==="reduce_and_retry"))return new g2(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&a(Object.assign(Error(),{code:Z.code}))==="unreachable")return new S(Z.reason==="host-accessor-missing"||Z.reason==="host-accessor-failed"?Z.reason:void 0);return $}function j$($){try{return $()}catch(Z){throw B6(Z)}}async function K0($){try{return await $()}catch(Z){throw B6(Z)}}function d2($){let Z=$.watchScoped?.bind($),X=$.reportUsageScoped?.bind($),z=$.reportCondition?.bind($),Y=$.clearCondition?.bind($);return{listScoped:(...J)=>K0(()=>$.listScoped(...J)),getScoped:(...J)=>K0(()=>$.getScoped(...J)),reportAuthFailureScoped:(...J)=>K0(()=>$.reportAuthFailureScoped(...J)),close:()=>j$(()=>$.close()),...Z&&{watchScoped:(...J)=>{let G=j$(()=>Z(...J));return{stop:()=>j$(()=>G.stop()),closed:K0(async()=>{let B=await G.closed;return B.kind==="refused"||B.kind==="transport_lost"?{...B,error:B6(B.error)}:B})}}},...X&&{reportUsageScoped:(...J)=>K0(()=>X(...J))},...z&&{reportCondition:(...J)=>K0(()=>z(...J))},...Y&&{clearCondition:(...J)=>K0(()=>Y(...J))},...$.insula&&{insula:c2($.insula)}}}function c2($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>K0(()=>$.getUsage()),...Z&&{watchUsage:(...X)=>{let z=j$(()=>Z(...X));return{stop:()=>j$(()=>z.stop()),closed:K0(()=>z.closed)}}}}}function m0($){if(!b()||!$)throw new S;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z==="function"){let X=d2(Z($));return X9.add(X),X}}catch{throw new S("host-accessor-failed")}throw new S("host-accessor-missing")}var Z4=1,QZ=16384,M9=30000,U6=/^[0-9a-f]{64}$/,q9="unknown_method",_9=new Set([q9,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),F9=new Set(["pending_queue_full"]);function K6($){if(!($ instanceof N9))return;if(_9.has($.code))return{code:$.code,disposition:"terminal"};if(F9.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function X4($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new N("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function L9($){let Z=Array.from($).length;return Z>=1&&Z<=40&&!/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test($)}function D6($){return Array.isArray($)&&$.length>=1&&$.length<=4&&Array.from($).every((Z)=>{if(!WZ(Z)||Object.keys(Z).length!==2||Z.operation!=="read"&&Z.operation!=="list"||!WZ(Z.selector))return!1;let X=Object.keys(Z.selector),z=X[0];return X.length===1&&(z==="category"||z==="exact")&&typeof Z.selector[z]==="string"&&Z.selector[z].trim().length>0})}function Q0($){return{...$.requestedGrants!==void 0&&{requestedGrants:$.requestedGrants},...$.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:$.requestedGrantsStatus}}}function z4($){return e2.connect(zZ($))}function O9($){let Z=Y9($)||".json",X=V9($,Y9($));return{statePath:W6(O0($),`${X}-state${Z}`),tokenPath:$}}function Y4($){let Z=$.override?.trim();if(Z&&!J9(Z)&&!$.cwd)throw new N("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?J9(Z)?Z:t2($.cwd,Z):W6($.stateDir,`${$.host}-enrollment.json`);return O9(X)}function WZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function KZ($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function P9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function R$(){return new N("invalid-state","invalid Claustrum enrollment state")}function DZ($){if(!WZ($)||$.version!==Z4||typeof $.proposedName!=="string"||$.proposedName.length===0)throw R$();if($.phase==="pending"){let Z=G9($);if(!U6.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!KZ($.createdAt)||!KZ($.updatedAt))throw R$();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt,...Z}}if($.phase==="approved"){let Z=G9($);if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!P9($.tokenGeneration)||!KZ($.updatedAt))throw R$();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"||!KZ($.updatedAt))throw R$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw R$()}function G9($){if($.requestedGrants!==void 0&&!D6($.requestedGrants)||$.requestedGrantsStatus!==void 0&&($.requestedGrants===void 0||$.requestedGrantsStatus!=="sent"&&$.requestedGrantsStatus!=="dropped"))return{};return Q0($)}function V6($){if(!WZ($)||!U6.test(String($.token??""))||!P9($.token_generation))throw new N("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function j9($){if(!$.isFile())throw new N("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new N("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new N("unsafe-file","Claustrum enrollment file must be owned by the current user")}function B9($){try{return JSON.parse($)}catch{throw new N("invalid-state","Claustrum enrollment file is not valid JSON")}}async function P0($){if(W0)try{await g0(O0($));let X=await UZ($,!0);if(Buffer.byteLength(X)>QZ)throw new N("unsafe-file","Claustrum enrollment file is too large");return B9(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await U9($,z9.O_RDONLY|z9.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new N("unsafe-file","Claustrum enrollment file could not be opened safely")}try{j9(await Z.stat());let X=Buffer.alloc(QZ+1),{bytesRead:z}=await Z.read(X,0,X.byteLength,0);if(z>QZ)throw new N("unsafe-file","Claustrum enrollment file is too large");return B9(X.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function H9($,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 J4($,Z,X){try{let[z,Y]=await Promise.all([H6(X.passwdPath??"/etc/passwd","utf8"),H6(X.groupPath??"/etc/group","utf8")]),J=H9(z,7),G=H9(Y,4);if(!J||!G)return!1;let B=J.filter((Q)=>Number(Q[2])===$),H=G.filter((Q)=>Number(Q[2])===Z);if(B.length!==1||H.length!==1)return!1;let K=B[0]?.[0],W=H[0]?.[3]??"";return(W===""||W.split(",").every((Q)=>Q===K))&&!J.some((Q)=>Number(Q[2])!==$&&Number(Q[3])===Z)}catch{return!1}}function R9($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>H6(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function T9($,Z={}){if(!W0){let X=process.geteuid?.();if(X===void 0)return;let z=process.getegid?.(),Y;try{Y=await o2($)}catch{return}let J;for(;;){let G=await D9(Y).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(J===void 0)J=z!==void 0&&await J4(X,z,Z);if((G.mode&2)!==0||G.uid!==X||G.gid!==z||!J)throw new N("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=O0(Y);if(B===Y)return;Y=B}}try{await Q9($,R9(Z))}catch(X){if(!(X instanceof G0))throw X;throw new N("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function Y$($,Z={},X="enrollment directory"){if(W0){await g0($,!1,R9(Z));return}await n2($,{recursive:!0,mode:448});let z=await D9($),Y=process.geteuid?.();if(Y!==void 0&&z.uid!==Y)throw new N("unsafe-file",`Claustrum ${X} must be owned by the current user`);if((z.mode&63)!==0)await a2($,448)}async function v0($,Z,X={}){let z=O0($);await Y$(z,X),await T9(z,X);let Y=`${JSON.stringify(Z)}
89
+ `;if(Buffer.byteLength(Y)>QZ)throw new N("invalid-state","Claustrum enrollment state is too large");if(W0)return W9($,Y);let J=W6(z,`.${V9($)}.${process.pid}.${s2()}.tmp`),G,B=!1;try{G=await U9(J,"wx",384),B=!0,await G.writeFile(Y,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await r2(J,$),B=!1}finally{if(await G?.close().catch(()=>{}),B)await Q6(J).catch(()=>{})}}var G4=new F0;async function N6($,Z){let X=W0?await K9($,Z):await G4.read([$.tokenPath,$.statePath],async([Y=$.tokenPath,J=$.statePath])=>K9({tokenPath:Y,statePath:J},Z),(Y)=>{for(let J of Y)if(J!=="absent")j9(J)}),z={...X.status};if(X.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function K9($,Z){let X=await P0($.tokenPath),z=X===void 0?void 0:V6(X),Y=await P0($.statePath),J=Y===void 0?void 0:DZ(Y);if(z)return{usesProposedName:J===void 0,status:{state:"approved",proposedName:J?.proposedName??Z,...J?.phase==="approved"&&J.approvedName!==void 0&&{approvedName:J.approvedName},tokenGeneration:z.token_generation,...J&&(J.phase==="approved"||J.phase==="pending")&&Q0(J)}};if(!J)return{status:{state:"idle"},usesProposedName:!1};if(J.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:J.proposedName,code:"missing_token"}};return{status:L0(J),usesProposedName:!1}}async function x9($,Z){let X;try{X=await N6($,Z)}catch(z){if(!(z instanceof N)||z.kind!=="invalid-state"&&z.kind!=="invalid-token")return"unreadable";try{let Y=await P0($.statePath);if(Y===void 0)return"unreadable";let J=DZ(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 B4($,Z){if(b())return"host";return x9($,Z)}async function j0($){let Z=await P0($);if(Z===void 0)throw new N("not-enrolled","Claustrum enrollment is not configured");return V6(Z)}function L0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId},...Q0($)};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,...Q0($)};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function A9(){return new N("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class E9{#$;#Z;#J;#G;#z;#K;#Y;#X;#W;constructor($){if($.displayName!==void 0&&!L9($.displayName))throw new N("invalid-state","invalid Claustrum enrollment display name");if($.requestedGrants!==void 0&&!D6($.requestedGrants))throw new N("invalid-state","invalid Claustrum enrollment requested grants");this.#z=$.requestedGrants?.map((Z)=>({selector:{...Z.selector},operation:Z.operation})),this.#W=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#J=$.proposedName,this.#G=$.displayName,this.#K=$.now??Date.now,this.#Y=$.mintSecret??(()=>i2(32).toString("hex")),this.#X=$.writeTokenFile??$4}async status(){return N6(this.#Z,this.#J)}async resetTerminal(){return S9(this.#Z,this.#J)}async#Q($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#K()};return await v0(this.#Z.statePath,X,this.#W),L0(X)}async reconcile(){await Y$(O0(this.#Z.statePath),this.#W);let $=await g({name:"ceremony",path:this.#Z.statePath,ttlMs:M9,renew:!0});if(!$)return{state:"busy"};try{let Z=await P0(this.#Z.tokenPath),X=Z===void 0?void 0:V6(Z),z=await P0(this.#Z.statePath),Y=z===void 0?void 0:DZ(z);if(Y&&Y.proposedName!==this.#J)throw A9();if(X){if(!Y||Y.phase==="pending"){let G={version:1,phase:"approved",proposedName:Y?.proposedName??this.#J,tokenGeneration:X.token_generation,...Y&&Q0(Y),updatedAt:this.#K()};await v0(this.#Z.statePath,G,this.#W),Y=G}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:X.token_generation,...Y.phase==="approved"&&Q0(Y)}}if(Y?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#K()};return await v0(this.#Z.statePath,G,this.#W),L0(G)}if(Y&&Y.phase!=="pending")return L0(Y);if(!Y){let G=this.#K();if(Y={version:1,phase:"pending",proposedName:this.#J,requestSecret:this.#Y(),createdAt:G,updatedAt:G,...this.#z!==void 0&&{requestedGrants:this.#z}},!U6.test(Y.requestSecret))throw new N("invalid-state","invalid minted Claustrum enrollment secret");await v0(this.#Z.statePath,Y,this.#W)}if(!Y.requestId)try{let G=u2("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B={name:Y.proposedName,requestSecretHash:G},H,K=Y.requestedGrantsStatus;try{if(H=await this.#$.enrollPropose({...B,...this.#G!==void 0&&{displayName:this.#G},...Y.requestedGrants!==void 0&&{requestedGrants:Y.requestedGrants}}),Y.requestedGrants!==void 0)K="sent"}catch(W){if(this.#G===void 0&&Y.requestedGrants===void 0||!(W instanceof N9)||W.code!=="invalid_params")throw W;if(H=await this.#$.enrollPropose(B),Y.requestedGrants!==void 0)K="dropped"}Y={...Y,requestId:H.requestId,updatedAt:this.#K(),...K!==void 0&&{requestedGrantsStatus:K}},await v0(this.#Z.statePath,Y,this.#W)}catch(G){let B=K6(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code,...Q0(Y)};if(B.code===q9)return await $.assertOwned(),await Q6(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:Y.proposedName,code:B.code};return this.#Q(Y,B.code)}let J=Y.requestId;if(!J)return L0(Y);try{let G=await this.#$.enrollPoll({requestId:J,requestSecret:Y.requestSecret});if(G.status==="pending")return L0(Y);if(G.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#K()};return await v0(this.#Z.statePath,H,this.#W),L0(H)}await Y$(O0(this.#Z.tokenPath),this.#W),await T9(O0(this.#Z.tokenPath),this.#W),await this.#X(this.#Z.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,...Q0(Y),updatedAt:this.#K()};return await v0(this.#Z.statePath,B,this.#W),L0(B)}catch(G){let B=K6(G);if(!B)throw G;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:J,retryCode:B.code,...Q0(Y)};return this.#Q(Y,B.code)}}finally{await $.release()}}}async function S9($,Z){await Y$(O0($.statePath));let X=await g({name:"ceremony",path:$.statePath,ttlMs:M9,renew:!0});if(!X)return"busy";try{if(await P0($.tokenPath)!==void 0)return"refused-approved";let z=await P0($.statePath);if(z===void 0)return"idle";let Y=DZ(z);if(Y.proposedName!==Z)throw A9();if(Y.phase==="pending")return"refused-pending";return await X.assertOwned(),await Q6($.statePath),"reset"}finally{await X.release()}}var T$="claustrum-tombstone:v1:";function VZ($){return`${T$}${$}`}function M6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function NZ($){return typeof $==="string"&&$.startsWith(T$)}function C9($,Z){if(!M6($)||$.type!=="oauth")return!1;return $.refresh===VZ(Z)}function I9($,Z){if(C9($,Z))return"placeholder";if(M6($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!NZ($.refresh))return"login";if(M6($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function H4($){let Z=I9($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new N("host-slot-login",`${$.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if($.mode==="local"&&Z==="placeholder")throw new N("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function J$($,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 G$($,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 K4}from"@cortexkit/claustrum-client";function b9($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class q6{options;#$=new Map;#Z=new Map;#J=new Set;#G;#z;#K=!1;#Y=!1;#X=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#z!==void 0,dropped:this.#X}}report($,Z){if(this.#K||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#X++;return}if(!b9(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(!b9(z)||"credentialId"in z||"vouched"in z||typeof z.observedAtMs!=="number"||!Number.isFinite(z.observedAtMs))throw Error("invalid reading");if(z.observedAtMs<=(this.#Z.get($)??-1/0)){this.#X++;return}if(this.#$.has($))this.#X++;if(this.#Z.set($,z.observedAtMs),this.#$.set($,z),!this.#G&&!this.#z)this.#G=this.options.setTimeout(()=>{this.#G=void 0,this.#W()},1000),this.#G.unref?.()}catch{this.#X++}}forget($){if(this.#$.delete($))this.#X++;this.#Z.delete($)}#W(){if(this.#z||!this.#$.size||this.#Y)return this.#z;let $=Promise.resolve().then(async()=>{while(!this.#Y&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[X,z]=Z;this.#$.delete(X);try{let Y=await this.options.token();if(this.#Y||!this.options.owns(X)){if(!this.#Y)this.#X++;continue}await this.options.client.reportUsageScoped?.({credentialId:X,reading:z,enrollmentToken:Y})}catch(Y){if(!this.#Y)this.#X++;this.#Q(Y)}}});return this.#z=$,$.finally(()=>{this.#z=void 0}),$}#Q($){let Z="transport_error";try{if($ instanceof K4)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#J.has(Z))return;this.#J.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#K=!0,this.#G)this.options.clearTimeout(this.#G);return this.#G=void 0,this.#W()}drop(){this.#Y=!0,this.#X+=this.#$.size+(this.#z?1:0),this.#z=void 0,this.#$.clear(),this.#Z.clear()}}function y9($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function W4($,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 L6=p("claustrum");function k9($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new N("invalid-token","Invalid Claustrum enrollment token");return $.token}var R0=Q4("common-auth.claustrum.phases");function P6($,Z,X,z=L6){let Y=y9(Z,X);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:Y,reason:W4(Z,X)}),Y}var O6=300000,w9=60000,h9=1e4,m9=60000;function F6(){return new N("invalid-material","Claustrum returned invalid credential material")}function U4($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw F6()}if(!X||typeof X!=="object")throw F6();let z=X,Y=z.access_token??z.access;Z=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(T$))throw F6();return Z}function D4($,Z){let X={kind:"not-mine"};if(!$.operations.includes("read"))return X;if(!$.categories.includes(Z.category))return X;if("classify"in Z){let J=f9($),G;switch(J.authMethod){case"apikey":G="api_key";break;case"chatgpt":case"antigravity":case"oauth":G="oauth";break;default:return{kind:"refused",code:"unknown-auth-method"}}let B={credentialId:$.id,credentialType:G,categories:$.categories,refreshAdapter:$.refreshAdapter,...J};if(B.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let H=Z.classify(B);if(H.kind==="not-mine")return X;if(H.kind==="mine"&&typeof H.member==="string")return{kind:"mine",type:G,member:H.member};if(H.kind==="refused"&&typeof H.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(H.code)&&!H.code.includes(`
90
+ `)&&Z.refusalCodes.includes(H.code))return{kind:"refused",code:H.code}}catch{}return{kind:"refused",code:"unclassified"}}let z=$.credentialType;if(z==="oauth"){if($.refreshAdapter!==Z.refreshAdapter)return X}else if(z==="api_key"){if(!Z.apiKeys||$.refreshAdapter!==void 0)return X}else return X;let{authMethod:Y}=f9($,{includeProviderIds:!1});if(Y!==void 0){if(!(z==="oauth"?Y==="chatgpt"||Y==="antigravity"||Y==="oauth":Y==="apikey"))return{kind:"refused",code:"unknown-auth-method"}}return{kind:"mine",type:z}}function f9($,{includeProviderIds:Z=!0}={}){let X=$;return{providerIds:Z?X.providerIds:void 0,authMethod:X.authMethod}}function v9($){return $==="provider_verification_required"||$==="provider_ineligible"}function V4($){let Z=$.condition;if(!Z)return;let{reason:X,sinceMs:z}=Z;if(v9(X)&&Number.isSafeInteger(z)&&z>0)return Object.freeze({reason:X,sinceMs:z});return}function N4($){if(typeof $!=="string")return;try{if(new URL($).protocol==="https:")return $}catch{}return}function M4($){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 B${#$;#Z;#J;#G;#z;#K;#Y;#X=new WeakMap;#W=new WeakMap;#Q=new Map;#U=new Map;#N=!1;#O=0;#B=new Map;#L=new WeakMap;#_;#P=new Map;#j;#T;#H=!1;#R=0;#x=!1;#V=new S;#M=new Map;#q;#A=!1;#I=-1/0;#y=2000;#D=!1;#E;#b=new Map;#S=new Set;#C=new Set;#w;#m;#l;constructor($){if(b()&&$.client&&!G6($.client))throw new S;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>j0(Z);else if(b())this.#Z=async()=>{throw new N("not-enrolled","Claustrum enrollment token path is required")};else throw new N("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client??m0($.pluginId),this.#G=$.family,this.#z=$.parseIdentity,this.#K=$.requireAssertion??!1,this.#J=$.now??Date.now,this.#Y=$.logger??L6,this.#w=J$(this.#Y),this.#j=$.setTimeoutImpl??setTimeout,this.#T=$.clearTimeoutImpl??clearTimeout;let X=()=>this.#$;this.#_=new q6({client:{get reportUsageScoped(){let z=X();return z.reportUsageScoped?.bind(z)}},owns:(z)=>this.#P.has(z),token:async()=>b()?"":k9(await this.#Z()),logger:this.#Y,setTimeout:this.#j,clearTimeout:this.#T})}replaceClient($){if(this.#F(),$===this.#$)return;if(b()&&!G6($))throw new S;this.#$=$,this.#N=!1;for(let Z of this.#S)Z.restart()}transportLost($){if(this.#D||this.#H)return;this.#H=!0,this.#R=this.#J(),this.#x=!1,this.#V=$ instanceof _6?$:new S($ instanceof S?$.reason:void 0),this.#Y.warn("serving kept vault receipt",{reason:"unreachable"}),this.#k()}reachable(){if(this.#D||!this.#H)return;if(this.#H=!1,this.#q)this.#T(this.#q);this.#q=void 0,this.#y=2000;for(let $ of this.#B.values())$.since=null;(this.#Y.info??L6.info)("vault receipt serving resumed",{reason:"reachable"})}#k(){if(this.#D||!this.#H||this.#q||this.#A)return;this.#q=this.#j(()=>{this.#q=void 0,this.#h(!0)},this.#y),this.#q.unref?.()}#h($=!1){if(this.#D||!this.#H||this.#A)return;if(this.#J()-this.#I<1000){this.#k();return}this.#I=this.#J(),this.#A=!0,this.#i().catch(()=>{if($&&this.#H)this.#y=Math.min(this.#y*2,30000)}).finally(()=>{this.#A=!1,this.#k()})}#F($){if(this.#D)throw new N("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#v($){if(this.#F($),b())return"";if(R0.hasSubscribers)R0.publish({logger:this.#Y,phase:"token read begin"});let Z=this.#Z();this.#C.add(Z);let X;try{X=await Z}finally{if(this.#C.delete(Z),R0.hasSubscribers)R0.publish({logger:this.#Y,phase:"token read end"})}return this.#F($),k9(X)}async#f($,Z){this.#F(Z);let X,z;try{let Y=$();X=Z?await Promise.race([Y,new Promise((J,G)=>{let B=()=>G(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),z=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await Y}catch(Y){if(this.#F(Z),a(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof _6)throw Y;if(a(Y)==="unreachable")throw new S(Y instanceof S?Y.reason:void 0);throw new N("unavailable","Claustrum scoped operation failed")}finally{z?.()}return this.#F(Z),this.reachable(),X}async discover($){let Z=await this.#i($);this.#E=Z.view,this.#b.clear();for(let{credentialId:X,condition:z}of Z.credentials)if(z)this.#b.set(X,z);return Z}async#i($){let Z,X;try{X=await this.#v($)}catch(Q){throw this.#B.clear(),this.#d(),Q}if(R0.hasSubscribers)R0.publish({logger:this.#Y,phase:"list scoped begin"});try{Z=await this.#f(()=>this.#$.listScoped(X),$)}catch(Q){throw this.listFailed(Q),Q}finally{if(R0.hasSubscribers)R0.publish({logger:this.#Y,phase:"list scoped end"})}let z=[],Y=[],J=0,G=[],B=new Map;for(let Q of Z.rows){let U=D4(Q,this.#G);if(U.kind==="not-mine"){J++;continue}if(U.kind==="refused"){Y.push({...Q.id.trim()&&{credentialId:Q.id},code:U.code});continue}G.push({row:Q,type:U.type,...U.member!==void 0&&{member:U.member}}),B.set(Q.id,(B.get(Q.id)??0)+1)}let H=[];for(let{row:Q,type:U,member:D}of G){let V;if(!Q.id.trim())V="empty credential id";else if((B.get(Q.id)??0)>1)V="duplicate credential id";else if(Q.accountId!==void 0&&!Q.accountId.trim())V="blank account identity";else if(!Q.state.trim())V="empty state";if(V){z.push({...Q.id.trim()&&{credentialId:Q.id},...D!==void 0&&{member:D},reason:V});continue}let _=V4(Q);H.push(Object.freeze({credentialId:Q.id,credentialType:U,...D!==void 0&&{member:D},...Q.accountId!==void 0&&{accountIdentity:Q.accountId},state:Q.state,...Q.email!==void 0&&{email:Q.email},...Q.orgName!==void 0&&{orgName:Q.orgName},..._&&{condition:_}}))}for(let Q of z)this.#Y.warn("skipped malformed vault record",Q);let K=M4(Z),W="classify"in this.#G;return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),...(W||Y.length>0)&&{refused:Object.freeze(Y)},...W&&{notMine:J},...K&&{grantReach:K}}}listFailed($){if(a($)==="unreachable")this.transportLost($);else this.reachable(),this.#B.clear(),this.#d()}forget($){this.#B.delete($),this.#P.delete($),this.#_.forget($)}#d(){for(let $ of this.#P.keys())this.#_.forget($);this.#P.clear()}retain($){let Z=new Map($.map((X)=>[X.credentialId,X]));for(let[X,z]of this.#B){let Y=Z.get(X);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==z.attempt.credentialType||Y.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(X)}for(let[X,z]of this.#P){let Y=Z.get(X);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==z.credentialType||Y.accountIdentity!==z.accountIdentity)this.forget(X)}}keptReceiptState(){let $=null;for(let[Z,X]of this.#B){if(!this.#c(X.attempt)){this.forget(Z);continue}if(X.since!==null)$=Math.min($??X.since,X.since)}return Object.freeze({active:$!==null,since:$})}#c($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#J()>w9}async authorize($,Z,X="vault"){this.#F(Z);let z=this.#J(),{credentialId:Y,credentialType:J,accountIdentity:G}=$,B=this.#B.get(Y);if(B&&(B.attempt.credentialType!==J||B.attempt.expectedAccountIdentity!==G||!this.#c(B.attempt)))this.forget(Y),B=void 0;let H;try{H=await this.#v(Z)}catch(K){throw this.#B.clear(),this.#d(),K}if(this.#H&&B)return this.#h(),this.#g(Y,B,H,X);try{let K;try{if(this.#H&&this.#M.has(this.#s({credentialId:Y,credentialType:J,accountIdentity:G},H)))throw this.#V;K=await this.#p({credentialId:Y,credentialType:J,accountIdentity:G},H,Z)}catch(W){if(this.#F(Z),a(W)!=="unreachable"||B)throw W;K=await this.#o({credentialId:Y,credentialType:J,accountIdentity:G},H,z,W,Z)}return this.#B.set(Y,{attempt:K,routeId:X,since:null}),this.#P.set(Y,{...$}),K}catch(K){if(this.#F(Z),a(K)!=="unreachable")throw this.forget(Y),K;return this.#g(Y,B,H,X,K)}}#s($,Z){return JSON.stringify([$.credentialId,$.credentialType,$.accountIdentity,Z])}async#o($,Z,X,z,Y){let J=h9-(this.#J()-X);if(J<=0||this.#x||this.#J()-this.#R>=m9)throw z;let G=this.#s($,Z),B=this.#M.get(G);if(!B){let Q=new AbortController,U={controller:Q,users:0,error:z,pending:Promise.resolve().then(async()=>{let V=250;for(;;){await this.#u(V,Q.signal);try{return await this.#p($,Z,Q.signal)}catch(_){if(this.#F(Q.signal),a(_)!=="unreachable")throw _;U.error=_,V=Math.min(V*2,1000)}}})};B=U,this.#M.set(G,B);let D=()=>{if(this.#M.get(G)===U)this.#M.delete(G)};B.pending.then(D,D)}let H=B;H.users++;let K,W;try{let Q=await Promise.race([H.pending,new Promise((D,V)=>{if(K=this.#j(()=>{if(this.#H)this.#x=!0;V(H.error)},J),K.unref?.(),Y){if(W=()=>V(Y.reason),Y.addEventListener("abort",W,{once:!0}),Y.aborted)W()}})]);this.#F(Y);let U=Object.freeze(Object.defineProperty({...Q},"accessToken",{value:Q.accessToken,enumerable:!1}));return this.#X.set(U,{token:Z}),U}finally{if(K)this.#T(K);if(W)Y?.removeEventListener("abort",W);if(--H.users===0){if(H.controller.abort(),this.#M.get(G)===H)this.#M.delete(G)}}}#u($,Z){return this.#F(Z),new Promise((X,z)=>{let Y=()=>{this.#T(J),Z.removeEventListener("abort",Y),z(Z.reason)},J=this.#j(()=>{Z.removeEventListener("abort",Y),X()},$);if(J.unref?.(),Z.addEventListener("abort",Y,{once:!0}),Z.aborted)Y()})}#g($,Z,X,z,Y=this.#V){if(!Z||this.#B.get($)!==Z||!this.#c(Z.attempt))throw this.forget($),Y;if(Z.since===null)Z.since=this.#J();let J=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#X.set(J,this.#X.get(Z.attempt)??{token:X}),this.#L.set(J,z),J}async#p($,Z,X){if(!$.credentialId)throw new N("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:Y,accountIdentity:J}=$;if(this.#K&&J===void 0)throw new N("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#f(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...Y==="oauth"&&{minTtlMs:O6}}),X);if(G.credentialId!==void 0&&G.credentialId!==z)throw new N("identity-changed","Claustrum served credential identity changed");let B=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#J()<O6))throw new N("insufficient-validity","Claustrum served credential has insufficient validity");let H=U4(G.material),K=G.accountId?.trim()?G.accountId:void 0;if(this.#K&&(G.credentialId===void 0||K===void 0))throw new N("identity-unasserted","Claustrum served credential did not assert its identity");let W=K===void 0?this.#z?.(H):void 0,Q=K??W;if(J!==void 0&&Q!==void 0&&Q!==J)throw new N("identity-changed","Claustrum served credential identity changed");let U=Q??J,V=Object.freeze(Object.defineProperty({credentialId:z,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:K!==void 0?"asserted":W!==void 0?"parsed":J!==void 0?"expected":"none",...J!==void 0&&{expectedAccountIdentity:J},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...K!==void 0&&{assertedAccountIdentity:K},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#X.set(V,{token:Z}),V}async reportFailure($,Z,X){if(Z!==401)return;this.#F();let z=this.#X.get($);if(!z)throw new N("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#L.get($);if(Y!==void 0){this.forget($.credentialId),this.#Y.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let J=this.#B.get($.credentialId);if(J&&J.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let G=this.#W.get($);if(G)return G;let B=this.#f(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#W.set($,B);try{await B,this.#Y.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(H){throw this.#W.delete($),H}}reportCondition($,Z){let X=this.#X.get($);if(!X)return Promise.reject(new N("no-receipt","Claustrum condition report requires an original dispatch receipt"));let{reason:z,providerStatus:Y}=Z??{};if(this.#D||this.#L.has($)||Y!==403||!v9(z))return Promise.resolve("skipped");let{credentialId:J,recordVersion:G}=$,B=z==="provider_verification_required"?N4(Z.actionUrl):void 0;return this.#a(this.#Q,JSON.stringify([J,G,z]),{credentialId:J,recordVersion:G,reason:z},(H)=>H.reportCondition?.({credentialId:J,recordVersion:G,reason:z,providerStatus:Y,...B!==void 0&&{actionUrl:B},enrollmentToken:X.token}))}clearCondition($){let Z=this.#X.get($);if(!Z)return Promise.reject(new N("no-receipt","Claustrum condition clear requires an original dispatch receipt"));if(this.#D||this.#L.has($))return Promise.resolve("skipped");let{credentialId:X,recordVersion:z}=$,Y=this.#b.get(X);if(!Y)return Promise.resolve("skipped");return this.#a(this.#U,JSON.stringify([X,Y.sinceMs]),{credentialId:X,recordVersion:z,reason:Y.reason},(J)=>J.clearCondition?.({credentialId:X,recordVersion:z,enrollmentToken:Z.token}))}#a($,Z,X,z){let Y=$.get(Z);if(Y)return Y;if(this.#N)return Promise.resolve("unsupported");let J=Promise.resolve().then(async()=>{let G=this.#$;if(this.#N)return"unsupported";try{let B=z(G);if(!B)return"unsupported";if(await B===!1)this.#n("scoped login condition not cleared",X);return"reported"}catch(B){if(B instanceof _6&&B.code==="unknown_method"){if(G===this.#$)this.#N=!0;return"unsupported"}return this.#n("scoped login condition update failed",X),"failed"}});return $.set(Z,J),this.#O++,this.#C.add(J),J.then(()=>{this.#O--,this.#C.delete(J)}),J}#n($,Z){try{this.#Y.debug($,Z)}catch{}}watchRoster($){this.#F();let Z=$.view??(()=>this.#E),X,z,Y=(G=!1)=>{let B=new GZ({client:this.#$,enrollmentToken:()=>this.#v(),view:()=>G?void 0:Z(),discover:async(H)=>{while(X)await X.catch(()=>{});if(z!==B)return;G=!1,X=Promise.resolve().then(()=>$.onView(H));try{await X}finally{X=void 0}},onRefused:(H)=>{this.listFailed(H),$.onRefused?.(H)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#Y,now:this.#J,setTimeoutImpl:this.#j,clearTimeoutImpl:this.#T});return B};z=Y();let J={restart:()=>{let G=z.mode;if(z.stop(),z=Y(!0),G!==z.mode)$.onMode?.(z.mode);z.start()},stop:()=>z.stop()};return this.#S.add(J),z.start(),{get mode(){return z.mode},close:()=>{this.#S.delete(J),z.stop()}}}reportUsage($){if(this.#D)return;try{this.#_.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#_.state()}close(){if(this.#D)return;this.#D=!0;for(let X of this.#M.values())X.controller.abort();if(this.#M.clear(),this.#q)this.#T(this.#q);this.#q=void 0;for(let X of this.#S)X.stop();this.#S.clear(),this.#B.clear();let $=this.#_.close(),Z=$!==void 0||this.#O>0;if($)this.#C.add($),$.then(()=>this.#C.delete($));if(!Z)this.#$.close();this.#l=G$(this.#C,(X)=>(this.#m??this.#w)(X)).finally(()=>{if(this.#_.drop(),this.#P.clear(),Z)this.#$.close()})}async dispose($=this.#w){this.#m=$,this.close(),await this.#l}}import{resolve as _Z}from"node:path";var g9=30000,p9={now:()=>performance.now(),schedule($,Z){let X=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(X),unref:()=>X.unref?.()}}};function l9($,Z=""){let X=new Map,{observation:z}=$,Y=(B,H,K)=>X.set(`${Z}:${B}`,{at:H,order:0,publication:{...$,observation:K}}),J=(B,H)=>JSON.stringify([B??"all",H]),G=new Set;for(let B of z.readings??[]){let H=J(B.scope,B.label);G.add(H),Y(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...B}]})}for(let B of z.coverage??[]){let H=J(B.scope,B.label);if(!G.has(H))Y(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...B}]})}if(z.budget)Y("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[B,H]of Object.entries(z.counters??{}))Y(`counter:${B}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[B]:{...H}}});if(z.credits)Y("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!X.size)Y("empty",z.checkedAt,{checkedAt:z.checkedAt});return X}import{createHash as q4}from"node:crypto";import{stat as _4}from"node:fs/promises";import{resolve as x$}from"node:path";function d9($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function j6($,Z,X){return $.some((z)=>d9(z,Z,X))}function R6($,Z,X){let z={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((Y)=>Y.credentialId!==Z||Y.accountIdentity!==X),z]}function T6($,Z,X){return $.filter((z)=>!Z.some((Y)=>d9(z,Y,X)))}function A6($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>$0(Z).map((X)=>({credentialId:X,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function F4($,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 qZ="vault:";function L4($){return q4("sha256").update($).digest("hex")}function O4($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function P4($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function $0($){return[$.credentialId,...$.aliases??[]]}function i9($,Z,X={}){let z=X.now??Date.now(),Y=X.routePrefix??qZ,J=X.reservedRouteIds??new Set,G=$?.rows??[],B=$?void 0:X.seed,H=[...$?.declined??B?.declined??[]],K=Z.skipped.length===0,W=new Set(Z.credentials.map((F)=>F.credentialId)),Q=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),U=Z.skipped.some((F)=>F.credentialId===void 0),D=(F)=>!W.has(F)&&(Q.has(F)||U),V=new Map;for(let F of G){if(F.accountIdentity===void 0)continue;for(let P of $0(F))if(!V.has(P))V.set(P,F.accountIdentity)}let _=new Map;for(let F of Z.credentials){let P=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:V.get(F.credentialId),claimed:!1},w=P4(P),d=_.get(w)??[];d.push(P),_.set(w,d)}let M=new Set,R=new Set(J),x=[],L=(F,P)=>F.credential.credentialId.localeCompare(P.credential.credentialId),O=[..._.values()].map((F)=>F.toSorted(L)).sort((F,P)=>F[0]&&P[0]?L(F[0],P[0]):0);for(let F of O){let P=F[0]?.identity,w=F.filter((T)=>T.credential.state==="active"),d=w.length?w:F,n0=d.filter((T)=>T.claimed),s=n0.length?n0:d,o0=new Set(F.map((T)=>T.credential.credentialId)),d$=G.find((T)=>!M.has(T)&&$0(T).some((t0)=>o0.has(t0))&&(T.accountIdentity===void 0||T.accountIdentity===P)),r0=s.find((T)=>T.credential.credentialId===d$?.credentialId)??s[0];if(!r0)continue;let h=r0.credential,c=d$??(P===void 0?void 0:G.find((T)=>!M.has(T)&&T.accountIdentity===P));if(c)M.add(c);let r=c?.routeId;if(!r||J.has(r)){let T=`${Y}${h.credentialId}${P===void 0?"":`~${L4(P).slice(0,10)}`}`;r=T;for(let t0=2;R.has(r);t0++)r=`${T}~${t0}`}R.add(r);let I=c?$0(c).filter(D):[],y=[...new Set([...F.map((T)=>T.credential.credentialId),...I])].filter((T)=>T!==h.credentialId).sort((T,t0)=>T.localeCompare(t0)),N0=X.mapAccount?.(h)??{};x.push({previousIndex:c?G.indexOf(c):1/0,row:{routeId:r,credentialId:h.credentialId,credentialType:h.credentialType,...P!==void 0&&{accountIdentity:P},...y.length&&{aliases:y},state:h.state,label:N0.label?.trim()||O4(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...y].some((T)=>j6(H,T,P)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!r0.claimed&&P!==void 0&&{unclaimed:!0}}});let Y0=x.at(-1);if(B&&Y0)Y0.previousIndex=F4(B,Y0.row)}return G.forEach((F,P)=>{if(M.has(F)||!$0(F).some(D))return;if(R.has(F.routeId))return;let[w,...d]=$0(F).filter((o0)=>!W.has(o0));if(w===void 0)return;R.add(F.routeId);let{aliases:n0,...s}=F;x.push({previousIndex:P,row:{...s,credentialId:w,...d.length&&{aliases:d},stale:!0}})}),x.sort((F,P)=>F.previousIndex===P.previousIndex?F.row.credentialId.localeCompare(P.row.credentialId):F.previousIndex-P.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:K,...!K&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:x.map((F)=>F.row),declined:H}}function E6($){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 A$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H$($){return $===void 0||typeof $==="string"}function j4($){let Z=A$($)?S0($.quota):void 0;if(!A$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!H$($.accountIdentity)||!H$($.email)||!H$($.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 R4=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function c9($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!A$(X)||!H$(X.credentialId)||typeof X.reason!=="string"||!R4.has(X.reason))return;Z.push(X)}return Z}function s9($){if(!A$($)||$.version!==1||!H$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!c9($.rejected))throw new N("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Y of $.rows){let J=j4(Y);if(!J)throw new N("invalid-state","Claustrum roster file is not valid");Z.push(J)}let X=[];for(let Y of $.declined){if(!A$(Y)||typeof Y.credentialId!=="string"||!H$(Y.accountIdentity))throw new N("invalid-state","Claustrum roster file is not valid");X.push(Y)}let z=c9($.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 S6($){return s9(JSON.parse(JSON.stringify($)))}var T4=new F0({followSymlinks:!0});async function f($){if(W0)return x6($);let Z=await T4.read([$],([X=$])=>x6(X));return structuredClone(Z)}async function x6($){let Z;try{Z=await UZ($,W0)}catch(z){if(z.code==="ENOENT")return;throw z}let X;try{X=JSON.parse(Z)}catch{throw new N("invalid-state","Claustrum roster file is not valid")}return s9(X)}var a9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},n9={name:"claustrum-roster",ttlMs:30000};async function p0($,Z,X={}){return I0($,{...a9,signal:X.signal},async(z)=>{let Y=await x6($),{next:J,result:G}=await Z(Y,{assertOwned:()=>z.assertOwned()});if(J){await z.assertOwned();try{await B0($,J,{beforeRename:async()=>{await X.beforePublish?.(),X.signal?.throwIfAborted(),await z.assertOwned()}})}catch(B){if(B&&typeof B==="object"&&"published"in B&&B.published===!0)X.onPublished?.();throw B}X.onPublished?.()}return G})}function C6($,Z){return p0($,(X)=>{let z=X?.rows.find((J)=>J.routeId===Z);if(!X||!z)throw new N("route-unavailable","Claustrum route is not in the roster");let Y=R6(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 I6($,Z){return p0($,(X)=>{let z=X?.rows.find((Y)=>Y.routeId===Z);if(!X||!z)throw new N("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:T6(X.declined,$0(z),z.accountIdentity),rows:X.rows.map((Y)=>Y===z?{...Y,enabled:!0}:Y)},result:void 0}})}function x4($){return new N("invalid-order",$)}function A4($,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 b6($,Z,X={}){return p0($,(z)=>{let Y=z?.rows??[],J=A4(Y,Z);if(J)throw x4(J);let G=new Map;for(let K of Y){let W=G.get(K.routeId);if(W)W.push(K);else G.set(K.routeId,[K])}let B=[...Z],H=B.flatMap((K)=>G.get(K)??[]);if(!z||H.every((K,W)=>K===Y[W]))return{result:{ids:B,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:B,outcome:"reordered"}}},{...X.signal&&{signal:X.signal}})}function E4($,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 k6($,Z){let{routeId:X,observation:z,...Y}=Z;return o9($,{routeId:X,observation:z,accountIdentity:Y.accountIdentity,receipt:Y})}async function o9($,Z){if(!$$(Z.observation))return!1;let X=i($,await f($));if(!T0(X,Z).kept)return!1;return t9($,Z)}function f6($,Z){return o9($,Z)}function T0($,Z){let X=$?.rows.find((G)=>G.routeId===Z.routeId),z=!X?"refuse":Z.receipt?E4(X,Z.receipt):X.accountIdentity!==void 0&&X.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!X||z==="refuse")return{roster:$,kept:!1};let Y=N$(X.quota,Z.observation),J=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((G)=>G===X?{...G,...J,quota:Y}:G)},kept:!0}}var MZ=new Map;function E$($){MZ.delete(x$($))}function r9($,Z){let X=x$($);if(Z instanceof N)return Z.kind==="roster-busy";if(Z instanceof e||Z instanceof _$)return x$(Z.details.target)===X;if(Z instanceof G0){let z=x$(Z.path);return[a9.name,n9.name].some((Y)=>{let J=q$(X,Y);return z===J||z.startsWith(`${J}.`)})}return!1}var S4=4;async function u9($){try{let{dev:Z,ino:X,size:z,mtimeMs:Y}=await _4($);return{dev:Z,ino:X,size:z,mtimeMs:Y}}catch{return}}function C4($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function I4($,Z,X){for(let z=0;z<S4;z++){let Y=await u9($),J=await f($),G,B,H;try{({target:G,local:B}=Z(J));let K=JSON.stringify(X(G));H=JSON.stringify(G)!==K||B!==void 0&&JSON.stringify(B)!==K}catch{return"commit"}if(!C4(Y,await u9($)))continue;if(H)return"commit";return e9($)?"commit":"unchanged"}return"commit"}async function S$($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){E$($.path);return}let X=await g({...n9,path:$.path,renew:!0});if(!X){let G=await f($.path);if($.signal?.throwIfAborted(),!G?.view)throw new N("roster-busy","Claustrum account discovery is already in progress");return G}let z=x$($.path),Y=$.listedOver,J;try{let G=await f($.path),B=Y?void 0:MZ.get(z);J=B&&(B.previousView===G?.view||B.inventory.view===G?.view)?B:{inventory:await $.custody.discover($.signal),previousView:G?.view},MZ.delete(z);let{inventory:H}=J;$.onInventory?.(H),$.signal?.throwIfAborted();let K=typeof $.projection==="function"?$.projection():$.projection,W=(D)=>i9(D,H,K),Q=async()=>{return $.signal?.throwIfAborted(),await X.assertOwned(),Z()};if(await I4($.path,(D)=>{if(Y)return{target:D};let V=i($.path,D);return{target:D,...V!==D&&{local:V}}},W)==="unchanged"){if(!await Q())return;return await f($.path)}return await p0($.path,async(D)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await X.assertOwned(),Y&&D?.view!==Y.view&&D?.view!==H.view)return{result:D};let V=W(D);return{...JSON.stringify(D)!==JSON.stringify(V)&&{next:V},result:V}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await X.assertOwned()}})}catch(G){if(G instanceof e&&J&&!Y&&!$.signal?.aborted&&await Z())MZ.set(z,J);throw G}finally{await X.release($.signal)}}var l0=new Map,b4=p("claustrum"),Z3=100;function X3($,Z=p9){let X=_Z($),z=l0.get(X);if(!z)z={path:X,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},l0.set(X,z);return z}function z3($,Z,X){let z=X3($,X);z.listeners.add(Z);let Y;return()=>Y??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():y6($)})()}function k4($){return l9($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function t9($,Z){if(!$$(Z.observation))return Promise.resolve(!1);let X=X3($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),Y=X.pending.get(z)??new Map;for(let[J,G]of k4(Z)){let B=Y.get(J);if(!B||G.at>=B.at){if(G.order=++X.order,G.publication.observation.coverage)G.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(J,G)}}if(Y.size)X.pending.set(z,Y);for(let J of X.listeners)J(Z);return J3(X,Z3),Promise.resolve(!0)}function Y3($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,X)=>Z.order-X.order)}function i($,Z){let X=l0.get(_Z($));if(X)for(let z of Y3(X.pending)){if(z.priorReading)Z=T0(Z,z.priorReading).roster;Z=T0(Z,z.publication).roster}return Z}function e9($){return!!l0.get(_Z($))?.pending.size}function J3($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let X=$.draining?0:($.committedAt??-1/0)+g9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,X),()=>{return $.timer=void 0,G3($)}),!$.draining)$.timer.unref?.()}function $3($){$.timer?.cancel(),$.timer=void 0}function G3($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([X,z])=>[X,new Map(z)]));return $.running=(async()=>{try{if(await p0($.path,(z)=>{let Y=z;for(let G of Y3(Z)){if(G.priorReading)Y=T0(Y,G.priorReading).roster;Y=T0(Y,G.publication).roster}let J=JSON.stringify(Y)!==JSON.stringify(z);return{...J&&{next:Y},result:J}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[z,Y]of Z){let J=$.pending.get(z);for(let[G,B]of Y)if(J?.get(G)===B)J.delete(G);if(!J?.size)$.pending.delete(z)}$.failures=0}catch(X){if(!$.abort.signal.aborted&&$.failures++===0)b4.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()):Z3;J3($,X)}})(),$.running}async function y6($,Z=1000){let X=_Z($),z=l0.get(X);if(!z)return;z.draining=!0,$3(z);let Y,J,G=new Promise((B)=>{J=()=>{if(!z.pending.size||z.abort.signal.aborted)B()},z.wake.add(J),J()});try{if(z.pending.size)G3(z);await Promise.race([G,new Promise((B)=>{Y=setTimeout(B,Math.max(0,Z))})])}finally{if(clearTimeout(Y),J)z.wake.delete(J);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),$3(z),z.pending.clear(),l0.get(X)===z)l0.delete(X)}}}var FZ=1e4;function B3(){return new S}var w6;function K3($,Z){if(!w6)throw Error("ClaustrumConsumer is not initialized");return w6($,Z)}function H3(){return new N("not-active","Claustrum scoped custody is not active")}class h6{#$;#Z=new AbortController;#J;#G;#z;#K;#Y;#X;#W;#Q;#U=!1;#N=new Set;#O;#B;#L;#_;#P=new Map;#j;#T;#H;#R;#x=new WeakMap;static{w6=($,Z)=>{let X=new h6(Z);return X.#H=$,{consumer:X,hooks:X.#m()}}}constructor($){this.#$=$,this.#J=$.logger??p("claustrum"),this.#G=J$(this.#J,this.#Z.signal),this.#T=z3($.rosterPath,(Z)=>{this.#X=T0(this.#X,Z).roster})}#V($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#M($){return this.#N.add($),$.then(()=>this.#N.delete($),()=>this.#N.delete($)),$}async#q(){if(b())return!0;return await this.#$.isCustodyActive?.()??!0}#A($,Z){let X=h0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,Y)=>{let J=()=>{X.signal.removeEventListener("abort",G),X.dispose()},G=()=>{J(),Y(X.signal.reason)};if(X.signal.addEventListener("abort",G,{once:!0}),$.then((B)=>{if(J(),X.signal.aborted)Y(X.signal.reason);else z(B)},(B)=>{J(),Y(B)}),X.signal.aborted)G()})}async#I(){if(this.#V(),this.#z)return this.#z;if(!this.#K){let $={timedOut:!1};this.#K=this.#y($),this.#M(this.#K)}return this.#A(this.#K)}#y($){let Z=this.#$.setTimeoutImpl??setTimeout,X=this.#$.clearTimeoutImpl??clearTimeout,z=(!b()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>m0(this.#$.pluginId))).then((G)=>{if(this.#Z.signal.aborted||$.timedOut){if(G.close(),!$.timedOut)this.#V();throw B3()}if(this.#z=new B$({client:G,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#J,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&G.insula)this.#B=J6(G.insula,this.#$.tokenPath);return this.#z}),Y,J=new Promise((G,B)=>{Y=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#J.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#D()}),B(B3())},this.#D()),Y.unref?.()});return Promise.race([z,J]).finally(()=>{if(Y)X(Y);this.#K=void 0})}#D(){return this.#$.connectTimeoutMs??FZ}snapshot(){return this.#X}grantReach(){if(this.#H)return this.#H.grantReach(this.#X?.view);let $=this.#W;return $&&this.#X?.view===$.view?$.reach:void 0}watchState(){if(this.#H)return Object.freeze({vault:this.#H.watchMode()});return Object.freeze({vault:this.#L?.mode??"polling",...this.#$.insula&&{insula:this.#B?.source.watchMode()??"polling"}})}#E(){this.#L?.close(),this.#L=void 0,this.#_?.(),this.#_=void 0}keptReceiptState(){if(this.#H){let $=this.#R;return $&&this.#H.leaseLive($)?$.custody.keptReceiptState():this.#H.keptReceiptState()}return this.#z?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return E6(this.#X)}refresh(){if(this.#V(),this.#H)return this.#M(this.#l(this.#H));if(this.#Y)return this.#Y;return this.#Y=(async()=>{if(!await this.#q()){if(this.#X=void 0,this.#W=void 0,this.#E(),this.#z)this.#z.close(),this.#M(this.#z.dispose(this.#G));this.#z=void 0,this.#B?.release(),this.#B=void 0;return}let $=await this.#I(),Z,X=await S$({path:this.#$.rosterPath,custody:$,onInventory:(Y)=>{Z=Y},isActive:()=>this.#q(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#V();let z=X?.view!==this.#X?.view;if(this.#X=i(this.#$.rosterPath,X),$.retain(X?.rows??[]),Z&&X?.view!==void 0)this.#W=Z.grantReach?{view:X.view,reach:Z.grantReach}:void 0;if(X&&z)this.#$.onRoster?.(X);return this.#j=(this.#$.now??Date.now)(),X})().finally(()=>{this.#Y=void 0}),this.#M(this.#Y),this.#b(this.#Y),this.#Y}#b($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#U)return;if(this.#V(),this.#U=!0,this.#H){this.#H.start();return}let $=async()=>{try{if(await this.#S())await this.refresh();await this.refreshInsulaQuota(),this.#C()}catch(X){if(!this.#Z.signal.aborted)this.#$.onError?.(X)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Q=void 0,this.#M($())},Z),this.#Q.unref?.()};this.#M($())}async#S(){if(this.#L?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#j===void 0||$-this.#j>=X$)return!0;return!await this.#q()}#C(){let $=this.#z;if(this.#Z.signal.aborted||!$)return;if(this.#L??=$.watchRoster({view:()=>this.#X?.view,onView:()=>this.#M((async()=>{while(this.#Y)await this.#Y.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#B&&!this.#_)this.#_=this.#B.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#q())return;try{if(!b())await j0(this.#$.tokenPath);await this.#I(),await this.#B?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#q())return;try{if(!b())await j0(this.#$.tokenPath);return this.#w($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#q())return;try{if(!b())await j0(this.#$.tokenPath);let X=i(this.#$.rosterPath,await f(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#w(X?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#q())return{miss:"unreachable"};try{if(!b())await j0(this.#$.tokenPath);let z=i(this.#$.rosterPath,await f(this.#$.rosterPath))?.rows.find((G)=>G.routeId===$)?.accountIdentity;if(!z||!this.#B)return{miss:"unreachable"};let Y=this.#B.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),J=Y.reading&&Z.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...J!==void 0&&{reading:J}};return J===void 0?{miss:"unreachable"}:{reading:J}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let X=await this.lookupInsulaQuotaForRoute($);if(X.miss==="cold"||X.miss==="upstream-failed"){if(this.#P.get($)!==X.miss)this.#P.set($,X.miss),this.#J.warn("skipped insula provider poll",{reason:X.miss});return}return this.#P.delete($),X.miss?Z():X.reading}#w($){if(!this.#$.insula||!$)return;let Z=this.#B?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#H)return this.#v(this.#H,$,Z);this.#V(Z);let X=this.#X??await this.#A(this.refresh(),Z);if(!X||!await this.#q())throw this.#z?.close(),this.#z=void 0,this.#E(),this.#B?.release(),this.#B=void 0,new N("not-active","Claustrum scoped custody is not active");let z=i(this.#$.rosterPath,await f(this.#$.rosterPath));this.#V(Z);let Y=X.rows.find((H)=>H.routeId===$),J=z?.rows.find((H)=>H.routeId===$);if(J&&!J.enabled){if(Y)this.#z?.forget(Y.credentialId);throw new N("route-declined","Claustrum route is disabled")}if(!Y||!J||J.state!=="active"||J.credentialId!==Y.credentialId||J.accountIdentity!==Y.accountIdentity||J.credentialType!==Y.credentialType){if(Y)this.#z?.forget(Y.credentialId);throw new N("route-unavailable","Claustrum route is disabled, removed or changed")}let G=await this.#A(this.#I(),Z),B=h0([this.#Z.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:J.credentialId,credentialType:J.credentialType,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity}},B.signal,$)}finally{B.dispose()}}#m(){return{discovery:($)=>{let Z=this.#H;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let X=this.#M($.then((z)=>this.#k(Z,z)));this.#b(X)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#X?.view;if(this.#X=i(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(X){this.#$.onError?.(X)}},reset:()=>{this.#X=void 0},roster:()=>this.#X,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#l($){let Z=await $.refresh();return this.#k($,Z)}#k($,Z){if(this.#V(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#X}#h($){if($&&this.#R!==$)return;this.#R?.release(),this.#R=void 0}async#F($,Z){let X=this.#R;if(X&&$.leaseLive(X))return X;this.#h();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#V();let Y=this.#R;if(Y&&$.leaseLive(Y))return z.release(),Y;return this.#R=z,z}async#v($,Z,X){if(this.#V(X),!this.#X)await this.#A($.refresh(),X);let z=this.#X;if(!await $.readAuthority())throw this.#h(),H3();if(this.#V(X),!z)throw new N("route-unavailable","Claustrum has no roster for this provider yet");let Y=i(this.#$.rosterPath,await f(this.#$.rosterPath));this.#V(X);let J=z.rows.find((K)=>K.routeId===Z),G=Y?.rows.find((K)=>K.routeId===Z);if(G&&!G.enabled){if(J)$.forget(J.credentialId);throw new N("route-declined","Claustrum route is disabled")}if(!J||!G||G.state!=="active"||G.credentialId!==J.credentialId||G.accountIdentity!==J.accountIdentity||G.credentialType!==J.credentialType){if(J)$.forget(J.credentialId);throw new N("route-unavailable","Claustrum route is disabled, removed or changed")}let B={credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},H=h0([this.#Z.signal,...X?[X]:[]]);try{for(let K=0;;K++){let W=await this.#F($,H.signal);try{let Q=await W.custody.authorize(B,H.signal,Z);return this.#x.set(Q,W),Q}catch(Q){if(K>0||H.signal.aborted||$.leaseLive(W)||!(Q instanceof N)||Q.kind!=="closed")throw Q;if(this.#h(W),!await $.readAuthority())throw H3()}}}finally{H.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#X?.rows.find((X)=>X.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#H){if(this.#R&&this.#H.leaseLive(this.#R))this.#R.custody.reportUsage($)}else this.#z?.reportUsage($)}catch{}}usageReportState(){try{return(this.#H?this.#R?.custody:this.#z)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,X){if(this.#V(),this.#H){let z=this.#x.get($);if(!z)throw new N("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,X);return}if(!this.#z)throw new N("no-receipt","Claustrum dispatch receipt has no active owner");await this.#z.reportFailure($,Z,X)}#f($){let Z=this.#H?this.#x.get($)?.custody:this.#z;if(!Z)throw new N("no-receipt","Claustrum dispatch receipt has no active owner");return Z}async reportCondition($,Z){if(this.#Z.signal.aborted)return"skipped";return this.#f($).reportCondition($,Z)}async clearCondition($){if(this.#Z.signal.aborted)return"skipped";return this.#f($).clearCondition($)}async send($,Z,X){let z=X.signal,Y=await this.authorize($,z),J=await Z(Y,z);if(J.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,X.reporterSource??"direct"),J;if(J.status===401&&!z?.aborted){let G;try{G=await this.authorize($,z),z?.throwIfAborted()}catch(B){if(z?.aborted)throw B}if(P6(X.site,Y,G,this.#J))await J.body?.cancel().catch(()=>{}),Y=G,J=await Z(G,z)}if(J.status===401)await this.reportFailure(Y,401,X.reporterSource??"direct").catch((G)=>this.#$.onError?.(G)),Promise.resolve().then(()=>this.refresh()).catch((G)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(G)});return J}async decline($){if(this.#V(),await C6(this.#$.rosterPath,$),this.#X=i(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#H?.publishRoster(this.#X);if(this.#H)this.#H.retainUnion();else this.#z?.retain(this.#X?.rows??[])}async accept($){if(this.#V(),await I6(this.#$.rosterPath,$),this.#X=i(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#H?.publishRoster(this.#X)}async reorder($){this.#V();let Z=await b6(this.#$.rosterPath,$);if(this.#X=i(this.#$.rosterPath,await f(this.#$.rosterPath)),this.#X)this.#H?.publishRoster(this.#X);return Z}async recordQuota($,Z,X){return this.#V(),k6(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:X.credentialId,accountIdentitySource:X.accountIdentitySource,...X.accountIdentity!==void 0&&{accountIdentity:X.accountIdentity},...X.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:X.expectedAccountIdentity}})}async recordAccountQuota($,Z,X){return this.#V(),f6(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new N("closed","Claustrum consumer is closed")),this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);if(this.#Q=void 0,this.#E(),this.#z)this.#z.close(),this.#M(this.#z.dispose(this.#G));this.#R?.release(),this.#R=void 0,this.#H?.detach(),this.#B?.release(),this.#B=void 0,this.#X=void 0,this.#W=void 0,this.#T(),E$(this.#$.rosterPath)}async dispose(){this.close(),this.#O??=Promise.all([G$(this.#N,this.#G),this.#T()]).then(()=>{}),await this.#O}}import{createHash as f4}from"node:crypto";import{channel as Q3}from"node:diagnostics_channel";import{readdir as y4,stat as w4}from"node:fs/promises";import{dirname as h4,join as K$,resolve as W3}from"node:path";var LZ=new Map,m4=/^[a-z0-9][a-z0-9._-]{0,63}$/,v4=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,g4=/^[0-9a-f]{16}$/,U3=3;function v6($,Z=new Set){if($===null)return"null";if(typeof $==="string"||typeof $==="boolean")return JSON.stringify($);if(typeof $==="number")return Number.isFinite($)?JSON.stringify($):void 0;if(typeof $!=="object"||Z.has($))return;let X=new Set(Z).add($),z=[];if(Array.isArray($)){for(let J=0;J<$.length;J++){let G=v6($[J],X);if(G===void 0)return;z.push(G)}return`[${z.join(",")}]`}let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return;for(let J of Object.keys($).sort()){let G=v6($[J],X);if(G===void 0)return;z.push(`${JSON.stringify(J)}:${G}`)}return`{${z.join(",")}}`}function p4($,Z){let X=v6({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??qZ,mapAccount:$.mapAccount?String($.mapAccount):null});if(X===void 0)throw new N("invalid-state","Claustrum hub classifierInput must be plain JSON");return f4("sha256").update(X).digest("hex").slice(0,16)}function D3($,Z){if(typeof $!=="string"||!m4.test($)||v4.test($))throw new N("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function x0($="Claustrum custody lease is closed"){return new N("closed",$)}function m6(){return new N("not-active","Claustrum scoped custody is not active")}function V3(){return new S}function l4($,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 N3($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class M3{#$;#Z;#J;#G=new AbortController;#z=new Map;#K=new WeakMap;#Y=0;#X;#W;#Q;#U;#N;#O=new Set;#B;#L=0;#_;#P;#j;#T=!1;#H=new Set;#R;#x;#V;constructor($){if(!$.family||!("classify"in $.family))throw new N("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=D3($.hostGeneration,"host generation"),X=$.members.map((Y)=>D3(Y,"member"));if(new Set(X).size!==X.length)throw new N("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??p("claustrum"),this.#J=J$(this.#Z,this.#G.signal),this.#x=K$($.stateDir,"rosters",Z),this.#V=p4($,X);let z=K$(this.#x,this.#V);for(let Y of X)this.#z.set(Y,{provider:Y,path:K$(z,`${Y}.json`),closed:!1})}#M($){return this.#H.add($),$.then(()=>this.#H.delete($),()=>this.#H.delete($)),$}#q(){if(this.#G.signal.aborted)throw x0("Claustrum discovery hub is closed")}#A($){let Z=this.#z.get($);if(!Z)throw new N("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#A($).path}member($,Z){this.#q();let X=this.#A($);if(X.hooks)throw new N("wrong-consumer","Claustrum hub member was already built");for(let Q of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(Q in Z)throw new N("wrong-consumer",`Claustrum hub members cannot take ${Q}`);let z={provider:X.provider,start:()=>this.start(),refresh:()=>this.#f(),readAuthority:()=>this.#k(),acquire:(Q)=>this.acquire(Q),leaseLive:(Q)=>this.#E(Q),grantReach:(Q)=>Q!==void 0&&this.#_?.view===Q?this.#_.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#p(),publishRoster:(Q)=>this.#I(X,Q),forget:(Q)=>this.#X?.custody?.forget(Q),detach:()=>{X.closed=!0,X.releaseRoster?.()}},Y={rosterPath:X.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:J,hooks:G}=K3(z,Y);X.hooks=G;let B=W3(X.path),H=LZ.get(B)??new Set,K=(Q)=>{if(X.closed||this.#B!==!0||!this.#X||!this.#D(this.#X)||!G.roster()||this.#u(G,Q))return;if(X.seen=JSON.stringify(S6(Q)),G.install(Q),Q.view!==this.#_?.view)X.pending??={failures:0,wait:0};this.#p()};H.add(K),X.receiveRoster=K,LZ.set(B,H);let W=!0;return X.releaseRoster=()=>{if(!W)return;if(W=!1,H.delete(K),!H.size)LZ.delete(B)},J}#I($,Z){let X=this.#X;if($.closed||!X||!this.#D(X))return;$.seen=JSON.stringify(S6(Z)),$.hooks?.install(Z);for(let z of LZ.get(W3($.path))??[]){if(!this.#D(X))return;if(z!==$.receiveRoster)z(Z)}}#y(){let $={id:++this.#Y,count:0,ended:!1,controller:new AbortController};return this.#X=$,$}#D($){return!$.ended&&this.#X===$&&!this.#G.signal.aborted}#E($){let Z=this.#K.get($);return!!Z&&!Z.released&&!Z.generation.ended}#b($,Z=x0()){if($.ended)return;if($.ended=!0,$.count=0,this.#X===$)this.#X=void 0;if(this.#Q&&this.#K.get(this.#Q)?.generation===$)this.#Q=void 0;if(this.#U?.generation===$)this.#U.watch.close(),this.#U=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#M($.custody.dispose(this.#J))}#S($){if($.ended)return;if($.count--,$.count<=0)this.#b($)}#C($){let Z=this.#W;if(Z?.generation===$&&Z.promise)return Z.promise;let X={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??FZ,Y,J=(!b()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>m0(this.#$.pluginId))).then((H)=>{if(X.timedOut)throw H.close(),V3();if(!this.#D($)||$.count<=0)throw H.close(),x0("Claustrum connection is no longer wanted");return $.custody=new B$({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),G=new Promise((H,K)=>{Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(X.timedOut=!0,!this.#D($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),K(V3())},z),Y.unref?.()});return X.promise=this.#M(Promise.race([J,G]).finally(()=>{if(Y)(this.#$.clearTimeoutImpl??clearTimeout)(Y)})),X.promise.finally(()=>{if(this.#W===X)this.#W=void 0}).catch(()=>{}),this.#W=X,X.promise}acquire($){try{if(this.#q(),$?.throwIfAborted(),this.#B===!1)throw m6()}catch(X){return Promise.reject(X)}let Z=this.#X??this.#y();return Z.count++,this.#w(Z,$,!0)}async#w($,Z,X){let z=$.custody;if(!z){let Y=h0([$.controller.signal,...Z?[Z]:[]]);try{z=await l4(this.#C($),Y.signal)}catch(J){if(!$.ended)throw this.#S($),J;return this.#m(Z,X)}finally{Y.dispose()}}if($.ended)return this.#m(Z,X);if(Z?.aborted)throw this.#S($),Z.reason;return this.#l($,z)}#m($,Z){if($?.throwIfAborted(),this.#q(),this.#B===!1)throw m6();if(!Z)throw x0();let X=this.#X??this.#y();return X.count++,this.#w(X,$,!1)}#l($,Z){let X={generation:$,custody:Z,released:!1},z=()=>{if(X.released||$.ended)throw x0()},Y=Object.freeze({authorize:async(G,B,H)=>{z();let K=h0([$.controller.signal,...B?[B]:[]]);try{return await Z.authorize(G,K.signal,H)}finally{K.dispose()}},reportFailure:async(G,B,H)=>{return z(),Z.reportFailure(G,B,H)},reportCondition:async(G,B)=>{if(X.released||$.ended)return"skipped";return Z.reportCondition(G,B)},clearCondition:async(G)=>{if(X.released||$.ended)return"skipped";return Z.clearCondition(G)},reportUsage:(G)=>{if(!X.released&&!$.ended)Z.reportUsage(G)},usageReportState:()=>{return z(),Z.usageReportState()},forget:(G)=>{z(),Z.forget(G)},keptReceiptState:()=>{return z(),Z.keptReceiptState()}}),J=Object.freeze({custody:Y,generation:$.id,release:()=>{if(X.released)return;X.released=!0,this.#S($)}});return this.#K.set(J,X),J}leaseState(){let $=this.#X;return Object.freeze({generation:$?.id,count:$?.count??0})}async#k(){let $=b()||(await this.#$.isCustodyActive?.()??!0);if(this.#G.signal.aborted)return!1;let Z=this.#B;if(this.#B=$,!$&&Z!==!1)this.#h();return $}#h(){this.#L++;let $=this.#X;if($)this.#b($,m6());this.#Q=void 0,this.#U?.watch.close(),this.#U=void 0,this.#_=void 0,this.#P=void 0;for(let Z of this.#z.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),E$(Z.path)}#F(){return[...this.#z.values()].filter(($)=>$.hooks&&!$.closed)}async#v(){let $=this.#Q,Z=$&&this.#K.get($);if($&&Z&&this.#E($))return Z;this.#Q=void 0;let X=await this.acquire(this.#G.signal),z=this.#Q&&this.#K.get(this.#Q);if(this.#Q&&z&&this.#E(this.#Q))return X.release(),z;this.#Q=X;let Y=this.#K.get(X);if(!Y)throw x0();return Y}#f(){try{this.#q()}catch(z){return Promise.reject(z)}let $=this.#N;if($&&!$.generation?.ended)return $.promise;let Z={},X=this.#M(this.#i(Z).finally(()=>{if(this.#N===Z)this.#N=void 0}));Z.promise=X,this.#N=Z;for(let z of this.#F())z.hooks?.discovery(X);return X}async#i($){if(!await this.#k())return;let Z=await this.#v(),X=Z.generation;if($.generation=X,!this.#D(X))return;let z=await this.#s().then(()=>{return},(Q)=>Q instanceof Error?Q:Error(String(Q)));if(await this.#c(),!this.#D(X))return;let Y=new Map(await Promise.all([...this.#z.values()].map(async(Q)=>[Q,await f(Q.path).then((U)=>U?{file:U}:{},(U)=>U instanceof Error?U:Error(String(U)))])));if(!this.#D(X))return;let J;try{J=await Z.custody.discover(X.controller.signal)}catch(Q){if(!this.#D(X))return;for(let U of this.#z.values())if(U.pending)this.#g(U);throw Q}if(!this.#D(X))return;let G=this.#F(),B=Promise.all(G.map((Q)=>Q.hooks&&!Q.closed?this.#d(Q,Q.hooks,J,z??Y.get(Q),X):void 0));this.#O.add(B);let H;try{H=await B}finally{this.#O.delete(B)}if(!this.#D(X))return;let K=new Map,W=!0;for(let[Q,U]of G.entries()){let D=U.hooks,V=H[Q];if(!D||!V)continue;if("error"in V){let{error:M}=V;if(W=!1,this.#g(U),r9(U.path,M))this.#Z.debug("claustrum hub member commit refused",{member:U.provider});else K.set(U.provider,M);continue}let{roster:_}=V;if(!this.#D(X))return;if(_?.view!==J.view)W=!1,this.#g(U);else U.pending=void 0;if(!_)continue;if(this.#u(D,_)){W=!1,this.#g(U);continue}this.#I(U,_)}if(!this.#D(X))return;if(this.#p(),W)this.#_=Object.freeze({view:J.view,...J.grantReach&&{reach:J.grantReach},refused:Object.freeze([...J.refused??[]]),notMine:J.notMine??0});return this.#P=(this.#$.now??Date.now)(),{errors:K}}async#d($,Z,X,z,Y){let J={...X,credentials:X.credentials.filter((G)=>G.member===$.provider),skipped:X.skipped.filter((G)=>G.member===$.provider)};try{if(!z)throw x0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let G;if(!z.file){let H=Q3("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{G=await this.#o($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await S$({path:$.path,custody:{discover:async()=>J},isActive:()=>this.#D(Y)&&this.#B===!0,signal:Y.controller.signal,projection:()=>({...Z.projection(),...G&&{seed:G}}),listedOver:{view:z.file?.view}})}}catch(G){return{error:G}}}async#c(){if(!this.#O.size)return;let $=Q3("common-auth.claustrum.phases"),Z=(X)=>{if($.hasSubscribers)$.publish({logger:this.#Z,phase:X})};Z("earlier fan-out drain begin");try{while(this.#O.size)await Promise.allSettled([...this.#O])}finally{Z("earlier fan-out drain end")}}async#s(){for(let $ of[h4(this.#x),this.#x,K$(this.#x,this.#V)])await Y$($,{},"roster directory")}async#o($){let Z=`${$.provider}.json`,X=[K$(this.#x,Z)];try{for(let Y of await y4(this.#x))if(Y!==this.#V&&g4.test(Y))X.push(K$(this.#x,Y,Z))}catch{}let z;for(let Y of X)try{let J=(await w4(Y)).mtimeMs,G=await f(Y);if(G&&(!z||J>z.modified))z={modified:J,roster:G}}catch{}return z&&A6(z.roster)}#u($,Z){let X=$.projection().reservedRouteIds;return!!X?.size&&Z.rows.some((z)=>X.has(z.routeId))}#g($){let Z=($.pending?.failures??0)+1,X=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(X$/X)),Y=Z<=U3?1:Math.min(2**(Z-U3),z);$.pending={failures:Z,wait:Y-1}}#p(){let $=this.#X?.custody;if(!$)return;$.retain(this.#F().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#a(){let $=this.#L;for(let Z of this.#F()){let X;try{X=await f(Z.path)}catch(B){Z.hooks?.onError(B);continue}if($!==this.#L||this.#B!==!0)return;let z=Z.hooks;if(!X||!z||Z.closed)continue;let Y=JSON.stringify(X);if(Y===Z.seen)continue;let J=z.roster();if(!J||J.view!==X.view||this.#u(z,X)){Z.pending??={failures:0,wait:0};continue}let G=N3(J);if(Z.seen=Y,this.#I(Z,X),N3(z.roster())!==G)this.#p()}}#n(){let $=!1;for(let X of this.#z.values()){if(!X.pending)continue;if(X.pending.wait<=0)$=!0;else X.pending.wait--}if(this.#U?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#P===void 0||Z-this.#P>=X$}#X0(){let $=this.#Q,Z=$&&this.#K.get($);if(!$||!Z||!this.#E($)||this.#B!==!0)return;let X=Z.generation;if(!this.#D(X)||this.#U?.generation===X)return;let z=Z.custody.watchRoster({view:()=>this.#_?.view,onView:()=>this.#M((async()=>{while(this.#N)await this.#N.promise.catch(()=>{});if(!this.#D(X))return;await this.#$0()})()),onRefused:(Y)=>this.#t(Y),onError:(Y)=>this.#r(Y)});this.#U={generation:X,watch:z}}#r($){if(!this.#G.signal.aborted)this.#$.onError?.($)}#t($){if(this.#G.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#F())Z.hooks?.onError($)}#e($){for(let[Z,X]of $?.errors??[])this.#z.get(Z)?.hooks?.onError(X)}async#$0(){let $;try{$=await this.#f()}catch(Z){this.#t(Z);return}this.#e($)}async#Z0(){try{if(await this.#k()){if(await this.#a(),this.#n())await this.#$0();this.#X0()}}catch(Z){this.#r(Z)}if(this.#G.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#j=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#j=void 0,this.#M(this.#Z0())},$),this.#j.unref?.()}start(){if(this.#T)return;this.#q(),this.#T=!0,this.#M(this.#Z0())}async refresh(){this.#e(await this.#f())}refusals(){let $=this.#_;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#_?.reach}watchState(){let $=this.#U;return $&&this.#D($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#X?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#G.signal.aborted)return;this.#G.abort(x0("Claustrum discovery hub is closed"));for(let Z of this.#z.values())Z.releaseRoster?.();if(this.#j)(this.#$.clearTimeoutImpl??clearTimeout)(this.#j);this.#j=void 0;let $=this.#X;if($)this.#b($);this.#Q=void 0,this.#U?.watch.close(),this.#U=void 0}async dispose(){this.close(),this.#R??=G$(this.#H,this.#J),await this.#R}}var c4=1e4;async function nY($){let{connectTimeoutMs:Z,...X}=$,z=Z??c4,Y=d4.connect(zZ(X)),J=!1,G,B=new Promise((H,K)=>{G=setTimeout(()=>{J=!0,K(new S)},z),G.unref?.()});try{let H=await Promise.race([Y,B]);return Object.assign(H,{insula:$9($)})}catch(H){throw Y.then((K)=>K.close(),()=>{}),H}finally{if(!J&&G)clearTimeout(G)}}var q3=VZ("openai");function _3($){return NZ($)}function d0($){if(!$||$.corrupt===!0)return!1;return _3($.refresh)}class C$ 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 OZ($){if(_3($))throw new C$}var u4=p("quota"),g6="primary",p6="secondary",i4="app_EMoamEEZ73f0CkXaXp7hrann",s4="https://auth.openai.com";async function FJ($){OZ($.refreshToken);let Z=await $.fetchImpl(`${s4}/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:i4}).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 a4="https://chatgpt.com/backend-api/wham/usage";async function LJ($){let Z=$.logger??u4,X=$.accountKey??"unknown",z=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let Y=await $.fetchImpl(a4,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Y.ok){let G=eZ(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:G})}let J=i8(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:F3(Y)}),Y}}import{createHash as n4}from"node:crypto";var o4=globalThis.setTimeout,r4=5;function I$($){let Z=$?.quota?.checkIntervalMinutes??r4;return Math.max(1,Z)*60000}function t4($){return $?.quota?.enabled!==!1}function PZ($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function AJ($,Z,X,z,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>X)return Y;let J=Z===g6?$?.primary:Z===p6?$?.secondary:void 0,G=J?.resetsAt?Date.parse(J.resetsAt):NaN;if(Number.isFinite(G)&&G>X)return G;return X+z}function e4($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function L3($,Z,X){if(!t4(Z))return X+I$(Z);let z=e4(Z),Y=[];for(let J of["primary","secondary"]){let G=$?.[J];if(!G)continue;if(G.remainingPercent>=z[J])continue;let B=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=X)return X+I$(Z);Y.push(B)}if(!Y.length)return X+I$(Z);return Math.min(...Y)+60000}function $7($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function Z7($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function n($){return n4("sha256").update($).digest("hex").slice(0,16)}class A0{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&&!O3(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,l6(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&&!O3(Z.quota))return;let J=this.fallbacks.get($)?.accountId;if(Y&&J&&Y!==J)this.clearRateLimited($);let G=Y??J;if(this.fallbacks.set($,{...Z,accountId:G}),X)this.fallbackTokenFps.set($,n(X));else this.fallbackTokenFps.delete($);if(l6(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=A0.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=Z7(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=$7($);if(!X)return;let z=Z?n(Z):null;if(z&&X.tokenFingerprint&&X.tokenFingerprint!==z)return;let Y={quota:X.quota,refreshAfter:L3(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&&Z$(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=I$(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 Z$(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==n(Z))return!1}return Z$(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<A0.API_CALL_GAP_MS)await new Promise((Y)=>{let J=o4(Y,A0.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:L3(Y,this.storage,J),checkedAt:J},l6(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:A0.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+I$(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(A0.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(A0.isAuthError($))return;this.mainLastApiError=F$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(A0.isAuthError(X))return;let z=n(Z),Y=this.fallbackErrorTokenFps.get($)===z?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,F$({error:X,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set($,z)}}function O3($){return Boolean($.primary||$.secondary)}function l6($){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 u7,randomUUID as i7}from"node:crypto";import{setTimeout as s7}from"node:timers/promises";import{createHash as h7}from"node:crypto";import{existsSync as m7,realpathSync as c3}from"node:fs";import{homedir as u3}from"node:os";import{basename as v7,dirname as g7,join as p7,posix as l7,resolve as r6,win32 as d7}from"node:path";function X7(){return Object.freeze({kind:"boolean"})}function z7({min:$,max:Z}={}){return Object.freeze({kind:"integer",min:$,max:Z})}function Y7({min:$,max:Z}={}){return Object.freeze({kind:"number",min:$,max:Z})}function J7(){return Object.freeze({kind:"string"})}function G7($){return Object.freeze({kind:"oneOf",values:Object.freeze([...$])})}function B7($){return c0({kind:"list",item:$})}function H7($){return c0({kind:"object",fields:{...$}})}function k($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let Z=Object.getPrototypeOf($);return Z===Object.prototype||Z===null}function o($,Z,X={}){switch($.kind){case"boolean":return typeof Z==="boolean";case"integer":case"number":return typeof Z==="number"&&Number.isFinite(Z)&&($.kind!=="integer"||Number.isInteger(Z))&&($.min===void 0||Z>=$.min)&&($.max===void 0||Z<=$.max);case"string":return typeof Z==="string";case"oneOf":return typeof Z==="string"&&$.values.includes(Z);case"list":return Array.isArray(Z)&&Array.from(Z).every((z)=>o($.item,z,{...X,completeObjects:!0}));case"object":return k(Z)&&Object.entries(Z).every(([z,Y])=>Object.hasOwn($.fields,z)?o($.fields[z],Y,X):X.allowUnknownFields===!0)&&(!X.completeObjects||Object.keys($.fields).every((z)=>Object.hasOwn(Z,z)));case"record":return k(Z)&&Object.values(Z).every((z)=>o($.value,z,{...X,completeObjects:!0}))}}function c0($){if($&&typeof $==="object"){for(let Z of Object.values($))c0(Z);Object.freeze($)}return $}function K7($){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");let{overrides:z}=X;if(z!==void 0&&(X.value.kind==="object"||X.value.kind==="record"))throw TypeError(`Object and record settings cannot use overrides: ${Z}`);if(z?.isolatedHosts!==void 0&&(z.host!==!0||z.model===!0||!Array.isArray(z.isolatedHosts)||z.isolatedHosts.length===0||!Array.from(z.isolatedHosts).every((Y)=>typeof Y==="string")))throw TypeError(`isolatedHosts must be a non-empty array of host names and requires host overrides without model overrides: ${Z}`);if(!Object.hasOwn(X,"default")||!o(X.value,X.default,{completeObjects:!0}))throw TypeError(`Invalid default for setting: ${Z}`)}return c0({plugin:$.plugin,settings:Object.fromEntries(Object.entries($.settings).map(([Z,X])=>[Z,structuredClone({...X,project:X.project??"user-only"})]))})}function P3($,Z){if(Z==="default")return!0;if(Z==="opencode"||Z==="pi")return $.host===!0;return $.model===!0}import{join as j7,resolve as i6}from"node:path";import*as C from"node:fs/promises";var Q7={readFile:C.readFile,stat:C.stat,lstat:C.lstat,readlink:C.readlink,realpath:C.realpath,open:C.open,rename:C.rename,link:C.link,unlink:C.unlink,mkdir:C.mkdir,readdir:C.readdir},j={...Q7};import{parseTree as W7}from"jsonc-parser";function U0($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function d6($,Z=()=>{},X=[]){if($.type==="object"){let z={};for(let Y of $.children??[]){let[J,G]=Y.children??[];if(!J||!G)continue;let B=J.value,H=[...X,B];if(Object.hasOwn(z,B))Z(H);U0(z,B,d6(G,Z,H))}return z}if($.type==="array")return($.children??[]).map((z,Y)=>d6(z,Z,[...X,String(Y)]));return $.value}function Q$($){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=W7(X,z,{allowTrailingComma:!0});if(z.length||Y?.type!=="object")return{parseable:!1,text:X,hasBom:Z,tree:Y,errors:z};let J=new Map,G=d6(Y,(B)=>{J.set(JSON.stringify(B),B)});return{parseable:!0,text:X,hasBom:Z,tree:Y,value:G,duplicateKeyPaths:[...J.values()],hasDuplicates:J.size>0}}function j3($,Z,X,z){if(!X||!Object.hasOwn(X.settings,Z))return;let Y=X.settings[Z],{overrides:J}=$,{model:G,host:B}=z,H=J?.isolatedHosts?.includes(B);if(J===void 0||!k(Y))return H?void 0:Y;if(J.model&&G!==void 0&&G!=="default"&&G!=="opencode"&&G!=="pi"&&Object.hasOwn(Y,G))return Y[G];if(J.host&&(B==="opencode"||B==="pi")&&Object.hasOwn(Y,B))return Y[B];return!H&&Object.hasOwn(Y,"default")?Y.default:void 0}function R3($,Z){if($.kind!=="object")return Z.find((z)=>z!==void 0);let X={};for(let[z,Y]of Object.entries($.fields)){let J=Z.map((G)=>k(G)&&Object.hasOwn(G,z)?G[z]:void 0);U0(X,z,R3(Y,J))}return X}function T3($,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(j3(Y,Z,z.project,X));return J.push(j3(Y,Z,z.user,X)),J.push(Y.default),structuredClone(R3(Y.value,J))}function b$($,Z,X,z,Y,J){let G=()=>{return J(X,"invalid-value"),{valid:!1}};if($.kind==="object"){if(!k(Z))return G();let B={},H=!0;for(let[K,W]of Object.entries(Z)){if(!Object.hasOwn($.fields,K)){J([...X,K],Y);continue}let Q=b$($.fields[K],W,[...X,K],z,Y,J);if(Q.valid)U0(B,K,Q.value);else H=!1}if(z){for(let K of Object.keys($.fields))if(!Object.hasOwn(Z,K))J([...X,K],"invalid-value"),H=!1}return H||!z?{valid:!0,value:B}:{valid:!1}}if($.kind==="list"){if(!Array.isArray(Z))return G();let B=[],H=!0;for(let[K,W]of Z.entries()){let Q=b$($.item,W,[...X,String(K)],!0,Y,J);if(Q.valid)B.push(Q.value);else H=!1}return H?{valid:!0,value:B}:{valid:!1}}if($.kind==="record"){if(!k(Z))return G();let B={},H=!0;for(let[K,W]of Object.entries(Z)){let Q=b$($.value,W,[...X,K],!0,Y,J);if(Q.valid)U0(B,K,Q.value);else H=!1}return H?{valid:!0,value:B}:{valid:!1}}return o($,Z)?{valid:!0,value:Z}:G()}function x3($,Z,X){let z=[],Y=new Set,J=(K,W)=>{let Q=JSON.stringify([K,W]);if(Y.has(Q))return;Y.add(Q),z.push({file:{...Z},keyPath:[...K],reason:W})},G={file:{...Z},settings:{},entries:z,schemaVersion:1,newer:!1,hasDuplicates:X.parseable&&X.hasDuplicates,parsed:X};if(!X.parseable)return J([],"unparseable"),G;for(let K of X.duplicateKeyPaths)J(K,"duplicate-key");let B=X.value;if(Object.hasOwn(B,"schema_version")){let K=B.schema_version;if(typeof K==="number"&&Number.isInteger(K)&&K>=1)G.schemaVersion=K,G.newer=K>1;else J(["schema_version"],"invalid-schema-version")}let H=G.newer?"newer-version-key-ignored":"unknown-key";for(let[K,W]of Object.entries(B)){if(K==="schema_version"||K==="$schema")continue;if(!Object.hasOwn($.settings,K)){J([K],H);continue}let Q=$.settings[K];if(!Q)continue;if(Z.kind!=="user"&&Q.project!=="allowed"){J([K],"user-only-in-project");continue}if(k(W)&&Q.overrides!==void 0){let D={};for(let[V,_]of Object.entries(W)){if(!P3(Q.overrides,V)){J([K,V],"override-not-allowed");continue}let M=b$(Q.value,_,[K,V],!1,H,J);if(M.valid)U0(D,V,M.value)}U0(G.settings,K,D);continue}if(k(W)&&Q.value.kind!=="object"&&Q.value.kind!=="record"){J([K],"override-not-allowed");continue}let U=b$(Q.value,W,[K],!1,H,J);if(U.valid)U0(G.settings,K,U.value)}return G}import{dirname as P7}from"node:path";import{isDeepStrictEqual as A3}from"node:util";import{applyEdits as c6,createScanner as D7,findNodeAtLocation as f$,modify as V7}from"jsonc-parser";var U7=Object.freeze(["settings-unparseable","settings-newer-version","settings-invalid-value","settings-busy","settings-unavailable"]);class A extends Error{code;name="SettingsRefusal";constructor($,Z,X){super(Z,X);this.code=$}}var E0={CommaToken:5,LineCommentTrivia:12,BlockCommentTrivia:13,Trivia:15,EOF:17};function Z0(){throw new A("settings-invalid-value","The settings edit does not match its declared value")}function k$($){let Z=Q$($);if(!Z.parseable||Z.hasDuplicates)throw new A("settings-unparseable","Settings must be an object without duplicate keys");return Z}function C3($,Z){let X=$;for(let z of Z)if(X.kind==="object"&&Object.hasOwn(X.fields,z))X=X.fields[z];else if(X.kind==="record")X=X.value;else Z0();return X}function N7($,Z,X,{host:z,model:Y},J){if(J!==void 0)return J==="default"&&!k(X)?[Z]:[Z,J];if($.overrides!==void 0&&k(X)){if($.overrides.model&&Y!==void 0&&Y!=="default"&&Y!=="opencode"&&Y!=="pi"&&Object.hasOwn(X,Y))return[Z,Y];if($.overrides.host&&(z==="opencode"||z==="pi")&&Object.hasOwn(X,z))return[Z,z];return[Z,"default"]}return[Z]}function M7($,Z,X){let z=$,Y=[...Z];for(let J of X){if(z.kind==="record"||z.kind==="list")break;z=C3(z,[J]),Y.push(J)}return{path:Y,descriptor:z}}function q7($,Z){for(let X=1;X<Z.length;X++){let z=$.tree&&f$($.tree,Z.slice(0,X));if(z&&z.type!=="object")Z0()}}function _7($,Z){let X=$.tree&&f$($.tree,[Z]);if(!X)Z0();let z=$.text.slice(X.offset,X.offset+X.length);return k$(c6($.text,[{offset:X.offset,length:X.length,content:`{ "default": ${z} }`}]))}function E3($,Z,X){let z=Z&&f$(Z,X)?.parent,Y=z?.parent;if(z?.type!=="property"||!Y?.children)return $;let J=D7($,!1),G=z.offset+z.length,B=Y.children.indexOf(z),K=Y.children[B+1]?.offset??Y.offset+Y.length-1,W;J.setPosition(G);while(J.getPosition()<K){let M=J.scan();if(M===E0.CommaToken){W={start:J.getTokenOffset(),end:J.getPosition()};break}if(M===E0.EOF)break}if(!W&&B>0){let M=Y.children[B-1];J.setPosition(M.offset+M.length);while(J.getPosition()<z.offset){let R=J.scan();if(R===E0.CommaToken){W={start:J.getTokenOffset(),end:J.getPosition()};break}if(R===E0.EOF)break}}let Q=G;J.setPosition(G);while(J.getPosition()<K){let M=J.scan();if(M===E0.Trivia||M===E0.CommaToken)continue;if(M!==E0.LineCommentTrivia&&M!==E0.BlockCommentTrivia)break;if(Q=J.getPosition(),/[\r\n]/.test(J.getTokenValue()))break}if(W&&W.start>=G&&!/[\r\n]/.test($.slice(G,W.start)))Q=Math.max(Q,W.end);let U=Math.max($.lastIndexOf(`
91
+ `,z.offset-1),$.lastIndexOf("\r",z.offset-1))+1,D=z.offset,V=/^[\t ]*(\r\n|\r|\n)/.exec($.slice(Q));if(/^[\t ]*$/.test($.slice(U,z.offset))&&V)D=U,Q+=V[0].length;let _=[{offset:D,length:Q-D,content:""}];if(W&&(W.start<D||W.start>=Q))_.push({offset:W.start,length:W.end-W.start,content:""});return c6($,_)}function I3($,Z,X,z){for(let B of X){if(!Object.hasOwn($.settings,B.setting))Z0();let H=$.settings[B.setting];if(B.level!==void 0){if(B.path!==void 0)Z0();if(B.level==="default"){if(H.overrides===void 0)Z0()}else if(B.level!=="opencode"&&B.level!=="pi"||!H.overrides?.host)Z0()}if(B.path!==void 0&&H.value.kind!=="object"&&H.value.kind!=="record")Z0();let K=C3(H.value,B.path??[]);if(B.remove!==!0&&!o(K,B.value))Z0()}let Y=k$(Z),J=Y,G=[];for(let B of X){let H=$.settings[B.setting];if(B.level!==void 0&&B.level!=="default"&&!k(J.value[B.setting])){if(B.remove===!0)continue;if(Object.hasOwn(J.value,B.setting))J=_7(J,B.setting);for(let D of G)if(D.path.length===1&&D.path[0]===B.setting)D.path.push("default")}let K=B.path!==void 0?[B.setting]:N7(H,B.setting,J.value[B.setting],z,B.level),W=[...K,...B.path??[]];q7(J,W),G.push(M7(H.value,K,B.path??[]));let Q=J.tree&&f$(J.tree,W),U;if(B.remove===!0){if(!Q)continue;U=E3(J.text,J.tree,W);let D=k$(U),V=D.value[B.setting];if(K.length===2&&k(V)&&Object.keys(V).length===0)U=E3(U,D.tree,[B.setting]),D=k$(U);J=D}else{if(Q&&A3(S3(J.value,W),B.value))continue;U=c6(J.text,V7(J.text,W,B.value,{formattingOptions:{insertSpaces:!0,tabSize:2}})),J=k$(U)}}for(let B of G)if(J.tree&&f$(J.tree,B.path)&&!o(B.descriptor,S3(J.value,B.path),{allowUnknownFields:!0}))Z0();if(A3(Y.value,J.value))return{outcome:"unchanged",text:Y.text,hasBom:Y.hasBom};return{outcome:"updated",text:J.text,hasBom:Y.hasBom}}function S3($,Z){let X=$;for(let z of Z){if(!k(X)||!Object.hasOwn(X,z))return;X=X[z]}return X}function jZ($,Z,X){if($ instanceof e||b3($,Z,X))throw new A("settings-busy",`Settings lock is busy: ${Z}`,{cause:$});if($ instanceof G0&&($.stage==="safe-parent"||$.stage==="directory"))throw new A("settings-unavailable",`Settings lock folder is unavailable: ${Z}`,{cause:$});throw $}import{randomUUID as F7}from"node:crypto";var L7,O7=new Set(["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS"]);async function k3($){let{target:Z,text:X,hasBom:z,existingMode:Y,lock:J,logger:G}=$,B=$.platform??process.platform,H=`${Z}.${F7()}.tmp`,K=!1,W=!1;try{let Q=await j.open(H,"wx",420);K=!0;try{if(await Q.writeFile(`${z?"\uFEFF":""}${X}`,"utf8"),B!=="win32"&&Y!==void 0)await Q.chmod(Y&511);await Q.sync()}finally{await Q.close()}if(await L7?.("staged",{target:Z,temp:H}),await J.assertOwned(),Y!==void 0){try{await j.rename(H,Z)}catch(U){if(B==="win32"&&["EPERM","EACCES","EBUSY"].includes(U.code??""))throw new A("settings-busy",`Settings file is busy: ${Z}`,{cause:U});throw U}W=!0}else{try{await j.link(H,Z)}catch(U){let D=U.code??"";if(D==="EEXIST")throw new A("settings-busy",`Settings file appeared before publication: ${Z}`,{cause:U});if(O7.has(D))throw new A("settings-unavailable",`Settings file cannot be created on this filesystem: ${Z}`,{cause:U});throw U}W=!0;try{await j.unlink(H)}catch(U){G?.warn("Settings temp cleanup failed after publication",{target:Z,temp:H,error:U})}}return{outcome:"updated"}}finally{if(K&&!W)await j.unlink(H).catch(()=>{})}}var u6=Object.freeze({name:"settings-write",ttlMs:1e4,timeoutMs:2000,renew:!0});function RZ($,Z){throw new A("settings-unavailable",`Settings file is unavailable: ${$}`,{cause:Z})}async function f3($){try{return await oZ($,j)}catch(Z){RZ($,Z)}}async function y3($,Z,X,z){if(Z.separateInstall)throw new A("settings-unavailable","Settings are unavailable for a separate install");let Y=P7(Z.file);try{if(!Z.createMissing)await j.stat(Y);else if(process.platform==="win32")await g0(Y);else await j.mkdir(Y,{recursive:!0,mode:448})}catch(B){RZ(Z.file,B)}let J=await f3(Z.file),G;try{return await I0(J,{...u6,timeoutMs:Z.lockTimeoutMs??u6.timeoutMs},async(B)=>{try{if(await f3(Z.file)!==J)throw new A("settings-busy",`Settings target changed while locking: ${Z.file}`);let H,K,W=!1;try{H=await j.readFile(J,"utf8")}catch(_){if(_.code!=="ENOENT"||!Z.createMissing)RZ(J,_);W=!0,H=""}if(!W)try{K=(await j.stat(J)).mode}catch(_){RZ(J,_)}let Q=Q$(H);if(!Q.parseable||Q.hasDuplicates)throw new A("settings-unparseable","Settings must be an object without duplicate keys");let U=Q.value.schema_version;if(Number.isInteger(U)&&U>1)throw new A("settings-newer-version","Settings were written by a newer version");if(typeof X==="function"){let _=X(c0(W?{status:"missing"}:{status:"ready",document:structuredClone(Q.value)}));if(_!==null&&(typeof _==="object"||typeof _==="function")&&"then"in _&&typeof _.then==="function")throw new A("settings-invalid-value","Settings update plans must be synchronous");X=_}if(!Q.tree)H=`${Q.hasBom?"\uFEFF":""}// ${$.plugin} settings
92
92
  {
93
93
  "schema_version": 1
94
94
  }
95
- `;let D=I3($,H,X,z),V=D.outcome==="unchanged"?{outcome:"unchanged"}:await k3({target:J,text:D.text,hasBom:D.hasBom,existingMode:K,lock:B,logger:Z.log});return G={outcome:"fulfilled",result:V},V}catch(H){throw G={outcome:"rejected",error:H},H}})}catch(B){if(!G)PZ(B,J,u6.name);if(G.outcome==="fulfilled"||B!==G.error)try{Z.log.warn("Settings lock release failed",{target:J,error:B})}catch{}if(G.outcome==="rejected")throw G.error;return G.result}}var w3=Symbol.for("cortexkit.common-auth.settings.reported.v1");function R7(){let $=Reflect.get(globalThis,w3);if(!$)$=new Set,Reflect.set(globalThis,w3,$);return $}function T7($,Z){Z={createMissing:!1,lockTimeoutMs:2000,...Z};let X=i6(Z.file),z={followSymlinks:!0,stat:(L)=>j.stat(L),lstat:(L)=>j.lstat(L)},Y=new _0(z),J=new _0(z),G,B=new Map,H=new Map,K=new Map,W=0,Q=new Map,U=(L)=>i6(j7(L,".cortexkit",`${$.plugin}.jsonc`)),D=process.platform==="win32",V=new Map,_={missing:Symbol("missing"),unreadable:Symbol("unreadable")};async function q(L,O){let F=++W,P=L.kind==="user"?Y:J,w=!1,d=(I,y)=>{if(!D){w=!0;return}w=V.get(I)!==y,V.set(I,y)},s0=async([I])=>{let y;try{y=await j.readFile(I,"utf8")}catch(Y0){let T=Y0.code==="ENOENT"?"missing":"unreadable";return d(I,_[T]),{status:T}}d(I,y);let N0;if(O){let Y0;try{Y0=O(y)}catch{return{status:"unreadable"}}if(!k(Y0))return{status:"unparseable"};N0={parseable:!0,text:y,hasBom:!1,tree:void 0,value:Y0,duplicateKeyPaths:[],hasDuplicates:!1}}else N0=H$(y);return N0.parseable?{status:"snapshot",snapshot:x3($,L,N0)}:{status:"unparseable"}},i=process.platform==="win32"?await s0([L.path]):await P.read([L.path],s0),a0=JSON.stringify([L.kind,L.path]);if(F<=(Q.get(a0)??0))return;Q.set(a0,F);let l$=L.kind==="user"?G:B.get(L.path),n0=i.status==="snapshot"?i.snapshot:i.status==="missing"?void 0:l$?.snapshot,h=[...n0?.entries??[]];if(i.status==="unparseable"||i.status==="unreadable")h.unshift({file:{...L},keyPath:[],reason:i.status});let c={status:i.status,snapshot:n0,entries:h};if(L.kind==="user")G=c;else{if(w)B.delete(L.path);if(!B.has(L.path)&&B.size>=64){let I=B.keys().next().value;if(I!==void 0){B.delete(I),V.delete(I);for(let[y,N0]of H)if(N0===I)H.delete(y)}}B.set(L.path,c)}let r=R7();for(let I of h){let y=JSON.stringify([I.file.path,I.keyPath,I.reason]);if(r.has(y))continue;r.add(y),Z.log.warn(`Settings ${I.reason}: ${I.file.path} (${I.keyPath.join(".")||"<root>"})`,structuredClone(I))}}async function R(L){let O=U(L),F=++W;if(await q({kind:"project",path:O}),F<=(K.get(O)??0))return;let P=O;if(B.get(O)?.status==="missing"){let w=Z.legacyProject?.(L);if(w)P=i6(w.path),await q({kind:"legacy-project",path:P},(d)=>w.read(d))}if(F<=(K.get(O)??0))return;K.set(O,F),H.set(O,P)}let x={async read({project:L}={}){if(Z.separateInstall)return;await Promise.all([q({kind:"user",path:X}),...L===void 0?[]:[R(L)]])},async get(L,O){if(!Object.hasOwn($.settings,L))throw TypeError(`Undeclared setting: ${L}`);return await x.read({project:O.project}),T3($,L,O,{user:G?.snapshot,project:O.project===void 0?void 0:B.get(H.get(U(O.project))??"")?.snapshot})},report(){return structuredClone([...G?.entries??[],...Array.from(new Set(H.values())).flatMap((L)=>B.get(L)?.entries??[])])},update(L,O){return y3($,{...Z,file:X},L,O)},watch(L){if(Z.separateInstall)return()=>{};return h3(X,L,{fs:{stat:(O)=>j.stat(O),readFile:(O)=>j.readFile(O,"utf8")}})}};return x}import{randomUUID as E7}from"node:crypto";import{basename as S7,dirname as f$,join as C7,resolve as I7}from"node:path";import{isDeepStrictEqual as m3}from"node:util";var s6=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function x7($,Z,X){let z=(G)=>{try{let B=X.onLockEvent?.({type:G,name:$.name,path:$.path});if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}},Y={...Z,...A7($)},J=performance.now();for(;;){let G=await g({name:$.name,path:$.path,ttlMs:Y.ttlMs,renew:Y.renew,onContended:()=>z("contended"),...X.onRenewalTimer?{onRenewalTimer:(K)=>X.onRenewalTimer?.({name:$.name,path:$.path},K)}:{},...Y.renewIntervalMs!==void 0?{renewIntervalMs:Y.renewIntervalMs}:{},...X.onLockStep?{onStep:(K)=>X.onLockStep?.({name:$.name,path:$.path},K)}:{}});if(G){z("acquired");let K={name:$.name,path:$.path,assertOwned:()=>G.assertOwned(),release:async()=>{await G.release(),z("released")}};try{await K.assertOwned()}catch(W){throw await K.release(),W}return K}let B=Y.timeoutMs-(performance.now()-J);if(B<=0)throw new e({target:$.path,name:$.name,timeoutMs:Y.timeoutMs});let H=Math.floor(Math.random()*(Y.retryMs+1));await new Promise((K)=>setTimeout(K,Math.min(Y.retryMs+H,B)))}}function A7($){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 a6{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await x7($,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 n6;function X0($){return{outcome:$,unmapped:[],differing:[],noteFailures:[],postPublishFailures:[]}}function TZ($,Z){return $!==null&&typeof $==="object"&&"code"in $&&$.code===Z}async function RZ($){try{return await j.lstat($),!0}catch(Z){if(TZ(Z,"ENOENT"))return!1;throw Z}}function y$($,Z,X,z){try{$.log[Z](X,z)}catch{}}function v3($,Z,X){let z=$,Y=new Set;while(z!==null&&typeof z==="object"&&!Y.has(z)){if(Y.add(z),z instanceof e||z instanceof M$||z instanceof G0)break;if(!("cause"in z))break;z=z.cause}try{PZ(z,Z,X)}catch(J){return{...X0(J instanceof A&&J.code==="settings-busy"?"busy":"failed"),cause:$}}}function b7($,Z,X,z){z.unmapped=[...X.unmapped];let Y=new Map;for(let G of X.entries){let B=Z[G.source];if(!Number.isInteger(G.source)||!B?.present)throw TypeError(`Move entry has no present source: ${G.source}`);let H=Object.hasOwn($.definition.settings,G.setting)?$.definition.settings[G.setting]:void 0,K=!H?"unknown-setting":!o(H.value,G.value)?"invalid-value":void 0;if(K){z.unmapped.push({source:G.source,key:G.setting,reason:K});continue}let W=Y.get(G.setting)??[];W.push({...G,host:B.host}),Y.set(G.setting,W)}let J={schema_version:1};for(let[G,B]of Object.entries($.definition.settings)){let H=Y.get(G)?.sort((U,D)=>U.source-D.source),K=H?.[0];if(!H||!K)continue;let W=new Map;if(B.overrides?.host)for(let U of["opencode","pi"]){let D=H.find((V)=>V.host===U);if(D&&!m3(D.value,K.value))W.set(U,D.value)}Object.defineProperty(J,G,{value:W.size?{default:K.value,...Object.fromEntries(W)}:K.value,enumerable:!0});let Q=H.map((U)=>({source:U.source,host:U.host,value:U.value}));if(Q.some(({host:U,value:D})=>!m3(W.has(U)?W.get(U):K.value,D)))z.differing.push({setting:G,values:Q}),y$($,"info",`Differing legacy settings: ${G}`,{values:Q})}return J}async function k7($){let Z=`${S7($)}.move-`,X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/i;for(let z of await j.readdir(f$($)))if(z.startsWith(Z)&&X.test(z.slice(Z.length)))await j.unlink(C7(f$($),z))}async function f7($,Z,X){for(let z of Z){if(!z.present)continue;let Y=`${z.path}.MOVED_READPLEASE`;try{let J;try{J=await j.open(Y,"wx")}catch(G){if(TZ(G,"EEXIST"))continue;throw G}try{await J.writeFile(`Settings moved to ${$.target}.
95
+ `;let D=I3($,H,X,z),V=D.outcome==="unchanged"?{outcome:"unchanged"}:await k3({target:J,text:D.text,hasBom:D.hasBom,existingMode:K,lock:B,logger:Z.log});return G={outcome:"fulfilled",result:V},V}catch(H){throw G={outcome:"rejected",error:H},H}})}catch(B){if(!G)jZ(B,J,u6.name);if(G.outcome==="fulfilled"||B!==G.error)try{Z.log.warn("Settings lock release failed",{target:J,error:B})}catch{}if(G.outcome==="rejected")throw G.error;return G.result}}var w3=Symbol.for("cortexkit.common-auth.settings.reported.v1");function R7(){let $=Reflect.get(globalThis,w3);if(!$)$=new Set,Reflect.set(globalThis,w3,$);return $}function T7($,Z){Z={createMissing:!1,lockTimeoutMs:2000,...Z};let X=i6(Z.file),z={followSymlinks:!0,stat:(L)=>j.stat(L),lstat:(L)=>j.lstat(L)},Y=new F0(z),J=new F0(z),G,B=new Map,H=new Map,K=new Map,W=0,Q=new Map,U=(L)=>i6(j7(L,".cortexkit",`${$.plugin}.jsonc`)),D=process.platform==="win32",V=new Map,_={missing:Symbol("missing"),unreadable:Symbol("unreadable")};async function M(L,O){let F=++W,P=L.kind==="user"?Y:J,w=!1,d=(I,y)=>{if(!D){w=!0;return}w=V.get(I)!==y,V.set(I,y)},n0=async([I])=>{let y;try{y=await j.readFile(I,"utf8")}catch(Y0){let T=Y0.code==="ENOENT"?"missing":"unreadable";return d(I,_[T]),{status:T}}d(I,y);let N0;if(O){let Y0;try{Y0=O(y)}catch{return{status:"unreadable"}}if(!k(Y0))return{status:"unparseable"};N0={parseable:!0,text:y,hasBom:!1,tree:void 0,value:Y0,duplicateKeyPaths:[],hasDuplicates:!1}}else N0=Q$(y);return N0.parseable?{status:"snapshot",snapshot:x3($,L,N0)}:{status:"unparseable"}},s=process.platform==="win32"?await n0([L.path]):await P.read([L.path],n0),o0=JSON.stringify([L.kind,L.path]);if(F<=(Q.get(o0)??0))return;Q.set(o0,F);let d$=L.kind==="user"?G:B.get(L.path),r0=s.status==="snapshot"?s.snapshot:s.status==="missing"?void 0:d$?.snapshot,h=[...r0?.entries??[]];if(s.status==="unparseable"||s.status==="unreadable")h.unshift({file:{...L},keyPath:[],reason:s.status});let c={status:s.status,snapshot:r0,entries:h};if(L.kind==="user")G=c;else{if(w)B.delete(L.path);if(!B.has(L.path)&&B.size>=64){let I=B.keys().next().value;if(I!==void 0){B.delete(I),V.delete(I);for(let[y,N0]of H)if(N0===I)H.delete(y)}}B.set(L.path,c)}let r=R7();for(let I of h){let y=JSON.stringify([I.file.path,I.keyPath,I.reason]);if(r.has(y))continue;r.add(y),Z.log.warn(`Settings ${I.reason}: ${I.file.path} (${I.keyPath.join(".")||"<root>"})`,structuredClone(I))}}async function R(L){let O=U(L),F=++W;if(await M({kind:"project",path:O}),F<=(K.get(O)??0))return;let P=O;if(B.get(O)?.status==="missing"){let w=Z.legacyProject?.(L);if(w)P=i6(w.path),await M({kind:"legacy-project",path:P},(d)=>w.read(d))}if(F<=(K.get(O)??0))return;K.set(O,F),H.set(O,P)}let x={async read({project:L}={}){if(Z.separateInstall)return;await Promise.all([M({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}),T3($,L,O,{user:G?.snapshot,project:O.project===void 0?void 0:B.get(H.get(U(O.project))??"")?.snapshot})},report(){return structuredClone([...G?.entries??[],...Array.from(new Set(H.values())).flatMap((L)=>B.get(L)?.entries??[])])},update(L,O){return y3($,{...Z,file:X},L,O)},watch(L){if(Z.separateInstall)return()=>{};return h3(X,L,{fs:{stat:(O)=>j.stat(O),readFile:(O)=>j.readFile(O,"utf8")}})}};return x}import{randomUUID as E7}from"node:crypto";import{basename as S7,dirname as y$,join as C7,resolve as I7}from"node:path";import{isDeepStrictEqual as m3}from"node:util";var s6=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function x7($,Z,X){let z=(G)=>{try{let B=X.onLockEvent?.({type:G,name:$.name,path:$.path});if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}},Y={...Z,...A7($)},J=performance.now();for(;;){let G=await g({name:$.name,path:$.path,ttlMs:Y.ttlMs,renew:Y.renew,onContended:()=>z("contended"),...X.onRenewalTimer?{onRenewalTimer:(K)=>X.onRenewalTimer?.({name:$.name,path:$.path},K)}:{},...Y.renewIntervalMs!==void 0?{renewIntervalMs:Y.renewIntervalMs}:{},...X.onLockStep?{onStep:(K)=>X.onLockStep?.({name:$.name,path:$.path},K)}:{}});if(G){z("acquired");let K={name:$.name,path:$.path,assertOwned:()=>G.assertOwned(),release:async()=>{await G.release(),z("released")}};try{await K.assertOwned()}catch(W){throw await K.release(),W}return K}let B=Y.timeoutMs-(performance.now()-J);if(B<=0)throw new e({target:$.path,name:$.name,timeoutMs:Y.timeoutMs});let H=Math.floor(Math.random()*(Y.retryMs+1));await new Promise((K)=>setTimeout(K,Math.min(Y.retryMs+H,B)))}}function A7($){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 a6{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await x7($,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 n6;function X0($){return{outcome:$,unmapped:[],differing:[],noteFailures:[],postPublishFailures:[]}}function xZ($,Z){return $!==null&&typeof $==="object"&&"code"in $&&$.code===Z}async function TZ($){try{return await j.lstat($),!0}catch(Z){if(xZ(Z,"ENOENT"))return!1;throw Z}}function w$($,Z,X,z){try{$.log[Z](X,z)}catch{}}function v3($,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 _$||z instanceof G0)break;if(!("cause"in z))break;z=z.cause}try{jZ(z,Z,X)}catch(J){return{...X0(J instanceof A&&J.code==="settings-busy"?"busy":"failed"),cause:$}}}function b7($,Z,X,z){z.unmapped=[...X.unmapped];let Y=new Map;for(let G of X.entries){let B=Z[G.source];if(!Number.isInteger(G.source)||!B?.present)throw TypeError(`Move entry has no present source: ${G.source}`);let H=Object.hasOwn($.definition.settings,G.setting)?$.definition.settings[G.setting]:void 0,K=!H?"unknown-setting":!o(H.value,G.value)?"invalid-value":void 0;if(K){z.unmapped.push({source:G.source,key:G.setting,reason:K});continue}let W=Y.get(G.setting)??[];W.push({...G,host:B.host}),Y.set(G.setting,W)}let J={schema_version:1};for(let[G,B]of Object.entries($.definition.settings)){let H=Y.get(G)?.sort((U,D)=>U.source-D.source),K=H?.[0];if(!H||!K)continue;let W=new Map;if(B.overrides?.host)for(let U of["opencode","pi"]){let D=H.find((V)=>V.host===U);if(D&&!m3(D.value,K.value))W.set(U,D.value)}Object.defineProperty(J,G,{value:W.size?{default:K.value,...Object.fromEntries(W)}:K.value,enumerable:!0});let Q=H.map((U)=>({source:U.source,host:U.host,value:U.value}));if(Q.some(({host:U,value:D})=>!m3(W.has(U)?W.get(U):K.value,D)))z.differing.push({setting:G,values:Q}),w$($,"info",`Differing legacy settings: ${G}`,{values:Q})}return J}async function k7($){let Z=`${S7($)}.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(y$($)))if(z.startsWith(Z)&&X.test(z.slice(Z.length)))await j.unlink(C7(y$($),z))}async function f7($,Z,X){for(let z of Z){if(!z.present)continue;let Y=`${z.path}.MOVED_READPLEASE`;try{let J;try{J=await j.open(Y,"wx")}catch(G){if(xZ(G,"EEXIST"))continue;throw G}try{await J.writeFile(`Settings moved to ${$.target}.
96
96
  A rollback loses changes made after the move.
97
- `,"utf8")}finally{await J.close()}}catch(J){X.noteFailures.push({path:Y,error:J}),y$($,"warn","Could not write settings move note",{path:Y,error:J})}}}async function y7($,Z,X,z,Y,J){let{target:G}=$,B=`${G}.move-${E7()}.tmp`,H=!1;try{let K=await j.open(B,"wx",420);H=!0;try{let W=[`// Settings moved on ${new Date().toISOString().slice(0,10)} (UTC) from:`,...$.sources.map((Q)=>`// ${JSON.stringify(Q.path)}`)].join(`
97
+ `,"utf8")}finally{await J.close()}}catch(J){X.noteFailures.push({path:Y,error:J}),w$($,"warn","Could not write settings move note",{path:Y,error:J})}}}async function y7($,Z,X,z,Y,J){let{target:G}=$,B=`${G}.move-${E7()}.tmp`,H=!1;try{let K=await j.open(B,"wx",420);H=!0;try{let W=[`// Settings moved on ${new Date().toISOString().slice(0,10)} (UTC) from:`,...$.sources.map((Q)=>`// ${JSON.stringify(Q.path)}`)].join(`
98
98
  `);await K.writeFile(`${W}
99
99
  ${JSON.stringify(X,null,2)}
100
- `,"utf8"),await K.sync()}finally{await K.close()}await n6?.("staged",{target:G,temp:B}),await n6?.("before-publish",{target:G,temp:B}),await z.assertOwned(),await Y.assertAll();try{await j.link(B,G)}catch(W){if(!TZ(W,"EEXIST"))throw W;return J.outcome="aborted-target-appeared",J}J.outcome="moved";try{await j.unlink(B),H=!1}catch(W){J.postPublishFailures.push({step:"temp-unlink",error:W}),y$($,"warn","Settings move temp cleanup failed",{temp:B,error:W})}if(process.platform!=="win32")try{let W=await j.open(f$(G),"r");try{await W.sync()}finally{await W.close()}}catch(W){J.postPublishFailures.push({step:"directory-sync",error:W}),y$($,"warn","Settings move directory sync failed",{target:G,error:W})}return await f7($,Z,J),J}finally{if(H&&J.outcome!=="moved")await j.unlink(B).catch(()=>{})}}async function w7($){try{if($.separateInstall)return X0("separate-install");if(await RZ($.target))return X0("done-already");if(!await $.fence())return X0("fence-closed");let Z=f$($.target);if(process.platform==="win32")await g0(Z);else await j.mkdir(Z,{recursive:!0,mode:448});let X;try{return await I0($.target,{name:"settings-move",...s6},async(z)=>{let Y=new a6(s6,{});try{let J=new Set,G=new Map;for(let B of $.sources)for(let H of B.locks){let K=I7(H.path),W=G.get(K)??new Set;if(W.has(H.name))continue;W.add(H.name),G.set(K,W);let Q=f$(q$(H.path,H.name));if(!await RZ(Q)){J.add(Q);continue}try{await Y.acquire(H)}catch(U){return X=v3(U,H.path,H.name),X}}if(await RZ($.target))X=X0("done-already");else if(!await $.fence())X=X0("fence-closed");else{await k7($.target),await n6?.("locked",{target:$.target});let B=[];for(let Q of $.sources){let U;try{U=await j.readFile(Q.path,"utf8")}catch(D){if(!TZ(D,"ENOENT"))throw D;B.push({host:Q.host,path:Q.path,present:!1});continue}B.push({host:Q.host,path:Q.path,present:!0,value:Q.read(U)})}let H=await $.map(B);for(let Q of J)if(await RZ(Q))return X=X0("busy"),X;let K=X0("failed"),W=b7($,B,H,K);X=await y7($,B,W,z,Y,K)}}catch(J){X={...X0("failed"),cause:J}}finally{await Y.releaseAll()}return X})}catch(z){if(!X)return v3(z,$.target,"settings-move");if(X.outcome==="moved")X.postPublishFailures.push({step:"lock-release",error:z});return y$($,"warn","Settings move lock release failed",{error:z}),X}}catch(Z){return{...X0("failed"),cause:Z}}}import{posix as g3,win32 as p3}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 l3({env:$,platform:Z,homedir:X}){let z=Z==="win32"?p3:g3,Y=(G)=>G!==void 0&&K$(G,Z),J;if(Y($.XDG_CONFIG_HOME))J=$.XDG_CONFIG_HOME;else if(Z==="win32"&&Y($.APPDATA))J=$.APPDATA;else{let G=Z==="win32"?$.USERPROFILE:$.HOME;if(!Y(G)){if(!Y(X))throw new A("settings-unavailable","No absolute home or config directory is available");G=X}J=Z==="win32"?z.join(z.join(G,"AppData"),"Roaming"):z.join(G,".config")}return z.join(J,"cortexkit")}function o6({plugin:$,override:Z,...X}){if(Z&&K$(Z,X.platform))return Z;return(X.platform==="win32"?p3:g3).join(l3(X),`${$}.jsonc`)}function Q$($){let Z=r6($),X=[];for(;;)try{return p7(c3.native(Z),...X)}catch{let z=g7(Z);if(z===Z)return r6($);X.unshift(v7(Z)),Z=z}}var d3=new Map;function t6($){let Z=d3.get($);if(Z===void 0)Z=Q$($),d3.set($,Z);return Z}function c7($={}){let Z=$.env??process.env,X=$.platform??process.platform,z=($.homedir??u3)(),Y=X==="win32"?d7:l7,J=Z.XDG_CONFIG_HOME,G=Y.join(J&&K$(J,X)?J:Y.join(z,".config"),"opencode"),B=Y.join(z,".config","opencode"),H=(D)=>{try{return c3.native(D)}catch{return r6(D)}},K=H(G),W=Y.join(Z.XDG_STATE_HOME||Y.join(z,".local","state"),"cortexkit","openai-auth",K===H(B)?"opencode":`opencode-${h7("sha256").update(K).digest("hex").slice(0,16)}`),Q=m7(Y.join(W,"layout.json"))?W:G,U=Y.join(z,".pi","agent");return[{host:"opencode",configPath:Y.join(G,xZ),statePath:Y.join(Q,AZ)},{host:"pi",configPath:Y.join(U,xZ),statePath:Y.join(U,AZ)}]}function JB($){let Z=$.env??process.env,X=$.platform??process.platform,z=$.homedir??u3,Y=c7({env:Z,platform:X,homedir:z}),J=Y[$.host==="opencode"?0:1],G=Q$($.paths.configPath),B=G!==Q$(J.configPath),H=$.host==="opencode"?"OPENCODE_OPENAI_AUTH_SETTINGS_FILE":"PI_OPENAI_AUTH_SETTINGS_FILE",K=Z[H],W=K!==void 0&&K$(K,X)?K:void 0;if(W!==void 0){let D=Q$(W);if([$.paths,...Y].some((_)=>Q$(_.configPath)===D||Q$(_.statePath)===D))W=void 0,($.logger??console).warn(`openai-auth ignored ${H}: the settings file must not be an account config or state file.`)}let Q=W!==void 0,U=!Q&&B;return{host:$.host,configIdentity:G,target:W??o6({plugin:"openai-auth",env:Z,platform:X,homedir:z()}),optIn:Q,separate:U,sources:U?[]:Q?B?[{host:$.host,...$.paths}]:[]:Y.map((D)=>D.host===$.host?{host:$.host,...$.paths}:D)}}var i3=Symbol.for("@cortexkit/openai-auth/settings-decisions"),s3=globalThis,EZ=s3[i3]??new Map;s3[i3]=EZ;function a3($){return EZ.get(t6($))}function HB($,Z){let X=t6($),z=EZ.get(X);if(z!==void 0)return z;return EZ.set(X,Z),Z}import{readFile as G5}from"node:fs/promises";var u0=p("refresh"),v$=p("accounts"),a7=1e4,n7=15000,e6=50;function D0($){return $.type==="oauth"&&$.corrupt!==!0}function o7($){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 r7="floors-v1";function PB($){return $.costZeroing?.enabled!==!1}class CZ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var t7=[401,403,429],n3={primary:0,secondary:0},e7=!1,Z8={primary:5,secondary:10};function M($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var $5=new Set(["__proto__","constructor","prototype"]);function Z5($){return $.length>0&&!$5.has($)}function X5($){return $ instanceof CZ||M($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function SZ($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():i7(),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 o3($){if(!M($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let X=Number($.nextRetryAt),z=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(X)?X:void 0,retryCount:Number.isFinite(z)?z:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function z5($){if(!M($))return;let Z={};for(let Y of["primary","secondary"]){let J=$[Y];if(!M(J))continue;let G=Number(J.usedPercent),B=Number(J.remainingPercent),H=Number(J.checkedAt);if(!Number.isFinite(G)||!Number.isFinite(B)||!Number.isFinite(H))continue;let K=typeof J.windowMinutes==="number"?J.windowMinutes:Number.NaN;Z[Y]={usedPercent:G,remainingPercent:B,checkedAt:H,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...Number.isFinite(K)&&K>0?{windowMinutes:K}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let J=typeof $[Y]==="number"?$[Y]:Number.NaN;if(Number.isFinite(J)&&J>=0)Z[Y]=J}let X=$.spendControl;if(M(X)){let Y=Number(X.limit),J=Number(X.used),G=Number(X.remaining),B=Number(X.usedPercent),H=Number(X.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof X.reached==="boolean")Z.spendControl={limit:Y,used:J,remaining:G,usedPercent:B,remainingPercent:H,resetsAt:typeof X.resetsAt==="string"?X.resetsAt:void 0,unit:typeof X.unit==="string"?X.unit:void 0,source:typeof X.source==="string"?X.source:void 0,reached:X.reached}}let z=$.credits;if(M(z)&&typeof z.hasCredits==="boolean"&&typeof z.unlimited==="boolean"&&(z.overageLimitReached===void 0||typeof z.overageLimitReached==="boolean")){let Y=Number(z.balance),J=typeof z.checkedAt==="number"?z.checkedAt:Number.NaN;Z.credits={hasCredits:z.hasCredits,unlimited:z.unlimited,...typeof z.overageLimitReached==="boolean"?{overageLimitReached:z.overageLimitReached}:{},...Number.isFinite(Y)?{balance:Y}:{},...Number.isFinite(J)?{checkedAt:J}:{}}}return Object.keys(Z).length?Z:void 0}function Y5($){if(!M($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!o7(Z))return null;let z=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...SZ($),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{...SZ($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...SZ($),type:"oauth",corrupt:!0}}return{...SZ($),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:o3($.lastRefreshError),lastQuotaRefreshError:o3($.lastQuotaRefreshError),quota:z5($.quota)}}function J5($){if(!M($))return;let Z=Object.create(null);for(let[X,z]of Object.entries($)){if(!Z5(X)||!M(z))continue;let Y={};if(M(z.inFlight))Y.inFlight={...z.inFlight};if(M(z.lastOutcome)&&typeof z.lastOutcome.code==="string"&&z.lastOutcome.code.length>0&&typeof z.lastOutcome.at==="number"&&Number.isFinite(z.lastOutcome.at))Y.lastOutcome={code:z.lastOutcome.code,at:z.lastOutcome.at,...M(z.lastOutcome.previousOutcome)&&typeof z.lastOutcome.previousOutcome.code==="string"&&z.lastOutcome.previousOutcome.code.length>0&&typeof z.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(z.lastOutcome.previousOutcome.at)?{previousOutcome:{code:z.lastOutcome.previousOutcome.code,at:z.lastOutcome.previousOutcome.at}}:{}};if(typeof z.cooldownUntil==="number"&&Number.isFinite(z.cooldownUntil))Y.cooldownUntil=z.cooldownUntil;if(Object.keys(Y).length>0)Z[X]=Y}return Object.keys(Z).length>0?Z:void 0}var r3=new Set;function J1($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(r3.has(Z))return;r3.add(Z),v$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function G1($){if(!M($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(Y5).filter((z)=>z!=null);if(X.length<Z.length){let z=new Set;for(let G of Z)if(M(G)&&typeof G.id==="string"&&G.id.trim())z.add(G.id.trim());let Y=new Set(X.map((G)=>G.id)),J=[];for(let G of z)if(!Y.has(G))J.push(G);J1(J)}return{version:1,main:{type:"opencode",provider:"openai"},routing:M($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((z)=>Number.isInteger(z)):void 0,refresh:M($.refresh)?$.refresh:void 0,quota:M($.quota)?$.quota:void 0,reset:J5($.reset),dump:M($.dump)?$.dump:void 0,costZeroing:M($.costZeroing)?$.costZeroing:void 0,killswitch:M($.killswitch)?$.killswitch:void 0,logging:M($.logging)?$.logging:void 0,cachekeep:M($.cachekeep)?$.cachekeep:void 0,cacheKeep:M($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:X}}function B1($){if(!("claustrum"in $))return $;let{claustrum:Z,...X}=$;return X}async function V0($){try{return{exists:!0,value:JSON.parse(await G5($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function z0($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function B5($){let Z;try{Z=(await V0($)).value}catch{return null}return J8(Z)}function H1($,Z){if(!M($))return $;let X=M(Z)?Z:{},z=M(X.main)?X.main:void 0,Y=M(X.accounts)?X.accounts:{},J=M($.quota)?$.quota:{},G=M($.refresh)?$.refresh:{},B=z??J,H=z??G,W=G.mainRefreshLeaseId!==void 0?{id:G.mainRefreshLeaseId,until:G.mainRefreshLeaseUntil,tokenHash:G.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!M(D))return D;let V=typeof D.id==="string"&&M(Y[D.id])?Y[D.id]:{};return{...D,...V}}):void 0;return K1({...$,refresh:z0({...G,mainLastRefreshError:G.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:z0({...J,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:U})}async function H5($){let Z=await V0($.configPath);if(!Z.exists)return null;let X=await V0($.statePath);return G1(H1(Z.value,X.value))}var t3=new Set;async function RB($){try{let{exists:Z,value:X}=await V0($.configPath);if(!Z)return null;if(!M(X))throw Error("settings must be an object");let z=M(X.refresh)?X.refresh:{},Y=M(X.quota)?X.quota:{};return{version:1,accounts:[],routing:M(X.routing)?X.routing:void 0,fallbackOn:Array.isArray(X.fallbackOn)?X.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:z0({enabled:z.enabled,refreshBeforeExpiryMinutes:z.refreshBeforeExpiryMinutes}),quota:z0({enabled:Y.enabled,checkIntervalMinutes:Y.checkIntervalMinutes,refreshEveryNRequests:Y.refreshEveryNRequests,minimumRemaining:Y.minimumRemaining,failClosedOnUnknownQuota:Y.failClosedOnUnknownQuota}),dump:M(X.dump)?X.dump:void 0,costZeroing:M(X.costZeroing)?X.costZeroing:void 0,killswitch:M(X.killswitch)?X.killswitch:void 0,logging:M(X.logging)?X.logging:void 0,cachekeep:M(X.cachekeep)?X.cachekeep:void 0,cacheKeep:M(X.cacheKeep)?X.cacheKeep:void 0}}catch{if(!t3.has($.configPath))t3.add($.configPath),v$.warn("could not read OpenAI auth settings; using defaults",{path:$.configPath});return null}}function K1($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function K5($){return z0({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function Q1($){if($.type==="api")return z0({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return z0({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function IZ($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function w$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function Q5($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function W5($,Z){if(!Q5($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var U5=300000;function e3($,Z){if($===void 0)return 0;return $>Z+U5?0:$}function D5($,Z,X){let z=Date.now(),Y=e3(Z.lastRefreshedAt,z),J=e3(X.lastRefreshedAt,z),G=Z.expires??0,B=X.expires??0,H=J>Y?X:Y>J?Z:B>G?X:G>B?Z:W5(Z,X);w$($,H,"access"),w$($,H,"refresh"),w$($,H,"expires"),w$($,H,"lastRefreshedAt"),w$($,H,"lastRefreshError")}function V5($,Z){if(!M($))return Z;let X=$,z=IZ(X.quota),Y=IZ(Z.quota),J=z>Y,G=J?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!J&&!("lastQuotaRefreshError"in Z))delete G.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete G.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))G.lastUsed=X.lastUsed;return D5(G,X,Z),G}function W1($){let Z=$.refresh?z0({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,X=$.quota?z0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return K1({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(K5)})}function N5($,Z,X,z){if(a3(z)!=="shared")return $;let Y={...$};for(let G of["routing","fallbackOn","refresh","quota","dump","costZeroing","killswitch","logging","cachekeep","cacheKeep","dumpDir","dumpMaxBytes","webSockets","rawWebSocket","responsesLite","codexApiEndpoint"])if(delete Y[G],Object.hasOwn(Z,G))Y[G]=Z[G];let J=M(Z.refresh)?{...Z.refresh}:{};for(let G of["mainLastRefreshError","mainRefreshLeaseId","mainRefreshLeaseUntil","mainRefreshLeaseTokenHash"]){delete J[G];let B=X.refresh?.[G];if(B!==void 0)J[G]=B}if(M(Z.refresh)||Object.keys(J).length>0)Y.refresh=J;return Y}async function g$($,Z=!1){let X=Date.now(),z=X+n7,Y=0;while(Date.now()<=z){Y++;let B=await g({name:"save",ttlMs:a7,path:$,renew:Z});if(B)return B;let H=z-Date.now();if(H<=0)break;await s7(Math.min(e6+q1(e6),H))}let J=Date.now()-X,G=Math.round(J/Math.max(1,Y));throw Error(`Timed out after ${J}ms waiting for the account store lock on ${$} (${Y} attempts, ~${G}ms apart; retry interval is ${e6}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 U1($){let Z=Object.fromEntries($.accounts.map((X)=>[X.id,Q1(X)]));return{version:1,main:z0({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function J8($){if(!M($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let X of $.accounts){if(!M(X))continue;if(typeof X.id!=="string")continue;let z=X.id.trim();if(!z)continue;Z.add(z)}return Z}function q5($,Z,X,z){if(!M($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],J=[];for(let G of Z){if(X.has(G))continue;if(z.has(G))continue;let B=$.accounts.find((H)=>M(H)&&typeof H.id==="string"&&H.id.trim()===G);if(!B)continue;Y.push(B),J.push(G)}return{preservedRawEntries:Y,preservedIds:J}}function M5($){if(!Array.isArray($))return[];let Z=[];for(let X of $){if(!M(X))continue;if(typeof X.id!=="string")continue;Z.push(X.id)}return Z}function _5($,Z,X){let z=J8($);if(z===null)return[];let{preservedRawEntries:Y,preservedIds:J}=q5($,z,Z,X);return J1(J),Y}async function TB($,Z,X={}){let{configPath:z,statePath:Y}=Z,J=await g$(z);try{let G=await g$(Y);try{let B=await V0(z),H=await V0(Y),K=M(B.value)?structuredClone(B.value):{},W=(B.exists?G1(H1(B.value,H.value)):null)??F5(),Q=new Set(W.accounts.map((O)=>O.id)),U=J8(B.value)??new Set,D=$(W,{rawRosterIds:[...U],loadedRosterIds:[...Q]})??W,V=new Set(X.allowDrop??[]),_=_5(B.value,Q,V),q=W1(D),R=new Set((Array.isArray(q.accounts)?q.accounts:[]).map((O)=>M(O)&&typeof O.id==="string"?O.id.trim():"").filter(Boolean)),x=_.filter((O)=>{if(!M(O))return!1;if(typeof O.id!=="string")return!1;return!R.has(O.id.trim())}),L={...B1(K),...q,accounts:[...Array.isArray(q.accounts)?q.accounts:[],...x]};if(X.canWrite&&!X.canWrite())return W;if(await B0(z,N5(L,K,D,z)),X.canWrite&&!X.canWrite())return W;return await B0(Y,U1(D)),v$.debug("account config written",{accountCount:L.accounts.length,accountIds:M5(L.accounts)}),D}finally{await G.release()}}finally{await J.release()}}function F5(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function L5($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:IZ($.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:IZ(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 O5($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function X8($){if(Array.isArray($))return $.map(X8);if(!M($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,X8(X)]))}async function P5($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},z){let Y=Z.statePath,J=await g$(Y);try{let G=(await V0(Y)).value,B=M(G)?{...G,version:1}:{version:1};if(X.mainQuota)L5(B,$);if(X.mainRefresh)O5(B,$);if(X.accounts){let H=X.accounts===!0?null:new Set(X.accounts),K=await B5(Z.configPath);B.accounts={...M(B.accounts)?B.accounts:{}};for(let W of $.accounts){if(H&&!H.has(W.id))continue;if(K&&!K.has(W.id))continue;B.accounts[W.id]=V5(B.accounts[W.id],Q1(W))}if(H){for(let W of H)if(!$.accounts.some((Q)=>Q.id===W))delete B.accounts[W]}if(K){for(let W of Object.keys(B.accounts))if(!K.has(W))delete B.accounts[W]}}if(z&&!z())return;await B0(Y,X8(B))}finally{await J.release()}}function j5($){return $?.fallbackOn?.length?$.fallbackOn:t7}function xB($,Z){return j5(Z).includes($)}function R5($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??n3.primary,secondary:Z.secondary??Z["1w"]??n3.secondary}}function z8($){return $?.quota?.enabled!==!1}function p$($){return $?.quota?.failClosedOnUnknownQuota??e7}function D1($,Z,X=Date.now()){if(!z8(Z))return!0;if(!$)return!p$(Z);let z=R5(Z),Y=p$(Z);for(let J of["primary","secondary"]){let G=$[J];if(!G)continue;if(OZ(G,X)){if(Y)return!1;continue}if(G.remainingPercent<z[J])return!1}return!0}function bZ($){return $?.killswitch?.enabled===!0}function $1($){return{primary:$?.primary??$?.["5h"]??Z8.primary,secondary:$?.secondary??$?.["1w"]??Z8.secondary}}function AB($){return $?.cacheKeep??$?.cachekeep}function Z1($){return typeof $==="number"&&Number.isFinite($)?$:0}function V1($,Z){if(!$?.killswitch)return Z8;if($.killswitch.schema===r7){let{accounts:X,defaults:z}=$.killswitch,Y=Z??"main",J=M(X)&&Object.hasOwn(X,Y)&&M(X[Y])?X[Y]:M(z)?z:void 0;return{primary:Z1(J?.primary),secondary:Z1(J?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return $1($.killswitch.accounts[Z]);return $1($.killswitch.main)}function N1($,Z,X,z=Date.now()){if(!bZ(Z))return!0;if(!$)return!p$(Z);let Y=V1(Z,X),J=p$(Z);for(let G of["primary","secondary"]){let B=$[G];if(!B)continue;if(OZ(B,z)){if(J)return!1;continue}if(B.remainingPercent<Y[G])return!1}return!0}function EB($,Z,X,z){if(!bZ(z))return 300;let Y=[],J=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:H}of J){if(!H)continue;let K=V1(z,B),W=[],Q=!1;for(let U of["primary","secondary"]){let D=H[U];if(!D||OZ(D,X))continue;if(D.remainingPercent>=K[U])continue;let V=D.resetsAt?Date.parse(D.resetsAt):NaN;if(!Number.isFinite(V)||V<=X){Q=!0;break}W.push(V)}if(Q||W.length===0)continue;Y.push(Math.max(...W))}if(Y.length===0)return 300;let G=Math.min(...Y);return Math.max(1,Math.ceil((G-X)/1000))}function X1($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function SB($,Z){let{configPath:X,statePath:z}=Z;if(!$)return;try{let J=await V0(X);if(J.exists&&M(J.value)&&X1(J.value))return}catch{}let Y=await g$(X);try{let J=await g$(z);try{let G=await V0(X);if(G.exists&&M(G.value)){if(X1(G.value))return}if(!$)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let W=t$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(W)B.mainAccountId=W}let H=G.exists&&M(G.value)?G.value:{},K={...B1(H),...W1(B)};await B0(X,K),await B0(z,U1(B))}finally{await J.release()}}finally{await Y.release()}}function T5($){return $?.refresh?.enabled!==!1}function x5($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function q1($){return Math.floor(Math.random()*($+1))}function i0($,Z,X){return!$.access||!$.expires||$.expires-X<=x5(Z)}function A5($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function h$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class M1 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 E5="common-auth-placeholder:v1:openai",_1="main";function CB($){return M($)&&$.type==="oauth"&&($.refresh===E5||$.refresh===M3)}function IB($){return $?.accounts.find((Z)=>Z.id===_1&&Z.enabled!==!1&&D0(Z))}function bB($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==_1)}}function l($,Z){let X=$.accounts.findIndex((z)=>z.id===Z.id);if(X!==-1)$.accounts[X]=Z}function m$($){return $ instanceof Error?$.message:String($)}function Y8($,Z,X){if(Z instanceof S$)return;$.lastRefreshError=C8({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function $8($,Z,X){if(Z instanceof S$)return;if($.lastQuotaRefreshError=_$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)Y8($,Z,X)}function z1($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function S5($,Z){if(!$)return!1;return z1($.primary,Z)||z1($.secondary,Z)}function C5($,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 Y1($,Z,X){return!C5($.quota,Z,X)}function I5($,Z,X,z){return tZ(X)&&D1($.quota,Z,z)&&S5($.quota,z)}function b5($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var k5=60000,f5=60000,y5=600000;function w5($){return`fallback-oauth-refresh-${u7("sha256").update($).digest("base64url").slice(0,16)}`}var h5=1e4,m5=100;class v5{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($)LZ($.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+b5(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return H5(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await P5($,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(()=>{})},k5+q1(f5)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($){let Z=$!==void 0?$:await this.load();if(!Z)return[];let X=[],z=!1;for(let Y of Z.accounts){if(Y.enabled===!1||!D0(Y))continue;if(h$(Z,Y))continue;if(d0(Y))continue;let J=!1,G=Y;try{if(i0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&b0(B,G.refresh,this.now()))throw J=!0,Error(o$(B,this.now()));try{G=await this.refreshAccount(G,Z),z=!0}catch(H){if(X5(H))continue;J=!0;let K=Z.accounts.find((W)=>W.id===Y.id&&D0(W));if(K&&!b0(K.lastRefreshError,K.refresh,this.now()))Y8(K,H,this.now()),l(Z,K),z=!0;throw H}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))X.push(G)}catch(B){let H=A5(G,this.now());if(J){if(!H)continue}else if(!H)continue;if(I5(G,Z,B,this.now()))u0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:m$(B)}),X.push(G);else if(!p$(Z))X.push(G)}}if(z){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((J)=>{v$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:m$(J)})})}return X}async markUsed($){try{let Z=await this.load();if(!Z)return;let X=Z.accounts.find((z)=>z.id===$.id);if(!X)return;X.lastUsed=this.now(),await this.save(Z,[X.id])}catch(Z){v$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:m$(Z)})}}accountPassesQuotaPolicy($,Z){return D1($.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(!$||!T5($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!D0(X))continue;if(h$($,X))continue;if(d0(X))continue;if(!i0(X,$,this.now()))continue;if(b0(X.lastRefreshError,X.refresh,this.now()))continue;try{u0.debug("fallback oauth background due",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),await this.refreshAccount(X,$),Z=!0}catch(z){u0.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:m$(z)}),Y8(X,z,this.now()),l($,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||!D0(X))continue;if(h$($,X))continue;if(d0(X))continue;let z=X;try{if(i0(z,$,this.now())){if(b0(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,$),Z=!0}if(e0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,$),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):Y1(z,$,this.now())))continue;await this.refreshAccountQuota(z,$),Z=!0}catch(Y){$8(X,Y,this.now()),l($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!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||!D0(J))continue;if(h$(Z,J))continue;if(d0(J))continue;let G=J;try{if(i0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&b0(B,G.refresh,this.now()))throw Error(o$(B,this.now()));G=await this.refreshAccount(G,Z),Y=!0}if(!z&&!Y1(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,l(Z,G),Y=!0;continue}await this.refreshAccountQuota(G,Z),Y=!0}catch(B){$8(J,B,this.now()),l(Z,J),Y=!0,X.push({accountId:J.id,message:m$(B)})}}if(Y)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let z=this.refreshPromises.get($.id);if(z){let G=await z;return l(Z,G),G}let Y=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let J=await Y;return l(Z,J),J}async waitForConcurrentFallbackRefresh($,Z,X,z){let Y=Date.now()+h5;while(Date.now()<Y){await new Promise((K)=>setTimeout(K,m5));let J=await this.load(),G=J?.accounts.find((K)=>K.id===$.id&&D0(K));if(!G)continue;if(this.assertNotTombstoned(G),(G.access!==X.access||G.refresh!==X.refresh||(G.expires??0)>(X.expires??0)+60000)&&(z.force||!i0(G,J,this.now())))return l(Z,G),u0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G;let H=G.lastRefreshError;if(H&&b0(H,G.refresh,this.now()))throw l(Z,G),Error(o$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(h$($,Z))throw new M1(Z.id)}async refreshAccountNow($,Z,X){let z=await this.load(),Y=z?.accounts.find((B)=>B.id===$.id&&D0(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(z,Y,X),Y&&!X.force&&!i0(Y,z,this.now()))return l(Z,Y),Y;let J=Y??$,G=await g({name:w5(J.id),ttlMs:y5,path:this.paths.configPath,renew:!0});if(!G){u0.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:J.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,J,X);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),Y=z?.accounts.find((W)=>W.id===$.id&&D0(W)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(z,Y,X),Y&&!X.force&&!i0(Y,z,this.now()))return l(Z,Y),Y;if(!Y)throw new CZ($.id);J=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});u0.debug("fallback oauth refresh request start",{pid:process.pid,accountId:J.id,force:X.force===!0,expiresInMs:J.expires?J.expires-this.now():void 0});let H=await B({refreshToken:J.refresh,fetchImpl:this.fetchImpl,now:this.now});if(J.access=H.access,J.refresh=H.refresh,J.expires=H.expires,J.lastRefreshedAt=H.expires-H.expiresIn*1000,J.lastRefreshError=void 0,l(Z,J),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new CZ($.id);return u0.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J}finally{await G.release()}}async refreshAccountQuota($,Z){let X=$;if(this.assertNotTombstoned(X),!X.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let z=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(J)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,J):z({accessToken:J,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${$.id} has no access token`);let J=await Y(X.access);X.quota=J,X.lastQuotaRefreshError=void 0,l(Z,X),await this.save(Z)}catch(J){throw $8($,J,this.now()),l(Z,$),J}}}var F1=["primary","secondary"];function kZ($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function W$($){return typeof $==="number"&&Number.isFinite($)}function g5($,Z){if(!kZ(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 p5($){let Z=$.spendControl;if(kZ(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 l5($,Z){if(!kZ($)||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 yB($,Z,X){if(!kZ($)||!W$(Z))return;let z=[],Y=[];for(let K of F1){let W=g5(K,$[K]);if(W)z.push(W);else if(X)Y.push({label:K})}let J=p5($),G=$.resetCreditsAvailable,B=typeof G==="number"&&Number.isSafeInteger(G)&&G>=0?{resetCredits:{value:G,checkedAt:Z}}:void 0,H=l5($.credits,Z);if(z.length===0&&Y.length===0&&!J&&!B&&!H)return;return{checkedAt:Z,...z.length>0?{readings:z}:{},...Y.length>0?{coverage:Y}:{},...J?{budget:J}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function L1($){if(!E0($))return;let Z=s($),X={};for(let z of F1){let Y=Z.limits.find((G)=>G.label===z&&G.kind==="reading");if(!Y||!W$(Y.usedPercent))continue;let J={usedPercent:Y.usedPercent,remainingPercent:100-Y.usedPercent,checkedAt:Y.checkedAt,...Y.resetsAt!==void 0?{resetsAt:Y.resetsAt}:{},...Y.windowMinutes!==void 0?{windowMinutes:Y.windowMinutes}:{}};X[z]=J}return X.primary||X.secondary?X:void 0}var P1="main";function pB($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function lB($,Z,X){let z=new Map;if(bZ(Z))for(let Y of $)z.set(Y.id,N1(L1(Y.quota),Z,Y.id===P1?void 0:Y.id,X));return z}var dB=5,d5=5000;function cB($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function uB($,Z=d5){let X=$.rows.filter((G)=>G.kind==="oauth"&&$.killswitch.get(G.id)!==!1&&s(G.quota).limits.length===0);if(X.length===0)return;if(t({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((G)=>$.killswitch.get(G.id)!==!1))return;let Y=[];if(t({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(G)=>{let B=$.requestPull(G);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let J;return Promise.race([Promise.all(Y),new Promise((G)=>{J=setTimeout(G,Z)})]).then(()=>{}).finally(()=>clearTimeout(J))}function fZ($){return $.reason==="exhausted"||$.reason==="budget-spent"}function c5($,Z){if(!J0($))return!1;let X=$;if(!(Z-X.checkedAt<=N$))return!1;if(X.overageLimitReached===!0)return!1;if(X.unlimited)return!0;return X.hasCredits&&(X.balance===void 0||X.balance>0)}function yZ($,Z,X){let z=(B)=>Z.killswitch.get(B)!==!1,Y=new Set(X.admitted.filter((B)=>B.lastPath!==!0&&z(B.id)).map((B)=>B.id)),J=new Map(X.refused.map((B)=>[B.id,B])),G=$.filter((B)=>{if(B.kind!=="oauth"||!z(B.id))return!1;if(J.get(B.id)?.reason!=="exhausted")return!1;let H=s(B.quota);if(C0(H,Z.now))return!1;return c5(H.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:G}}function u5($,Z=$.rows){return t({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class i5{#$=new Set;served($,Z,X){let z=u5($),Y=yZ($.rows,$,z),J=new Set(Y.credits);if(Y.free.has(Z)){this.#$.clear();return}for(let G of[...this.#$])if(!J.has(G))this.#$.delete(G);if(!J.has(Z)||this.#$.has(Z))return;this.#$.add(Z),X?.info("serving requests on prepaid credits",{accountId:Z,reason:"free quota used up"})}has($){return this.#$.has($)}ids(){return new Set(this.#$)}}function j1($,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 O1($,Z,X){if(Z.refused.find((Y)=>!fZ(Y)&&X.get(Y.id)!==!1))return{reason:"quota-unknown"};return j1($[0],Z,X)}function iB($){let Z=$.replayable!==!1,X=$.mainId===void 0?P1:$.mainId??"",z=Z?$.placement:"main-first",Y=cZ({rows:$.rows,placement:z,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),J=a$($.rows.map((U)=>U.id),z,X),G=new Set(Y.admission.refused.filter((U)=>fZ(U)&&$.killswitch.get(U.id)!==!1).map((U)=>U.id)),B=J.filter((U)=>G.has(U)),H=yZ($.rows,$,Y.admission),K=Y.order.filter((U)=>H.free.has(U)),W=J.filter((U)=>H.credits.includes(U)),Q=(U,D)=>({kind:"send",order:U,lastPath:D,tiers:Object.fromEntries(U.map((V)=>[V,H.free.has(V)?"free":H.credits.includes(V)?"credits":"last-path"]))});if(!Z){let U=J.includes(X),D=U?X:K[0]??W[0]??Y.order[0]??B[0];if(D!==void 0&&Y.order.includes(D))return Q([D],!1);if(D!==void 0&&W.includes(D))return Q([D],!1);if(D!==void 0&&G.has(D))return Q([D],!0);return{kind:"block",block:U?j1(X,Y.admission,$.killswitch):O1(J,Y.admission,$.killswitch)}}if(K.length>0)return Q(K,!1);if(W.length>0){let U=Y.order.length>0?Y.order:B;return Q([...W,...U.filter((D)=>!W.includes(D))],!1)}if(Y.order.length>0)return Q(Y.order,!1);if(B.length>0)return Q(B,!0);return{kind:"block",block:O1(J,Y.admission,$.killswitch)}}function sB($){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 R1($,Z,X){let z=X.exclude,Y=z?$.rows.filter((G)=>!z.has(G.id)):$.rows,J=new Map;for(let G of Y){let B=Z.resetCredits(G.id);if(B!==void 0)J.set(G.id,B)}return nZ({rows:Y,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(G)=>Z.reservePercent(G.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:J,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function aB($,Z,X,z){let Y=R1($,Z,{exclude:X,pendingBytes:z}),J=$.rows.filter((W)=>!X.has(W.id)),G=yZ(J,$,Y.admission),B=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,tier:G.free.has(Y.accountId)?"free":"last-path",...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(B&&G.free.has(B.accountId))return B;let H=G.credits[0];if(H===void 0)return B;let K=s(J.find((W)=>W.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",tier:"credits",...K===void 0?{}:{quotaCheckedAt:K}}}function nB($,Z,X){let z=$.killswitch.get(X)===!1,Y={kind:"move",reason:z?"killswitch":"exhausted"},J=R1($,Z,{pin:X}),G=yZ($.rows,$,J.admission),B=G.credits.includes(X),H=G.credits.some((Q)=>Q!==X);if(J.outcome==="dispatch"){let Q=!G.free.has(J.accountId);if(J.pin.action==="assign"){if(Q&&B)return{kind:"serve",tier:"credits"};return Y}if(J.accountId!==X)return{kind:"detour"};if(Q&&H)return Y;return{kind:"serve",tier:Q?"last-path":"free"}}let K=J.admission.refused.find((Q)=>Q.id===X),W=z||K!==void 0&&fZ(K);if(B)return{kind:"serve",tier:"credits"};if(H)return W?Y:{kind:"detour"};if(!z&&K&&fZ(K))return{kind:"last-path"};return{kind:"none"}}function oB($,Z,X,z){let Y=$.killswitch.get(X);return aZ({quota:Z.projections.get(X),now:$.now,...z===void 0?{}:{status:z},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as T1}from"node:os";import{join as x1}from"node:path";function s5(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?x1(T1(),"opencode-openai-auth","opencode-openai-auth.log"):x1(T1(),"opencode-openai-auth.log"))}function a5(){return A1(process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL)}E1({file:s5,level:a5});
101
- export{E0 as be,V$ as ce,t1 as de,gZ as ee,y1 as fe,F8 as ge,g1 as he,p1 as ie,s as je,C0 as ke,j8 as le,$2 as me,a$ as ne,Z2 as oe,uZ as pe,X2 as qe,s6 as re,a6 as se,g9 as te,p9 as ue,_0 as ve,N as we,S as xe,h0 as ye,p2 as ze,l2 as Ae,b as Be,m0 as Ce,M9 as De,X4 as Ee,D6 as Fe,z4 as Ge,Y4 as He,N6 as Ie,B4 as Je,P0 as Ke,E9 as Le,H4 as Me,P6 as Ne,f as Oe,p0 as Pe,h6 as Qe,nY as Re,J2 as Se,W2 as Te,S8 as Ue,C8 as Ve,b0 as We,o$ as Xe,y8 as Ye,h8 as Ze,q2 as _e,b8 as $e,k8 as af,t$ as bf,_2 as cf,w0 as df,P2 as ef,j2 as ff,R2 as gf,T2 as hf,lX as if,cX as jf,uX as kf,iX as lf,d0 as mf,S$ as nf,FJ as of,LJ as pf,AJ as qf,n as rf,x0 as sf,X7 as tf,z7 as uf,Y7 as vf,J7 as wf,G7 as xf,B7 as yf,H7 as zf,K7 as Af,A as Bf,T7 as Cf,w7 as Df,Q$ as Ef,t6 as Ff,JB as Gf,a3 as Hf,HB as If,D0 as Jf,r7 as Kf,PB as Lf,Z8 as Mf,Z5 as Nf,B5 as Of,H5 as Pf,RB as Qf,TB as Rf,P5 as Sf,j5 as Tf,xB as Uf,D1 as Vf,bZ as Wf,AB as Xf,V1 as Yf,N1 as Zf,EB as _f,SB as $f,x5 as ag,h$ as bg,_1 as cg,CB as dg,IB as eg,bB as fg,y5 as gg,w5 as hg,v5 as ig,yB as jg,L1 as kg,P1 as lg,pB as mg,lB as ng,dB as og,d5 as pg,cB as qg,uB as rg,c5 as sg,i5 as tg,iB as ug,sB as vg,aB as wg,nB as xg,oB as yg};
100
+ `,"utf8"),await K.sync()}finally{await K.close()}await n6?.("staged",{target:G,temp:B}),await n6?.("before-publish",{target:G,temp:B}),await z.assertOwned(),await Y.assertAll();try{await j.link(B,G)}catch(W){if(!xZ(W,"EEXIST"))throw W;return J.outcome="aborted-target-appeared",J}J.outcome="moved";try{await j.unlink(B),H=!1}catch(W){J.postPublishFailures.push({step:"temp-unlink",error:W}),w$($,"warn","Settings move temp cleanup failed",{temp:B,error:W})}if(process.platform!=="win32")try{let W=await j.open(y$(G),"r");try{await W.sync()}finally{await W.close()}}catch(W){J.postPublishFailures.push({step:"directory-sync",error:W}),w$($,"warn","Settings move directory sync failed",{target:G,error:W})}return await f7($,Z,J),J}finally{if(H&&J.outcome!=="moved")await j.unlink(B).catch(()=>{})}}async function w7($){try{if($.separateInstall)return X0("separate-install");if(await TZ($.target))return X0("done-already");if(!await $.fence())return X0("fence-closed");let Z=y$($.target);if(process.platform==="win32")await g0(Z);else await j.mkdir(Z,{recursive:!0,mode:448});let X;try{return await I0($.target,{name:"settings-move",...s6},async(z)=>{let Y=new a6(s6,{});try{let J=new Set,G=new Map;for(let B of $.sources)for(let H of B.locks){let K=I7(H.path),W=G.get(K)??new Set;if(W.has(H.name))continue;W.add(H.name),G.set(K,W);let Q=y$(q$(H.path,H.name));if(!await TZ(Q)){J.add(Q);continue}try{await Y.acquire(H)}catch(U){return X=v3(U,H.path,H.name),X}}if(await TZ($.target))X=X0("done-already");else if(!await $.fence())X=X0("fence-closed");else{await k7($.target),await n6?.("locked",{target:$.target});let B=[];for(let Q of $.sources){let U;try{U=await j.readFile(Q.path,"utf8")}catch(D){if(!xZ(D,"ENOENT"))throw D;B.push({host:Q.host,path:Q.path,present:!1});continue}B.push({host:Q.host,path:Q.path,present:!0,value:Q.read(U)})}let H=await $.map(B);for(let Q of J)if(await TZ(Q))return X=X0("busy"),X;let K=X0("failed"),W=b7($,B,H,K);X=await y7($,B,W,z,Y,K)}}catch(J){X={...X0("failed"),cause:J}}finally{await Y.releaseAll()}return X})}catch(z){if(!X)return v3(z,$.target,"settings-move");if(X.outcome==="moved")X.postPublishFailures.push({step:"lock-release",error:z});return w$($,"warn","Settings move lock release failed",{error:z}),X}}catch(Z){return{...X0("failed"),cause:Z}}}import{posix as g3,win32 as p3}from"node:path";function W$($,Z){if(Z!=="win32")return $.startsWith("/");if($.startsWith("\\\\?\\")||$.startsWith("\\\\.\\"))return!0;if(/^[a-zA-Z]:[\\/]/.test($))return!0;return/^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test($)}function l3({env:$,platform:Z,homedir:X}){let z=Z==="win32"?p3:g3,Y=(G)=>G!==void 0&&W$(G,Z),J;if(Y($.XDG_CONFIG_HOME))J=$.XDG_CONFIG_HOME;else if(Z==="win32"&&Y($.APPDATA))J=$.APPDATA;else{let G=Z==="win32"?$.USERPROFILE:$.HOME;if(!Y(G)){if(!Y(X))throw new A("settings-unavailable","No absolute home or config directory is available");G=X}J=Z==="win32"?z.join(z.join(G,"AppData"),"Roaming"):z.join(G,".config")}return z.join(J,"cortexkit")}function o6({plugin:$,override:Z,...X}){if(Z&&W$(Z,X.platform))return Z;return(X.platform==="win32"?p3:g3).join(l3(X),`${$}.jsonc`)}function U$($){let Z=r6($),X=[];for(;;)try{return p7(c3.native(Z),...X)}catch{let z=g7(Z);if(z===Z)return r6($);X.unshift(v7(Z)),Z=z}}var d3=new Map;function t6($){let Z=d3.get($);if(Z===void 0)Z=U$($),d3.set($,Z);return Z}function c7($={}){let Z=$.env??process.env,X=$.platform??process.platform,z=($.homedir??u3)(),Y=X==="win32"?d7:l7,J=Z.XDG_CONFIG_HOME,G=Y.join(J&&W$(J,X)?J:Y.join(z,".config"),"opencode"),B=Y.join(z,".config","opencode"),H=(D)=>{try{return c3.native(D)}catch{return r6(D)}},K=H(G),W=Y.join(Z.XDG_STATE_HOME||Y.join(z,".local","state"),"cortexkit","openai-auth",K===H(B)?"opencode":`opencode-${h7("sha256").update(K).digest("hex").slice(0,16)}`),Q=m7(Y.join(W,"layout.json"))?W:G,U=Y.join(z,".pi","agent");return[{host:"opencode",configPath:Y.join(G,AZ),statePath:Y.join(Q,EZ)},{host:"pi",configPath:Y.join(U,AZ),statePath:Y.join(U,EZ)}]}function JB($){let Z=$.env??process.env,X=$.platform??process.platform,z=$.homedir??u3,Y=c7({env:Z,platform:X,homedir:z}),J=Y[$.host==="opencode"?0:1],G=U$($.paths.configPath),B=G!==U$(J.configPath),H=$.host==="opencode"?"OPENCODE_OPENAI_AUTH_SETTINGS_FILE":"PI_OPENAI_AUTH_SETTINGS_FILE",K=Z[H],W=K!==void 0&&W$(K,X)?K:void 0;if(W!==void 0){let D=U$(W);if([$.paths,...Y].some((_)=>U$(_.configPath)===D||U$(_.statePath)===D))W=void 0,($.logger??console).warn(`openai-auth ignored ${H}: the settings file must not be an account config or state file.`)}let Q=W!==void 0,U=!Q&&B;return{host:$.host,configIdentity:G,target:W??o6({plugin:"openai-auth",env:Z,platform:X,homedir:z()}),optIn:Q,separate:U,sources:U?[]:Q?B?[{host:$.host,...$.paths}]:[]:Y.map((D)=>D.host===$.host?{host:$.host,...$.paths}:D)}}var i3=Symbol.for("@cortexkit/openai-auth/settings-decisions"),s3=globalThis,SZ=s3[i3]??new Map;s3[i3]=SZ;function a3($){return SZ.get(t6($))}function HB($,Z){let X=t6($),z=SZ.get(X);if(z!==void 0)return z;return SZ.set(X,Z),Z}import{readFile as G5}from"node:fs/promises";var u0=p("refresh"),g$=p("accounts"),a7=1e4,n7=15000,e6=50;function D0($){return $.type==="oauth"&&$.corrupt!==!0}function o7($){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 r7="floors-v1";function PB($){return $.costZeroing?.enabled!==!1}class IZ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var t7=[401,403,429],n3={primary:0,secondary:0},e7=!1,Z8={primary:5,secondary:10};function q($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var $5=new Set(["__proto__","constructor","prototype"]);function Z5($){return $.length>0&&!$5.has($)}function X5($){return $ instanceof IZ||q($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function CZ($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():i7(),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 o3($){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 z5($){if(!q($))return;let Z={};for(let Y of["primary","secondary"]){let J=$[Y];if(!q(J))continue;let G=Number(J.usedPercent),B=Number(J.remainingPercent),H=Number(J.checkedAt);if(!Number.isFinite(G)||!Number.isFinite(B)||!Number.isFinite(H))continue;let K=typeof J.windowMinutes==="number"?J.windowMinutes:Number.NaN;Z[Y]={usedPercent:G,remainingPercent:B,checkedAt:H,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...Number.isFinite(K)&&K>0?{windowMinutes:K}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let J=typeof $[Y]==="number"?$[Y]:Number.NaN;if(Number.isFinite(J)&&J>=0)Z[Y]=J}let X=$.spendControl;if(q(X)){let Y=Number(X.limit),J=Number(X.used),G=Number(X.remaining),B=Number(X.usedPercent),H=Number(X.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof X.reached==="boolean")Z.spendControl={limit:Y,used:J,remaining:G,usedPercent:B,remainingPercent:H,resetsAt:typeof X.resetsAt==="string"?X.resetsAt:void 0,unit:typeof X.unit==="string"?X.unit:void 0,source:typeof X.source==="string"?X.source:void 0,reached:X.reached}}let z=$.credits;if(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 Y5($){if(!q($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!o7(Z))return null;let z=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...CZ($),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{...CZ($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...CZ($),type:"oauth",corrupt:!0}}return{...CZ($),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:o3($.lastRefreshError),lastQuotaRefreshError:o3($.lastQuotaRefreshError),quota:z5($.quota)}}function J5($){if(!q($))return;let Z=Object.create(null);for(let[X,z]of Object.entries($)){if(!Z5(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 r3=new Set;function J1($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(r3.has(Z))return;r3.add(Z),g$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function G1($){if(!q($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(Y5).filter((z)=>z!=null);if(X.length<Z.length){let z=new Set;for(let G of Z)if(q(G)&&typeof G.id==="string"&&G.id.trim())z.add(G.id.trim());let Y=new Set(X.map((G)=>G.id)),J=[];for(let G of z)if(!Y.has(G))J.push(G);J1(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:J5($.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 B1($){if(!("claustrum"in $))return $;let{claustrum:Z,...X}=$;return X}async function V0($){try{return{exists:!0,value:JSON.parse(await G5($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function z0($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function B5($){let Z;try{Z=(await V0($)).value}catch{return null}return J8(Z)}function H1($,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:{},G=q($.refresh)?$.refresh:{},B=z??J,H=z??G,W=G.mainRefreshLeaseId!==void 0?{id:G.mainRefreshLeaseId,until:G.mainRefreshLeaseUntil,tokenHash:G.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((D)=>{if(!q(D))return D;let V=typeof D.id==="string"&&q(Y[D.id])?Y[D.id]:{};return{...D,...V}}):void 0;return K1({...$,refresh:z0({...G,mainLastRefreshError:G.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:z0({...J,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:U})}async function H5($){let Z=await V0($.configPath);if(!Z.exists)return null;let X=await V0($.statePath);return G1(H1(Z.value,X.value))}var t3=new Set;async function RB($){try{let{exists:Z,value:X}=await V0($.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:z0({enabled:z.enabled,refreshBeforeExpiryMinutes:z.refreshBeforeExpiryMinutes}),quota:z0({enabled:Y.enabled,checkIntervalMinutes:Y.checkIntervalMinutes,refreshEveryNRequests:Y.refreshEveryNRequests,minimumRemaining:Y.minimumRemaining,failClosedOnUnknownQuota:Y.failClosedOnUnknownQuota}),dump: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(!t3.has($.configPath))t3.add($.configPath),g$.warn("could not read OpenAI auth settings; using defaults",{path:$.configPath});return null}}function K1($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function K5($){return z0({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function Q1($){if($.type==="api")return z0({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return z0({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function bZ($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function h$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function Q5($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function W5($,Z){if(!Q5($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var U5=300000;function e3($,Z){if($===void 0)return 0;return $>Z+U5?0:$}function D5($,Z,X){let z=Date.now(),Y=e3(Z.lastRefreshedAt,z),J=e3(X.lastRefreshedAt,z),G=Z.expires??0,B=X.expires??0,H=J>Y?X:Y>J?Z:B>G?X:G>B?Z:W5(Z,X);h$($,H,"access"),h$($,H,"refresh"),h$($,H,"expires"),h$($,H,"lastRefreshedAt"),h$($,H,"lastRefreshError")}function V5($,Z){if(!q($))return Z;let X=$,z=bZ(X.quota),Y=bZ(Z.quota),J=z>Y,G=J?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!J&&!("lastQuotaRefreshError"in Z))delete G.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete G.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))G.lastUsed=X.lastUsed;return D5(G,X,Z),G}function W1($){let Z=$.refresh?z0({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,X=$.quota?z0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return K1({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(K5)})}function N5($,Z,X,z){if(a3(z)!=="shared")return $;let Y={...$};for(let G of["routing","fallbackOn","refresh","quota","dump","costZeroing","killswitch","logging","cachekeep","cacheKeep","dumpDir","dumpMaxBytes","webSockets","rawWebSocket","responsesLite","codexApiEndpoint"])if(delete Y[G],Object.hasOwn(Z,G))Y[G]=Z[G];let J=q(Z.refresh)?{...Z.refresh}:{};for(let G of["mainLastRefreshError","mainRefreshLeaseId","mainRefreshLeaseUntil","mainRefreshLeaseTokenHash"]){delete J[G];let B=X.refresh?.[G];if(B!==void 0)J[G]=B}if(q(Z.refresh)||Object.keys(J).length>0)Y.refresh=J;return Y}async function p$($,Z=!1){let X=Date.now(),z=X+n7,Y=0;while(Date.now()<=z){Y++;let B=await g({name:"save",ttlMs:a7,path:$,renew:Z});if(B)return B;let H=z-Date.now();if(H<=0)break;await s7(Math.min(e6+M1(e6),H))}let J=Date.now()-X,G=Math.round(J/Math.max(1,Y));throw Error(`Timed out after ${J}ms waiting for the account store lock on ${$} (${Y} attempts, ~${G}ms apart; retry interval is ${e6}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 U1($){let Z=Object.fromEntries($.accounts.map((X)=>[X.id,Q1(X)]));return{version:1,main:z0({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function J8($){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 M5($,Z,X,z){if(!q($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],J=[];for(let G of Z){if(X.has(G))continue;if(z.has(G))continue;let B=$.accounts.find((H)=>q(H)&&typeof H.id==="string"&&H.id.trim()===G);if(!B)continue;Y.push(B),J.push(G)}return{preservedRawEntries:Y,preservedIds:J}}function q5($){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 _5($,Z,X){let z=J8($);if(z===null)return[];let{preservedRawEntries:Y,preservedIds:J}=M5($,z,Z,X);return J1(J),Y}async function TB($,Z,X={}){let{configPath:z,statePath:Y}=Z,J=await p$(z);try{let G=await p$(Y);try{let B=await V0(z),H=await V0(Y),K=q(B.value)?structuredClone(B.value):{},W=(B.exists?G1(H1(B.value,H.value)):null)??F5(),Q=new Set(W.accounts.map((O)=>O.id)),U=J8(B.value)??new Set,D=$(W,{rawRosterIds:[...U],loadedRosterIds:[...Q]})??W,V=new Set(X.allowDrop??[]),_=_5(B.value,Q,V),M=W1(D),R=new Set((Array.isArray(M.accounts)?M.accounts:[]).map((O)=>q(O)&&typeof O.id==="string"?O.id.trim():"").filter(Boolean)),x=_.filter((O)=>{if(!q(O))return!1;if(typeof O.id!=="string")return!1;return!R.has(O.id.trim())}),L={...B1(K),...M,accounts:[...Array.isArray(M.accounts)?M.accounts:[],...x]};if(X.canWrite&&!X.canWrite())return W;if(await B0(z,N5(L,K,D,z)),X.canWrite&&!X.canWrite())return W;return await B0(Y,U1(D)),g$.debug("account config written",{accountCount:L.accounts.length,accountIds:q5(L.accounts)}),D}finally{await G.release()}}finally{await J.release()}}function F5(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function L5($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:bZ($.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:bZ(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 O5($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function X8($){if(Array.isArray($))return $.map(X8);if(!q($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,X8(X)]))}async function P5($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},z){let Y=Z.statePath,J=await p$(Y);try{let G=(await V0(Y)).value,B=q(G)?{...G,version:1}:{version:1};if(X.mainQuota)L5(B,$);if(X.mainRefresh)O5(B,$);if(X.accounts){let H=X.accounts===!0?null:new Set(X.accounts),K=await B5(Z.configPath);B.accounts={...q(B.accounts)?B.accounts:{}};for(let W of $.accounts){if(H&&!H.has(W.id))continue;if(K&&!K.has(W.id))continue;B.accounts[W.id]=V5(B.accounts[W.id],Q1(W))}if(H){for(let W of H)if(!$.accounts.some((Q)=>Q.id===W))delete B.accounts[W]}if(K){for(let W of Object.keys(B.accounts))if(!K.has(W))delete B.accounts[W]}}if(z&&!z())return;await B0(Y,X8(B))}finally{await J.release()}}function j5($){return $?.fallbackOn?.length?$.fallbackOn:t7}function xB($,Z){return j5(Z).includes($)}function R5($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??n3.primary,secondary:Z.secondary??Z["1w"]??n3.secondary}}function z8($){return $?.quota?.enabled!==!1}function l$($){return $?.quota?.failClosedOnUnknownQuota??e7}function D1($,Z,X=Date.now()){if(!z8(Z))return!0;if(!$)return!l$(Z);let z=R5(Z),Y=l$(Z);for(let J of["primary","secondary"]){let G=$[J];if(!G)continue;if(PZ(G,X)){if(Y)return!1;continue}if(G.remainingPercent<z[J])return!1}return!0}function kZ($){return $?.killswitch?.enabled===!0}function $1($){return{primary:$?.primary??$?.["5h"]??Z8.primary,secondary:$?.secondary??$?.["1w"]??Z8.secondary}}function AB($){return $?.cacheKeep??$?.cachekeep}function Z1($){return typeof $==="number"&&Number.isFinite($)?$:0}function V1($,Z){if(!$?.killswitch)return Z8;if($.killswitch.schema===r7){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:Z1(J?.primary),secondary:Z1(J?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return $1($.killswitch.accounts[Z]);return $1($.killswitch.main)}function N1($,Z,X,z=Date.now()){if(!kZ(Z))return!0;if(!$)return!l$(Z);let Y=V1(Z,X),J=l$(Z);for(let G of["primary","secondary"]){let B=$[G];if(!B)continue;if(PZ(B,z)){if(J)return!1;continue}if(B.remainingPercent<Y[G])return!1}return!0}function EB($,Z,X,z){if(!kZ(z))return 300;let Y=[],J=[{accountId:void 0,quota:$},...Z];for(let{accountId:B,quota:H}of J){if(!H)continue;let K=V1(z,B),W=[],Q=!1;for(let U of["primary","secondary"]){let D=H[U];if(!D||PZ(D,X))continue;if(D.remainingPercent>=K[U])continue;let V=D.resetsAt?Date.parse(D.resetsAt):NaN;if(!Number.isFinite(V)||V<=X){Q=!0;break}W.push(V)}if(Q||W.length===0)continue;Y.push(Math.max(...W))}if(Y.length===0)return 300;let G=Math.min(...Y);return Math.max(1,Math.ceil((G-X)/1000))}function X1($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function SB($,Z){let{configPath:X,statePath:z}=Z;if(!$)return;try{let J=await V0(X);if(J.exists&&q(J.value)&&X1(J.value))return}catch{}let Y=await p$(X);try{let J=await p$(z);try{let G=await V0(X);if(G.exists&&q(G.value)){if(X1(G.value))return}if(!$)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let W=e$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(W)B.mainAccountId=W}let H=G.exists&&q(G.value)?G.value:{},K={...B1(H),...W1(B)};await B0(X,K),await B0(z,U1(B))}finally{await J.release()}}finally{await Y.release()}}function T5($){return $?.refresh?.enabled!==!1}function x5($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function M1($){return Math.floor(Math.random()*($+1))}function i0($,Z,X){return!$.access||!$.expires||$.expires-X<=x5(Z)}function A5($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function m$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class q1 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 E5="common-auth-placeholder:v1:openai",_1="main";function CB($){return q($)&&$.type==="oauth"&&($.refresh===E5||$.refresh===q3)}function IB($){return $?.accounts.find((Z)=>Z.id===_1&&Z.enabled!==!1&&D0(Z))}function bB($){if(!$)return $;return{...$,accounts:$.accounts.filter((Z)=>Z.id!==_1)}}function l($,Z){let X=$.accounts.findIndex((z)=>z.id===Z.id);if(X!==-1)$.accounts[X]=Z}function v$($){return $ instanceof Error?$.message:String($)}function Y8($,Z,X){if(Z instanceof C$)return;$.lastRefreshError=C8({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function $8($,Z,X){if(Z instanceof C$)return;if($.lastQuotaRefreshError=F$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)Y8($,Z,X)}function z1($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function S5($,Z){if(!$)return!1;return z1($.primary,Z)||z1($.secondary,Z)}function C5($,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 Y1($,Z,X){return!C5($.quota,Z,X)}function I5($,Z,X,z){return tZ(X)&&D1($.quota,Z,z)&&S5($.quota,z)}function b5($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var k5=60000,f5=60000,y5=600000;function w5($){return`fallback-oauth-refresh-${u7("sha256").update($).digest("base64url").slice(0,16)}`}var h5=1e4,m5=100;class v5{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($)OZ($.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+b5(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return H5(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await P5($,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(()=>{})},k5+M1(f5)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($){let Z=$!==void 0?$:await this.load();if(!Z)return[];let X=[],z=!1;for(let Y of Z.accounts){if(Y.enabled===!1||!D0(Y))continue;if(m$(Z,Y))continue;if(d0(Y))continue;let J=!1,G=Y;try{if(i0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&b0(B,G.refresh,this.now()))throw J=!0,Error(r$(B,this.now()));try{G=await this.refreshAccount(G,Z),z=!0}catch(H){if(X5(H))continue;J=!0;let K=Z.accounts.find((W)=>W.id===Y.id&&D0(W));if(K&&!b0(K.lastRefreshError,K.refresh,this.now()))Y8(K,H,this.now()),l(Z,K),z=!0;throw H}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))X.push(G)}catch(B){let H=A5(G,this.now());if(J){if(!H)continue}else if(!H)continue;if(I5(G,Z,B,this.now()))u0.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:v$(B)}),X.push(G);else if(!l$(Z))X.push(G)}}if(z){let Y=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((J)=>{g$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:v$(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){g$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:v$(Z)})}}accountPassesQuotaPolicy($,Z){return D1($.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(!$||!T5($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!D0(X))continue;if(m$($,X))continue;if(d0(X))continue;if(!i0(X,$,this.now()))continue;if(b0(X.lastRefreshError,X.refresh,this.now()))continue;try{u0.debug("fallback oauth background due",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),await this.refreshAccount(X,$),Z=!0}catch(z){u0.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:v$(z)}),Y8(X,z,this.now()),l($,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||!D0(X))continue;if(m$($,X))continue;if(d0(X))continue;let z=X;try{if(i0(z,$,this.now())){if(b0(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,$),Z=!0}if(Z$(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,$),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):Y1(z,$,this.now())))continue;await this.refreshAccountQuota(z,$),Z=!0}catch(Y){$8(X,Y,this.now()),l($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!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||!D0(J))continue;if(m$(Z,J))continue;if(d0(J))continue;let G=J;try{if(i0(G,Z,this.now())){let B=G.lastRefreshError;if(B&&b0(B,G.refresh,this.now()))throw Error(r$(B,this.now()));G=await this.refreshAccount(G,Z),Y=!0}if(!z&&!Y1(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,l(Z,G),Y=!0;continue}await this.refreshAccountQuota(G,Z),Y=!0}catch(B){$8(J,B,this.now()),l(Z,J),Y=!0,X.push({accountId:J.id,message:v$(B)})}}if(Y)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let z=this.refreshPromises.get($.id);if(z){let G=await z;return l(Z,G),G}let Y=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,Y);let J=await Y;return l(Z,J),J}async waitForConcurrentFallbackRefresh($,Z,X,z){let Y=Date.now()+h5;while(Date.now()<Y){await new Promise((K)=>setTimeout(K,m5));let J=await this.load(),G=J?.accounts.find((K)=>K.id===$.id&&D0(K));if(!G)continue;if(this.assertNotTombstoned(G),(G.access!==X.access||G.refresh!==X.refresh||(G.expires??0)>(X.expires??0)+60000)&&(z.force||!i0(G,J,this.now())))return l(Z,G),u0.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G;let H=G.lastRefreshError;if(H&&b0(H,G.refresh,this.now()))throw l(Z,G),Error(r$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(m$($,Z))throw new q1(Z.id)}async refreshAccountNow($,Z,X){let z=await this.load(),Y=z?.accounts.find((B)=>B.id===$.id&&D0(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(z,Y,X),Y&&!X.force&&!i0(Y,z,this.now()))return l(Z,Y),Y;let J=Y??$,G=await g({name:w5(J.id),ttlMs:y5,path:this.paths.configPath,renew:!0});if(!G){u0.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:J.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,J,X);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),Y=z?.accounts.find((W)=>W.id===$.id&&D0(W)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(z,Y,X),Y&&!X.force&&!i0(Y,z,this.now()))return l(Z,Y),Y;if(!Y)throw new IZ($.id);J=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});u0.debug("fallback oauth refresh request start",{pid:process.pid,accountId:J.id,force:X.force===!0,expiresInMs:J.expires?J.expires-this.now():void 0});let H=await B({refreshToken:J.refresh,fetchImpl:this.fetchImpl,now:this.now});if(J.access=H.access,J.refresh=H.refresh,J.expires=H.expires,J.lastRefreshedAt=H.expires-H.expiresIn*1000,J.lastRefreshError=void 0,l(Z,J),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new IZ($.id);return u0.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J}finally{await G.release()}}async refreshAccountQuota($,Z){let X=$;if(this.assertNotTombstoned(X),!X.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let z=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(J)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,J):z({accessToken:J,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${$.id} has no access token`);let J=await Y(X.access);X.quota=J,X.lastQuotaRefreshError=void 0,l(Z,X),await this.save(Z)}catch(J){throw $8($,J,this.now()),l(Z,$),J}}}var F1=["primary","secondary"];function s0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function a0($){return typeof $==="number"&&Number.isFinite($)}function yB($){let Z=s0($)?$.counters:void 0,X=s0(Z)?Z.resetCredits:void 0,z=s0(X)?X.value:void 0;return a0(z)?z:void 0}function wB($){if(!M0($.quota))return;let Z=u($.quota);return Z.limits.some((X)=>X.kind==="reading")?Z.checkedAt:void 0}function g5($,Z){if(!s0(Z))return;let X=Z.usedPercent;if(!a0(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...a0(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function p5($){let Z=$.spendControl;if(s0(Z)&&typeof Z.reached==="boolean"){let X=(z)=>a0(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 l5($,Z){if(!s0($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...a0($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function hB($,Z,X){if(!s0($)||!a0(Z))return;let z=[],Y=[];for(let K of F1){let W=g5(K,$[K]);if(W)z.push(W);else if(X)Y.push({label:K})}let J=p5($),G=$.resetCreditsAvailable,B=typeof G==="number"&&Number.isSafeInteger(G)&&G>=0?{resetCredits:{value:G,checkedAt:Z}}:void 0,H=l5($.credits,Z);if(z.length===0&&Y.length===0&&!J&&!B&&!H)return;return{checkedAt:Z,...z.length>0?{readings:z}:{},...Y.length>0?{coverage:Y}:{},...J?{budget:J}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function L1($){if(!M0($))return;let Z=u($),X={};for(let z of F1){let Y=Z.limits.find((G)=>G.label===z&&G.kind==="reading");if(!Y||!a0(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 P1="main";function dB($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function cB($,Z,X){let z=new Map;if(kZ(Z))for(let Y of $)z.set(Y.id,N1(L1(Y.quota),Z,Y.id===P1?void 0:Y.id,X));return z}var uB=5,d5=5000;function iB($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function sB($,Z=d5){let X=$.rows.filter((G)=>G.kind==="oauth"&&$.killswitch.get(G.id)!==!1&&u(G.quota).limits.length===0);if(X.length===0)return;if(t({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((G)=>$.killswitch.get(G.id)!==!1))return;let Y=[];if(t({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(G)=>{let B=$.requestPull(G);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let J;return Promise.race([Promise.all(Y),new Promise((G)=>{J=setTimeout(G,Z)})]).then(()=>{}).finally(()=>clearTimeout(J))}function fZ($){return $.reason==="exhausted"||$.reason==="budget-spent"}function c5($,Z){if(!J0($))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 yZ($,Z,X){let z=(B)=>Z.killswitch.get(B)!==!1,Y=new Set(X.admitted.filter((B)=>B.lastPath!==!0&&z(B.id)).map((B)=>B.id)),J=new Map(X.refused.map((B)=>[B.id,B])),G=$.filter((B)=>{if(B.kind!=="oauth"||!z(B.id))return!1;if(J.get(B.id)?.reason!=="exhausted")return!1;let H=u(B.quota);if(C0(H,Z.now))return!1;return c5(H.credits,Z.now)}).map((B)=>B.id);return{free:Y,credits:G}}function u5($,Z=$.rows){return t({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class i5{#$=new Set;served($,Z,X){let z=u5($),Y=yZ($.rows,$,z),J=new Set(Y.credits);if(Y.free.has(Z)){this.#$.clear();return}for(let G of[...this.#$])if(!J.has(G))this.#$.delete(G);if(!J.has(Z)||this.#$.has(Z))return;this.#$.add(Z),X?.info("serving requests on prepaid credits",{accountId:Z,reason:"free quota used up"})}has($){return this.#$.has($)}ids(){return new Set(this.#$)}}function j1($,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 O1($,Z,X){if(Z.refused.find((Y)=>!fZ(Y)&&X.get(Y.id)!==!1))return{reason:"quota-unknown"};return j1($[0],Z,X)}function aB($){let Z=$.replayable!==!1,X=$.mainId===void 0?P1:$.mainId??"",z=Z?$.placement:"main-first",Y=cZ({rows:$.rows,placement:z,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),J=n$($.rows.map((U)=>U.id),z,X),G=new Set(Y.admission.refused.filter((U)=>fZ(U)&&$.killswitch.get(U.id)!==!1).map((U)=>U.id)),B=J.filter((U)=>G.has(U)),H=yZ($.rows,$,Y.admission),K=Y.order.filter((U)=>H.free.has(U)),W=J.filter((U)=>H.credits.includes(U)),Q=(U,D)=>({kind:"send",order:U,lastPath:D,tiers:Object.fromEntries(U.map((V)=>[V,H.free.has(V)?"free":H.credits.includes(V)?"credits":"last-path"]))});if(!Z){let U=J.includes(X),D=U?X:K[0]??W[0]??Y.order[0]??B[0];if(D!==void 0&&Y.order.includes(D))return Q([D],!1);if(D!==void 0&&W.includes(D))return Q([D],!1);if(D!==void 0&&G.has(D))return Q([D],!0);return{kind:"block",block:U?j1(X,Y.admission,$.killswitch):O1(J,Y.admission,$.killswitch)}}if(K.length>0)return Q(K,!1);if(W.length>0){let U=Y.order.length>0?Y.order:B;return Q([...W,...U.filter((D)=>!W.includes(D))],!1)}if(Y.order.length>0)return Q(Y.order,!1);if(B.length>0)return Q(B,!0);return{kind:"block",block:O1(J,Y.admission,$.killswitch)}}function nB($){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,u(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 R1($,Z,X){let z=X.exclude,Y=z?$.rows.filter((G)=>!z.has(G.id)):$.rows,J=new Map;for(let G of Y){let B=Z.resetCredits(G.id);if(B!==void 0)J.set(G.id,B)}return nZ({rows:Y,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(G)=>Z.reservePercent(G.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:J,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function oB($,Z,X,z){let Y=R1($,Z,{exclude:X,pendingBytes:z}),J=$.rows.filter((W)=>!X.has(W.id)),G=yZ(J,$,Y.admission),B=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,tier:G.free.has(Y.accountId)?"free":"last-path",...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(B&&G.free.has(B.accountId))return B;let H=G.credits[0];if(H===void 0)return B;let K=u(J.find((W)=>W.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",tier:"credits",...K===void 0?{}:{quotaCheckedAt:K}}}function rB($,Z,X){let z=$.killswitch.get(X)===!1,Y={kind:"move",reason:z?"killswitch":"exhausted"},J=R1($,Z,{pin:X}),G=yZ($.rows,$,J.admission),B=G.credits.includes(X),H=G.credits.some((Q)=>Q!==X);if(J.outcome==="dispatch"){let Q=!G.free.has(J.accountId);if(J.pin.action==="assign"){if(Q&&B)return{kind:"serve",tier:"credits"};return Y}if(J.accountId!==X)return{kind:"detour"};if(Q&&H)return Y;return{kind:"serve",tier:Q?"last-path":"free"}}let K=J.admission.refused.find((Q)=>Q.id===X),W=z||K!==void 0&&fZ(K);if(B)return{kind:"serve",tier:"credits"};if(H)return W?Y:{kind:"detour"};if(!z&&K&&fZ(K))return{kind:"last-path"};return{kind:"none"}}function tB($,Z,X,z){let Y=$.killswitch.get(X);return aZ({quota:Z.projections.get(X),now:$.now,...z===void 0?{}:{status:z},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as T1}from"node:os";import{join as x1}from"node:path";function s5(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?x1(T1(),"opencode-openai-auth","opencode-openai-auth.log"):x1(T1(),"opencode-openai-auth.log"))}function a5(){return A1(process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL)}E1({file:s5,level:a5});
101
+ export{M0 as de,N$ as ee,t1 as fe,gZ as ge,y1 as he,F8 as ie,g1 as je,p1 as ke,u as le,C0 as me,j8 as ne,$2 as oe,n$ as pe,Z2 as qe,uZ as re,X2 as se,s6 as te,a6 as ue,g9 as ve,p9 as we,F0 as xe,N as ye,S as ze,h0 as Ae,p2 as Be,l2 as Ce,b as De,m0 as Ee,q9 as Fe,X4 as Ge,D6 as He,z4 as Ie,Y4 as Je,N6 as Ke,B4 as Le,j0 as Me,E9 as Ne,H4 as Oe,P6 as Pe,f as Qe,p0 as Re,h6 as Se,nY as Te,J2 as Ue,W2 as Ve,S8 as We,C8 as Xe,b0 as Ye,r$ as Ze,y8 as _e,h8 as $e,M2 as af,b8 as bf,k8 as cf,e$ as df,_2 as ef,w0 as ff,P2 as gf,j2 as hf,R2 as if,T2 as jf,lX as kf,cX as lf,uX as mf,iX as nf,d0 as of,C$ as pf,FJ as qf,LJ as rf,AJ as sf,n as tf,A0 as uf,X7 as vf,z7 as wf,Y7 as xf,J7 as yf,G7 as zf,B7 as Af,H7 as Bf,K7 as Cf,A as Df,T7 as Ef,w7 as Ff,U$ as Gf,t6 as Hf,JB as If,a3 as Jf,HB as Kf,D0 as Lf,r7 as Mf,PB as Nf,Z8 as Of,Z5 as Pf,B5 as Qf,H5 as Rf,RB as Sf,TB as Tf,P5 as Uf,j5 as Vf,xB as Wf,D1 as Xf,kZ as Yf,AB as Zf,V1 as _f,N1 as $f,EB as ag,SB as bg,x5 as cg,m$ as dg,_1 as eg,CB as fg,IB as gg,bB as hg,y5 as ig,w5 as jg,v5 as kg,yB as lg,wB as mg,hB as ng,L1 as og,P1 as pg,dB as qg,cB as rg,uB as sg,d5 as tg,iB as ug,sB as vg,c5 as wg,i5 as xg,aB as yg,nB as zg,oB as Ag,rB as Bg,tB as Cg};